@sentry/junior 0.314.0 → 0.316.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 (667) hide show
  1. package/dist/{channel-access-BOL29BG3.js → adapter-context-Bref7aPI.js} +42 -3
  2. package/dist/{admin-BXGAySz0.js → admin-QYiDMnsu.js} +1 -1
  3. package/dist/agent-runner-Cr5Fhjf-.js +23870 -0
  4. package/dist/{agent-update-delivery-CZ5M8RDa.js → agent-update-delivery-BY13DPSD.js} +46 -9
  5. package/dist/api/schema.d.ts +9549 -2
  6. package/dist/api/schema.js +4 -6
  7. package/dist/api.d.ts +2 -3
  8. package/dist/api.js +747 -293
  9. package/dist/{app-D7tKnw9a.d.ts → app-BhvzRD__.d.ts} +314 -29
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +268 -58
  12. package/dist/change-record-Bqsa5ZXE.d.ts +175 -0
  13. package/dist/chat-core-engine-3dtlMku3.js +123 -0
  14. package/dist/cli/chat.d.ts +4 -1
  15. package/dist/cli/chat.js +39 -21
  16. package/dist/cli/check.js +4 -4
  17. package/dist/cli/main.js +2 -2
  18. package/dist/cli/plugins.js +3 -4
  19. package/dist/cli/run.d.ts +1 -1
  20. package/dist/cli/run.js +1 -1
  21. package/dist/cli/snapshot-create.js +2 -5
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +46 -74
  24. package/dist/{continue-in-slack-fnmD2Ifb.js → continue-in-slack-DbQUFe_F.js} +3 -5
  25. package/dist/{conversation-feed-DdFQuQDR.js → conversation-feed-B84pMjHo.js} +28 -3
  26. package/dist/{conversation-turn-DScuDYmN.js → conversation-turn-DzEpTIaf.js} +152 -199
  27. package/dist/{create-CrNt4Ewu.js → create-DUJBXr6E.js} +4 -4
  28. package/dist/{credential-sync-CtqsGjj1.js → credential-sync-JH_K9Adg.js} +10 -15
  29. package/dist/db-BpxcYXfD.d.ts +2 -0
  30. package/dist/{credentialed-dWRA3-oJ.js → db-DhzvUY23.js} +21830 -9264
  31. package/dist/deployment-BhvrhQeh.js +51 -0
  32. package/dist/engine-context-C9Nal48K.js +1814 -0
  33. package/dist/{html-B8rBt7F4.js → html-B_12WjKT.js} +2 -5
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/job-runner-DO8nslyY.js +1139 -0
  36. package/dist/{lineage-EULJkGO1.js → lineage-D3AZAJVe.js} +1 -1
  37. package/dist/{list-C5400AlJ.js → list-B0zsb5Cp.js} +307 -146
  38. package/dist/{markers-DUP8aBOp.js → list-mkB_GU8R.js} +96 -124
  39. package/dist/local-server-CpnGhYml.js +276 -0
  40. package/dist/{conversation-privacy-DtZhI91r.js → logging-B8KEJegM.js} +2 -231
  41. package/dist/{media-FYM-Bl3H.js → media-BebquhET.js} +684 -37
  42. package/dist/{message-DuDelZFr.js → message-B5fKDYzz.js} +18 -16
  43. package/dist/{model-input-0osF3pBS.js → model-input-CuMWy37l.js} +3 -3
  44. package/dist/nitro.d.ts +7 -1
  45. package/dist/nitro.js +48 -293
  46. package/dist/{oauth-callback-server-DX2fQ7Nq.js → oauth-callback-server-B3Vvlydo.js} +2 -2
  47. package/dist/{oauth-relay-PwPMdZJv.js → oauth-relay-6ERrGPbA.js} +1 -1
  48. package/dist/{package-discovery-DD9vencX.js → package-discovery-BI6T_RkD.js} +50 -1
  49. package/dist/people-CUtFApfL.js +81 -0
  50. package/dist/proxy-path-BTmXDjfx.js +203 -0
  51. package/dist/{resolve-D8CPJcNK.js → resolve-D5JVvv6A.js} +229 -4
  52. package/dist/{result-D090hxr5.js → result-CS_7mo8a.js} +95 -144
  53. package/dist/{runner-BU7fgrm-.js → runner-BzAES5W3.js} +7 -7
  54. package/dist/{sandbox-egress-signals-BUmVrsoG.js → sandbox-egress-signals-Dwhk2Q5F.js} +1 -1
  55. package/dist/{schema-7gW9vBpJ.js → schema-z5-wA6N4.js} +132 -15
  56. package/dist/{service-account-plA-uzIB.js → service-account-D6AsAtc1.js} +1 -3
  57. package/dist/{mailbox-turn-DL3Lvsm0.js → session-stop-DponjDUZ.js} +3259 -3793
  58. package/dist/{skills-CIosT6bS.js → skills-DgJ9GBPR.js} +4 -4
  59. package/dist/{slack-conversation-unfurl-CBgZqth6.js → slack-conversation-unfurl-Dq71EkhM.js} +6 -8
  60. package/dist/{spawn-DRjdzh3R.js → spawn-BJWpdwhQ.js} +4 -5
  61. package/dist/start-conversation-B-LIqqNi.js +162 -0
  62. package/dist/system-prompt-table-iIgpmslr.js +1171 -0
  63. package/dist/{task-runner-C-pXsgHM.js → task-runner-BJae4JwE.js} +83 -17
  64. package/dist/{thread-context-CDX4dSZd.js → thread-context-fiMNylbg.js} +5 -6
  65. package/dist/topic-CRYYBYp-.js +7 -0
  66. package/dist/transcript-CCi7323k.js +410 -0
  67. package/dist/turn-session-routing-D15orfwy.js +1309 -0
  68. package/dist/{turn-wake-Bzq1Efrm.js → turn-wake-BjDW7x-5.js} +5 -7
  69. package/dist/{validation-bTq88sya.js → validation-D5WmmmhX.js} +1 -1
  70. package/dist/{version-DGUa1dZK.js → version-CBQoanXb.js} +1 -1
  71. package/dist/version.js +1 -1
  72. package/dist/virtual-module-BeKA_EII.js +12 -0
  73. package/dist/{worker-AkZg7Dg1.js → worker-Cyb4kF17.js} +3 -5
  74. package/migrations/20260711145847_initial/snapshot.json +2103 -0
  75. package/migrations/20260711145900_conversation_metrics/snapshot.json +135 -0
  76. package/migrations/20260712153649_conversation_message_search/snapshot.json +50 -0
  77. package/migrations/20260713040256_peaceful_scalphunter/snapshot.json +42 -0
  78. package/migrations/20260715174202_useful_magus/snapshot.json +42 -0
  79. package/migrations/20260715174203_conversation_events/snapshot.json +539 -0
  80. package/migrations/20260723042835_drop_legacy_conversation_messages/snapshot.json +9 -0
  81. package/migrations/20260723050612_thick_sugar_man/snapshot.json +120 -0
  82. package/migrations/20260727223822_sticky_rage/snapshot.json +274 -0
  83. package/migrations/20260728033158_slippery_harrier/snapshot.json +191 -0
  84. package/migrations/20260728040836_native_conversation_history/snapshot.json +9 -0
  85. package/migrations/20260728204900_sour_golden_guardian/snapshot.json +124 -0
  86. package/migrations/20260730233332_structured_conversation_events/snapshot.json +9 -0
  87. package/migrations/20260731164038_conversation_session_source/snapshot.json +42 -0
  88. package/migrations/20260801230336_source_visibility/snapshot.json +9 -0
  89. package/migrations/20260802023731_magical_ezekiel_stane/snapshot.json +266 -0
  90. package/migrations/20260804015843_neat_the_anarchist/snapshot.json +714 -0
  91. package/migrations/20260804165952_drop_paused_scheduled_tasks/snapshot.json +9 -0
  92. package/migrations/20260804225613_curvy_excalibur/snapshot.json +223 -0
  93. package/migrations/20260805174033_lowly_valkyrie/snapshot.json +344 -0
  94. package/migrations/20260805200301_restrict_task_execution_kinds/snapshot.json +36 -0
  95. package/migrations/20260806030729_first_warhawk/snapshot.json +690 -0
  96. package/migrations/20260807185200_task_execution_status/snapshot.json +92 -0
  97. package/migrations/20260808014743_task_title_columns/snapshot.json +68 -0
  98. package/migrations/20260809220421_misty_typhoid_mary/snapshot.json +191 -0
  99. package/migrations/20260811193709_mcp_credential_subject/snapshot.json +9 -0
  100. package/migrations/20260812032924_conversation_event_actor_and_participants/snapshot.json +393 -0
  101. package/migrations/20260812172418_attachment_storage/snapshot.json +341 -0
  102. package/migrations/20260813230732_artifacts/snapshot.json +349 -0
  103. package/migrations/20260814062905_dizzy_barracuda/snapshot.json +342 -0
  104. package/migrations/20260814231353_drop_workspace_repo_primary/snapshot.json +55 -0
  105. package/migrations/20260815030100_wild_phantom_reporter/snapshot.json +135 -0
  106. package/migrations/20260817082233_workspace_snapshots_table/snapshot.json +625 -0
  107. package/migrations/20260818160339_workspace_snapshot_active_build/snapshot.json +62 -0
  108. package/migrations/20260821180755_strong_randall/snapshot.json +42 -0
  109. package/migrations/20260823030308_workspace_snapshot_size_bytes/snapshot.json +62 -0
  110. package/migrations/20260824190313_complex_rage/snapshot.json +690 -0
  111. package/migrations/20260827233711_conversation_location/snapshot.json +42 -0
  112. package/migrations/20260901224306_event_task_status/snapshot.json +100 -0
  113. package/migrations/20260904153232_attachment_provider/snapshot.json +234 -0
  114. package/migrations/20260909111415_conversation_briefs/snapshot.json +364 -0
  115. package/migrations/20260910144928_automation_outcomes_backfill/snapshot.json +9 -0
  116. package/migrations/20260911184346_conversation_metrics/snapshot.json +226 -0
  117. package/migrations/20260921140842_scheduled_automation_channel_destinations/snapshot.json +9 -0
  118. package/migrations/20260922221709_event_automation_channel_destinations/snapshot.json +9 -0
  119. package/migrations/20261001113455_conversation_forks/snapshot.json +120 -0
  120. package/migrations/20261005161844_automation_versions/snapshot.json +150 -0
  121. package/migrations/20261006152043_user_timezone/snapshot.json +37 -0
  122. package/migrations/20261008200858_user_admin/snapshot.json +37 -0
  123. package/migrations/20261009145407_event_automation_status_reason/snapshot.json +42 -0
  124. package/migrations/20261013160816_agent_invocation_parent_mailbox/snapshot.json +93 -0
  125. package/migrations/20261013215020_agent_invocation_parent_tool_call/snapshot.json +42 -0
  126. package/migrations/20261014011138_agent_invocation_title/snapshot.json +42 -0
  127. package/migrations/20261014211942_conversation_stopped_at/snapshot.json +42 -0
  128. package/migrations/20261015012820_flowery_rage/snapshot.json +42 -0
  129. package/migrations/20261017000924_automations/snapshot.json +790 -0
  130. package/migrations/20261017134736_automation_runs/snapshot.json +474 -0
  131. package/migrations/20261017170250_drop_legacy_automation_tables/snapshot.json +397 -0
  132. package/migrations/20261018134754_automation_creator_identity/snapshot.json +130 -0
  133. package/migrations/20261023071954_automation_run_version/snapshot.json +79 -0
  134. package/migrations/20261025233137_identity_signed_in_at/snapshot.json +42 -0
  135. package/migrations/20261027234315_workspace_vcpus/snapshot.json +37 -0
  136. package/migrations/20261028124242_plugin_report_index/snapshot.json +68 -0
  137. package/migrations/20261028154230_agent_invocation_type/snapshot.json +42 -0
  138. package/migrations/20261030021803_any_resource_event_triggers/snapshot.json +42 -0
  139. package/migrations/20261030234309_user_customization/snapshot.json +37 -0
  140. package/migrations/20261031020656_review_items/snapshot.json +1078 -0
  141. package/migrations/20261031024151_review_item_dedupe_tenant/snapshot.json +62 -0
  142. package/migrations/20261031024246_review_item_slack_cards/snapshot.json +159 -0
  143. package/migrations/20261031155308_system_identity/snapshot.json +9 -0
  144. package/migrations/20261101193952_review_item_foreign_keys/snapshot.json +108 -0
  145. package/migrations/20261102172751_review_item_turn/snapshot.json +42 -0
  146. package/migrations/20261102221411_conversation_read_positions/snapshot.json +190 -0
  147. package/migrations/20261104085028_conversation_quick_question/snapshot.json +42 -0
  148. package/migrations/20261104145136_conversation_participant_pins/snapshot.json +42 -0
  149. package/migrations/20261104164429_conversation_detail_version/snapshot.json +42 -0
  150. package/migrations/20261104172055_conversation_auto_archive/snapshot.json +206 -0
  151. package/migrations/20261105005443_drop_agent_invocation_model_profile/snapshot.json +30 -0
  152. package/migrations/20261105043807_plugin_conversation_index/snapshot.json +76 -0
  153. package/migrations/20261105051837_conversation_event_author_index/snapshot.json +70 -0
  154. package/migrations/20261105182854_conversation_event_latest_message_indexes/snapshot.json +136 -0
  155. package/migrations/20261106011443_conversation_pin_position/snapshot.json +42 -0
  156. package/migrations/20261106095004_push_notifications/snapshot.json +308 -0
  157. package/migrations/20261106162740_conversation_kind/snapshot.json +88 -0
  158. package/migrations/20261107002001_read_position_backfill/snapshot.json +9 -0
  159. package/migrations/20261107025209_child_archived_at/snapshot.json +42 -0
  160. package/migrations/20261107035735_shared_archive/snapshot.json +67 -0
  161. package/migrations/20261107215055_child_location/snapshot.json +9 -0
  162. package/migrations/20261108191927_conversation_unsubscribe/snapshot.json +42 -0
  163. package/migrations/20261109021618_conversation_paused_status/snapshot.json +9 -0
  164. package/migrations/20261109111553_guardian_review_time_index/snapshot.json +54 -0
  165. package/migrations/20261109173130_conversation_participant_unsubscribed_index/snapshot.json +62 -0
  166. package/migrations/20261109182006_turn_metric_actor/snapshot.json +128 -0
  167. package/migrations/20261109202836_participant_root_actor_backfill/snapshot.json +9 -0
  168. package/migrations/20261109232640_conversation_delivery_paused_at/snapshot.json +42 -0
  169. package/migrations/20261110120937_web_linked_slack_identity_repair/snapshot.json +9 -0
  170. package/migrations/20261110175824_automation_task_kind/snapshot.json +145 -0
  171. package/migrations/20261110210242_conversation_kind_automation/snapshot.json +55 -0
  172. package/migrations/20261110222632_review_item_plugin_actions/snapshot.json +37 -0
  173. package/migrations/20261110225157_conversation_last_message_at/snapshot.json +42 -0
  174. package/migrations/20261111013351_automation_task_kind_repair/snapshot.json +9 -0
  175. package/migrations/20261111163126_drop_legacy_columns/snapshot.json +9 -0
  176. package/migrations/20261111170150_code_change_last_activity/snapshot.json +42 -0
  177. package/migrations/20261111191441_agent_invocation_fork/snapshot.json +42 -0
  178. package/migrations/20261112142841_code_change_draft/snapshot.json +37 -0
  179. package/migrations/20261112202901_attachment_uploads/snapshot.json +255 -0
  180. package/migrations/20261112220407_conversation_agent_config/snapshot.json +42 -0
  181. package/migrations/20261113081247_attachment_deferred_download/snapshot.json +52 -0
  182. package/migrations/20261113225551_conversation_embeddings/snapshot.json +203 -0
  183. package/migrations/20261114213238_user_preferences/snapshot.json +37 -0
  184. package/migrations/20261114222527_code_change_repository_state_index/snapshot.json +70 -0
  185. package/migrations/20261115172605_attachment_kinds/snapshot.json +244 -0
  186. package/migrations/20261115173004_attachment_url_fill/snapshot.json +9 -0
  187. package/migrations/20261115180216_attachment_url_index/snapshot.json +62 -0
  188. package/migrations/20261116103700_plan_items/snapshot.json +420 -0
  189. package/migrations/20261117100100_automation_creator_slack_index/snapshot.json +62 -0
  190. package/migrations/20261117132522_conversation_event_search/snapshot.json +396 -0
  191. package/migrations/20261117164007_automation_last_run/snapshot.json +108 -0
  192. package/migrations/20261117164047_automation_last_run_index/snapshot.json +54 -0
  193. package/migrations/20261117210444_money_micro_usd/snapshot.json +68 -0
  194. package/migrations/20261117210505_conversation_cost_micro_usd/snapshot.json +9 -0
  195. package/migrations/20261118081416_people_list_metric_index/snapshot.json +86 -0
  196. package/migrations/20261118095216_automation_rollout_repair/snapshot.json +9 -0
  197. package/migrations/20261118143948_cache_warming_history_reset/snapshot.json +9 -0
  198. package/migrations/20261119040651_artifact_visibility/snapshot.json +132 -0
  199. package/migrations/20261119040715_artifact_public_sha_index/snapshot.json +9 -0
  200. package/migrations/20261119052706_artifact_drop_public/snapshot.json +71 -0
  201. package/migrations/20261119053831_artifact_path/snapshot.json +114 -0
  202. package/migrations/20261119053844_artifact_path_index/snapshot.json +9 -0
  203. package/migrations/20261119091949_review_item_answered_index/snapshot.json +70 -0
  204. package/migrations/20261119100029_review_item_status_index/snapshot.json +54 -0
  205. package/migrations/20261119165607_brief_outcome_status/snapshot.json +42 -0
  206. package/migrations/20261119165622_brief_outcome_status_backfill/snapshot.json +9 -0
  207. package/migrations/20261119213716_brief_created_at_index/snapshot.json +62 -0
  208. package/migrations/20261119222456_slack_person_search_index/snapshot.json +50 -0
  209. package/migrations/20261119225522_code_change_size/snapshot.json +104 -0
  210. package/migrations/20261119232253_merge_conflict_notice_dismiss/snapshot.json +9 -0
  211. package/migrations/20261119235649_inbox_snoozes/snapshot.json +605 -0
  212. package/migrations/20261120093118_code_change_search_index/snapshot.json +89 -0
  213. package/migrations/20261120093452_review_item_owner/snapshot.json +314 -0
  214. package/migrations/20261120185654_review_item_owner_index/snapshot.json +62 -0
  215. package/migrations/20261120185754_memory_core_adoption/snapshot.json +1184 -0
  216. package/migrations/20261120185854_memory_core_indexes/snapshot.json +70 -0
  217. package/migrations/20261120235226_todos/snapshot.json +473 -0
  218. package/migrations/20261121082316_inbox_items/snapshot.json +2026 -0
  219. package/migrations/20261121175651_todo_changed_by_agent/snapshot.json +42 -0
  220. package/migrations/20261121183527_inbox_item_subject_title_parts/snapshot.json +42 -0
  221. package/migrations/20261121194143_inbox_snooze_wake_reason/snapshot.json +42 -0
  222. package/migrations/20261121222400_authorization_request_index/snapshot.json +62 -0
  223. package/migrations/20261121225908_conversation_metadata/snapshot.json +184 -0
  224. package/migrations/20261121225910_conversation_metadata_fill/snapshot.json +9 -0
  225. package/migrations/20261121225913_conversation_search_index/snapshot.json +50 -0
  226. package/migrations/20261122022900_inbox_item_legacy_automation_keys/snapshot.json +9 -0
  227. package/migrations/20261122024454_artifact_expiry/snapshot.json +37 -0
  228. package/migrations/20261122024455_artifact_permanent_sha_index/snapshot.json +62 -0
  229. package/migrations/20261122024457_artifact_drop_public_sha_index/snapshot.json +37 -0
  230. package/migrations/20261122024458_conversation_kind_lead/snapshot.json +55 -0
  231. package/migrations/20261122024459_conversation_lead_actor_index/snapshot.json +54 -0
  232. package/migrations/20261122071549_keep_legacy_archive_columns/snapshot.json +49 -0
  233. package/migrations/20261122191400_conversation_embeddings_fk_validate/snapshot.json +9 -0
  234. package/migrations/20261122204325_money_micro_usd_repair/snapshot.json +9 -0
  235. package/migrations/20261122204326_agent_config_backfill/snapshot.json +143 -0
  236. package/migrations/20261122221456_inbox_item_deliveries/snapshot.json +301 -0
  237. package/migrations/20261123155735_pg_trgm/snapshot.json +9 -0
  238. package/migrations/20261123155739_search_indexes/snapshot.json +167 -0
  239. package/migrations/20261123172647_drop_legacy_archive_columns/snapshot.json +9 -0
  240. package/migrations/20261123192506_memory_prefix_index/snapshot.json +69 -0
  241. package/migrations/20261123201740_todo_search_indexes/snapshot.json +89 -0
  242. package/migrations/20261123211505_todo_inbox_items/snapshot.json +38 -0
  243. package/migrations/20261123214917_drop_code_urls/snapshot.json +44 -0
  244. package/migrations/20261123224000_code_change_conversations_index/migration.sql +1 -0
  245. package/migrations/20261123224000_code_change_conversations_index/snapshot.json +54 -0
  246. package/migrations/20261124122023_drop_code_change_sizes/migration.sql +4 -0
  247. package/migrations/20261124122023_drop_code_change_sizes/snapshot.json +82 -0
  248. package/migrations/20261124142958_conversation_root_lookup_index/migration.sql +1 -0
  249. package/migrations/20261124142958_conversation_root_lookup_index/snapshot.json +62 -0
  250. package/migrations/20261124183352_legacy_brief_metadata_fill/migration.sql +26 -0
  251. package/migrations/20261124183352_legacy_brief_metadata_fill/snapshot.json +114 -0
  252. package/migrations/20261124202143_drizzle_v1_baseline/migration.sql +5 -0
  253. package/migrations/20261124202143_drizzle_v1_baseline/snapshot.json +2012 -0
  254. package/migrations/20261124221751_spaces/migration.sql +22 -0
  255. package/migrations/20261124221751_spaces/snapshot.json +436 -0
  256. package/migrations/20261124230319_conversation_metrics_utc_day_stats/migration.sql +11 -0
  257. package/migrations/20261124230319_conversation_metrics_utc_day_stats/snapshot.json +9 -0
  258. package/migrations/20261124234024_space_conversations/migration.sql +5 -0
  259. package/migrations/20261124234024_space_conversations/snapshot.json +103 -0
  260. package/migrations/20261124234026_space_conversations_index/migration.sql +1 -0
  261. package/migrations/20261124234026_space_conversations_index/snapshot.json +62 -0
  262. package/migrations/20261125012448_drop_lead_actor_index/migration.sql +3 -0
  263. package/migrations/20261125012448_drop_lead_actor_index/snapshot.json +36 -0
  264. package/migrations/20261125012452_space_lead_index/migration.sql +1 -0
  265. package/migrations/20261125012452_space_lead_index/snapshot.json +54 -0
  266. package/migrations/20261125043821_space_configurations/migration.sql +11 -0
  267. package/migrations/20261125043821_space_configurations/snapshot.json +194 -0
  268. package/migrations/20261125064854_agent_update_done_status/migration.sql +9 -0
  269. package/migrations/20261125064854_agent_update_done_status/snapshot.json +9 -0
  270. package/migrations/20261125073321_turn_engine_tables/migration.sql +75 -0
  271. package/migrations/20261125073321_turn_engine_tables/snapshot.json +1497 -0
  272. package/migrations/20261125073339_turn_inbox_one_source/migration.sql +5 -0
  273. package/migrations/20261125073339_turn_inbox_one_source/snapshot.json +9 -0
  274. package/migrations/20261125124506_versions_notify/migration.sql +27 -0
  275. package/migrations/20261125124506_versions_notify/snapshot.json +9 -0
  276. package/migrations/20261125140339_turn_group_key/migration.sql +14 -0
  277. package/migrations/20261125140339_turn_group_key/snapshot.json +75 -0
  278. package/migrations/20261125140343_turn_group_key_not_null/migration.sql +4 -0
  279. package/migrations/20261125140343_turn_group_key_not_null/snapshot.json +29 -0
  280. package/migrations/20261125142845_code_change_requesters/migration.sql +1 -0
  281. package/migrations/20261125142845_code_change_requesters/snapshot.json +42 -0
  282. package/migrations/20261125142846_code_change_requesters_index/migration.sql +1 -0
  283. package/migrations/20261125142846_code_change_requesters_index/snapshot.json +54 -0
  284. package/migrations/20261125143903_space_visibility/migration.sql +1 -0
  285. package/migrations/20261125143903_space_visibility/snapshot.json +37 -0
  286. package/migrations/20261125154848_merge_leaves/migration.sql +2 -0
  287. package/migrations/20261125154848_merge_leaves/snapshot.json +14 -0
  288. package/migrations/20261125171254_conversation_visibility/migration.sql +4 -0
  289. package/migrations/20261125171254_conversation_visibility/snapshot.json +67 -0
  290. package/migrations/20261125171257_conversation_visibility_backfill/migration.sql +25 -0
  291. package/migrations/20261125171257_conversation_visibility_backfill/snapshot.json +9 -0
  292. package/migrations/20261125213232_drop_versions_notify/migration.sql +19 -0
  293. package/migrations/20261125213232_drop_versions_notify/snapshot.json +9 -0
  294. package/migrations/20261125225138_conversation_kind_root_thread/migration.sql +23 -0
  295. package/migrations/20261125225138_conversation_kind_root_thread/snapshot.json +55 -0
  296. package/migrations/20261125225142_conversation_kind_root_thread_backfill/migration.sql +7 -0
  297. package/migrations/20261125225142_conversation_kind_root_thread_backfill/snapshot.json +9 -0
  298. package/migrations/20261126000151_conversation_event_message_role_seq_index/migration.sql +1 -0
  299. package/migrations/20261126000151_conversation_event_message_role_seq_index/snapshot.json +69 -0
  300. package/migrations/20261126012917_merge_leaves/migration.sql +2 -0
  301. package/migrations/20261126012917_merge_leaves/snapshot.json +12 -0
  302. package/package.json +13 -12
  303. package/skills/design-automation-skill/SKILL.md +1 -1
  304. package/skills/jr-rpc/SKILL.md +3 -5
  305. package/dist/adapter-JARQvoLw.js +0 -258
  306. package/dist/adapter-context-B4BrJZuS.js +0 -43
  307. package/dist/agent-runner-qZU5TR8i.js +0 -11974
  308. package/dist/agent-update-cS7Z9mnG.js +0 -26
  309. package/dist/background-compaction-queue-C_uIBUvS.js +0 -145
  310. package/dist/callback-C8SdXCwr.js +0 -68
  311. package/dist/catalog-runtime-BLKtnUL3.js +0 -6
  312. package/dist/config-BIfHKNXN.js +0 -2336
  313. package/dist/db-BTmLKZrp.js +0 -5804
  314. package/dist/db-DcmzbA55.d.ts +0 -274
  315. package/dist/history-CneKY7_V.js +0 -595
  316. package/dist/install-OtFboxOM.js +0 -228
  317. package/dist/proxy-path-BHYoKZdq.js +0 -15
  318. package/dist/registry-D6kS6xYH.js +0 -3024
  319. package/dist/rule-DAxQY-1h.js +0 -20
  320. package/dist/schema-BB6E0wyV.d.ts +0 -9472
  321. package/dist/start-conversation-a4NXH4X9.js +0 -752
  322. package/dist/store-BuhF1QDm.js +0 -490
  323. package/dist/task-queue-CrRjFzOh.js +0 -79
  324. package/dist/turn-session-routing-CZTRU8IY.js +0 -116
  325. package/dist/vercel-queue-nL0Hq3hr.js +0 -234
  326. package/dist/warmup-CCOuIwAS.js +0 -12759
  327. package/migrations/meta/0000_snapshot.json +0 -946
  328. package/migrations/meta/0001_snapshot.json +0 -972
  329. package/migrations/meta/0002_snapshot.json +0 -987
  330. package/migrations/meta/0003_snapshot.json +0 -1035
  331. package/migrations/meta/0004_snapshot.json +0 -1041
  332. package/migrations/meta/0005_snapshot.json +0 -948
  333. package/migrations/meta/0006_snapshot.json +0 -948
  334. package/migrations/meta/0007_snapshot.json +0 -1013
  335. package/migrations/meta/0008_snapshot.json +0 -1076
  336. package/migrations/meta/0009_snapshot.json +0 -1146
  337. package/migrations/meta/0010_snapshot.json +0 -1190
  338. package/migrations/meta/0011_snapshot.json +0 -1195
  339. package/migrations/meta/0012_snapshot.json +0 -1244
  340. package/migrations/meta/0013_snapshot.json +0 -1250
  341. package/migrations/meta/0014_snapshot.json +0 -1201
  342. package/migrations/meta/0015_snapshot.json +0 -1360
  343. package/migrations/meta/0016_snapshot.json +0 -1617
  344. package/migrations/meta/0017_snapshot.json +0 -1666
  345. package/migrations/meta/0018_snapshot.json +0 -1756
  346. package/migrations/meta/0019_snapshot.json +0 -1904
  347. package/migrations/meta/0020_snapshot.json +0 -1848
  348. package/migrations/meta/0021_snapshot.json +0 -2176
  349. package/migrations/meta/0022_snapshot.json +0 -2186
  350. package/migrations/meta/0023_snapshot.json +0 -2198
  351. package/migrations/meta/0024_snapshot.json +0 -2275
  352. package/migrations/meta/0025_snapshot.json +0 -2275
  353. package/migrations/meta/0026_snapshot.json +0 -2424
  354. package/migrations/meta/0027_snapshot.json +0 -2554
  355. package/migrations/meta/0028_snapshot.json +0 -2685
  356. package/migrations/meta/0029_snapshot.json +0 -2709
  357. package/migrations/meta/0030_snapshot.json +0 -2799
  358. package/migrations/meta/0031_snapshot.json +0 -2823
  359. package/migrations/meta/0032_snapshot.json +0 -2892
  360. package/migrations/meta/0033_snapshot.json +0 -2914
  361. package/migrations/meta/0034_snapshot.json +0 -3038
  362. package/migrations/meta/0035_snapshot.json +0 -3048
  363. package/migrations/meta/0036_snapshot.json +0 -3186
  364. package/migrations/meta/0037_snapshot.json +0 -3192
  365. package/migrations/meta/0038_snapshot.json +0 -3323
  366. package/migrations/meta/0039_snapshot.json +0 -3368
  367. package/migrations/meta/0040_snapshot.json +0 -3516
  368. package/migrations/meta/0041_snapshot.json +0 -3516
  369. package/migrations/meta/0042_snapshot.json +0 -3610
  370. package/migrations/meta/0043_snapshot.json +0 -3610
  371. package/migrations/meta/0044_snapshot.json +0 -3473
  372. package/migrations/meta/0045_snapshot.json +0 -3503
  373. package/migrations/meta/0046_snapshot.json +0 -3707
  374. package/migrations/meta/0047_snapshot.json +0 -3713
  375. package/migrations/meta/0048_snapshot.json +0 -3720
  376. package/migrations/meta/0049_snapshot.json +0 -3581
  377. package/migrations/meta/0050_snapshot.json +0 -3753
  378. package/migrations/meta/0051_snapshot.json +0 -3759
  379. package/migrations/meta/0052_snapshot.json +0 -3765
  380. package/migrations/meta/0053_snapshot.json +0 -3771
  381. package/migrations/meta/0054_snapshot.json +0 -3777
  382. package/migrations/meta/0055_snapshot.json +0 -3948
  383. package/migrations/meta/0056_snapshot.json +0 -4280
  384. package/migrations/meta/0057_snapshot.json +0 -3618
  385. package/migrations/meta/0058_snapshot.json +0 -3598
  386. package/migrations/meta/0059_snapshot.json +0 -3619
  387. package/migrations/meta/0060_snapshot.json +0 -3465
  388. package/migrations/meta/0061_snapshot.json +0 -3471
  389. package/migrations/meta/0062_snapshot.json +0 -3499
  390. package/migrations/meta/0063_snapshot.json +0 -3505
  391. package/migrations/meta/0064_snapshot.json +0 -3505
  392. package/migrations/meta/0065_snapshot.json +0 -3511
  393. package/migrations/meta/0066_snapshot.json +0 -4099
  394. package/migrations/meta/0067_snapshot.json +0 -3921
  395. package/migrations/meta/0068_snapshot.json +0 -4176
  396. package/migrations/meta/0069_snapshot.json +0 -3979
  397. package/migrations/meta/0070_snapshot.json +0 -3997
  398. package/migrations/meta/0071_snapshot.json +0 -4003
  399. package/migrations/meta/0072_snapshot.json +0 -4064
  400. package/migrations/meta/0073_snapshot.json +0 -4070
  401. package/migrations/meta/0074_snapshot.json +0 -4076
  402. package/migrations/meta/0075_snapshot.json +0 -4083
  403. package/migrations/meta/0076_snapshot.json +0 -4147
  404. package/migrations/meta/0077_snapshot.json +0 -4141
  405. package/migrations/meta/0078_snapshot.json +0 -4175
  406. package/migrations/meta/0079_snapshot.json +0 -4203
  407. package/migrations/meta/0080_snapshot.json +0 -4265
  408. package/migrations/meta/0081_snapshot.json +0 -4271
  409. package/migrations/meta/0082_snapshot.json +0 -4373
  410. package/migrations/meta/0083_snapshot.json +0 -4388
  411. package/migrations/meta/0084_snapshot.json +0 -4388
  412. package/migrations/meta/0085_snapshot.json +0 -4394
  413. package/migrations/meta/0086_snapshot.json +0 -4366
  414. package/migrations/meta/0087_snapshot.json +0 -4366
  415. package/migrations/meta/0088_snapshot.json +0 -4372
  416. package/migrations/meta/0089_snapshot.json +0 -4372
  417. package/migrations/meta/0090_snapshot.json +0 -4388
  418. package/migrations/meta/0091_snapshot.json +0 -4410
  419. package/migrations/meta/0092_snapshot.json +0 -4446
  420. package/migrations/meta/0093_snapshot.json +0 -4446
  421. package/migrations/meta/0094_snapshot.json +0 -4452
  422. package/migrations/meta/0095_snapshot.json +0 -4452
  423. package/migrations/meta/0096_snapshot.json +0 -4490
  424. package/migrations/meta/0097_snapshot.json +0 -4490
  425. package/migrations/meta/0098_snapshot.json +0 -4490
  426. package/migrations/meta/0099_snapshot.json +0 -4496
  427. package/migrations/meta/0100_snapshot.json +0 -4496
  428. package/migrations/meta/0101_snapshot.json +0 -4496
  429. package/migrations/meta/0102_snapshot.json +0 -4502
  430. package/migrations/meta/0103_snapshot.json +0 -4509
  431. package/migrations/meta/0104_snapshot.json +0 -4516
  432. package/migrations/meta/0105_snapshot.json +0 -4611
  433. package/migrations/meta/0106_snapshot.json +0 -4617
  434. package/migrations/meta/0107_snapshot.json +0 -4617
  435. package/migrations/meta/0108_snapshot.json +0 -4688
  436. package/migrations/meta/0109_snapshot.json +0 -4925
  437. package/migrations/meta/0110_snapshot.json +0 -4952
  438. package/migrations/meta/0111_snapshot.json +0 -5011
  439. package/migrations/meta/0112_snapshot.json +0 -5011
  440. package/migrations/meta/0113_snapshot.json +0 -5033
  441. package/migrations/meta/0114_snapshot.json +0 -5203
  442. package/migrations/meta/0115_snapshot.json +0 -5225
  443. package/migrations/meta/0116_snapshot.json +0 -5388
  444. package/migrations/meta/0117_snapshot.json +0 -5413
  445. package/migrations/meta/0118_snapshot.json +0 -5428
  446. package/migrations/meta/0119_snapshot.json +0 -5441
  447. package/migrations/meta/0120_snapshot.json +0 -5441
  448. package/migrations/meta/0121_snapshot.json +0 -5481
  449. package/migrations/meta/0122_snapshot.json +0 -5481
  450. package/migrations/meta/0123_snapshot.json +0 -5481
  451. package/migrations/meta/0124_snapshot.json +0 -5516
  452. package/migrations/meta/0125_snapshot.json +0 -5516
  453. package/migrations/meta/0126_snapshot.json +0 -5488
  454. package/migrations/meta/0127_snapshot.json +0 -5519
  455. package/migrations/meta/0128_snapshot.json +0 -5519
  456. package/migrations/meta/0129_snapshot.json +0 -5547
  457. package/migrations/meta/0130_snapshot.json +0 -5563
  458. package/migrations/meta/0131_snapshot.json +0 -5569
  459. package/migrations/meta/0132_snapshot.json +0 -5569
  460. package/migrations/meta/0133_snapshot.json +0 -5590
  461. package/migrations/meta/0134_snapshot.json +0 -5606
  462. package/migrations/meta/0135_snapshot.json +0 -5624
  463. package/migrations/meta/0136_snapshot.json +0 -5624
  464. package/migrations/meta/0137_snapshot.json +0 -5864
  465. package/migrations/meta/0138_snapshot.json +0 -5894
  466. package/migrations/meta/0139_snapshot.json +0 -5898
  467. package/migrations/meta/0140_snapshot.json +0 -5919
  468. package/migrations/meta/0141_snapshot.json +0 -6429
  469. package/migrations/meta/0142_snapshot.json +0 -6457
  470. package/migrations/meta/0143_snapshot.json +0 -6434
  471. package/migrations/meta/0144_snapshot.json +0 -6434
  472. package/migrations/meta/0145_snapshot.json +0 -6440
  473. package/migrations/meta/0146_snapshot.json +0 -6446
  474. package/migrations/meta/0147_snapshot.json +0 -6452
  475. package/migrations/meta/0148_snapshot.json +0 -6474
  476. package/migrations/meta/0149_snapshot.json +0 -6490
  477. package/migrations/meta/0150_snapshot.json +0 -6490
  478. package/migrations/meta/0151_snapshot.json +0 -6505
  479. package/migrations/meta/0152_snapshot.json +0 -6505
  480. package/migrations/meta/0153_snapshot.json +0 -6511
  481. package/migrations/meta/0154_snapshot.json +0 -6533
  482. package/migrations/meta/0155_snapshot.json +0 -6511
  483. package/migrations/meta/0156_snapshot.json +0 -6511
  484. package/migrations/meta/0157_snapshot.json +0 -6527
  485. package/migrations/meta/0158_snapshot.json +0 -6515
  486. package/migrations/meta/0159_snapshot.json +0 -6515
  487. package/migrations/meta/0160_snapshot.json +0 -6515
  488. package/migrations/meta/0161_snapshot.json +0 -6278
  489. package/migrations/meta/0162_snapshot.json +0 -6404
  490. package/migrations/meta/0163_snapshot.json +0 -6404
  491. package/migrations/meta/0164_snapshot.json +0 -6466
  492. package/migrations/meta/0165_snapshot.json +0 -6466
  493. package/migrations/meta/0166_snapshot.json +0 -6494
  494. package/migrations/meta/0167_snapshot.json +0 -6525
  495. package/migrations/meta/0168_snapshot.json +0 -6525
  496. package/migrations/meta/0169_snapshot.json +0 -6513
  497. package/migrations/meta/_journal.json +0 -1196
  498. /package/migrations/{0000_initial.sql → 20260711145847_initial/migration.sql} +0 -0
  499. /package/migrations/{0001_conversation_metrics.sql → 20260711145900_conversation_metrics/migration.sql} +0 -0
  500. /package/migrations/{0002_conversation_message_search.sql → 20260712153649_conversation_message_search/migration.sql} +0 -0
  501. /package/migrations/{0003_peaceful_scalphunter.sql → 20260713040256_peaceful_scalphunter/migration.sql} +0 -0
  502. /package/migrations/{0004_useful_magus.sql → 20260715174202_useful_magus/migration.sql} +0 -0
  503. /package/migrations/{0005_conversation_events.sql → 20260715174203_conversation_events/migration.sql} +0 -0
  504. /package/migrations/{0006_drop_legacy_conversation_messages.sql → 20260723042835_drop_legacy_conversation_messages/migration.sql} +0 -0
  505. /package/migrations/{0007_thick_sugar_man.sql → 20260723050612_thick_sugar_man/migration.sql} +0 -0
  506. /package/migrations/{0008_sticky_rage.sql → 20260727223822_sticky_rage/migration.sql} +0 -0
  507. /package/migrations/{0009_slippery_harrier.sql → 20260728033158_slippery_harrier/migration.sql} +0 -0
  508. /package/migrations/{0010_native_conversation_history.sql → 20260728040836_native_conversation_history/migration.sql} +0 -0
  509. /package/migrations/{0011_sour_golden_guardian.sql → 20260728204900_sour_golden_guardian/migration.sql} +0 -0
  510. /package/migrations/{0012_structured_conversation_events.sql → 20260730233332_structured_conversation_events/migration.sql} +0 -0
  511. /package/migrations/{0013_conversation_session_source.sql → 20260731164038_conversation_session_source/migration.sql} +0 -0
  512. /package/migrations/{0014_source_visibility.sql → 20260801230336_source_visibility/migration.sql} +0 -0
  513. /package/migrations/{0015_magical_ezekiel_stane.sql → 20260802023731_magical_ezekiel_stane/migration.sql} +0 -0
  514. /package/migrations/{0016_neat_the_anarchist.sql → 20260804015843_neat_the_anarchist/migration.sql} +0 -0
  515. /package/migrations/{0017_drop_paused_scheduled_tasks.sql → 20260804165952_drop_paused_scheduled_tasks/migration.sql} +0 -0
  516. /package/migrations/{0018_curvy_excalibur.sql → 20260804225613_curvy_excalibur/migration.sql} +0 -0
  517. /package/migrations/{0019_lowly_valkyrie.sql → 20260805174033_lowly_valkyrie/migration.sql} +0 -0
  518. /package/migrations/{0020_restrict_task_execution_kinds.sql → 20260805200301_restrict_task_execution_kinds/migration.sql} +0 -0
  519. /package/migrations/{0021_first_warhawk.sql → 20260806030729_first_warhawk/migration.sql} +0 -0
  520. /package/migrations/{0022_task_execution_status.sql → 20260807185200_task_execution_status/migration.sql} +0 -0
  521. /package/migrations/{0023_task_title_columns.sql → 20260808014743_task_title_columns/migration.sql} +0 -0
  522. /package/migrations/{0024_misty_typhoid_mary.sql → 20260809220421_misty_typhoid_mary/migration.sql} +0 -0
  523. /package/migrations/{0025_mcp_credential_subject.sql → 20260811193709_mcp_credential_subject/migration.sql} +0 -0
  524. /package/migrations/{0026_conversation_event_actor_and_participants.sql → 20260812032924_conversation_event_actor_and_participants/migration.sql} +0 -0
  525. /package/migrations/{0027_attachment_storage.sql → 20260812172418_attachment_storage/migration.sql} +0 -0
  526. /package/migrations/{0028_artifacts.sql → 20260813230732_artifacts/migration.sql} +0 -0
  527. /package/migrations/{0029_dizzy_barracuda.sql → 20260814062905_dizzy_barracuda/migration.sql} +0 -0
  528. /package/migrations/{0030_drop_workspace_repo_primary.sql → 20260814231353_drop_workspace_repo_primary/migration.sql} +0 -0
  529. /package/migrations/{0031_wild_phantom_reporter.sql → 20260815030100_wild_phantom_reporter/migration.sql} +0 -0
  530. /package/migrations/{0032_workspace_snapshots_table.sql → 20260817082233_workspace_snapshots_table/migration.sql} +0 -0
  531. /package/migrations/{0033_workspace_snapshot_active_build.sql → 20260818160339_workspace_snapshot_active_build/migration.sql} +0 -0
  532. /package/migrations/{0034_strong_randall.sql → 20260821180755_strong_randall/migration.sql} +0 -0
  533. /package/migrations/{0035_workspace_snapshot_size_bytes.sql → 20260823030308_workspace_snapshot_size_bytes/migration.sql} +0 -0
  534. /package/migrations/{0036_complex_rage.sql → 20260824190313_complex_rage/migration.sql} +0 -0
  535. /package/migrations/{0037_conversation_location.sql → 20260827233711_conversation_location/migration.sql} +0 -0
  536. /package/migrations/{0038_event_task_status.sql → 20260901224306_event_task_status/migration.sql} +0 -0
  537. /package/migrations/{0039_attachment_provider.sql → 20260904153232_attachment_provider/migration.sql} +0 -0
  538. /package/migrations/{0040_conversation_briefs.sql → 20260909111415_conversation_briefs/migration.sql} +0 -0
  539. /package/migrations/{0041_automation_outcomes_backfill.sql → 20260910144928_automation_outcomes_backfill/migration.sql} +0 -0
  540. /package/migrations/{0042_conversation_metrics.sql → 20260911184346_conversation_metrics/migration.sql} +0 -0
  541. /package/migrations/{0043_scheduled_automation_channel_destinations.sql → 20260921140842_scheduled_automation_channel_destinations/migration.sql} +0 -0
  542. /package/migrations/{0044_event_automation_channel_destinations.sql → 20260922221709_event_automation_channel_destinations/migration.sql} +0 -0
  543. /package/migrations/{0045_conversation_forks.sql → 20261001113455_conversation_forks/migration.sql} +0 -0
  544. /package/migrations/{0046_automation_versions.sql → 20261005161844_automation_versions/migration.sql} +0 -0
  545. /package/migrations/{0047_user_timezone.sql → 20261006152043_user_timezone/migration.sql} +0 -0
  546. /package/migrations/{0048_user_admin.sql → 20261008200858_user_admin/migration.sql} +0 -0
  547. /package/migrations/{0049_event_automation_status_reason.sql → 20261009145407_event_automation_status_reason/migration.sql} +0 -0
  548. /package/migrations/{0050_agent_invocation_parent_mailbox.sql → 20261013160816_agent_invocation_parent_mailbox/migration.sql} +0 -0
  549. /package/migrations/{0051_agent_invocation_parent_tool_call.sql → 20261013215020_agent_invocation_parent_tool_call/migration.sql} +0 -0
  550. /package/migrations/{0052_agent_invocation_title.sql → 20261014011138_agent_invocation_title/migration.sql} +0 -0
  551. /package/migrations/{0053_conversation_stopped_at.sql → 20261014211942_conversation_stopped_at/migration.sql} +0 -0
  552. /package/migrations/{0054_flowery_rage.sql → 20261015012820_flowery_rage/migration.sql} +0 -0
  553. /package/migrations/{0055_automations.sql → 20261017000924_automations/migration.sql} +0 -0
  554. /package/migrations/{0056_automation_runs.sql → 20261017134736_automation_runs/migration.sql} +0 -0
  555. /package/migrations/{0057_drop_legacy_automation_tables.sql → 20261017170250_drop_legacy_automation_tables/migration.sql} +0 -0
  556. /package/migrations/{0058_automation_creator_identity.sql → 20261018134754_automation_creator_identity/migration.sql} +0 -0
  557. /package/migrations/{0059_automation_run_version.sql → 20261023071954_automation_run_version/migration.sql} +0 -0
  558. /package/migrations/{0060_identity_signed_in_at.sql → 20261025233137_identity_signed_in_at/migration.sql} +0 -0
  559. /package/migrations/{0061_workspace_vcpus.sql → 20261027234315_workspace_vcpus/migration.sql} +0 -0
  560. /package/migrations/{0062_plugin_report_index.sql → 20261028124242_plugin_report_index/migration.sql} +0 -0
  561. /package/migrations/{0063_agent_invocation_type.sql → 20261028154230_agent_invocation_type/migration.sql} +0 -0
  562. /package/migrations/{0064_any_resource_event_triggers.sql → 20261030021803_any_resource_event_triggers/migration.sql} +0 -0
  563. /package/migrations/{0065_user_customization.sql → 20261030234309_user_customization/migration.sql} +0 -0
  564. /package/migrations/{0066_review_items.sql → 20261031020656_review_items/migration.sql} +0 -0
  565. /package/migrations/{0067_review_item_dedupe_tenant.sql → 20261031024151_review_item_dedupe_tenant/migration.sql} +0 -0
  566. /package/migrations/{0068_review_item_slack_cards.sql → 20261031024246_review_item_slack_cards/migration.sql} +0 -0
  567. /package/migrations/{0069_system_identity.sql → 20261031155308_system_identity/migration.sql} +0 -0
  568. /package/migrations/{0070_review_item_foreign_keys.sql → 20261101193952_review_item_foreign_keys/migration.sql} +0 -0
  569. /package/migrations/{0071_review_item_turn.sql → 20261102172751_review_item_turn/migration.sql} +0 -0
  570. /package/migrations/{0072_conversation_read_positions.sql → 20261102221411_conversation_read_positions/migration.sql} +0 -0
  571. /package/migrations/{0073_conversation_quick_question.sql → 20261104085028_conversation_quick_question/migration.sql} +0 -0
  572. /package/migrations/{0074_conversation_participant_pins.sql → 20261104145136_conversation_participant_pins/migration.sql} +0 -0
  573. /package/migrations/{0075_conversation_detail_version.sql → 20261104164429_conversation_detail_version/migration.sql} +0 -0
  574. /package/migrations/{0076_conversation_auto_archive.sql → 20261104172055_conversation_auto_archive/migration.sql} +0 -0
  575. /package/migrations/{0077_drop_agent_invocation_model_profile.sql → 20261105005443_drop_agent_invocation_model_profile/migration.sql} +0 -0
  576. /package/migrations/{0078_plugin_conversation_index.sql → 20261105043807_plugin_conversation_index/migration.sql} +0 -0
  577. /package/migrations/{0079_conversation_event_author_index.sql → 20261105051837_conversation_event_author_index/migration.sql} +0 -0
  578. /package/migrations/{0080_conversation_event_latest_message_indexes.sql → 20261105182854_conversation_event_latest_message_indexes/migration.sql} +0 -0
  579. /package/migrations/{0081_conversation_pin_position.sql → 20261106011443_conversation_pin_position/migration.sql} +0 -0
  580. /package/migrations/{0082_push_notifications.sql → 20261106095004_push_notifications/migration.sql} +0 -0
  581. /package/migrations/{0083_conversation_kind.sql → 20261106162740_conversation_kind/migration.sql} +0 -0
  582. /package/migrations/{0084_read_position_backfill.sql → 20261107002001_read_position_backfill/migration.sql} +0 -0
  583. /package/migrations/{0085_child_archived_at.sql → 20261107025209_child_archived_at/migration.sql} +0 -0
  584. /package/migrations/{0086_shared_archive.sql → 20261107035735_shared_archive/migration.sql} +0 -0
  585. /package/migrations/{0087_child_location.sql → 20261107215055_child_location/migration.sql} +0 -0
  586. /package/migrations/{0088_conversation_unsubscribe.sql → 20261108191927_conversation_unsubscribe/migration.sql} +0 -0
  587. /package/migrations/{0089_conversation_paused_status.sql → 20261109021618_conversation_paused_status/migration.sql} +0 -0
  588. /package/migrations/{0090_guardian_review_time_index.sql → 20261109111553_guardian_review_time_index/migration.sql} +0 -0
  589. /package/migrations/{0091_conversation_participant_unsubscribed_index.sql → 20261109173130_conversation_participant_unsubscribed_index/migration.sql} +0 -0
  590. /package/migrations/{0092_turn_metric_actor.sql → 20261109182006_turn_metric_actor/migration.sql} +0 -0
  591. /package/migrations/{0093_participant_root_actor_backfill.sql → 20261109202836_participant_root_actor_backfill/migration.sql} +0 -0
  592. /package/migrations/{0094_conversation_delivery_paused_at.sql → 20261109232640_conversation_delivery_paused_at/migration.sql} +0 -0
  593. /package/migrations/{0095_web_linked_slack_identity_repair.sql → 20261110120937_web_linked_slack_identity_repair/migration.sql} +0 -0
  594. /package/migrations/{0096_automation_task_kind.sql → 20261110175824_automation_task_kind/migration.sql} +0 -0
  595. /package/migrations/{0097_conversation_kind_automation.sql → 20261110210242_conversation_kind_automation/migration.sql} +0 -0
  596. /package/migrations/{0098_review_item_plugin_actions.sql → 20261110222632_review_item_plugin_actions/migration.sql} +0 -0
  597. /package/migrations/{0099_conversation_last_message_at.sql → 20261110225157_conversation_last_message_at/migration.sql} +0 -0
  598. /package/migrations/{0100_automation_task_kind_repair.sql → 20261111013351_automation_task_kind_repair/migration.sql} +0 -0
  599. /package/migrations/{0101_drop_legacy_columns.sql → 20261111163126_drop_legacy_columns/migration.sql} +0 -0
  600. /package/migrations/{0102_code_change_last_activity.sql → 20261111170150_code_change_last_activity/migration.sql} +0 -0
  601. /package/migrations/{0103_agent_invocation_fork.sql → 20261111191441_agent_invocation_fork/migration.sql} +0 -0
  602. /package/migrations/{0104_code_change_draft.sql → 20261112142841_code_change_draft/migration.sql} +0 -0
  603. /package/migrations/{0105_attachment_uploads.sql → 20261112202901_attachment_uploads/migration.sql} +0 -0
  604. /package/migrations/{0106_conversation_agent_config.sql → 20261112220407_conversation_agent_config/migration.sql} +0 -0
  605. /package/migrations/{0107_attachment_deferred_download.sql → 20261113081247_attachment_deferred_download/migration.sql} +0 -0
  606. /package/migrations/{0108_conversation_embeddings.sql → 20261113225551_conversation_embeddings/migration.sql} +0 -0
  607. /package/migrations/{0109_user_preferences.sql → 20261114213238_user_preferences/migration.sql} +0 -0
  608. /package/migrations/{0110_code_change_repository_state_index.sql → 20261114222527_code_change_repository_state_index/migration.sql} +0 -0
  609. /package/migrations/{0111_attachment_kinds.sql → 20261115172605_attachment_kinds/migration.sql} +0 -0
  610. /package/migrations/{0112_attachment_url_fill.sql → 20261115173004_attachment_url_fill/migration.sql} +0 -0
  611. /package/migrations/{0113_attachment_url_index.sql → 20261115180216_attachment_url_index/migration.sql} +0 -0
  612. /package/migrations/{0114_plan_items.sql → 20261116103700_plan_items/migration.sql} +0 -0
  613. /package/migrations/{0115_automation_creator_slack_index.sql → 20261117100100_automation_creator_slack_index/migration.sql} +0 -0
  614. /package/migrations/{0116_conversation_event_search.sql → 20261117132522_conversation_event_search/migration.sql} +0 -0
  615. /package/migrations/{0117_automation_last_run.sql → 20261117164007_automation_last_run/migration.sql} +0 -0
  616. /package/migrations/{0118_automation_last_run_index.sql → 20261117164047_automation_last_run_index/migration.sql} +0 -0
  617. /package/migrations/{0119_money_micro_usd.sql → 20261117210444_money_micro_usd/migration.sql} +0 -0
  618. /package/migrations/{0120_conversation_cost_micro_usd.sql → 20261117210505_conversation_cost_micro_usd/migration.sql} +0 -0
  619. /package/migrations/{0121_people_list_metric_index.sql → 20261118081416_people_list_metric_index/migration.sql} +0 -0
  620. /package/migrations/{0122_automation_rollout_repair.sql → 20261118095216_automation_rollout_repair/migration.sql} +0 -0
  621. /package/migrations/{0123_cache_warming_history_reset.sql → 20261118143948_cache_warming_history_reset/migration.sql} +0 -0
  622. /package/migrations/{0124_artifact_visibility.sql → 20261119040651_artifact_visibility/migration.sql} +0 -0
  623. /package/migrations/{0125_artifact_public_sha_index.sql → 20261119040715_artifact_public_sha_index/migration.sql} +0 -0
  624. /package/migrations/{0126_artifact_drop_public.sql → 20261119052706_artifact_drop_public/migration.sql} +0 -0
  625. /package/migrations/{0127_artifact_path.sql → 20261119053831_artifact_path/migration.sql} +0 -0
  626. /package/migrations/{0128_artifact_path_index.sql → 20261119053844_artifact_path_index/migration.sql} +0 -0
  627. /package/migrations/{0129_review_item_answered_index.sql → 20261119091949_review_item_answered_index/migration.sql} +0 -0
  628. /package/migrations/{0130_review_item_status_index.sql → 20261119100029_review_item_status_index/migration.sql} +0 -0
  629. /package/migrations/{0131_brief_outcome_status.sql → 20261119165607_brief_outcome_status/migration.sql} +0 -0
  630. /package/migrations/{0132_brief_outcome_status_backfill.sql → 20261119165622_brief_outcome_status_backfill/migration.sql} +0 -0
  631. /package/migrations/{0133_brief_created_at_index.sql → 20261119213716_brief_created_at_index/migration.sql} +0 -0
  632. /package/migrations/{0134_slack_person_search_index.sql → 20261119222456_slack_person_search_index/migration.sql} +0 -0
  633. /package/migrations/{0135_code_change_size.sql → 20261119225522_code_change_size/migration.sql} +0 -0
  634. /package/migrations/{0136_merge_conflict_notice_dismiss.sql → 20261119232253_merge_conflict_notice_dismiss/migration.sql} +0 -0
  635. /package/migrations/{0137_inbox_snoozes.sql → 20261119235649_inbox_snoozes/migration.sql} +0 -0
  636. /package/migrations/{0138_code_change_search_index.sql → 20261120093118_code_change_search_index/migration.sql} +0 -0
  637. /package/migrations/{0139_review_item_owner.sql → 20261120093452_review_item_owner/migration.sql} +0 -0
  638. /package/migrations/{0140_review_item_owner_index.sql → 20261120185654_review_item_owner_index/migration.sql} +0 -0
  639. /package/migrations/{0141_memory_core_adoption.sql → 20261120185754_memory_core_adoption/migration.sql} +0 -0
  640. /package/migrations/{0142_memory_core_indexes.sql → 20261120185854_memory_core_indexes/migration.sql} +0 -0
  641. /package/migrations/{0143_todos.sql → 20261120235226_todos/migration.sql} +0 -0
  642. /package/migrations/{0144_inbox_items.sql → 20261121082316_inbox_items/migration.sql} +0 -0
  643. /package/migrations/{0145_todo_changed_by_agent.sql → 20261121175651_todo_changed_by_agent/migration.sql} +0 -0
  644. /package/migrations/{0146_inbox_item_subject_title_parts.sql → 20261121183527_inbox_item_subject_title_parts/migration.sql} +0 -0
  645. /package/migrations/{0147_inbox_snooze_wake_reason.sql → 20261121194143_inbox_snooze_wake_reason/migration.sql} +0 -0
  646. /package/migrations/{0148_authorization_request_index.sql → 20261121222400_authorization_request_index/migration.sql} +0 -0
  647. /package/migrations/{0149_conversation_metadata.sql → 20261121225908_conversation_metadata/migration.sql} +0 -0
  648. /package/migrations/{0150_conversation_metadata_fill.sql → 20261121225910_conversation_metadata_fill/migration.sql} +0 -0
  649. /package/migrations/{0151_conversation_search_index.sql → 20261121225913_conversation_search_index/migration.sql} +0 -0
  650. /package/migrations/{0152_inbox_item_legacy_automation_keys.sql → 20261122022900_inbox_item_legacy_automation_keys/migration.sql} +0 -0
  651. /package/migrations/{0153_artifact_expiry.sql → 20261122024454_artifact_expiry/migration.sql} +0 -0
  652. /package/migrations/{0154_artifact_permanent_sha_index.sql → 20261122024455_artifact_permanent_sha_index/migration.sql} +0 -0
  653. /package/migrations/{0155_artifact_drop_public_sha_index.sql → 20261122024457_artifact_drop_public_sha_index/migration.sql} +0 -0
  654. /package/migrations/{0156_conversation_kind_lead.sql → 20261122024458_conversation_kind_lead/migration.sql} +0 -0
  655. /package/migrations/{0157_conversation_lead_actor_index.sql → 20261122024459_conversation_lead_actor_index/migration.sql} +0 -0
  656. /package/migrations/{0158_keep_legacy_archive_columns.sql → 20261122071549_keep_legacy_archive_columns/migration.sql} +0 -0
  657. /package/migrations/{0159_conversation_embeddings_fk_validate.sql → 20261122191400_conversation_embeddings_fk_validate/migration.sql} +0 -0
  658. /package/migrations/{0160_money_micro_usd_repair.sql → 20261122204325_money_micro_usd_repair/migration.sql} +0 -0
  659. /package/migrations/{0161_agent_config_backfill.sql → 20261122204326_agent_config_backfill/migration.sql} +0 -0
  660. /package/migrations/{0162_inbox_item_deliveries.sql → 20261122221456_inbox_item_deliveries/migration.sql} +0 -0
  661. /package/migrations/{0163_pg_trgm.sql → 20261123155735_pg_trgm/migration.sql} +0 -0
  662. /package/migrations/{0164_search_indexes.sql → 20261123155739_search_indexes/migration.sql} +0 -0
  663. /package/migrations/{0165_drop_legacy_archive_columns.sql → 20261123172647_drop_legacy_archive_columns/migration.sql} +0 -0
  664. /package/migrations/{0166_memory_prefix_index.sql → 20261123192506_memory_prefix_index/migration.sql} +0 -0
  665. /package/migrations/{0167_todo_search_indexes.sql → 20261123201740_todo_search_indexes/migration.sql} +0 -0
  666. /package/migrations/{0168_todo_inbox_items.sql → 20261123211505_todo_inbox_items/migration.sql} +0 -0
  667. /package/migrations/{0169_drop_code_urls.sql → 20261123214917_drop_code_urls/migration.sql} +0 -0
@@ -0,0 +1,1814 @@
1
+ import { $f as resolveGatewayModel, E as locationSchema, Gl as juniorTurns, Op as getGatewayApiKey, Pn as getWorkspace, Rl as resolveRootVisibility, Tu as juniorConversations, Ul as juniorTurnOutbox, Wl as juniorTurnInbox, a as getDb, aa as QUEUE_SIGNATURE_MAX_AGE_MS, ca as getQueueProvider, d as eventFromRow, gp as gatewayRoutingAttributes, hu as juniorConversationEvents, lp as requestPrefixAttributes, m as withConversationEventLock, o as getSqlExecutor, oa as signQueueMessage, of as credentialContextForActor, sa as verifyQueueMessage, u as createSqlConversationEventStore } from "./db-DhzvUY23.js";
2
+ import { G as mapBounded } from "./transcript-CCi7323k.js";
3
+ import { g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-B8KEJegM.js";
4
+ import { h as SERVICE_INSTANCE_ID } from "./deployment-BhvrhQeh.js";
5
+ import { a as resolveConversationPrivacy, c as toCanonicalOutputMessage, l as toGenAiMessagesTraceAttributes, s as toCanonicalInputMessage } from "./proxy-path-BTmXDjfx.js";
6
+ import { bt as instructionProvenanceFor, vt as contextProvenance } from "./media-BebquhET.js";
7
+ import { $i as piMessageFromHistoryItem, In as buildDeploymentSystemPrompt, Qi as historyItemFromPiMessage, ea as projectConversationEvents, it as persistThreadRuntimeState, nt as getPersistedSandboxState, rt as getPersistedThreadState } from "./session-stop-DponjDUZ.js";
8
+ import { d as createReadFileTool, g as createBashTool, l as createWriteFileTool, p as createEditFileTool, s as createSystemTimeTool } from "./job-runner-DO8nslyY.js";
9
+ import { F as createAgentSandbox, I as normalizeToolResult, c as buildSandboxInput } from "./agent-runner-Cr5Fhjf-.js";
10
+ import { n as TURN_STEP_TOPIC, t as DELIVERY_TOPIC } from "./topic-CRYYBYp-.js";
11
+ import * as z from "zod";
12
+ import { streamSimple } from "@earendil-works/pi-ai/compat";
13
+ import * as Sentry from "@sentry/node";
14
+ import { randomUUID } from "node:crypto";
15
+ import { toToolDeclaration, validateToolArguments } from "@earendil-works/pi-ai";
16
+ import { actorSchema, destinationSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
17
+ import { and, asc, eq, exists, inArray, like, lt, lte, ne, notExists, or, sql } from "drizzle-orm";
18
+ import { alias } from "drizzle-orm/pg-core";
19
+ import { performance as performance$1 } from "node:perf_hooks";
20
+ // src/core/model/failure.ts
21
+ const RETRYABLE_KINDS = /* @__PURE__ */ new Set([
22
+ "rate_limit",
23
+ "capacity",
24
+ "timeout",
25
+ "network",
26
+ "server"
27
+ ]);
28
+ const KIND_BY_ERROR_TYPE = {
29
+ invalid_request_error: "invalid_request",
30
+ authentication_error: "auth",
31
+ billing_error: "quota",
32
+ permission_error: "permission",
33
+ not_found_error: "invalid_request",
34
+ request_too_large: "invalid_request",
35
+ rate_limit_error: "rate_limit",
36
+ api_error: "server",
37
+ timeout_error: "timeout",
38
+ overloaded_error: "capacity"
39
+ };
40
+ const REFUSAL_STOP_REASONS = /* @__PURE__ */ new Set(["refusal", "sensitive"]);
41
+ const MESSAGE_MAX_CHARS = 240;
42
+ /**
43
+ * The body of an Anthropic or AI Gateway error, in an error response or a
44
+ * stream `error` event.
45
+ */
46
+ const providerErrorBodySchema = z.object({ error: z.object({
47
+ type: z.string().optional(),
48
+ message: z.string().optional()
49
+ }) });
50
+ function kindForStatus(status) {
51
+ if (status === 401) return "auth";
52
+ if (status === 402) return "quota";
53
+ if (status === 403) return "permission";
54
+ if (status === 408 || status === 504) return "timeout";
55
+ if (status === 429) return "rate_limit";
56
+ if (status === 529) return "capacity";
57
+ if (status >= 500) return "server";
58
+ if (status >= 400) return "invalid_request";
59
+ return "unknown";
60
+ }
61
+ function kindForTransportError(name) {
62
+ return name === "TimeoutError" ? "timeout" : "network";
63
+ }
64
+ function streamErrorBody(reply) {
65
+ if (!reply.errorMessage?.startsWith("{")) return;
66
+ try {
67
+ const parsed = providerErrorBodySchema.safeParse(JSON.parse(reply.errorMessage));
68
+ return parsed.success ? parsed.data.error : void 0;
69
+ } catch {
70
+ return;
71
+ }
72
+ }
73
+ function shorten(text) {
74
+ const normalized = text.trim().replace(/\s+/g, " ");
75
+ return normalized.length > MESSAGE_MAX_CHARS ? `${normalized.slice(0, 239)}…` : normalized;
76
+ }
77
+ /** Classifies the failure of a reply with stop reason `error` or `aborted`. */
78
+ function classifyFailure(observed, reply) {
79
+ const response = observed.errorResponse;
80
+ const streamError = response ? void 0 : streamErrorBody(reply);
81
+ const providerType = response?.errorType ?? streamError?.type;
82
+ const kind = reply.rawStopReason && REFUSAL_STOP_REASONS.has(reply.rawStopReason) ? "content_policy" : (providerType ? KIND_BY_ERROR_TYPE[providerType] : void 0) ?? (response ? kindForStatus(response.status) : void 0) ?? (observed.transportError ? kindForTransportError(observed.transportError) : "unknown");
83
+ const message = response?.errorMessage ?? streamError?.message ?? reply.errorMessage ?? `Model request ended with ${reply.stopReason}`;
84
+ return {
85
+ kind,
86
+ retryable: RETRYABLE_KINDS.has(kind),
87
+ ...response ? { status: response.status } : void 0,
88
+ ...providerType ? { providerType } : void 0,
89
+ ...response?.retryAfterMs !== void 0 ? { retryAfterMs: response.retryAfterMs } : void 0,
90
+ message: shorten(message)
91
+ };
92
+ }
93
+ /** The wait that a `retry-after-ms` or `retry-after` header asks for. */
94
+ function retryAfterMs(headers) {
95
+ const milliseconds = Number.parseFloat(headers.get("retry-after-ms") ?? "");
96
+ if (Number.isFinite(milliseconds) && milliseconds >= 0) return milliseconds;
97
+ const value = headers.get("retry-after");
98
+ if (!value) return;
99
+ const seconds = Number.parseFloat(value);
100
+ if (Number.isFinite(seconds) && seconds >= 0) return seconds * 1e3;
101
+ const date = Date.parse(value);
102
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
103
+ }
104
+ /** The error that core reports to Sentry for a failed model request. */
105
+ var ModelRequestError = class extends Error {
106
+ constructor(failure) {
107
+ super(`Model request failed: ${failure.kind}`);
108
+ this.name = "ModelRequestError";
109
+ }
110
+ };
111
+ /** The span and log attributes of a failure, with main's names. */
112
+ function modelFailureAttributes(failure) {
113
+ return {
114
+ "app.ai.provider_error.kind": failure.kind,
115
+ "app.ai.provider_error.retryable": failure.retryable,
116
+ "app.ai.provider_error.summary": failure.message,
117
+ ...failure.status !== void 0 ? { "app.ai.provider_error.status": failure.status } : void 0,
118
+ ...failure.providerType ? { "app.ai.provider_error.type": failure.providerType } : void 0,
119
+ ...failure.retryAfterMs !== void 0 ? { "app.ai.provider_error.retry_after_ms": failure.retryAfterMs } : void 0
120
+ };
121
+ }
122
+ // src/core/model/span.ts
123
+ const GATEWAY_ATTRIBUTES = {
124
+ "gen_ai.provider.name": "vercel-ai-gateway",
125
+ "server.address": "ai-gateway.vercel.sh",
126
+ "server.port": 443
127
+ };
128
+ const NON_CONTENT_EVENT_TYPES = /* @__PURE__ */ new Set([
129
+ "start",
130
+ "done",
131
+ "error"
132
+ ]);
133
+ /** The attributes that a request has before it is sent. */
134
+ function chatStartAttributes({ model, session, context }) {
135
+ const content = model.privacy === "public";
136
+ return {
137
+ ...GATEWAY_ATTRIBUTES,
138
+ "gen_ai.operation.name": "chat",
139
+ "gen_ai.request.model": model.id,
140
+ "gen_ai.request.stream": true,
141
+ "gen_ai.output.type": "text",
142
+ "gen_ai.conversation.id": session,
143
+ ...model.reasoning !== "none" ? { "gen_ai.request.reasoning.level": model.reasoning } : void 0,
144
+ "app.conversation.privacy": model.privacy,
145
+ ...toGenAiMessagesTraceAttributes("gen_ai.input", context.messages),
146
+ ...content ? { "gen_ai.input.messages": serializeGenAiAttribute(context.messages.map(toCanonicalInputMessage)) } : void 0,
147
+ ...context.systemPrompt ? {
148
+ "gen_ai.system_instructions.content_chars": context.systemPrompt.length,
149
+ ...content ? { "gen_ai.system_instructions": serializeGenAiAttribute([{
150
+ type: "text",
151
+ content: context.systemPrompt
152
+ }]) } : void 0
153
+ } : void 0
154
+ };
155
+ }
156
+ /** The attributes that the final reply of a request gives. */
157
+ function chatEndAttributes(message, privacy) {
158
+ return {
159
+ ...toGenAiMessagesTraceAttributes("gen_ai.output", [message]),
160
+ ...privacy === "public" ? { "gen_ai.output.messages": serializeGenAiAttribute([toCanonicalOutputMessage(message)]) } : void 0,
161
+ ...extractGenAiUsageAttributes(message),
162
+ "app.ai.usage.cache_write_1h": message.usage.cacheWrite1h,
163
+ "gen_ai.response.finish_reasons": [normalizeGenAiFinishReason(message.stopReason)],
164
+ "gen_ai.response.model": message.model,
165
+ "gen_ai.response.id": message.responseId
166
+ };
167
+ }
168
+ /**
169
+ * Records when the first stream event and the first content event of a
170
+ * response arrive. A request that fails before any event records
171
+ * `gen_ai.response.streaming: false` and no timing.
172
+ */
173
+ function responseTiming(requestStartedAtMs) {
174
+ let firstByteAtMs;
175
+ let firstToken;
176
+ return {
177
+ observe: (event) => {
178
+ if (firstByteAtMs === void 0 && event.type !== "error") firstByteAtMs = Date.now();
179
+ if (!firstToken && !NON_CONTENT_EVENT_TYPES.has(event.type)) firstToken = {
180
+ type: event.type,
181
+ receivedAtMs: Date.now()
182
+ };
183
+ },
184
+ attributes: () => firstByteAtMs === void 0 ? { "gen_ai.response.streaming": false } : {
185
+ "gen_ai.response.streaming": true,
186
+ "app.ai.time_to_first_byte_ms": firstByteAtMs - requestStartedAtMs,
187
+ ...firstToken ? {
188
+ "gen_ai.response.time_to_first_chunk": (firstToken.receivedAtMs - requestStartedAtMs) / 1e3,
189
+ "app.ai.first_token_type": firstToken.type
190
+ } : void 0
191
+ }
192
+ };
193
+ }
194
+ // src/core/telemetry.ts
195
+ const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
196
+ function spanLink({ sentryTrace }) {
197
+ const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
198
+ return traceId && spanId ? [{ context: {
199
+ traceId,
200
+ spanId,
201
+ traceFlags: sampled === "1" ? 1 : 0
202
+ } }] : [];
203
+ }
204
+ /** Returns the trace context of the active span, so other work can link to it. */
205
+ function activeTraceContext() {
206
+ const sentryTrace = Sentry.getTraceData()["sentry-trace"];
207
+ return sentryTrace ? { sentryTrace } : void 0;
208
+ }
209
+ /** Sets attributes on the active span, such as ids that a step learns late. */
210
+ function setActiveSpanAttributes(attributes) {
211
+ Sentry.getActiveSpan()?.setAttributes(attributes);
212
+ }
213
+ /** Adds one to a counter metric. Metrics are not sampled, unlike spans. */
214
+ function countMetric(name, attributes) {
215
+ Sentry.metrics.count(name, 1, { attributes });
216
+ }
217
+ const SPAN_STATUS_ERROR = 2;
218
+ /** Runs `run` in a span whose op is `name`, and whose name is too by default. */
219
+ function withSpan(name, attributes, run, options = {}) {
220
+ const start = () => Sentry.startSpanManual({
221
+ name: options.spanName ?? name,
222
+ op: name,
223
+ attributes,
224
+ links: options.links?.flatMap(spanLink)
225
+ }, async (span) => {
226
+ try {
227
+ return await run({
228
+ setAttribute: (key, value) => span.setAttribute(key, value),
229
+ setAttributes: (values) => span.setAttributes(values),
230
+ fail: (message) => span.setStatus({
231
+ code: SPAN_STATUS_ERROR,
232
+ message
233
+ })
234
+ });
235
+ } catch (error) {
236
+ if (!options.isExpectedError?.(error)) {
237
+ span.setStatus({
238
+ code: SPAN_STATUS_ERROR,
239
+ message: "internal_error"
240
+ });
241
+ span.setAttribute("error.type", error instanceof Error ? error.name : typeof error);
242
+ }
243
+ throw error;
244
+ } finally {
245
+ span.end();
246
+ }
247
+ });
248
+ return options.newTrace ? Sentry.startNewTrace(start) : start();
249
+ }
250
+ // src/core/model/client.ts
251
+ function errorName(error) {
252
+ return error instanceof Error ? error.name : "Error";
253
+ }
254
+ function observedBody(body, observed) {
255
+ const reader = body.getReader();
256
+ return new ReadableStream({
257
+ async pull(controller) {
258
+ try {
259
+ const { done, value } = await reader.read();
260
+ if (done) controller.close();
261
+ else controller.enqueue(value);
262
+ } catch (error) {
263
+ observed.transportError = errorName(error);
264
+ controller.error(error);
265
+ }
266
+ },
267
+ cancel: (reason) => reader.cancel(reason)
268
+ });
269
+ }
270
+ function observingFetch(base, observed) {
271
+ return async (input, init) => {
272
+ let response;
273
+ try {
274
+ response = await base(input, init);
275
+ } catch (error) {
276
+ observed.transportError = errorName(error);
277
+ throw error;
278
+ }
279
+ if (response.ok) {
280
+ delete observed.errorResponse;
281
+ return response.body ? new Response(observedBody(response.body, observed), {
282
+ status: response.status,
283
+ statusText: response.statusText,
284
+ headers: response.headers
285
+ }) : response;
286
+ }
287
+ const body = providerErrorBodySchema.safeParse(await response.clone().json().catch(() => void 0));
288
+ const wait = retryAfterMs(response.headers);
289
+ observed.errorResponse = {
290
+ status: response.status,
291
+ ...wait !== void 0 ? { retryAfterMs: wait } : void 0,
292
+ ...body.success && body.data.error.type ? { errorType: body.data.error.type } : void 0,
293
+ ...body.success && body.data.error.message ? { errorMessage: body.data.error.message } : void 0
294
+ };
295
+ return response;
296
+ };
297
+ }
298
+ function diagnosticHooks(span) {
299
+ const eventLoopStart = performance$1.eventLoopUtilization();
300
+ return {
301
+ onPayload: (payload) => {
302
+ span.setAttributes(requestPrefixAttributes(payload));
303
+ },
304
+ onResponse: (response) => {
305
+ const vercelId = response.headers["x-vercel-id"];
306
+ if (vercelId) span.setAttribute("app.ai.gateway.vercel_id", vercelId);
307
+ const { utilization } = performance$1.eventLoopUtilization(eventLoopStart);
308
+ span.setAttribute("app.ai.event_loop.utilization", Math.round(utilization * 1e3) / 1e3);
309
+ },
310
+ onProviderStreamEvent: (event) => {
311
+ const attributes = gatewayRoutingAttributes(event);
312
+ if (attributes) span.setAttributes(attributes);
313
+ }
314
+ };
315
+ }
316
+ /**
317
+ * Builds the model client. `apiKey` runs before each request, because a
318
+ * credential can rotate between requests. `send` sends the request, such as
319
+ * pi-ai's `streamSimple`. `fetch` is the HTTP client that `send` uses.
320
+ */
321
+ function modelClient(dependencies) {
322
+ return { complete: ({ model, session, context }, signal) => withSpan("gen_ai.chat", chatStartAttributes({
323
+ model,
324
+ session,
325
+ context
326
+ }), async (span) => {
327
+ const observed = {};
328
+ const startedAtMs = Date.now();
329
+ const stream = await dependencies.send(dependencies.resolveModel(model.id), context, {
330
+ apiKey: await dependencies.apiKey(),
331
+ sessionId: session,
332
+ reasoning: model.reasoning === "none" ? void 0 : model.reasoning,
333
+ signal,
334
+ fetch: observingFetch(dependencies.fetch ?? globalThis.fetch, observed),
335
+ ...diagnosticHooks(span)
336
+ });
337
+ const timing = responseTiming(startedAtMs);
338
+ for await (const event of stream) timing.observe(event);
339
+ const message = await stream.result();
340
+ const failure = !signal.aborted && (message.stopReason === "error" || message.stopReason === "aborted") ? classifyFailure(observed, message) : void 0;
341
+ span.setAttributes({
342
+ ...chatEndAttributes(message, model.privacy),
343
+ ...timing.attributes(),
344
+ ...failure ? {
345
+ ...modelFailureAttributes(failure),
346
+ "error.type": failure.kind
347
+ } : void 0
348
+ });
349
+ if (failure) span.fail(failure.message);
350
+ return failure ? {
351
+ message,
352
+ failure
353
+ } : { message };
354
+ }, { spanName: `chat ${model.id}` }) };
355
+ }
356
+ // src/core/prompt/layout.ts
357
+ const inputFormats = /* @__PURE__ */ new WeakMap();
358
+ /**
359
+ * Declares where the Turn's unread inputs go in the messages. `format` turns
360
+ * each input into a user message and its provenance. A layout has exactly
361
+ * one, named `inputs`. It has no loader: it reads `ctx.inputs`. Core keeps
362
+ * each input's id with its message, so the commit marks the input read.
363
+ */
364
+ function inputs({ format }) {
365
+ const item = {
366
+ name: "inputs",
367
+ render: (values) => values.ctx.inputs.map((input) => format(input).message)
368
+ };
369
+ inputFormats.set(item, format);
370
+ return item;
371
+ }
372
+ /**
373
+ * The `format` of an `inputs()` fragment, or undefined for any other
374
+ * fragment. Core calls it.
375
+ */
376
+ function inputFormatOf(item) {
377
+ return inputFormats.get(item);
378
+ }
379
+ /**
380
+ * Checks a layout and returns the copy that core builds each prompt from. It
381
+ * throws on an empty or repeated system prompt section name, on two
382
+ * fragments with one name, on one fragment used twice, on two loaders with
383
+ * one label, and unless the messages hold exactly one `inputs()` fragment.
384
+ * It freezes the system prompt sections and the messages list.
385
+ *
386
+ * The rules:
387
+ * - Loaders do all of the I/O. Core runs each needed loader once per step.
388
+ * - Fragments are pure. `enabled` and `format` do no I/O, and read no clock
389
+ * and no random value, so the same inputs give the same prompt. Their
390
+ * messages have no timestamp: core gives each one the step's time, and
391
+ * each input its send time.
392
+ * - Message fragments only append. Their messages go after the history, and
393
+ * a later step sees them in its history. Core builds them only for a step
394
+ * that sends a model request, not for a step that runs tool calls.
395
+ * - The `inputs()` fragment sets where the Turn's unread inputs go.
396
+ * - The system prompt holds no Conversation data. The host builds its
397
+ * sections once at startup, so the model provider can cache that part of
398
+ * the request.
399
+ * - Tools and model settings are not in the layout. They belong to the Turn,
400
+ * and the step gets them separately.
401
+ *
402
+ * @example
403
+ * // At startup:
404
+ * const soul = await readFile("SOUL.md", "utf8");
405
+ * const memories = loader(
406
+ * "memories",
407
+ * (ctx, signal) => memoryStore.recall(ctx.turn.conversationId, signal),
408
+ * { timeoutMs: 2_000, optional: true },
409
+ * );
410
+ * const recalled = fragment("recalled-memories", {
411
+ * loader: memories,
412
+ * // Recall only for a step that has new inputs.
413
+ * enabled: (ctx) => ctx.inputs.length > 0,
414
+ * format: (notes): FragmentMessage | Skip =>
415
+ * notes && notes.length > 0
416
+ * ? { role: "user", content: notes.join("\n") }
417
+ * : skip("no memories"),
418
+ * });
419
+ * const layout = definePromptLayout({
420
+ * systemPrompt: [
421
+ * { name: "identity", text: "You are Junior, Sentry's Slack bot." },
422
+ * { name: "personality", text: soul },
423
+ * ],
424
+ * messages: [
425
+ * recalled,
426
+ * inputs({
427
+ * format: (input) => ({
428
+ * message: { role: "user", content: String(input.payload["text"]) },
429
+ * provenance: { authority: "instruction" },
430
+ * }),
431
+ * }),
432
+ * ],
433
+ * });
434
+ */
435
+ function definePromptLayout(layout) {
436
+ const sectionNames = /* @__PURE__ */ new Set();
437
+ for (const { name } of layout.systemPrompt) {
438
+ if (name === "") throw new Error("A system prompt section has no name");
439
+ if (sectionNames.has(name)) throw new Error(`Two system prompt sections are named "${name}"`);
440
+ sectionNames.add(name);
441
+ }
442
+ const inputFragments = layout.messages.filter((item) => inputFormats.has(item)).length;
443
+ if (inputFragments !== 1) throw new Error(`A prompt layout needs exactly one inputs() fragment, not ${inputFragments}`);
444
+ const seenFragments = /* @__PURE__ */ new Set();
445
+ const names = /* @__PURE__ */ new Set();
446
+ const loaders = /* @__PURE__ */ new Map();
447
+ for (const item of layout.messages) {
448
+ if (seenFragments.has(item)) throw new Error(`Fragment "${item.name}" is used more than once`);
449
+ seenFragments.add(item);
450
+ if (names.has(item.name)) throw new Error(`Two fragments are named "${item.name}"`);
451
+ names.add(item.name);
452
+ if (!item.loader) continue;
453
+ const known = loaders.get(item.loader.label);
454
+ if (known && known !== item.loader) throw new Error(`Two loaders are labeled "${item.loader.label}"`);
455
+ loaders.set(item.loader.label, item.loader);
456
+ }
457
+ return {
458
+ systemPrompt: Object.freeze(layout.systemPrompt.map(({ name, text }) => Object.freeze({
459
+ name,
460
+ text
461
+ }))),
462
+ messages: Object.freeze([...layout.messages])
463
+ };
464
+ }
465
+ // src/core/prompt/assemble.ts
466
+ /**
467
+ * Builds the prompt for one step. A required loader that fails or times out
468
+ * throws an error that names it. An optional one gives `undefined` to its
469
+ * fragments. A fragment whose `enabled` or `format` throws gives an error
470
+ * that names it. When `signal` aborts, each load's signal aborts too, and
471
+ * this throws the abort reason. `newMessages` are the new messages in layout
472
+ * order, which go after `ctx.history` in `messages`. Core sets their
473
+ * timestamps: an input's send time, or the step's time for a fragment
474
+ * message.
475
+ */
476
+ async function assemblePrompt(layout, ctx, { signal }) {
477
+ signal.throwIfAborted();
478
+ const disabled = /* @__PURE__ */ new Set();
479
+ const needed = /* @__PURE__ */ new Set();
480
+ for (const item of layout.messages) {
481
+ const { enabled } = item;
482
+ if (enabled && !inFragment(item.name, () => enabled(ctx))) disabled.add(item);
483
+ else if (item.loader) needed.add(item.loader);
484
+ }
485
+ const values = { ctx };
486
+ const runs = await mapBounded(needed, async (source) => ({
487
+ source,
488
+ ...await runLoader(source, values, signal)
489
+ }));
490
+ signal.throwIfAborted();
491
+ for (const { source, diagnostics, error } of runs) {
492
+ if (source.optional) continue;
493
+ if (diagnostics.status === "failed") throw new Error(`Loader "${source.label}" failed`, { cause: error });
494
+ if (diagnostics.status === "timed_out") throw new Error(`Loader "${source.label}" timed out after ${source.timeoutMs} ms`);
495
+ }
496
+ const stepTime = Date.now();
497
+ const fragments = [];
498
+ const newMessages = [];
499
+ for (const item of layout.messages) {
500
+ const { name } = item;
501
+ if (disabled.has(item)) {
502
+ fragments.push({
503
+ name,
504
+ field: "messages",
505
+ status: "disabled"
506
+ });
507
+ continue;
508
+ }
509
+ const formatInput = inputFormatOf(item);
510
+ if (formatInput) {
511
+ for (const input of ctx.inputs) {
512
+ const { message, provenance } = inFragment(name, () => formatInput(input));
513
+ newMessages.push({
514
+ source: "input",
515
+ inputId: input.inputId,
516
+ message: {
517
+ ...message,
518
+ timestamp: input.sentAt.getTime()
519
+ },
520
+ provenance
521
+ });
522
+ }
523
+ fragments.push({
524
+ name,
525
+ field: "messages",
526
+ status: "included"
527
+ });
528
+ continue;
529
+ }
530
+ const output = inFragment(name, () => item.render(values));
531
+ if (isSkip(output)) {
532
+ fragments.push({
533
+ name,
534
+ field: "messages",
535
+ status: "skipped",
536
+ reason: output.skipped
537
+ });
538
+ continue;
539
+ }
540
+ fragments.push({
541
+ name,
542
+ field: "messages",
543
+ status: "included"
544
+ });
545
+ for (const message of Array.isArray(output) ? output : [output]) newMessages.push({
546
+ source: "fragment",
547
+ fragment: name,
548
+ message: {
549
+ ...message,
550
+ timestamp: stepTime
551
+ }
552
+ });
553
+ }
554
+ return {
555
+ systemPrompt: layout.systemPrompt.map(({ text }) => text).join("\n\n"),
556
+ messages: [...ctx.history, ...newMessages.map(({ message }) => message)],
557
+ newMessages,
558
+ diagnostics: {
559
+ systemPrompt: layout.systemPrompt.map(({ name, text }) => ({
560
+ name,
561
+ chars: text.length
562
+ })),
563
+ loaders: runs.map((run) => run.diagnostics),
564
+ fragments
565
+ }
566
+ };
567
+ }
568
+ /** Runs a fragment's own code, and names the fragment when it throws. */
569
+ function inFragment(name, run) {
570
+ try {
571
+ return run();
572
+ } catch (error) {
573
+ throw new Error(`Fragment "${name}" failed`, { cause: error });
574
+ }
575
+ }
576
+ function isSkip(output) {
577
+ return typeof output === "object" && output !== null && !Array.isArray(output) && "skipped" in output;
578
+ }
579
+ /** Loads one loader's value for a prompt, and times the load. */
580
+ async function runLoader(source, values, signal) {
581
+ const started = performance.now();
582
+ const { status, error } = await loadWithTimeout(source, values, signal);
583
+ const ms = Math.round(performance.now() - started);
584
+ return {
585
+ diagnostics: {
586
+ label: source.label,
587
+ ms,
588
+ status
589
+ },
590
+ error
591
+ };
592
+ }
593
+ /**
594
+ * Runs one load, and aborts its signal and stops waiting after its timeout
595
+ * or when the step's `signal` aborts.
596
+ */
597
+ async function loadWithTimeout(source, values, signal) {
598
+ if (signal.aborted) return { status: "timed_out" };
599
+ const controller = new AbortController();
600
+ let timer;
601
+ let stopStep = () => {};
602
+ const stopped = new Promise((resolve) => {
603
+ timer = setTimeout(() => {
604
+ resolve("timed_out");
605
+ controller.abort(/* @__PURE__ */ new Error(`Loader "${source.label}" timed out`));
606
+ }, source.timeoutMs);
607
+ stopStep = () => {
608
+ resolve("timed_out");
609
+ controller.abort(signal.reason);
610
+ };
611
+ signal.addEventListener("abort", stopStep, { once: true });
612
+ });
613
+ try {
614
+ const loaded = source.loadInto(values, controller.signal).then(() => "ok");
615
+ return { status: await Promise.race([loaded, stopped]) };
616
+ } catch (error) {
617
+ return controller.signal.aborted ? { status: "timed_out" } : {
618
+ status: "failed",
619
+ error
620
+ };
621
+ } finally {
622
+ clearTimeout(timer);
623
+ signal.removeEventListener("abort", stopStep);
624
+ }
625
+ }
626
+ // src/core/turn/inbox.ts
627
+ /**
628
+ * Finds the Turn of the input that has this idempotency key in the
629
+ * Conversation. Undefined when no such input exists.
630
+ */
631
+ async function findInputTurn({ executor }, args) {
632
+ const [turn] = await executor.db().select({
633
+ turnId: juniorTurns.id,
634
+ state: juniorTurns.state
635
+ }).from(juniorTurnInbox).innerJoin(juniorTurns, eq(juniorTurns.id, juniorTurnInbox.turnId)).where(and(eq(juniorTurnInbox.conversationId, args.conversationId), eq(juniorTurnInbox.idempotencyKey, args.idempotencyKey)));
636
+ return turn;
637
+ }
638
+ /**
639
+ * Finds where a Turn's answer goes: the Destination of its first input. Null
640
+ * when the Turn answers only in the Conversation history.
641
+ */
642
+ async function findTurnDestination({ executor }, turnId) {
643
+ const [input] = await executor.db().select({ destination: juniorTurnInbox.destination }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
644
+ return input?.destination ? destinationSchema.parse(input.destination) : null;
645
+ }
646
+ /** Finds every input of a Turn, oldest first. */
647
+ async function findTurnInputs({ executor }, turnId) {
648
+ return executor.db().select({
649
+ inputId: juniorTurnInbox.id,
650
+ payload: juniorTurnInbox.payload
651
+ }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
652
+ }
653
+ const INPUT_EVENT_KEY_PREFIX = "inbox:";
654
+ /** The idempotency key of the history event that reads an input. */
655
+ function inputEventKey(inputId) {
656
+ return `${INPUT_EVENT_KEY_PREFIX}${inputId}`;
657
+ }
658
+ /** Finds the inputs of a Turn that the history has not read, oldest first. */
659
+ async function findUnreadInputs({ executor }, turnId) {
660
+ const db = executor.db();
661
+ const readEvent = db.select({ one: sql`1` }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorTurnInbox.conversationId), eq(juniorConversationEvents.idempotencyKey, sql`${INPUT_EVENT_KEY_PREFIX}::text || ${juniorTurnInbox.id}::text`)));
662
+ return db.select({
663
+ inputId: juniorTurnInbox.id,
664
+ groupKey: juniorTurnInbox.groupKey,
665
+ payload: juniorTurnInbox.payload,
666
+ sentAt: juniorTurnInbox.sentAt,
667
+ traceContext: juniorTurnInbox.traceContext,
668
+ attemptedAt: juniorTurnInbox.attemptedAt
669
+ }).from(juniorTurnInbox).where(and(eq(juniorTurnInbox.turnId, turnId), notExists(readEvent))).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
670
+ }
671
+ /**
672
+ * Records that an attempt of the Turn claimed it with these inputs unread.
673
+ * The first attempt keeps its time. It does not mark the inputs read.
674
+ */
675
+ async function markInputsAttempted({ executor }, inputIds) {
676
+ if (inputIds.length === 0) return;
677
+ await executor.db().update(juniorTurnInbox).set({ attemptedAt: sql`coalesce(${juniorTurnInbox.attemptedAt}, now())` }).where(inArray(juniorTurnInbox.id, inputIds));
678
+ }
679
+ // src/core/queue.ts
680
+ const VISIBILITY_TIMEOUT_BUFFER_SECONDS = 30;
681
+ /** Defines one signed topic. Returns its publish function and its consumer. */
682
+ function signedTopic(def) {
683
+ const publish = async ({ queue }, message, options = {}) => {
684
+ await withSpan("queue.publish", {
685
+ ...def.attributes(message),
686
+ "messaging.destination.name": def.topic,
687
+ "messaging.system": queue.messagingSystem
688
+ }, async (span) => {
689
+ const traceContext = activeTraceContext();
690
+ const payload = signQueueMessage(def.sign, traceContext ? {
691
+ ...message,
692
+ traceContext
693
+ } : message);
694
+ span.setAttribute("messaging.message.body.size", Buffer.byteLength(JSON.stringify(payload)));
695
+ const result = await queue.send(def.topic, payload, {
696
+ delaySeconds: options.delayMs && options.delayMs > 0 ? Math.ceil(options.delayMs / 1e3) : void 0,
697
+ idempotencyKey: options.idempotencyKey,
698
+ retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
699
+ });
700
+ if (result.messageId) span.setAttribute("messaging.message.id", result.messageId);
701
+ });
702
+ };
703
+ const consumer = ({ queue, leaseMs }, run) => ({
704
+ handler: async (value, metadata) => {
705
+ const checked = verifyQueueMessage(def.sign, value);
706
+ if (checked.status === "rejected") {
707
+ def.onRejected({
708
+ "app.queue.consumer_group": metadata.consumerGroup,
709
+ "app.queue.delivery_count": metadata.deliveryCount,
710
+ "app.queue.message_id": metadata.messageId,
711
+ "app.queue.reject_reason": checked.reason,
712
+ "app.queue.topic_name": metadata.topicName
713
+ });
714
+ return;
715
+ }
716
+ if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
717
+ const message = checked.message;
718
+ await withSpan("queue.process", {
719
+ ...def.attributes(message),
720
+ "messaging.destination.name": metadata.topicName,
721
+ "messaging.system": queue.messagingSystem,
722
+ "messaging.message.id": metadata.messageId,
723
+ "messaging.message.receive.latency": Date.now() - metadata.createdAt.getTime(),
724
+ "messaging.message.retry.count": metadata.deliveryCount - 1
725
+ }, () => run(message, metadata), {
726
+ links: message.traceContext ? [message.traceContext] : [],
727
+ newTrace: true
728
+ });
729
+ },
730
+ retry: () => void 0,
731
+ visibilityTimeoutSeconds: leaseMs / 1e3 + VISIBILITY_TIMEOUT_BUFFER_SECONDS
732
+ });
733
+ return {
734
+ publish,
735
+ consumer
736
+ };
737
+ }
738
+ // src/core/turn/queue.ts
739
+ const turnStepMessageSchema = z.object({
740
+ turnId: z.string().min(1),
741
+ traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
742
+ }).strict();
743
+ const turnStepTopic = signedTopic({
744
+ topic: TURN_STEP_TOPIC,
745
+ sign: {
746
+ context: "junior.turn_step.v1",
747
+ schema: turnStepMessageSchema,
748
+ signatureVersion: "v1",
749
+ parts: (message) => [message.turnId, message.traceContext?.sentryTrace ?? ""]
750
+ },
751
+ onRejected: (attributes) => logWarn("turn.step.queue_message.rejected", attributes),
752
+ attributes: (message) => ({ "app.turn.id": message.turnId })
753
+ });
754
+ /**
755
+ * Sends a message that runs the next step of a Turn. `idempotencyKey` drops a
756
+ * second send with the same key.
757
+ */
758
+ async function publishTurnStep(ctx, turnId, options = {}) {
759
+ await turnStepTopic.publish(ctx, { turnId }, options);
760
+ }
761
+ /**
762
+ * Builds the queue consumer of Turn step messages. It acknowledges a message
763
+ * with a bad or expired signature and retries one that cannot be checked yet.
764
+ * advanceTurn fails a Turn after `maxAttempts` tries of one step. The host
765
+ * mounts the consumer on its queue provider.
766
+ */
767
+ function createTurnStepConsumer(ctx, run) {
768
+ return turnStepTopic.consumer(ctx, (message, metadata) => run({ turnId: message.turnId }, metadata));
769
+ }
770
+ // src/core/delivery/queue.ts
771
+ const deliveryMessageSchema = z.object({
772
+ conversationId: z.string().min(1),
773
+ turnId: z.string().min(1),
774
+ traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
775
+ }).strict();
776
+ const deliveryTopic = signedTopic({
777
+ topic: DELIVERY_TOPIC,
778
+ sign: {
779
+ context: "junior.delivery.v1",
780
+ schema: deliveryMessageSchema,
781
+ signatureVersion: "v1",
782
+ parts: (message) => [
783
+ message.conversationId,
784
+ message.turnId,
785
+ message.traceContext?.sentryTrace ?? ""
786
+ ]
787
+ },
788
+ onRejected: (attributes) => logWarn("turn.delivery.queue_message.rejected", attributes),
789
+ attributes: (message) => ({
790
+ "app.turn.id": message.turnId,
791
+ "gen_ai.conversation.id": message.conversationId
792
+ })
793
+ });
794
+ /** Sends a message that delivers the Turn's replies, after `delayMs` if set. */
795
+ async function publishDelivery(ctx, message, options = {}) {
796
+ await deliveryTopic.publish(ctx, message, options);
797
+ }
798
+ /**
799
+ * Builds the queue consumer of delivery messages. It acknowledges a message
800
+ * with a bad or expired signature and retries one that cannot be checked yet.
801
+ * The outbox rows hold the delivery state, so a retry only sends what is
802
+ * left. The host mounts the consumer on its queue provider.
803
+ */
804
+ function createDeliveryConsumer(ctx, run) {
805
+ return deliveryTopic.consumer(ctx, (message, metadata) => run({
806
+ conversationId: message.conversationId,
807
+ turnId: message.turnId
808
+ }, metadata));
809
+ }
810
+ // src/core/turn/replies.ts
811
+ const LEGACY_NO_REPLY_MARKERS = ["[[NO_REPLY]]", "[[QUIET]]"];
812
+ const THINKING_BLOCK_PATTERN = /[ \t]*<thinking\b[^>]*>[\s\S]*?<\/thinking>[ \t]*(?:\r?\n)?/gi;
813
+ function isClosedFence(source) {
814
+ const opener = source.trimStart();
815
+ const marker = opener.startsWith("```") ? "`" : opener.startsWith("~~~") ? "~" : void 0;
816
+ const lastLine = source.lastIndexOf("\n");
817
+ let closer = lastLine < 0 ? "" : source.slice(lastLine + 1).trim();
818
+ while (closer.startsWith(">")) closer = closer.slice(1).trimStart();
819
+ return marker !== void 0 && closer.length >= 3 && closer === marker.repeat(closer.length);
820
+ }
821
+ function stripThinking(text) {
822
+ let result = "";
823
+ let cursor = 0;
824
+ for (const { position } of markdownNodes(parseMarkdown(text), ["code"])) {
825
+ const start = position?.start.offset ?? 0;
826
+ const end = position?.end.offset ?? 0;
827
+ if (!isClosedFence(text.slice(start, end))) continue;
828
+ result += text.slice(cursor, start).replace(THINKING_BLOCK_PATTERN, "");
829
+ result += text.slice(start, end);
830
+ cursor = end;
831
+ }
832
+ return result + text.slice(cursor).replace(THINKING_BLOCK_PATTERN, "");
833
+ }
834
+ /**
835
+ * The text that an assistant message delivers to a person, or undefined when
836
+ * it is no reply. Text next to a tool call is the model working, not a reply.
837
+ */
838
+ function assistantReplyText(message) {
839
+ if (message.content.some((part) => part.type === "toolCall")) return;
840
+ const text = stripThinking(message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n")).trim();
841
+ return text && !LEGACY_NO_REPLY_MARKERS.includes(text) ? text : void 0;
842
+ }
843
+ /** The key prefix of the message events that a Turn's steps wrote. */
844
+ function turnEventKeyPrefix(turnId) {
845
+ return `step:${turnId}:`;
846
+ }
847
+ /** The text that a message event delivers, or undefined when it is no reply. */
848
+ function replyText(row) {
849
+ const { data } = eventFromRow(row);
850
+ if (data.type !== "assistant_message") return;
851
+ const message = piMessageFromHistoryItem(data);
852
+ return message.role === "assistant" ? assistantReplyText(message) : void 0;
853
+ }
854
+ /** Finds the reply events of a Turn, in history order. */
855
+ async function findTurnReplies({ executor }, conversationId, turnId) {
856
+ return (await executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "assistant_message"), like(juniorConversationEvents.idempotencyKey, `${turnEventKeyPrefix(turnId)}%`))).orderBy(asc(juniorConversationEvents.seq))).filter((row) => replyText(row) !== void 0);
857
+ }
858
+ // src/core/delivery/outbox.ts
859
+ /**
860
+ * Adds an outbox row for each reply of the Turn that has none, but only while
861
+ * the Turn has a Destination. Call it in the transaction that commits the
862
+ * replies.
863
+ */
864
+ async function recordReplies({ executor }, turn) {
865
+ const destination = await findTurnDestination({ executor }, turn.turnId);
866
+ if (!destination) return;
867
+ const replies = await findTurnReplies({ executor }, turn.conversationId, turn.turnId);
868
+ if (replies.length === 0) return;
869
+ await executor.db().insert(juniorTurnOutbox).values(replies.map((row) => ({
870
+ id: randomUUID(),
871
+ conversationId: turn.conversationId,
872
+ turnId: turn.turnId,
873
+ eventSeq: row.seq,
874
+ destination,
875
+ state: "pending"
876
+ }))).onConflictDoNothing({ target: [juniorTurnOutbox.conversationId, juniorTurnOutbox.eventSeq] });
877
+ }
878
+ /**
879
+ * Finds Conversations whose first pending reply has not changed for
880
+ * `staleMs`, so no delivery message is likely to reach it. A row behind a
881
+ * first row that is still retried waits; it is not stalled.
882
+ */
883
+ async function findStalledDeliveries({ executor }, { staleMs, limit }) {
884
+ const staleBefore = sql`now() - make_interval(secs => ${staleMs / 1e3})`;
885
+ const earlier = alias(juniorTurnOutbox, "earlier");
886
+ const rows = await executor.db().select({
887
+ conversationId: juniorTurnOutbox.conversationId,
888
+ turnId: juniorTurnOutbox.turnId,
889
+ updatedAt: juniorTurnOutbox.updatedAt
890
+ }).from(juniorTurnOutbox).where(and(eq(juniorTurnOutbox.state, "pending"), lt(juniorTurnOutbox.createdAt, staleBefore), lt(juniorTurnOutbox.updatedAt, staleBefore), notExists(executor.db().select({ one: sql`1` }).from(earlier).where(and(eq(earlier.conversationId, juniorTurnOutbox.conversationId), eq(earlier.state, "pending"), lt(earlier.eventSeq, juniorTurnOutbox.eventSeq)))))).limit(limit);
891
+ const nowMs = Date.now();
892
+ return rows.map((row) => ({
893
+ conversationId: row.conversationId,
894
+ turnId: row.turnId,
895
+ stalledMs: Math.max(0, nowMs - row.updatedAt.getTime())
896
+ }));
897
+ }
898
+ // src/core/turn/state.ts
899
+ /**
900
+ * Turn priorities: a lower number runs first. A Turn that supersedes the
901
+ * running Turn runs before every other queued Turn.
902
+ */
903
+ const TURN_PRIORITY = {
904
+ supersede: 0,
905
+ normal: 1
906
+ };
907
+ const SUPERSEDED_END = {
908
+ state: "cancelled",
909
+ endReason: "superseded",
910
+ endedAt: sql`now()`
911
+ };
912
+ function leaseExpiry(leaseMs) {
913
+ return sql`now() + ${leaseMs}::integer * interval '1 millisecond'`;
914
+ }
915
+ function leaseFence(lease) {
916
+ return and(eq(juniorTurns.id, lease.turnId), eq(juniorTurns.state, "running"), eq(juniorTurns.leaseEpoch, lease.leaseEpoch));
917
+ }
918
+ /**
919
+ * Inserts a queued Turn. It sends no step message: the caller publishes the
920
+ * Turn after its transaction commits, so a worker can claim it.
921
+ */
922
+ async function createTurn({ executor }, args) {
923
+ const turnId = randomUUID();
924
+ await executor.db().insert(juniorTurns).values({
925
+ ...args,
926
+ id: turnId,
927
+ state: "queued"
928
+ });
929
+ return {
930
+ turnId,
931
+ state: "queued"
932
+ };
933
+ }
934
+ /** Finds a Turn by id. Undefined when it does not exist. */
935
+ async function findTurn({ executor }, turnId) {
936
+ const [turn] = await executor.db().select({
937
+ turnId: juniorTurns.id,
938
+ state: juniorTurns.state,
939
+ conversationId: juniorTurns.conversationId,
940
+ failureCode: juniorTurns.failureCode,
941
+ failureReason: juniorTurns.failureReason,
942
+ failureEventId: juniorTurns.failureEventId
943
+ }).from(juniorTurns).where(eq(juniorTurns.id, turnId));
944
+ return turn;
945
+ }
946
+ const runOrder = [
947
+ sql`${juniorTurns.state} = 'running' desc`,
948
+ asc(juniorTurns.priority),
949
+ asc(juniorTurns.createdAt),
950
+ asc(juniorTurns.id)
951
+ ];
952
+ /**
953
+ * Finds the Turn of a Conversation that has not ended: the running Turn, else
954
+ * the next queued Turn by priority and age.
955
+ */
956
+ async function findOpenTurn({ executor }, conversationId) {
957
+ const [turn] = await executor.db().select({
958
+ turnId: juniorTurns.id,
959
+ state: juniorTurns.state
960
+ }).from(juniorTurns).where(and(eq(juniorTurns.conversationId, conversationId), inArray(juniorTurns.state, ["queued", "running"]))).orderBy(...runOrder).limit(1);
961
+ return turn;
962
+ }
963
+ /**
964
+ * Finds the Turns of a Conversation that can still take inputs, in run order:
965
+ * those that have not ended, less a running Turn that another Turn
966
+ * supersedes.
967
+ */
968
+ async function findOpenTurns({ executor }, conversationId) {
969
+ return (await executor.db().select({
970
+ turnId: juniorTurns.id,
971
+ state: juniorTurns.state,
972
+ groupKey: juniorTurnInbox.groupKey,
973
+ stepSeq: juniorTurns.stepSeq,
974
+ attempts: juniorTurns.attempts
975
+ }).from(juniorTurns).innerJoin(juniorTurnInbox, eq(juniorTurnInbox.turnId, juniorTurns.id)).where(and(eq(juniorTurns.conversationId, conversationId), or(eq(juniorTurns.state, "queued"), and(eq(juniorTurns.state, "running"), notExists(turnAhead({ executor })))))).groupBy(juniorTurns.id, juniorTurnInbox.groupKey).orderBy(...runOrder)).map(({ stepSeq, attempts, ...turn }) => ({
976
+ ...turn,
977
+ started: stepSeq > 0 || attempts > 0
978
+ }));
979
+ }
980
+ function turnAhead({ executor }) {
981
+ const ahead = alias(juniorTurns, "ahead");
982
+ return executor.db().select({ one: sql`1` }).from(ahead).where(and(eq(ahead.conversationId, juniorTurns.conversationId), ne(ahead.id, juniorTurns.id), or(eq(ahead.state, "running"), and(eq(ahead.state, "queued"), sql`(${ahead.priority}, ${ahead.createdAt}, ${ahead.id}) < (${juniorTurns.priority}, ${juniorTurns.createdAt}, ${juniorTurns.id})`))));
983
+ }
984
+ async function isSuperseded({ executor }, turnId) {
985
+ return (await executor.db().select({ id: juniorTurns.id }).from(juniorTurns).where(and(eq(juniorTurns.id, turnId), exists(turnAhead({ executor }))))).length > 0;
986
+ }
987
+ /**
988
+ * Makes way for a Turn that supersedes this one. Call it under the
989
+ * Conversation lock. A queued Turn has no step in flight, so it ends now. A
990
+ * running Turn moves behind the new Turn, and `commitStep` ends it when its
991
+ * step commits, so the step's work is kept.
992
+ */
993
+ async function supersedeTurn({ executor }, turnId) {
994
+ const db = executor.db();
995
+ await db.update(juniorTurns).set({
996
+ ...SUPERSEDED_END,
997
+ leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
998
+ updatedAt: sql`now()`
999
+ }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued")));
1000
+ await db.update(juniorTurns).set({
1001
+ priority: TURN_PRIORITY.normal,
1002
+ updatedAt: sql`now()`
1003
+ }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "running")));
1004
+ }
1005
+ /**
1006
+ * Claims a Turn to run its next step: the Conversation's next queued Turn, or
1007
+ * a running Turn whose lease expired. Returns undefined for any other Turn, so
1008
+ * of two concurrent claims only one gets the Turn, and a Turn waits while
1009
+ * another Turn of its Conversation runs. It holds the Conversation lock.
1010
+ */
1011
+ async function claimTurn({ executor, owner, leaseMs }, turnId) {
1012
+ const turn = await findTurn({ executor }, turnId);
1013
+ if (!turn) return;
1014
+ const claim = () => executor.db().update(juniorTurns).set({
1015
+ state: "running",
1016
+ leaseOwner: owner,
1017
+ leaseExpiresAt: leaseExpiry(leaseMs),
1018
+ leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
1019
+ attempts: sql`${juniorTurns.attempts} + 1`,
1020
+ updatedAt: sql`now()`
1021
+ }).where(and(eq(juniorTurns.id, turnId), or(and(eq(juniorTurns.state, "queued"), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lte(juniorTurns.leaseExpiresAt, sql`now()`))))).returning({
1022
+ turnId: juniorTurns.id,
1023
+ leaseEpoch: juniorTurns.leaseEpoch,
1024
+ conversationId: juniorTurns.conversationId,
1025
+ stepSeq: juniorTurns.stepSeq,
1026
+ attempts: juniorTurns.attempts
1027
+ });
1028
+ const [claimed] = await executor.transaction(() => withConversationEventLock(executor, turn.conversationId, claim));
1029
+ return claimed;
1030
+ }
1031
+ /**
1032
+ * Checks without a write that the lease still holds: the Turn runs under the
1033
+ * caller's `lease_epoch`. False after a cancel or a takeover.
1034
+ */
1035
+ async function holdsLease({ executor }, lease) {
1036
+ return (await executor.db().select({ id: juniorTurns.id }).from(juniorTurns).where(leaseFence(lease))).length > 0;
1037
+ }
1038
+ /**
1039
+ * Finds Turns that a claim could take now but that no message is likely to
1040
+ * reach: the next queued Turn of its Conversation, unchanged for `staleMs`,
1041
+ * and running Turns whose lease expired `staleMs` ago. The queue redelivers
1042
+ * a dead step's message soon after its lease expires, so only a Turn that
1043
+ * missed that redelivery is stalled.
1044
+ */
1045
+ async function findStalledTurns({ executor }, { staleMs, limit }) {
1046
+ const staleBefore = sql`now() - make_interval(secs => ${staleMs / 1e3})`;
1047
+ const rows = await executor.db().select({
1048
+ turnId: juniorTurns.id,
1049
+ conversationId: juniorTurns.conversationId,
1050
+ state: juniorTurns.state,
1051
+ updatedAt: juniorTurns.updatedAt,
1052
+ leaseExpiresAt: juniorTurns.leaseExpiresAt
1053
+ }).from(juniorTurns).where(or(and(eq(juniorTurns.state, "queued"), lt(juniorTurns.updatedAt, staleBefore), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lt(juniorTurns.leaseExpiresAt, staleBefore)))).limit(limit);
1054
+ const nowMs = Date.now();
1055
+ return rows.map((row) => {
1056
+ const since = row.state === "running" && row.leaseExpiresAt ? row.leaseExpiresAt : row.updatedAt;
1057
+ return {
1058
+ turnId: row.turnId,
1059
+ conversationId: row.conversationId,
1060
+ reason: row.state === "running" ? "lease_expired" : "queued_lost",
1061
+ stalledMs: Math.max(0, nowMs - since.getTime())
1062
+ };
1063
+ });
1064
+ }
1065
+ /**
1066
+ * The idempotency key of one message event of a step. It names the Turn and
1067
+ * the step that wrote it, so Delivery finds a Turn's replies without reading
1068
+ * the rest of the history.
1069
+ */
1070
+ function stepEventKey(turnId, stepSeq, index) {
1071
+ return `${turnEventKeyPrefix(turnId)}${stepSeq}:${index}`;
1072
+ }
1073
+ /**
1074
+ * The idempotency key of one new message that a step's prompt added from a
1075
+ * message fragment. It is not a step event key, so Delivery does not read it.
1076
+ */
1077
+ function promptEventKey(turnId, stepSeq, index) {
1078
+ return `prompt:${turnId}:${stepSeq}:${index}`;
1079
+ }
1080
+ /**
1081
+ * Commits a step in one transaction: it appends the prompt's new messages in
1082
+ * layout order, which hold the inputs that the step read, then the step's
1083
+ * messages keyed by Turn and step, to the Conversation history, adds an
1084
+ * outbox row for each new reply and releases the lease. A Turn that
1085
+ * continues goes back to queued for its next step, which needs a new claim.
1086
+ * A Turn that the step completed ends, unless it still has unread inputs:
1087
+ * then it continues, so the next step reads them.
1088
+ * Returns what the Turn does next. Undefined when the lease is lost or the
1089
+ * step is already committed, and then nothing is written.
1090
+ */
1091
+ async function commitStep({ executor }, turn, step, prompt) {
1092
+ const nextStep = {
1093
+ stepSeq: sql`${juniorTurns.stepSeq} + 1`,
1094
+ attempts: 0,
1095
+ leaseOwner: null,
1096
+ leaseExpiresAt: null,
1097
+ updatedAt: sql`now()`
1098
+ };
1099
+ return executor.transaction(() => withConversationEventLock(executor, turn.conversationId, async () => {
1100
+ const outcome = await commitOutcome({ executor }, turn.turnId, step, prompt);
1101
+ if ((await executor.db().update(juniorTurns).set(outcome === "completed" ? {
1102
+ ...nextStep,
1103
+ state: "completed",
1104
+ endedAt: sql`now()`
1105
+ } : outcome === "superseded" ? {
1106
+ ...nextStep,
1107
+ ...SUPERSEDED_END
1108
+ } : {
1109
+ ...nextStep,
1110
+ state: "queued"
1111
+ }).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length === 0) return;
1112
+ await createSqlConversationEventStore(executor).append(turn.conversationId, [...prompt.map((entry, index) => entry.source === "input" ? {
1113
+ data: historyItemFromPiMessage(entry.message, entry.provenance),
1114
+ idempotencyKey: inputEventKey(entry.inputId),
1115
+ createdAtMs: entry.message.timestamp
1116
+ } : {
1117
+ data: historyItemFromPiMessage(entry.message, contextProvenance),
1118
+ idempotencyKey: promptEventKey(turn.turnId, turn.stepSeq, index),
1119
+ createdAtMs: entry.message.timestamp
1120
+ }), ...step.messages.map((message, index) => ({
1121
+ data: historyItemFromPiMessage(message, contextProvenance),
1122
+ idempotencyKey: stepEventKey(turn.turnId, turn.stepSeq, index),
1123
+ createdAtMs: message.timestamp
1124
+ }))]);
1125
+ await recordReplies({ executor }, turn);
1126
+ return outcome;
1127
+ }));
1128
+ }
1129
+ /**
1130
+ * A completed step ends the Turn only when the commit reads every unread
1131
+ * input. The scheduler can add an input after the step read them, and the
1132
+ * Conversation lock keeps more out until the commit ends.
1133
+ */
1134
+ async function commitOutcome({ executor }, turnId, step, prompt) {
1135
+ if (step.outcome === "completed") {
1136
+ const read = new Set(prompt.flatMap((entry) => entry.source === "input" ? [entry.inputId] : []));
1137
+ if ((await findUnreadInputs({ executor }, turnId)).every((input) => read.has(input.inputId))) return "completed";
1138
+ }
1139
+ return await isSuperseded({ executor }, turnId) ? "superseded" : "continue";
1140
+ }
1141
+ /**
1142
+ * Ends a running Turn as failed, with the reason and the failure details.
1143
+ * False when the lease is lost. The engine calls it through `endFailedTurn`,
1144
+ * which also moves the Turn's late inputs.
1145
+ */
1146
+ async function failTurn({ executor }, lease, endReason, failure) {
1147
+ return (await executor.db().update(juniorTurns).set({
1148
+ state: "failed",
1149
+ endReason,
1150
+ failureCode: failure.failureCode,
1151
+ failureReason: failure.failureReason ?? null,
1152
+ failureEventId: failure.eventId ?? null,
1153
+ leaseOwner: null,
1154
+ leaseExpiresAt: null,
1155
+ updatedAt: sql`now()`,
1156
+ endedAt: sql`now()`
1157
+ }).where(leaseFence(lease)).returning({ id: juniorTurns.id })).length > 0;
1158
+ }
1159
+ /**
1160
+ * Queues a running Turn again after its invocation failed, so the queue's
1161
+ * retry can claim the step at once. The failed attempt still counts. A Turn
1162
+ * that another Turn supersedes ends instead, like at a commit. False when the
1163
+ * lease is lost.
1164
+ */
1165
+ async function releaseTurn({ executor }, lease) {
1166
+ return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
1167
+ const released = {
1168
+ leaseOwner: null,
1169
+ leaseExpiresAt: null,
1170
+ updatedAt: sql`now()`
1171
+ };
1172
+ return (await executor.db().update(juniorTurns).set(await isSuperseded({ executor }, lease.turnId) ? {
1173
+ ...released,
1174
+ ...SUPERSEDED_END
1175
+ } : {
1176
+ ...released,
1177
+ state: "queued"
1178
+ }).where(leaseFence(lease)).returning({ id: juniorTurns.id })).length > 0;
1179
+ }));
1180
+ }
1181
+ // src/core/turn/schedule.ts
1182
+ async function addInput({ executor }, input) {
1183
+ await executor.db().insert(juniorTurnInbox).values({
1184
+ ...input,
1185
+ id: randomUUID()
1186
+ });
1187
+ }
1188
+ /**
1189
+ * The rule for which Turn takes an input that is not a duplicate. Core owns
1190
+ * it, so every Source schedules the same way, and the host decides who may
1191
+ * share a Turn through the group key. An input joins a Turn only when its
1192
+ * group key matches. An interrupt joins the Turn that has started, and an
1193
+ * interrupt with another group key supersedes that Turn. Any input
1194
+ * joins the last Turn in line while no step of it has started. Otherwise the
1195
+ * input waits in a new Turn at the end of the line, so A1 B1 A2 makes A2 wait
1196
+ * for B1. It runs under the Conversation lock, so `openTurns` cannot change
1197
+ * before the write.
1198
+ */
1199
+ function assignTurn(input, openTurns) {
1200
+ const sameGroup = (turn) => turn.groupKey === input.groupKey;
1201
+ const started = openTurns.find((turn) => turn.started);
1202
+ if (input.delivery === "interrupt" && started) return sameGroup(started) ? { join: started } : {
1203
+ create: { priority: TURN_PRIORITY.supersede },
1204
+ supersede: started
1205
+ };
1206
+ const last = openTurns.at(-1);
1207
+ if (last && !last.started && sameGroup(last)) return { join: last };
1208
+ return { create: { priority: TURN_PRIORITY.normal } };
1209
+ }
1210
+ async function placeInput({ executor }, { delivery, ...input }) {
1211
+ const existing = await findInputTurn({ executor }, input);
1212
+ if (existing) return {
1213
+ turnId: existing.turnId,
1214
+ created: false,
1215
+ publish: existing.state === "queued"
1216
+ };
1217
+ const openTurns = await findOpenTurns({ executor }, input.conversationId);
1218
+ const choice = assignTurn({
1219
+ ...input,
1220
+ delivery
1221
+ }, openTurns);
1222
+ if ("join" in choice) {
1223
+ const { turnId } = choice.join;
1224
+ await addInput({ executor }, {
1225
+ ...input,
1226
+ turnId
1227
+ });
1228
+ return {
1229
+ turnId,
1230
+ created: false,
1231
+ publish: false
1232
+ };
1233
+ }
1234
+ if (choice.supersede) await supersedeTurn({ executor }, choice.supersede.turnId);
1235
+ const turn = await createTurn({ executor }, {
1236
+ conversationId: input.conversationId,
1237
+ priority: choice.create.priority
1238
+ });
1239
+ await addInput({ executor }, {
1240
+ ...input,
1241
+ turnId: turn.turnId
1242
+ });
1243
+ return {
1244
+ turnId: turn.turnId,
1245
+ created: true,
1246
+ publish: openTurns.length === 0 || choice.supersede !== void 0
1247
+ };
1248
+ }
1249
+ /**
1250
+ * Puts an input into the Turn that `assignTurn` picks, and publishes a Turn
1251
+ * that the input created when no other Turn is open or when it supersedes
1252
+ * one. An input with a known idempotency key writes nothing. Call it outside
1253
+ * a transaction: it publishes after its own commit, and a publish error
1254
+ * reaches the caller with the input already stored.
1255
+ */
1256
+ async function scheduleInput({ executor, queue }, input) {
1257
+ const placement = await withConversationEventLock(executor, input.conversationId, () => placeInput({ executor }, input));
1258
+ if (placement.publish) await publishTurnStep({ queue }, placement.turnId);
1259
+ return {
1260
+ turnId: placement.turnId,
1261
+ created: placement.created
1262
+ };
1263
+ }
1264
+ async function moveInputs({ executor }, inputIds, turnId) {
1265
+ await executor.db().update(juniorTurnInbox).set({ turnId }).where(inArray(juniorTurnInbox.id, inputIds));
1266
+ }
1267
+ /**
1268
+ * Moves the unread inputs of a failed Turn that arrived after its last claim
1269
+ * to the Turn that `assignTurn` picks for a deferred input. They share the
1270
+ * failed Turn's group key, so they move together. The failed Turn
1271
+ * keeps, and so drops, the inputs that an attempt claimed it with.
1272
+ */
1273
+ async function moveLeftovers({ executor }, ended) {
1274
+ const leftovers = (await findUnreadInputs({ executor }, ended.turnId)).filter((input) => input.attemptedAt === null);
1275
+ const [first] = leftovers;
1276
+ if (!first) return;
1277
+ const choice = assignTurn({
1278
+ ...first,
1279
+ delivery: "defer"
1280
+ }, await findOpenTurns({ executor }, ended.conversationId));
1281
+ const target = "join" in choice ? choice.join : await createTurn({ executor }, {
1282
+ conversationId: ended.conversationId,
1283
+ priority: choice.create.priority
1284
+ });
1285
+ await moveInputs({ executor }, leftovers.map((input) => input.inputId), target.turnId);
1286
+ }
1287
+ /**
1288
+ * Ends a running Turn as failed and, in the same commit, moves its inputs
1289
+ * that arrived after its last claim to the next Turn. A crash after the
1290
+ * commit loses no input: the next Turn is queued, so the sweep finds it.
1291
+ * False when the lease is lost, and then nothing changes.
1292
+ */
1293
+ async function endFailedTurn({ executor }, lease, endReason, failure) {
1294
+ return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
1295
+ if (!await failTurn({ executor }, lease, endReason, failure)) return false;
1296
+ await moveLeftovers({ executor }, lease);
1297
+ return true;
1298
+ }));
1299
+ }
1300
+ /**
1301
+ * Brings delivery and the queue in line with this Turn's stored state. Safe
1302
+ * to repeat. It publishes the Turn's delivery message, then publishes the
1303
+ * Conversation's open Turn if it is queued. What it does depends only on the
1304
+ * stored state, not on why it runs. Call it outside a transaction, after the
1305
+ * commit that it follows, so a worker that takes a message sees that commit.
1306
+ */
1307
+ async function reconcileTurn({ executor, queue }, turnId) {
1308
+ const turn = await findTurn({ executor }, turnId);
1309
+ if (!turn) return;
1310
+ await publishDelivery({ queue }, {
1311
+ conversationId: turn.conversationId,
1312
+ turnId
1313
+ });
1314
+ const openTurn = await findOpenTurn({ executor }, turn.conversationId);
1315
+ if (openTurn?.state === "queued") await publishTurnStep({ queue }, openTurn.turnId);
1316
+ }
1317
+ // src/core/turn/step.ts
1318
+ /**
1319
+ * Runs one step of a Turn: the pending tool calls if there are any, else one
1320
+ * model request. Only a model request calls `request`, and the step returns
1321
+ * its new messages. A tool batch returns none.
1322
+ */
1323
+ async function runStep(input) {
1324
+ const pending = collectPendingToolCalls(input.history);
1325
+ if (pending.calls.length > 0) return {
1326
+ result: await runToolCalls(pending, input),
1327
+ newMessages: []
1328
+ };
1329
+ const request = await input.request();
1330
+ if (request.messages.at(-1)?.role === "assistant") throw new Error("The history ends with a reply, so the Turn has no step");
1331
+ return {
1332
+ result: await requestModel(request, input),
1333
+ newMessages: request.newMessages
1334
+ };
1335
+ }
1336
+ async function requestModel({ systemPrompt, messages, model }, { client, session, tools, signal }) {
1337
+ const { message: reply, failure } = await client.complete({
1338
+ model,
1339
+ session,
1340
+ context: {
1341
+ systemPrompt,
1342
+ messages,
1343
+ tools: tools.map(toToolDeclaration)
1344
+ }
1345
+ }, signal);
1346
+ if (signal.aborted) throw signal.reason;
1347
+ if (failure) return {
1348
+ outcome: "failed",
1349
+ reply,
1350
+ failure
1351
+ };
1352
+ if (reply.content.some((block) => block.type === "toolCall")) return {
1353
+ outcome: "continue",
1354
+ messages: [reply]
1355
+ };
1356
+ if (reply.stopReason === "stop" || reply.stopReason === "length") return {
1357
+ outcome: "completed",
1358
+ messages: [reply]
1359
+ };
1360
+ return {
1361
+ outcome: "failed",
1362
+ reply,
1363
+ failure: {
1364
+ kind: "invalid_response",
1365
+ retryable: false,
1366
+ message: `Unsupported stop reason: ${reply.stopReason}`
1367
+ }
1368
+ };
1369
+ }
1370
+ /**
1371
+ * The tool calls of the last reply that have no result yet. Only tool results
1372
+ * may follow the reply. Any other message means the reply has no open calls.
1373
+ */
1374
+ function collectPendingToolCalls(messages) {
1375
+ const answered = /* @__PURE__ */ new Set();
1376
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
1377
+ const message = messages[index];
1378
+ if (message?.role === "toolResult") {
1379
+ answered.add(message.toolCallId);
1380
+ continue;
1381
+ }
1382
+ if (message?.role !== "assistant") return {
1383
+ calls: [],
1384
+ truncated: false
1385
+ };
1386
+ return {
1387
+ calls: message.content.filter((block) => block.type === "toolCall" && !answered.has(block.id)),
1388
+ truncated: message.stopReason === "length"
1389
+ };
1390
+ }
1391
+ return {
1392
+ calls: [],
1393
+ truncated: false
1394
+ };
1395
+ }
1396
+ async function runToolCalls(pending, input) {
1397
+ const results = await Promise.all(pending.calls.map((call) => runToolCall(call, pending.truncated, input)));
1398
+ if (input.signal.aborted) throw input.signal.reason;
1399
+ return {
1400
+ outcome: results.every(({ result }) => result.endsTurn === true) ? "completed" : "continue",
1401
+ messages: results.map(({ result, call }) => toResultMessage(call, result))
1402
+ };
1403
+ }
1404
+ function runToolCall(call, truncated, input) {
1405
+ return withSpan("gen_ai.execute_tool", {
1406
+ "gen_ai.operation.name": "execute_tool",
1407
+ "gen_ai.tool.name": call.name,
1408
+ "gen_ai.tool.call.id": call.id,
1409
+ "gen_ai.tool.type": "function"
1410
+ }, async (span) => {
1411
+ const { status, result } = await executeToolCall(call, truncated, input);
1412
+ span.setAttribute("app.tool_call.outcome", status);
1413
+ return {
1414
+ call,
1415
+ result
1416
+ };
1417
+ });
1418
+ }
1419
+ async function executeToolCall(call, truncated, input) {
1420
+ if (input.skipDanglingToolCalls) return danglingRun(call, input);
1421
+ if (truncated) return errorRun("truncated", `Tool call "${call.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`);
1422
+ const tool = input.tools.find((candidate) => candidate.name === call.name);
1423
+ if (!tool) return errorRun("not_found", `Tool ${call.name} not found`);
1424
+ if (input.replay && tool.replay === "never") return errorRun("replay_skipped", "This call was interrupted before its result was saved, so it may have run. Check its effect before you call it again.");
1425
+ let args;
1426
+ try {
1427
+ args = validateToolArguments(tool, call);
1428
+ } catch (error) {
1429
+ return errorRun("invalid_arguments", errorText(error));
1430
+ }
1431
+ if (!isJsonObject(args)) return errorRun("invalid_arguments", "Tool arguments must be a JSON object");
1432
+ try {
1433
+ const result = await tool.execute(args, {
1434
+ callId: call.id,
1435
+ signal: input.signal
1436
+ });
1437
+ return {
1438
+ status: result.isError ? "failed" : "completed",
1439
+ result
1440
+ };
1441
+ } catch (error) {
1442
+ return errorRun(input.signal.aborted ? "aborted" : "failed", errorText(error));
1443
+ }
1444
+ }
1445
+ function danglingRun(call, input) {
1446
+ return errorRun("dangling_skipped", input.tools.find((candidate) => candidate.name === call.name)?.replay === "safe" ? "The previous Turn ended before this call returned, so there is no result. Call it again if you still need it." : "The previous Turn ended before this call's result was saved. It may or may not have run. Check its effect before you call it again.");
1447
+ }
1448
+ function isJsonObject(value) {
1449
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1450
+ }
1451
+ function errorText(error) {
1452
+ return error instanceof Error ? error.message : String(error);
1453
+ }
1454
+ function errorRun(status, text) {
1455
+ return {
1456
+ status,
1457
+ result: {
1458
+ content: [{
1459
+ type: "text",
1460
+ text
1461
+ }],
1462
+ isError: true
1463
+ }
1464
+ };
1465
+ }
1466
+ function toResultMessage(call, result) {
1467
+ const message = {
1468
+ role: "toolResult",
1469
+ toolCallId: call.id,
1470
+ toolName: call.name,
1471
+ content: result.content,
1472
+ isError: result.isError === true,
1473
+ timestamp: Date.now()
1474
+ };
1475
+ if (result.details !== void 0) message.details = result.details;
1476
+ return message;
1477
+ }
1478
+ // src/core/turn/advance.ts
1479
+ const LEASE_CHECK_INTERVAL_MS = 1e3;
1480
+ /**
1481
+ * Runs the next step of a Turn. It does nothing when the Turn cannot be
1482
+ * claimed, for example after a duplicate message or when the Turn has ended.
1483
+ */
1484
+ async function advanceTurn({ executor, queue, owner, leaseMs }, message, options) {
1485
+ const claim = await claimTurn({
1486
+ executor,
1487
+ owner,
1488
+ leaseMs
1489
+ }, message.turnId);
1490
+ if (!claim) {
1491
+ await reconcileTurn({
1492
+ executor,
1493
+ queue
1494
+ }, message.turnId);
1495
+ return;
1496
+ }
1497
+ try {
1498
+ const unread = await findUnreadInputs({ executor }, claim.turnId);
1499
+ await markInputsAttempted({ executor }, unread.map((input) => input.inputId));
1500
+ if (claim.attempts > options.maxAttempts) {
1501
+ if (await endFailedTurn({ executor }, claim, "attempts_exhausted", { failureCode: "agent_run_failed" })) await reconcileTurn({
1502
+ executor,
1503
+ queue
1504
+ }, claim.turnId);
1505
+ return;
1506
+ }
1507
+ await runClaimedStep({
1508
+ executor,
1509
+ queue
1510
+ }, claim, unread, options);
1511
+ } catch (error) {
1512
+ try {
1513
+ await releaseTurn({ executor }, claim);
1514
+ } catch (releaseError) {
1515
+ logException(releaseError, "turn.release.failed", { "app.turn.id": claim.turnId });
1516
+ }
1517
+ throw error;
1518
+ }
1519
+ }
1520
+ async function runClaimedStep({ executor, queue }, claim, unread, { client, prompt, modelSettings, tools, maxAttempts }) {
1521
+ const events = await createSqlConversationEventStore(executor).loadCurrentHistory(claim.conversationId);
1522
+ setActiveSpanAttributes({
1523
+ "app.turn.step_seq": claim.stepSeq,
1524
+ "gen_ai.conversation.id": claim.conversationId
1525
+ });
1526
+ const history = projectConversationEvents(events).messages;
1527
+ const stepTools = await tools(claim, await findTurnInputs({ executor }, claim.turnId));
1528
+ const step = await whileLeased({ executor }, claim, (signal) => runStep({
1529
+ history,
1530
+ request: async () => ({
1531
+ ...await assemblePrompt(await prompt(claim), {
1532
+ turn: claim,
1533
+ history,
1534
+ inputs: unread
1535
+ }, { signal }),
1536
+ model: await modelSettings(claim)
1537
+ }),
1538
+ tools: stepTools.definitions,
1539
+ client,
1540
+ session: claim.conversationId,
1541
+ replay: claim.attempts > 1,
1542
+ skipDanglingToolCalls: claim.stepSeq === 0,
1543
+ signal
1544
+ })).finally(() => stepTools.close());
1545
+ if (!step) return;
1546
+ const { result, newMessages } = step;
1547
+ switch (result.outcome) {
1548
+ case "continue":
1549
+ case "completed":
1550
+ if (await commitStep({ executor }, claim, result, newMessages)) await reconcileTurn({
1551
+ executor,
1552
+ queue
1553
+ }, claim.turnId);
1554
+ return;
1555
+ case "failed": {
1556
+ const delayMs = modelRetryDelayMs(result.failure, claim.attempts, maxAttempts);
1557
+ if (delayMs !== void 0) {
1558
+ if (await releaseTurn({ executor }, claim)) {
1559
+ await publishTurnStep({ queue }, claim.turnId, { delayMs });
1560
+ logWarn("agent.turn.provider.retrying", {
1561
+ ...modelFailureAttributes(result.failure),
1562
+ "app.ai.provider_error.retry_attempt": claim.attempts,
1563
+ "app.turn.id": claim.turnId
1564
+ });
1565
+ }
1566
+ return;
1567
+ }
1568
+ const failure = captureModelFailure(result.failure);
1569
+ if (await endFailedTurn({ executor }, claim, result.failure.message, failure)) await reconcileTurn({
1570
+ executor,
1571
+ queue
1572
+ }, claim.turnId);
1573
+ return;
1574
+ }
1575
+ default: throw new Error(`Unhandled step result: ${JSON.stringify(result)}`);
1576
+ }
1577
+ }
1578
+ const MODEL_RETRY_BASE_DELAY_MS = 2e3;
1579
+ const MODEL_RETRY_MAX_DELAY_MS = 6e4;
1580
+ /**
1581
+ * The wait before the step runs again after a failed model request, or
1582
+ * undefined when the failure ends the Turn: it cannot work later, or the
1583
+ * step has used its last try.
1584
+ */
1585
+ function modelRetryDelayMs(failure, attempts, maxAttempts) {
1586
+ if (!failure.retryable || attempts >= maxAttempts) return;
1587
+ const backoffMs = MODEL_RETRY_BASE_DELAY_MS * 2 ** (attempts - 1);
1588
+ return Math.min(MODEL_RETRY_MAX_DELAY_MS, Math.max(backoffMs, failure.retryAfterMs ?? 0)) * (1 + Math.random() / 2);
1589
+ }
1590
+ /**
1591
+ * Reports a failed model request to Sentry under main's event name, and
1592
+ * returns the failure details that `endFailedTurn` stores.
1593
+ */
1594
+ function captureModelFailure(failure) {
1595
+ const eventId = logException(new ModelRequestError(failure), "agent.turn.provider_error", {
1596
+ ...modelFailureAttributes(failure),
1597
+ "app.ai.failure_reason": failure.kind
1598
+ });
1599
+ if (!eventId) throw new Error("Sentry did not return an event ID for a model failure");
1600
+ return {
1601
+ failureCode: "model_execution_failed",
1602
+ failureReason: failure.kind,
1603
+ eventId
1604
+ };
1605
+ }
1606
+ /**
1607
+ * Runs `run`, the step and the prompt it builds, and aborts its signal when a
1608
+ * check finds that the lease is lost. Undefined when it stopped for that
1609
+ * reason: the new lease holder or the cancel owns the Turn, so this
1610
+ * invocation writes nothing.
1611
+ */
1612
+ async function whileLeased({ executor }, lease, run) {
1613
+ const abort = new AbortController();
1614
+ let checking = false;
1615
+ let failureLogged = false;
1616
+ const check = async () => {
1617
+ if (checking || abort.signal.aborted) return;
1618
+ checking = true;
1619
+ try {
1620
+ if (!await holdsLease({ executor }, lease)) abort.abort(/* @__PURE__ */ new Error("The Turn was cancelled or taken over"));
1621
+ } catch (error) {
1622
+ if (!failureLogged) {
1623
+ failureLogged = true;
1624
+ logException(error, "turn.lease_check.failed", { "app.turn.id": lease.turnId });
1625
+ }
1626
+ } finally {
1627
+ checking = false;
1628
+ }
1629
+ };
1630
+ const timer = setInterval(() => void check(), LEASE_CHECK_INTERVAL_MS);
1631
+ timer.unref?.();
1632
+ try {
1633
+ return await run(abort.signal);
1634
+ } catch (error) {
1635
+ if (abort.signal.aborted) {
1636
+ if (error !== abort.signal.reason) logException(error, "turn.step.error_after_abort", { "app.turn.id": lease.turnId });
1637
+ return;
1638
+ }
1639
+ throw error;
1640
+ } finally {
1641
+ clearInterval(timer);
1642
+ }
1643
+ }
1644
+ // src/turn-steps/input-payload.ts
1645
+ /** Parses the payload of an inbox row that the host wrote. */
1646
+ const turnInputPayloadSchema = z.object({
1647
+ text: z.string().min(1),
1648
+ actor: actorSchema
1649
+ }).strict();
1650
+ // src/turn-steps/prompt.ts
1651
+ function formatInput(input) {
1652
+ const payload = turnInputPayloadSchema.parse(input.payload);
1653
+ return {
1654
+ message: {
1655
+ role: "user",
1656
+ content: [{
1657
+ type: "text",
1658
+ text: payload.text
1659
+ }]
1660
+ },
1661
+ provenance: instructionProvenanceFor(payload.actor)
1662
+ };
1663
+ }
1664
+ async function platformPromptLayout(platform) {
1665
+ return definePromptLayout({
1666
+ systemPrompt: [{
1667
+ name: "deployment",
1668
+ text: await buildDeploymentSystemPrompt(platform, "conversation")
1669
+ }],
1670
+ messages: [inputs({ format: formatInput })]
1671
+ });
1672
+ }
1673
+ /**
1674
+ * Builds the host's prompt layouts once, one for each platform: the
1675
+ * platform's deployment system prompt, then the unread inputs after the
1676
+ * history. Every Turn on a platform gets the same system prompt.
1677
+ */
1678
+ async function buildTurnPromptLayouts() {
1679
+ return {
1680
+ slack: await platformPromptLayout("slack"),
1681
+ local: await platformPromptLayout("local")
1682
+ };
1683
+ }
1684
+ /**
1685
+ * Gives the prompt layout of a claimed Turn: the layout of the platform of
1686
+ * its Conversation's Location, which Delivery sends the replies to. A Turn
1687
+ * with no Location gets the `local` layout. It only picks one of `layouts`.
1688
+ */
1689
+ function turnPromptLayout({ executor }, layouts) {
1690
+ return async (turn) => {
1691
+ const [conversation] = await executor.db().select({ location: juniorConversations.location }).from(juniorConversations).where(eq(juniorConversations.conversationId, turn.conversationId)).limit(1);
1692
+ return layouts[(conversation?.location ? locationSchema.parse(conversation.location) : void 0)?.provider ?? "local"];
1693
+ };
1694
+ }
1695
+ /**
1696
+ * Gives the model settings of a claimed Turn: `bot`'s model with the
1697
+ * Conversation's privacy. It reads `bot` at each step, so a later change
1698
+ * applies.
1699
+ */
1700
+ function turnModelSettings({ executor, bot }) {
1701
+ return async (turn) => {
1702
+ const { visibility } = await resolveRootVisibility(executor, turn.conversationId);
1703
+ return {
1704
+ id: bot.modelId,
1705
+ reasoning: bot.reasoningLevel,
1706
+ privacy: resolveConversationPrivacy({ visibility: visibility ?? void 0 })
1707
+ };
1708
+ };
1709
+ }
1710
+ // src/turn-steps/consumer.ts
1711
+ const MAX_ATTEMPTS = 4;
1712
+ /** The model client of core Turns on this deployment: the AI Gateway. */
1713
+ function createGatewayModelClient() {
1714
+ return modelClient({
1715
+ apiKey: getGatewayApiKey,
1716
+ resolveModel: resolveGatewayModel,
1717
+ send: streamSimple
1718
+ });
1719
+ }
1720
+ /**
1721
+ * The queue consumer of Turn step messages. The host mounts it on
1722
+ * `engineCtx.queue`, and gives the model client, the bot settings and the
1723
+ * tools that its steps use. It builds the prompt layouts once.
1724
+ */
1725
+ async function turnStepConsumer(engineCtx, { client, bot, tools }) {
1726
+ const prompt = turnPromptLayout(engineCtx, await buildTurnPromptLayouts());
1727
+ const modelSettings = turnModelSettings({
1728
+ executor: engineCtx.executor,
1729
+ bot
1730
+ });
1731
+ return createTurnStepConsumer(engineCtx, (message) => advanceTurn(engineCtx, message, {
1732
+ client,
1733
+ prompt,
1734
+ modelSettings,
1735
+ tools,
1736
+ maxAttempts: MAX_ATTEMPTS
1737
+ }));
1738
+ }
1739
+ // src/turn-steps/tools.ts
1740
+ function storedDetails(details) {
1741
+ return details === void 0 ? void 0 : z.json().parse(JSON.parse(JSON.stringify(details)));
1742
+ }
1743
+ const sandboxInputSchema = z.record(z.string(), z.unknown());
1744
+ function coreTool(name, tool, run) {
1745
+ return {
1746
+ name,
1747
+ description: tool.description,
1748
+ parameters: tool.inputSchema,
1749
+ replay: tool.annotations?.idempotentHint ? "safe" : "never",
1750
+ async execute(args, context) {
1751
+ const input = tool.prepareArguments ? tool.prepareArguments(args) : args;
1752
+ const result = normalizeToolResult(await run(input, context), {
1753
+ requireStructuredResult: Boolean(tool.outputSchema),
1754
+ toolName: name
1755
+ });
1756
+ return {
1757
+ content: result.content,
1758
+ details: storedDetails(result.details)
1759
+ };
1760
+ }
1761
+ };
1762
+ }
1763
+ const SANDBOX_TOOLS = {
1764
+ bash: createBashTool,
1765
+ readFile: createReadFileTool,
1766
+ writeFile: createWriteFileTool,
1767
+ editFile: createEditFileTool
1768
+ };
1769
+ /**
1770
+ * Builds the tools of one step of a core Turn. Every input of a Turn has the
1771
+ * same Actor, so the latest input's Actor gives the sandbox its credentials.
1772
+ * The sandbox reference is kept where main keeps it, so a later step, and
1773
+ * main's engine, reopen the same sandbox.
1774
+ */
1775
+ async function turnTools(turn, inputs) {
1776
+ const latest = inputs.at(-1);
1777
+ if (!latest) throw new Error(`Turn ${turn.turnId} has no inputs`);
1778
+ const { actor } = turnInputPayloadSchema.parse(latest.payload);
1779
+ const sandboxRef = getPersistedSandboxState(await getPersistedThreadState(turn.conversationId));
1780
+ const sandbox = createAgentSandbox({
1781
+ sandboxRef,
1782
+ workspace: sandboxRef?.workspaceId ? await getWorkspace(getDb(), sandboxRef.workspaceId) : void 0,
1783
+ skills: [],
1784
+ traceContext: { conversationId: turn.conversationId },
1785
+ conversationId: turn.conversationId,
1786
+ credentialEgress: credentialContextForActor(actor),
1787
+ prepareSandbox: () => {},
1788
+ onSandboxRefChanged: () => {},
1789
+ persistSandboxRef: (sandboxRef) => persistThreadRuntimeState(turn.conversationId, { sandboxRef })
1790
+ });
1791
+ const systemTime = createSystemTimeTool();
1792
+ return {
1793
+ definitions: [coreTool("systemTime", systemTime, (input, { callId, signal }) => Promise.resolve(systemTime.execute(input, {
1794
+ signal,
1795
+ toolCallId: callId
1796
+ }))), ...Object.entries(SANDBOX_TOOLS).map(([name, create]) => coreTool(name, create(), (input, { signal }) => sandbox.tools.execute({
1797
+ toolName: name,
1798
+ input: buildSandboxInput(name, sandboxInputSchema.parse(input)),
1799
+ signal
1800
+ })))],
1801
+ close: () => sandbox.close()
1802
+ };
1803
+ }
1804
+ // src/turn-steps/engine-context.ts
1805
+ /** Builds the context that core's Turn engine runs with. */
1806
+ function createEngineContext(config) {
1807
+ return {
1808
+ executor: getSqlExecutor(),
1809
+ queue: getQueueProvider(),
1810
+ owner: SERVICE_INSTANCE_ID,
1811
+ leaseMs: config.functionMaxDurationSeconds * 1e3
1812
+ };
1813
+ }
1814
+ export { scheduleInput as a, replyText as c, publishTurnStep as d, countMetric as f, turnStepConsumer as i, createDeliveryConsumer as l, turnTools as n, findStalledTurns as o, withSpan as p, createGatewayModelClient as r, findStalledDeliveries as s, createEngineContext as t, publishDelivery as u };