@truefoundry/trueforge 0.180.0 → 0.181.0-rc.1

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 (237) hide show
  1. package/dist/_frontend/assets/{AgentCodeSnippets-SQIFBJRR-DzPCvf4d.js → AgentCodeSnippets-7YBGYKYT-COw5-jCA.js} +1 -1
  2. package/dist/_frontend/assets/AgentCodeSnippets-7YBGYKYT-COw5-jCA.js.br +0 -0
  3. package/dist/_frontend/assets/AgentCodeSnippets-7YBGYKYT-COw5-jCA.js.gz +0 -0
  4. package/dist/_frontend/assets/AgentMetricChart-ECYBDKGM-DJTSZ671.js +1 -0
  5. package/dist/_frontend/assets/AgentMetricChart-ECYBDKGM-DJTSZ671.js.br +0 -0
  6. package/dist/_frontend/assets/AgentMetricChart-ECYBDKGM-DJTSZ671.js.gz +0 -0
  7. package/dist/_frontend/assets/{AgentOverview-SONOXEA2-DVW9dpOp.js → AgentOverview-NCWC4XDZ-DqZqGo8V.js} +1 -1
  8. package/dist/_frontend/assets/AgentOverview-NCWC4XDZ-DqZqGo8V.js.br +0 -0
  9. package/dist/_frontend/assets/AgentOverview-NCWC4XDZ-DqZqGo8V.js.gz +0 -0
  10. package/dist/_frontend/assets/AgentSessionEventTimeline-GSHWZCTN-BrVSrckq.js +1 -0
  11. package/dist/_frontend/assets/AgentSessionEventTimeline-GSHWZCTN-BrVSrckq.js.br +0 -0
  12. package/dist/_frontend/assets/AgentSessionEventTimeline-GSHWZCTN-BrVSrckq.js.gz +0 -0
  13. package/dist/_frontend/assets/AgentSessionEventTimelineChart-UY4YNTFB-DAeb-1-p.js +1 -0
  14. package/dist/_frontend/assets/AgentSessionEventTimelineChart-UY4YNTFB-DAeb-1-p.js.br +0 -0
  15. package/dist/_frontend/assets/AgentSessionEventTimelineChart-UY4YNTFB-DAeb-1-p.js.gz +0 -0
  16. package/dist/_frontend/assets/AgentSessions-V2V6W7CC-D1eUhvgn.js +1 -0
  17. package/dist/_frontend/assets/AgentSessions-V2V6W7CC-D1eUhvgn.js.br +0 -0
  18. package/dist/_frontend/assets/AgentSessions-V2V6W7CC-D1eUhvgn.js.gz +0 -0
  19. package/dist/_frontend/assets/{ConnectorSettings-FAMLKHRT-CbgoOQBA.js → ConnectorSettings-DYJ6Z6YL-DhF84SXP.js} +1 -1
  20. package/dist/_frontend/assets/ConnectorSettings-DYJ6Z6YL-DhF84SXP.js.br +0 -0
  21. package/dist/_frontend/assets/ConnectorSettings-DYJ6Z6YL-DhF84SXP.js.gz +0 -0
  22. package/dist/_frontend/assets/DockLayout-YZPEWKJV-DyDyUCtl.js +1 -0
  23. package/dist/_frontend/assets/{DrawerLayout-MB3JP4YC-Cs4K8WbP.js → DrawerLayout-OWUKLUSV-DQnh_BPt.js} +2 -2
  24. package/dist/_frontend/assets/DrawerLayout-OWUKLUSV-DQnh_BPt.js.br +0 -0
  25. package/dist/_frontend/assets/DrawerLayout-OWUKLUSV-DQnh_BPt.js.gz +0 -0
  26. package/dist/_frontend/assets/EnvironmentsPage-KOMO4W53-DT8-DDE7.js +3 -0
  27. package/dist/_frontend/assets/EnvironmentsPage-KOMO4W53-DT8-DDE7.js.br +0 -0
  28. package/dist/_frontend/assets/EnvironmentsPage-KOMO4W53-DT8-DDE7.js.gz +0 -0
  29. package/dist/_frontend/assets/{ModelSettings-KYX762EG-fzXe6Th3.js → ModelSettings-Y5NTNBCL-BFS8Ev0r.js} +1 -1
  30. package/dist/_frontend/assets/ModelSettings-Y5NTNBCL-BFS8Ev0r.js.br +0 -0
  31. package/dist/_frontend/assets/ModelSettings-Y5NTNBCL-BFS8Ev0r.js.gz +0 -0
  32. package/dist/_frontend/assets/{SandboxSettings-ZE4Z65F5-RaO5UYxl.js → SandboxSettings-KLDK6WZH-BB_J0XaX.js} +1 -1
  33. package/dist/_frontend/assets/SandboxSettings-KLDK6WZH-BB_J0XaX.js.br +0 -0
  34. package/dist/_frontend/assets/SandboxSettings-KLDK6WZH-BB_J0XaX.js.gz +0 -0
  35. package/dist/_frontend/assets/SchedulesPage-4F5FX65T-DVKEEd4R.js +1 -0
  36. package/dist/_frontend/assets/SchedulesPage-4F5FX65T-DVKEEd4R.js.br +0 -0
  37. package/dist/_frontend/assets/SchedulesPage-4F5FX65T-DVKEEd4R.js.gz +0 -0
  38. package/dist/_frontend/assets/SettingsBuilder-72KREKYT-Dmu76Wzi.js +2 -0
  39. package/dist/_frontend/assets/SettingsBuilder-72KREKYT-Dmu76Wzi.js.br +0 -0
  40. package/dist/_frontend/assets/SettingsBuilder-72KREKYT-Dmu76Wzi.js.gz +0 -0
  41. package/dist/_frontend/assets/ShellRouteSync-G2PJ3G3L-C4RD0M9w.js +1 -0
  42. package/dist/_frontend/assets/ShellRouteSync-G2PJ3G3L-C4RD0M9w.js.br +0 -0
  43. package/dist/_frontend/assets/ShellRouteSync-G2PJ3G3L-C4RD0M9w.js.gz +0 -0
  44. package/dist/_frontend/assets/SidebarLayout-BWR7N76R-B3Zm0kWX.js +2 -0
  45. package/dist/_frontend/assets/SidebarLayout-BWR7N76R-B3Zm0kWX.js.br +0 -0
  46. package/dist/_frontend/assets/SidebarLayout-BWR7N76R-B3Zm0kWX.js.gz +0 -0
  47. package/dist/_frontend/assets/SkillSettings-F7X7TZII-DYRS-1zQ.js +1 -0
  48. package/dist/_frontend/assets/SkillSettings-F7X7TZII-DYRS-1zQ.js.br +0 -0
  49. package/dist/_frontend/assets/SkillSettings-F7X7TZII-DYRS-1zQ.js.gz +0 -0
  50. package/dist/_frontend/assets/{TrueForgeUIWithRouter-76JMT47N-CnpzH7-n.js → TrueForgeUIWithRouter-KPZEEO7D-BAuDAM4m.js} +1 -1
  51. package/dist/_frontend/assets/{WebSearchSettings-LFQ4V4FB-D7w_63MH.js → WebSearchSettings-VNL63UFQ-BL3QLgS_.js} +1 -1
  52. package/dist/_frontend/assets/WebSearchSettings-VNL63UFQ-BL3QLgS_.js.br +0 -0
  53. package/dist/_frontend/assets/WebSearchSettings-VNL63UFQ-BL3QLgS_.js.gz +0 -0
  54. package/dist/_frontend/assets/WidgetLayout-5E2MCZOP-BXKkzHl9.js +1 -0
  55. package/dist/_frontend/assets/WidgetLayout-5E2MCZOP-BXKkzHl9.js.br +0 -0
  56. package/dist/_frontend/assets/WidgetLayout-5E2MCZOP-BXKkzHl9.js.gz +0 -0
  57. package/dist/_frontend/assets/{chunk-C43ZVKUS-ClJ9CpD6.js → chunk-HB2ZQ4CZ-DnCTK9KS.js} +1 -1
  58. package/dist/_frontend/assets/chunk-NRMAG6HF-BKTcpJl0.js +1 -0
  59. package/dist/_frontend/assets/chunk-NRMAG6HF-BKTcpJl0.js.br +0 -0
  60. package/dist/_frontend/assets/chunk-NRMAG6HF-BKTcpJl0.js.gz +0 -0
  61. package/dist/_frontend/assets/{chunk-OB3PAWPO-D3Luy7W3.js → chunk-OB3PAWPO-CDXWnkeP.js} +1 -1
  62. package/dist/_frontend/assets/chunk-OB3PAWPO-CDXWnkeP.js.br +0 -0
  63. package/dist/_frontend/assets/chunk-OB3PAWPO-CDXWnkeP.js.gz +0 -0
  64. package/dist/_frontend/assets/{chunk-ZSP5XG3J-9vEyCWu1.js → chunk-QYZB5BFZ-C1Zl8SCi.js} +2 -2
  65. package/dist/_frontend/assets/chunk-QYZB5BFZ-C1Zl8SCi.js.br +0 -0
  66. package/dist/_frontend/assets/chunk-QYZB5BFZ-C1Zl8SCi.js.gz +0 -0
  67. package/dist/_frontend/assets/{chunk-4BKRLRXL-DLUyrNQ3.js → chunk-XIE7TJW5-C05XSTa4.js} +1 -1
  68. package/dist/_frontend/assets/chunk-XIE7TJW5-C05XSTa4.js.br +0 -0
  69. package/dist/_frontend/assets/chunk-XIE7TJW5-C05XSTa4.js.gz +0 -0
  70. package/dist/_frontend/assets/{cssMode-JOuT28rz.js → cssMode-XDzIuvZX.js} +1 -1
  71. package/dist/_frontend/assets/cssMode-XDzIuvZX.js.br +6 -0
  72. package/dist/_frontend/assets/cssMode-XDzIuvZX.js.gz +0 -0
  73. package/dist/_frontend/assets/{freemarker2-CZJ58vDF.js → freemarker2-CMM6eRZY.js} +1 -1
  74. package/dist/_frontend/assets/freemarker2-CMM6eRZY.js.br +0 -0
  75. package/dist/_frontend/assets/freemarker2-CMM6eRZY.js.gz +0 -0
  76. package/dist/_frontend/assets/{handlebars-CUvie110.js → handlebars-zWdybys2.js} +1 -1
  77. package/dist/_frontend/assets/handlebars-zWdybys2.js.br +0 -0
  78. package/dist/_frontend/assets/handlebars-zWdybys2.js.gz +0 -0
  79. package/dist/_frontend/assets/{html-DD_vjw5l.js → html-FSsE5b6P.js} +1 -1
  80. package/dist/_frontend/assets/html-FSsE5b6P.js.br +0 -0
  81. package/dist/_frontend/assets/html-FSsE5b6P.js.gz +0 -0
  82. package/dist/_frontend/assets/{htmlMode-Bs5cHvWx.js → htmlMode-Ba0OQ7ke.js} +1 -1
  83. package/dist/_frontend/assets/htmlMode-Ba0OQ7ke.js.br +0 -0
  84. package/dist/_frontend/assets/htmlMode-Ba0OQ7ke.js.gz +0 -0
  85. package/dist/_frontend/assets/index-CHtf87eT.js +1019 -0
  86. package/dist/_frontend/assets/index-CHtf87eT.js.br +0 -0
  87. package/dist/_frontend/assets/index-CHtf87eT.js.gz +0 -0
  88. package/dist/_frontend/assets/{index-IV_K3kGI.js → index-DJwMhvnU.js} +3 -3
  89. package/dist/_frontend/assets/index-DJwMhvnU.js.br +0 -0
  90. package/dist/_frontend/assets/index-DJwMhvnU.js.gz +0 -0
  91. package/dist/_frontend/assets/{javascript-R_9qXwYL.js → javascript-Ce1crFvb.js} +1 -1
  92. package/dist/_frontend/assets/{jsonMode-8OQdDgk6.js → jsonMode-BMBeYqZi.js} +1 -1
  93. package/dist/_frontend/assets/jsonMode-BMBeYqZi.js.br +0 -0
  94. package/dist/_frontend/assets/jsonMode-BMBeYqZi.js.gz +0 -0
  95. package/dist/_frontend/assets/{liquid-BAdDEBi9.js → liquid-cKR-cSWX.js} +1 -1
  96. package/dist/_frontend/assets/liquid-cKR-cSWX.js.br +0 -0
  97. package/dist/_frontend/assets/liquid-cKR-cSWX.js.gz +0 -0
  98. package/dist/_frontend/assets/{lspLanguageFeatures-CNxTXCEe.js → lspLanguageFeatures-RvCvbT7h.js} +1 -1
  99. package/dist/_frontend/assets/lspLanguageFeatures-RvCvbT7h.js.br +0 -0
  100. package/dist/_frontend/assets/lspLanguageFeatures-RvCvbT7h.js.gz +0 -0
  101. package/dist/_frontend/assets/{mdx-zRCES-UR.js → mdx-DWyx_s0A.js} +1 -1
  102. package/dist/_frontend/assets/mdx-DWyx_s0A.js.br +0 -0
  103. package/dist/_frontend/assets/mdx-DWyx_s0A.js.gz +0 -0
  104. package/dist/_frontend/assets/{python-CHTiGyj6.js → python-BZT89b5u.js} +1 -1
  105. package/dist/_frontend/assets/python-BZT89b5u.js.br +0 -0
  106. package/dist/_frontend/assets/python-BZT89b5u.js.gz +0 -0
  107. package/dist/_frontend/assets/{razor-CU2s7Hbi.js → razor-C4RJ85c7.js} +1 -1
  108. package/dist/_frontend/assets/razor-C4RJ85c7.js.br +0 -0
  109. package/dist/_frontend/assets/razor-C4RJ85c7.js.gz +0 -0
  110. package/dist/_frontend/assets/{tsMode-CJLsaAN3.js → tsMode-BFOytUIs.js} +1 -1
  111. package/dist/_frontend/assets/tsMode-BFOytUIs.js.br +0 -0
  112. package/dist/_frontend/assets/tsMode-BFOytUIs.js.gz +0 -0
  113. package/dist/_frontend/assets/{typescript-C6qGKHm0.js → typescript-B_aWPfCP.js} +1 -1
  114. package/dist/_frontend/assets/typescript-B_aWPfCP.js.br +0 -0
  115. package/dist/_frontend/assets/typescript-B_aWPfCP.js.gz +0 -0
  116. package/dist/_frontend/assets/{workers-DeOwcFUN.js → workers-DhT6ONBN.js} +1 -1
  117. package/dist/_frontend/assets/workers-DhT6ONBN.js.br +0 -0
  118. package/dist/_frontend/assets/workers-DhT6ONBN.js.gz +0 -0
  119. package/dist/_frontend/assets/{xml-ccL_LPm9.js → xml-CIXW7ba5.js} +1 -1
  120. package/dist/_frontend/assets/xml-CIXW7ba5.js.br +0 -0
  121. package/dist/_frontend/assets/xml-CIXW7ba5.js.gz +0 -0
  122. package/dist/_frontend/assets/{yaml-YzcQ27WY.js → yaml-B06RGyXK.js} +1 -1
  123. package/dist/_frontend/assets/yaml-B06RGyXK.js.br +0 -0
  124. package/dist/_frontend/assets/yaml-B06RGyXK.js.gz +0 -0
  125. package/dist/_frontend/index.html +1 -1
  126. package/dist/controller-main.js +338 -200
  127. package/dist/controller-main.js.map +1 -1
  128. package/dist/main.js +1262 -437
  129. package/dist/main.js.map +1 -1
  130. package/dist/postgres/migrations/20260727_000001_init.js +1 -1
  131. package/dist/postgres/migrations/20260727_000001_init.js.map +1 -1
  132. package/dist/postgres/migrations/20261016_000001_schedule_run_session_id.js +22 -0
  133. package/dist/postgres/migrations/20261016_000001_schedule_run_session_id.js.map +1 -0
  134. package/dist/postgres/migrations/20261018_000001_session_last_turn_details.js +25 -0
  135. package/dist/postgres/migrations/20261018_000001_session_last_turn_details.js.map +1 -0
  136. package/dist/sqlite/migrations/20261016_000001_schedule_run_session_id.js +28 -0
  137. package/dist/sqlite/migrations/20261016_000001_schedule_run_session_id.js.map +1 -0
  138. package/dist/sqlite/migrations/20261018_000001_session_last_turn_details.js +26 -0
  139. package/dist/sqlite/migrations/20261018_000001_session_last_turn_details.js.map +1 -0
  140. package/package.json +9 -6
  141. package/dist/_frontend/assets/AgentCodeSnippets-SQIFBJRR-DzPCvf4d.js.br +0 -0
  142. package/dist/_frontend/assets/AgentCodeSnippets-SQIFBJRR-DzPCvf4d.js.gz +0 -0
  143. package/dist/_frontend/assets/AgentMetricChart-GGEDYHIM-D4y11_kp.js +0 -1
  144. package/dist/_frontend/assets/AgentMetricChart-GGEDYHIM-D4y11_kp.js.br +0 -0
  145. package/dist/_frontend/assets/AgentMetricChart-GGEDYHIM-D4y11_kp.js.gz +0 -0
  146. package/dist/_frontend/assets/AgentOverview-SONOXEA2-DVW9dpOp.js.br +0 -0
  147. package/dist/_frontend/assets/AgentOverview-SONOXEA2-DVW9dpOp.js.gz +0 -0
  148. package/dist/_frontend/assets/AgentSessionEventTimeline-VTUD4LL3-uCjuzqN4.js +0 -1
  149. package/dist/_frontend/assets/AgentSessionEventTimeline-VTUD4LL3-uCjuzqN4.js.br +0 -0
  150. package/dist/_frontend/assets/AgentSessionEventTimeline-VTUD4LL3-uCjuzqN4.js.gz +0 -0
  151. package/dist/_frontend/assets/AgentSessionEventTimelineChart-K3HU6HSO-XJLVw6b2.js +0 -1
  152. package/dist/_frontend/assets/AgentSessionEventTimelineChart-K3HU6HSO-XJLVw6b2.js.br +0 -0
  153. package/dist/_frontend/assets/AgentSessionEventTimelineChart-K3HU6HSO-XJLVw6b2.js.gz +0 -0
  154. package/dist/_frontend/assets/AgentSessions-5AD6ZDRM-C5RT7EY0.js +0 -1
  155. package/dist/_frontend/assets/AgentSessions-5AD6ZDRM-C5RT7EY0.js.br +0 -0
  156. package/dist/_frontend/assets/AgentSessions-5AD6ZDRM-C5RT7EY0.js.gz +0 -0
  157. package/dist/_frontend/assets/ConnectorSettings-FAMLKHRT-CbgoOQBA.js.br +0 -0
  158. package/dist/_frontend/assets/ConnectorSettings-FAMLKHRT-CbgoOQBA.js.gz +0 -0
  159. package/dist/_frontend/assets/DockLayout-6X5P5E3T-DKDOGTZ4.js +0 -1
  160. package/dist/_frontend/assets/DrawerLayout-MB3JP4YC-Cs4K8WbP.js.br +0 -0
  161. package/dist/_frontend/assets/DrawerLayout-MB3JP4YC-Cs4K8WbP.js.gz +0 -0
  162. package/dist/_frontend/assets/EnvironmentsPage-AD3I5BXA-B1Bwzgoh.js +0 -3
  163. package/dist/_frontend/assets/EnvironmentsPage-AD3I5BXA-B1Bwzgoh.js.br +0 -0
  164. package/dist/_frontend/assets/EnvironmentsPage-AD3I5BXA-B1Bwzgoh.js.gz +0 -0
  165. package/dist/_frontend/assets/ModelSettings-KYX762EG-fzXe6Th3.js.br +0 -0
  166. package/dist/_frontend/assets/ModelSettings-KYX762EG-fzXe6Th3.js.gz +0 -0
  167. package/dist/_frontend/assets/SandboxSettings-ZE4Z65F5-RaO5UYxl.js.br +0 -0
  168. package/dist/_frontend/assets/SandboxSettings-ZE4Z65F5-RaO5UYxl.js.gz +0 -0
  169. package/dist/_frontend/assets/SchedulesPage-QI2TK6XX-C_OjU_1-.js +0 -1
  170. package/dist/_frontend/assets/SchedulesPage-QI2TK6XX-C_OjU_1-.js.br +0 -0
  171. package/dist/_frontend/assets/SchedulesPage-QI2TK6XX-C_OjU_1-.js.gz +0 -0
  172. package/dist/_frontend/assets/SettingsBuilder-OTFRXULU-Cc6qAu_o.js +0 -2
  173. package/dist/_frontend/assets/SettingsBuilder-OTFRXULU-Cc6qAu_o.js.br +0 -0
  174. package/dist/_frontend/assets/SettingsBuilder-OTFRXULU-Cc6qAu_o.js.gz +0 -0
  175. package/dist/_frontend/assets/ShellRouteSync-ZNUJRPCZ-7PDpM3Tt.js +0 -1
  176. package/dist/_frontend/assets/ShellRouteSync-ZNUJRPCZ-7PDpM3Tt.js.br +0 -0
  177. package/dist/_frontend/assets/ShellRouteSync-ZNUJRPCZ-7PDpM3Tt.js.gz +0 -0
  178. package/dist/_frontend/assets/SidebarLayout-WMJUGCNE-DlivhNaL.js +0 -2
  179. package/dist/_frontend/assets/SidebarLayout-WMJUGCNE-DlivhNaL.js.br +0 -0
  180. package/dist/_frontend/assets/SidebarLayout-WMJUGCNE-DlivhNaL.js.gz +0 -0
  181. package/dist/_frontend/assets/SkillSettings-V2YF42KU-BJs98jMY.js +0 -1
  182. package/dist/_frontend/assets/SkillSettings-V2YF42KU-BJs98jMY.js.br +0 -0
  183. package/dist/_frontend/assets/SkillSettings-V2YF42KU-BJs98jMY.js.gz +0 -0
  184. package/dist/_frontend/assets/WebSearchSettings-LFQ4V4FB-D7w_63MH.js.br +0 -0
  185. package/dist/_frontend/assets/WebSearchSettings-LFQ4V4FB-D7w_63MH.js.gz +0 -0
  186. package/dist/_frontend/assets/WidgetLayout-TB2YRZUR-Bymizc6I.js +0 -1
  187. package/dist/_frontend/assets/WidgetLayout-TB2YRZUR-Bymizc6I.js.br +0 -0
  188. package/dist/_frontend/assets/WidgetLayout-TB2YRZUR-Bymizc6I.js.gz +0 -0
  189. package/dist/_frontend/assets/chunk-4BKRLRXL-DLUyrNQ3.js.br +0 -0
  190. package/dist/_frontend/assets/chunk-4BKRLRXL-DLUyrNQ3.js.gz +0 -0
  191. package/dist/_frontend/assets/chunk-OB3PAWPO-D3Luy7W3.js.br +0 -0
  192. package/dist/_frontend/assets/chunk-OB3PAWPO-D3Luy7W3.js.gz +0 -0
  193. package/dist/_frontend/assets/chunk-W7NO436B-9jA-ex4y.js +0 -1
  194. package/dist/_frontend/assets/chunk-W7NO436B-9jA-ex4y.js.br +0 -0
  195. package/dist/_frontend/assets/chunk-W7NO436B-9jA-ex4y.js.gz +0 -0
  196. package/dist/_frontend/assets/chunk-ZSP5XG3J-9vEyCWu1.js.br +0 -0
  197. package/dist/_frontend/assets/chunk-ZSP5XG3J-9vEyCWu1.js.gz +0 -0
  198. package/dist/_frontend/assets/cssMode-JOuT28rz.js.br +0 -0
  199. package/dist/_frontend/assets/cssMode-JOuT28rz.js.gz +0 -0
  200. package/dist/_frontend/assets/freemarker2-CZJ58vDF.js.br +0 -0
  201. package/dist/_frontend/assets/freemarker2-CZJ58vDF.js.gz +0 -0
  202. package/dist/_frontend/assets/handlebars-CUvie110.js.br +0 -0
  203. package/dist/_frontend/assets/handlebars-CUvie110.js.gz +0 -0
  204. package/dist/_frontend/assets/html-DD_vjw5l.js.br +0 -0
  205. package/dist/_frontend/assets/html-DD_vjw5l.js.gz +0 -0
  206. package/dist/_frontend/assets/htmlMode-Bs5cHvWx.js.br +0 -0
  207. package/dist/_frontend/assets/htmlMode-Bs5cHvWx.js.gz +0 -0
  208. package/dist/_frontend/assets/index-IV_K3kGI.js.br +0 -0
  209. package/dist/_frontend/assets/index-IV_K3kGI.js.gz +0 -0
  210. package/dist/_frontend/assets/index-JVnCghrh.js +0 -18
  211. package/dist/_frontend/assets/index-JVnCghrh.js.br +0 -0
  212. package/dist/_frontend/assets/index-JVnCghrh.js.gz +0 -0
  213. package/dist/_frontend/assets/index-PV6Uc-B5.js +0 -1000
  214. package/dist/_frontend/assets/index-PV6Uc-B5.js.br +0 -0
  215. package/dist/_frontend/assets/index-PV6Uc-B5.js.gz +0 -0
  216. package/dist/_frontend/assets/jsonMode-8OQdDgk6.js.br +0 -0
  217. package/dist/_frontend/assets/jsonMode-8OQdDgk6.js.gz +0 -0
  218. package/dist/_frontend/assets/liquid-BAdDEBi9.js.br +0 -0
  219. package/dist/_frontend/assets/liquid-BAdDEBi9.js.gz +0 -0
  220. package/dist/_frontend/assets/lspLanguageFeatures-CNxTXCEe.js.br +0 -0
  221. package/dist/_frontend/assets/lspLanguageFeatures-CNxTXCEe.js.gz +0 -0
  222. package/dist/_frontend/assets/mdx-zRCES-UR.js.br +0 -0
  223. package/dist/_frontend/assets/mdx-zRCES-UR.js.gz +0 -0
  224. package/dist/_frontend/assets/python-CHTiGyj6.js.br +0 -0
  225. package/dist/_frontend/assets/python-CHTiGyj6.js.gz +0 -0
  226. package/dist/_frontend/assets/razor-CU2s7Hbi.js.br +0 -0
  227. package/dist/_frontend/assets/razor-CU2s7Hbi.js.gz +0 -0
  228. package/dist/_frontend/assets/tsMode-CJLsaAN3.js.br +0 -0
  229. package/dist/_frontend/assets/tsMode-CJLsaAN3.js.gz +0 -0
  230. package/dist/_frontend/assets/typescript-C6qGKHm0.js.br +0 -0
  231. package/dist/_frontend/assets/typescript-C6qGKHm0.js.gz +0 -0
  232. package/dist/_frontend/assets/workers-DeOwcFUN.js.br +0 -0
  233. package/dist/_frontend/assets/workers-DeOwcFUN.js.gz +0 -0
  234. package/dist/_frontend/assets/xml-ccL_LPm9.js.br +0 -0
  235. package/dist/_frontend/assets/xml-ccL_LPm9.js.gz +0 -0
  236. package/dist/_frontend/assets/yaml-YzcQ27WY.js.br +0 -0
  237. package/dist/_frontend/assets/yaml-YzcQ27WY.js.gz +0 -0
package/dist/main.js CHANGED
@@ -12,12 +12,27 @@ var __export = (target, all) => {
12
12
  var redis_exports = {};
13
13
  __export(redis_exports, {
14
14
  connectRedis: () => connectRedis,
15
+ enableRedisOpenTelemetry: () => enableRedisOpenTelemetry,
15
16
  parseRedisSentinelNodes: () => parseRedisSentinelNodes
16
17
  });
17
18
  import { existsSync as existsSync2, readFileSync } from "fs";
18
19
  import { setTimeout as sleep } from "timers/promises";
19
20
  import { extractErrorLogFields } from "@truefoundry/trueforge-core/core";
20
- import { createClient, createSentinel } from "redis";
21
+ import { createClient, createSentinel, OpenTelemetry } from "redis";
22
+ function enableRedisOpenTelemetry() {
23
+ if (redisMetricsEnabled) {
24
+ return;
25
+ }
26
+ OpenTelemetry.init({
27
+ metrics: {
28
+ enabled: true,
29
+ enabledMetricGroups: ["command", "connection-basic", "connection-advanced", "resiliency", "pubsub", "streaming"],
30
+ hidePubSubChannelNames: true,
31
+ hideStreamNames: true
32
+ }
33
+ });
34
+ redisMetricsEnabled = true;
35
+ }
21
36
  function parseRedisSentinelNodes(raw) {
22
37
  return raw.split(",").map((entry) => entry.trim()).filter(Boolean).map((entry) => {
23
38
  const lastColon = entry.lastIndexOf(":");
@@ -88,7 +103,10 @@ async function connectSentinelWithRetry(input) {
88
103
  }
89
104
  });
90
105
  client2.on("error", (error) => {
91
- input.logger.error("[Redis] Client error", extractErrorLogFields(error));
106
+ input.logger.error("[Redis] Client error", {
107
+ ...extractErrorLogFields(error),
108
+ reportable_error: { error }
109
+ });
92
110
  });
93
111
  try {
94
112
  await client2.connect();
@@ -105,7 +123,8 @@ async function connectSentinelWithRetry(input) {
105
123
  }
106
124
  input.logger.error("[Redis] Sentinel connect failed, rebuilding and retrying", {
107
125
  attempt,
108
- ...extractErrorLogFields(error)
126
+ ...extractErrorLogFields(error),
127
+ reportable_error: { error, extra: { attempt } }
109
128
  });
110
129
  await sleep(Math.min(SENTINEL_RETRY_BASE_MS * 2 ** attempt, SENTINEL_RETRY_MAX_MS));
111
130
  }
@@ -137,7 +156,10 @@ async function connectRedis(input) {
137
156
  socket: { connectTimeout: input.connectTimeoutMs, ...socketTls ?? {} }
138
157
  });
139
158
  created.on("error", (error) => {
140
- input.logger.error("[Redis] Client error", extractErrorLogFields(error));
159
+ input.logger.error("[Redis] Client error", {
160
+ ...extractErrorLogFields(error),
161
+ reportable_error: { error }
162
+ });
141
163
  });
142
164
  await created.connect();
143
165
  input.logger.info("Connected to Redis");
@@ -146,10 +168,11 @@ async function connectRedis(input) {
146
168
  }
147
169
  }
148
170
  }
149
- var DEFAULT_SENTINEL_PORT, SENTINEL_RETRY_BASE_MS, SENTINEL_RETRY_MAX_MS, PEM_MARKER;
171
+ var redisMetricsEnabled, DEFAULT_SENTINEL_PORT, SENTINEL_RETRY_BASE_MS, SENTINEL_RETRY_MAX_MS, PEM_MARKER;
150
172
  var init_redis = __esm({
151
173
  "src/runtime/redis.ts"() {
152
174
  "use strict";
175
+ redisMetricsEnabled = false;
153
176
  DEFAULT_SENTINEL_PORT = 26379;
154
177
  SENTINEL_RETRY_BASE_MS = 200;
155
178
  SENTINEL_RETRY_MAX_MS = 3e3;
@@ -3136,6 +3159,7 @@ var init_schedule = __esm({
3136
3159
  created_by_subject: CreatedBySubjectSchema3,
3137
3160
  triggered_at: NullableIsoTimestamp,
3138
3161
  reason: z27.string().nullable(),
3162
+ session_id: z27.string().nullable(),
3139
3163
  created_at: IsoTimestamp2,
3140
3164
  updated_at: IsoTimestamp2
3141
3165
  }).strict().openapi("ScheduleRun");
@@ -3479,14 +3503,32 @@ var init_sessionMetricsStore = __esm({
3479
3503
  });
3480
3504
 
3481
3505
  // src/db/modelProviderStore.ts
3506
+ function modelPropertiesWarning(input) {
3507
+ const missing = [];
3508
+ if (input.properties.reasoning_efforts === void 0 || input.properties.reasoning_efforts.length === 0) {
3509
+ missing.push("reasoning effort");
3510
+ }
3511
+ if (input.properties.context_length === void 0) {
3512
+ missing.push("context length");
3513
+ }
3514
+ if (missing.length === 0) {
3515
+ return void 0;
3516
+ }
3517
+ const missingText = missing.join(" and ");
3518
+ return `${missingText.charAt(0).toUpperCase()}${missingText.slice(1)} ${missing.length > 1 ? "are" : "is"} not configured for this model, which may affect TrueForge's performance.`;
3519
+ }
3482
3520
  function flattenProviderModels(records) {
3483
3521
  return records.flatMap(
3484
- (record) => record.manifest.models.map((model) => ({
3485
- name: `${record.name}/${model.name}`,
3486
- model_id: model.model_id,
3487
- provider: { name: record.name },
3488
- properties: model.properties
3489
- }))
3522
+ (record) => record.manifest.models.map((model) => {
3523
+ const warning = modelPropertiesWarning({ properties: model.properties });
3524
+ return {
3525
+ name: `${record.name}/${model.name}`,
3526
+ model_id: model.model_id,
3527
+ provider: { name: record.name },
3528
+ properties: model.properties,
3529
+ ...warning === void 0 ? {} : { warning }
3530
+ };
3531
+ })
3490
3532
  );
3491
3533
  }
3492
3534
  var ModelProviderNameConflictError;
@@ -3628,6 +3670,7 @@ __export(client_exports, {
3628
3670
  isPgErrorCode: () => isPgErrorCode,
3629
3671
  isUniqueViolation: () => isUniqueViolation
3630
3672
  });
3673
+ import { getOperationMetrics as getOperationMetrics3 } from "@truefoundry/trueforge-core/core";
3631
3674
  import { Kysely, PostgresDialect } from "kysely";
3632
3675
  import pg, { Pool } from "pg";
3633
3676
  function parseInt8Array(value) {
@@ -3660,7 +3703,13 @@ function createDb(options) {
3660
3703
  return new Kysely({
3661
3704
  dialect: new PostgresDialect({
3662
3705
  pool
3663
- })
3706
+ }),
3707
+ log(event) {
3708
+ getOperationMetrics3()?.recordPostgresQuery({
3709
+ outcome: event.level === "error" ? "error" : "success",
3710
+ durationSeconds: event.queryDurationMillis / 1e3
3711
+ });
3712
+ }
3664
3713
  });
3665
3714
  }
3666
3715
  function isPgErrorCode(err, code) {
@@ -4037,6 +4086,7 @@ var init_client2 = __esm({
4037
4086
  "custom",
4038
4087
  "metadata",
4039
4088
  "metrics",
4089
+ "last_turn_details",
4040
4090
  "ancestor_ids",
4041
4091
  "input",
4042
4092
  "state",
@@ -4167,6 +4217,7 @@ var init_sqlExpressions3 = __esm({
4167
4217
  });
4168
4218
 
4169
4219
  // src/db/sqlite/session-store/queries/turns.ts
4220
+ import { SessionLastTurnDetailsSchema } from "@truefoundry/trueforge-core/agent-session";
4170
4221
  import {
4171
4222
  isNonTerminalTurnState
4172
4223
  } from "@truefoundry/trueforge-core/agent-session/schemas/turn";
@@ -4195,22 +4246,35 @@ function parseTurnCustom(value) {
4195
4246
  }
4196
4247
  return value;
4197
4248
  }
4198
- async function addSessionCostAndDuration(trx, input) {
4199
- const elapsed_ms = Date.parse(input.turn_state.completed_at) - input.turn_created_at.getTime();
4200
- const total_duration_ms = elapsed_ms > 0 ? Math.trunc(elapsed_ms) : 0;
4201
- const turnCost = input.turn_state.metrics?.total_cost_in_usd;
4202
- const withDuration = sql5`jsonb_set(
4203
- metrics,
4204
- '$.total_duration_ms',
4205
- jsonb((metrics->>'total_duration_ms') + ${total_duration_ms})
4206
- )`;
4249
+ function lastTurnDetails(input) {
4250
+ return jsonbBind(SessionLastTurnDetailsSchema.parse({ id: input.turn_id, state: input.turn_state }));
4251
+ }
4252
+ async function applyTurnStateToSession(trx, input) {
4253
+ let metrics2;
4254
+ if (!isNonTerminalTurnState(input.turn_state)) {
4255
+ const elapsed_ms = Date.parse(input.turn_state.completed_at) - input.turn_created_at.getTime();
4256
+ const total_duration_ms = elapsed_ms > 0 ? Math.trunc(elapsed_ms) : 0;
4257
+ const turnCost = input.turn_state.metrics?.total_cost_in_usd;
4258
+ metrics2 = sql5`jsonb_set(
4259
+ metrics,
4260
+ '$.total_duration_ms',
4261
+ jsonb((metrics->>'total_duration_ms') + ${total_duration_ms})
4262
+ )`;
4263
+ if (turnCost !== void 0) {
4264
+ metrics2 = sql5`jsonb_set(
4265
+ ${metrics2},
4266
+ '$.total_cost_in_usd',
4267
+ jsonb(COALESCE(metrics->>'total_cost_in_usd', 0) + ${turnCost})
4268
+ )`;
4269
+ }
4270
+ }
4207
4271
  await trx.updateTable("session").set({
4208
- metrics: turnCost === void 0 ? withDuration : sql5`jsonb_set(
4209
- ${withDuration},
4210
- '$.total_cost_in_usd',
4211
- jsonb(COALESCE(metrics->>'total_cost_in_usd', 0) + ${turnCost})
4212
- )`
4213
- }).where("session_id", "=", input.session_id).execute();
4272
+ last_turn_details: sql5`CASE
4273
+ WHEN json_extract(last_turn_details, '$.id') = ${input.turn_id} THEN ${lastTurnDetails(input)}
4274
+ ELSE last_turn_details
4275
+ END`,
4276
+ ...metrics2 === void 0 ? {} : { metrics: metrics2 }
4277
+ }).where("session_id", "=", input.id).execute();
4214
4278
  }
4215
4279
  function terminalTurnState(state, turn_id) {
4216
4280
  switch (state.status) {
@@ -4358,6 +4422,7 @@ async function createTurn(db, input) {
4358
4422
  }
4359
4423
  let sessionUpdate = trx.updateTable("session").set({
4360
4424
  last_turn_id: input.turn.turn_id,
4425
+ last_turn_details: lastTurnDetails({ turn_id: input.turn.turn_id, turn_state: input.turn.state }),
4361
4426
  updated_at: nowIso(),
4362
4427
  last_activity_timestamp_ms: input.last_activity_timestamp_ms,
4363
4428
  // total_turns rides the same tip UPDATE so a later failure in this tx rolls it back.
@@ -4604,8 +4669,9 @@ async function freezeAndGetTurn(db, input) {
4604
4669
  event: jsonbBind(input.turn_done_event),
4605
4670
  created_at: input.turn_done_event.created_at
4606
4671
  }).execute();
4607
- await addSessionCostAndDuration(trx, {
4608
- session_id: input.session_id,
4672
+ await applyTurnStateToSession(trx, {
4673
+ id: input.session_id,
4674
+ turn_id: input.turn_id,
4609
4675
  turn_created_at: new Date(updateResult.created_at),
4610
4676
  turn_state: cancelledState
4611
4677
  });
@@ -4660,7 +4726,7 @@ async function updateTurnNonTerminalState(db, input) {
4660
4726
  const result = await trx.updateTable("turn").set({
4661
4727
  state: jsonbBind(input.state),
4662
4728
  updated_at: nowIso()
4663
- }).where("session_id", "=", input.session_id).where("turn_id", "=", input.turn_id).where(sql5`state->>'status' = ${expectedSourceStatus}`).returning("turn_id").executeTakeFirst();
4729
+ }).where("session_id", "=", input.session_id).where("turn_id", "=", input.turn_id).where(sql5`state->>'status' = ${expectedSourceStatus}`).returning(["created_at"]).executeTakeFirst();
4664
4730
  if (result === void 0) {
4665
4731
  const existing = await trx.selectFrom("turn").select([jsonText(sql5.ref("state")).as("state")]).where("session_id", "=", input.session_id).where("turn_id", "=", input.turn_id).executeTakeFirst();
4666
4732
  if (!existing) {
@@ -4680,6 +4746,12 @@ async function updateTurnNonTerminalState(db, input) {
4680
4746
  event: jsonbBind(input.turn_update_event),
4681
4747
  created_at: input.turn_update_event.created_at
4682
4748
  }).execute();
4749
+ await applyTurnStateToSession(trx, {
4750
+ id: input.session_id,
4751
+ turn_id: input.turn_id,
4752
+ turn_created_at: new Date(result.created_at),
4753
+ turn_state: input.state
4754
+ });
4683
4755
  });
4684
4756
  }
4685
4757
  async function updateTurnTerminalState(db, input) {
@@ -4695,8 +4767,9 @@ async function updateTurnTerminalState(db, input) {
4695
4767
  }
4696
4768
  throw new TurnNotRunningError(input.turn_id, terminalTurnState(existing.state, input.turn_id));
4697
4769
  }
4698
- await addSessionCostAndDuration(trx, {
4699
- session_id: input.session_id,
4770
+ await applyTurnStateToSession(trx, {
4771
+ id: input.session_id,
4772
+ turn_id: input.turn_id,
4700
4773
  turn_created_at: new Date(result.created_at),
4701
4774
  turn_state: input.state
4702
4775
  });
@@ -4989,6 +5062,7 @@ var init_sessionAgentColumns = __esm({
4989
5062
  // src/db/sqlite/session-store/queries/sessions.ts
4990
5063
  import {
4991
5064
  CreatedBySubjectSchema as CreatedBySubjectSchema5,
5065
+ SessionLastTurnDetailsSchema as SessionLastTurnDetailsSchema2,
4992
5066
  SessionMetadataSchema as SessionMetadataSchema2,
4993
5067
  SessionSourceSchema
4994
5068
  } from "@truefoundry/trueforge-core/agent-session";
@@ -5033,6 +5107,7 @@ function mapRowToSessionRecord(row) {
5033
5107
  title: row.title,
5034
5108
  shared: row.shared !== 0,
5035
5109
  last_turn_id: row.last_turn_id,
5110
+ last_turn_details: SessionLastTurnDetailsSchema2.nullable().parse(row.last_turn_details),
5036
5111
  external_id: row.external_id,
5037
5112
  custom: parseSessionCustom(row.custom),
5038
5113
  metadata: parseSessionMetadata(row.metadata),
@@ -5054,6 +5129,7 @@ function sessionSelectColumns() {
5054
5129
  "title",
5055
5130
  "shared",
5056
5131
  "last_turn_id",
5132
+ jsonText(sql8.ref("last_turn_details")).as("last_turn_details"),
5057
5133
  "external_id",
5058
5134
  jsonText(sql8.ref("custom")).as("custom"),
5059
5135
  jsonText(sql8.ref("metadata")).as("metadata"),
@@ -6506,6 +6582,7 @@ function runColumns(eb) {
6506
6582
  jsonText(eb.ref("created_by_subject")).as("created_by_subject"),
6507
6583
  "triggered_at",
6508
6584
  "reason",
6585
+ "session_id",
6509
6586
  "created_at",
6510
6587
  "updated_at"
6511
6588
  ];
@@ -6656,13 +6733,16 @@ var init_SqliteScheduleStore = __esm({
6656
6733
  const { data, pagination } = paginateOffsetRows4(rows, input.limit, offset);
6657
6734
  return { data: data.map(toScheduleRecord), pagination };
6658
6735
  }
6659
- async getOwnedIds(input, transaction) {
6736
+ async getSchedulesByIds(input, transaction) {
6660
6737
  if (input.ids.length === 0) {
6661
6738
  return [];
6662
6739
  }
6663
6740
  const db = transaction ?? this.#db;
6664
- const rows = await db.selectFrom("schedule").select("id").where("tenant_id", "=", input.tenant_id).where("id", "in", [...input.ids]).where(sql14`json_extract(created_by_subject, '$.subject_id')`, "=", input.subject_id).execute();
6665
- return rows.map((row) => row.id);
6741
+ const rows = await db.selectFrom("schedule").select(["id", jsonText(sql14.ref("created_by_subject")).as("created_by_subject")]).where("tenant_id", "=", input.tenant_id).where("id", "in", [...input.ids]).execute();
6742
+ return rows.map((row) => ({
6743
+ id: row.id,
6744
+ created_by_subject: CreatedBySubjectSchema7.parse(row.created_by_subject)
6745
+ }));
6666
6746
  }
6667
6747
  async listRuns(input, transaction) {
6668
6748
  const offset = decodeOffsetPageToken5(input.page_token);
@@ -6700,6 +6780,7 @@ var init_SqliteScheduleStore = __esm({
6700
6780
  created_by_subject: jsonbBind(input.created_by_subject),
6701
6781
  triggered_at: input.triggered_at?.toISOString() ?? null,
6702
6782
  reason: input.reason ?? null,
6783
+ session_id: null,
6703
6784
  created_at: timestamp,
6704
6785
  updated_at: timestamp
6705
6786
  }).returning(runColumns).executeTakeFirstOrThrow();
@@ -6711,11 +6792,20 @@ var init_SqliteScheduleStore = __esm({
6711
6792
  throw error;
6712
6793
  }
6713
6794
  }
6714
- async updateRunStatus(input, transaction) {
6795
+ async updateRun(input, transaction) {
6715
6796
  const db = transaction ?? this.#db;
6716
6797
  const timestamp = nowIso();
6717
- const reason = input.status === "failed" ? input.reason ?? null : null;
6718
- const patch = input.status === "triggered" ? { status: input.status, triggered_at: timestamp, reason, updated_at: timestamp } : { status: input.status, reason, updated_at: timestamp };
6798
+ const patch = { updated_at: timestamp };
6799
+ if (input.status !== void 0) {
6800
+ patch.status = input.status;
6801
+ patch.reason = input.status === "failed" ? input.reason ?? null : null;
6802
+ if (input.status === "triggered") {
6803
+ patch.triggered_at = timestamp;
6804
+ }
6805
+ }
6806
+ if (input.session_id !== void 0) {
6807
+ patch.session_id = input.session_id;
6808
+ }
6719
6809
  const row = await db.updateTable("schedule_run").set(patch).where("tenant_id", "=", input.tenant_id).where("id", "=", input.id).returning(runColumns).executeTakeFirst();
6720
6810
  return row === void 0 ? void 0 : toRunRecord(row);
6721
6811
  }
@@ -6913,6 +7003,18 @@ var init_SqliteSandboxEnvironmentStore = __esm({
6913
7003
  }
6914
7004
  return this.#withMountedSecrets(toWithVersion(row), db);
6915
7005
  }
7006
+ async getEnvironmentsByIds(input, transaction) {
7007
+ if (input.ids.length === 0) {
7008
+ return [];
7009
+ }
7010
+ const db = transaction ?? this.#db;
7011
+ const rows = await db.selectFrom("sandbox_environment").select(["id", "name", jsonText(sql15.ref("created_by_subject")).as("created_by_subject")]).where("tenant_id", "=", input.tenant_id).where("id", "in", [...input.ids]).where("lifecycle_stage", "=", "active").execute();
7012
+ return rows.map((row) => ({
7013
+ id: row.id,
7014
+ name: row.name,
7015
+ created_by_subject: CreatedBySubjectSchema8.parse(row.created_by_subject)
7016
+ }));
7017
+ }
6916
7018
  async getActiveEnvironment(input, transaction) {
6917
7019
  const db = transaction ?? this.#db;
6918
7020
  let query = activeVersionJoin(db).where("env.tenant_id", "=", input.tenant_id).where("env.name", "=", input.name).where("env.lifecycle_stage", "=", "active");
@@ -7133,7 +7235,7 @@ var init_SqliteSandboxEnvironmentStore = __esm({
7133
7235
  return this.#db.transaction().execute((db) => this.#deleteEnvironment(input, db));
7134
7236
  }
7135
7237
  async #deleteEnvironment(input, db) {
7136
- const environment = await db.selectFrom("sandbox_environment").select("id").where("tenant_id", "=", input.tenant_id).where("name", "=", input.name).where("lifecycle_stage", "=", "active").where(sql15`json_extract(created_by_subject, '$.subject_id')`, "=", input.created_by_subject_id).executeTakeFirst();
7238
+ const environment = await db.selectFrom("sandbox_environment").select("id").where("tenant_id", "=", input.tenant_id).where("name", "=", input.name).where("lifecycle_stage", "=", "active").executeTakeFirst();
7137
7239
  if (environment === void 0) {
7138
7240
  return;
7139
7241
  }
@@ -7357,6 +7459,9 @@ var init_sqlExpressions4 = __esm({
7357
7459
  });
7358
7460
 
7359
7461
  // src/db/postgres/session-store/queries/turns.ts
7462
+ import {
7463
+ SessionLastTurnDetailsSchema as SessionLastTurnDetailsSchema3
7464
+ } from "@truefoundry/trueforge-core/agent-session";
7360
7465
  import {
7361
7466
  isNonTerminalTurnState as isNonTerminalTurnState2
7362
7467
  } from "@truefoundry/trueforge-core/agent-session/schemas/turn";
@@ -7392,22 +7497,35 @@ function incrementSessionTotalTurns() {
7392
7497
  sql17`to_jsonb((metrics->>'total_turns')::int + 1)`
7393
7498
  );
7394
7499
  }
7395
- async function addSessionCostAndDuration2(trx, input) {
7396
- const elapsed_ms = Date.parse(input.turn_state.completed_at) - input.turn_created_at.getTime();
7397
- const total_duration_ms = elapsed_ms > 0 ? Math.trunc(elapsed_ms) : 0;
7398
- const turnCost = input.turn_state.metrics?.total_cost_in_usd;
7399
- const withDuration = jsonbSet(
7400
- sql17`metrics`,
7401
- sql17`'{total_duration_ms}'`,
7402
- sql17`to_jsonb((metrics->>'total_duration_ms')::bigint + ${total_duration_ms}::bigint)`
7403
- );
7500
+ function lastTurnDetails2(input) {
7501
+ return json(SessionLastTurnDetailsSchema3.parse({ id: input.turn_id, state: input.turn_state }));
7502
+ }
7503
+ async function applyTurnStateToSession2(trx, input) {
7504
+ let metrics2;
7505
+ if (!isNonTerminalTurnState2(input.turn_state)) {
7506
+ const elapsed_ms = Date.parse(input.turn_state.completed_at) - input.turn_created_at.getTime();
7507
+ const total_duration_ms = elapsed_ms > 0 ? Math.trunc(elapsed_ms) : 0;
7508
+ const turnCost = input.turn_state.metrics?.total_cost_in_usd;
7509
+ metrics2 = jsonbSet(
7510
+ sql17`metrics`,
7511
+ sql17`'{total_duration_ms}'`,
7512
+ sql17`to_jsonb((metrics->>'total_duration_ms')::bigint + ${total_duration_ms}::bigint)`
7513
+ );
7514
+ if (turnCost !== void 0) {
7515
+ metrics2 = jsonbSet(
7516
+ metrics2,
7517
+ sql17`'{total_cost_in_usd}'`,
7518
+ sql17`to_jsonb(COALESCE((metrics->>'total_cost_in_usd')::double precision, 0) + ${turnCost}::double precision)`
7519
+ );
7520
+ }
7521
+ }
7404
7522
  await trx.updateTable("session").set({
7405
- metrics: turnCost === void 0 ? withDuration : jsonbSet(
7406
- withDuration,
7407
- sql17`'{total_cost_in_usd}'`,
7408
- sql17`to_jsonb(COALESCE((metrics->>'total_cost_in_usd')::double precision, 0) + ${turnCost}::double precision)`
7409
- )
7410
- }).where("session_id", "=", input.session_id).execute();
7523
+ last_turn_details: sql17`CASE
7524
+ WHEN last_turn_details->>'id' = ${input.turn_id} THEN ${lastTurnDetails2(input)}
7525
+ ELSE last_turn_details
7526
+ END`,
7527
+ ...metrics2 === void 0 ? {} : { metrics: metrics2 }
7528
+ }).where("session_id", "=", input.id).execute();
7411
7529
  }
7412
7530
  function terminalTurnState2(state, turn_id) {
7413
7531
  switch (state.status) {
@@ -7528,6 +7646,7 @@ async function createTurn2(db, input) {
7528
7646
  }
7529
7647
  await trx.updateTable("session").set({
7530
7648
  last_turn_id: input.turn.turn_id,
7649
+ last_turn_details: lastTurnDetails2({ turn_id: input.turn.turn_id, turn_state: input.turn.state }),
7531
7650
  updated_at: sql17`now()`,
7532
7651
  last_activity_timestamp_ms: input.last_activity_timestamp_ms,
7533
7652
  // total_turns rides the same tip UPDATE so a later failure in this tx rolls it back.
@@ -7723,8 +7842,9 @@ async function freezeAndGetTurn2(db, input) {
7723
7842
  event: json(input.turn_done_event),
7724
7843
  created_at: new Date(input.turn_done_event.created_at)
7725
7844
  }).execute();
7726
- await addSessionCostAndDuration2(trx, {
7727
- session_id: input.session_id,
7845
+ await applyTurnStateToSession2(trx, {
7846
+ id: input.session_id,
7847
+ turn_id: input.turn_id,
7728
7848
  turn_created_at: updateResult.created_at,
7729
7849
  turn_state: cancelledState
7730
7850
  });
@@ -7769,7 +7889,7 @@ async function updateTurnNonTerminalState2(db, input) {
7769
7889
  const result = await trx.updateTable("turn").set({
7770
7890
  state: input.state,
7771
7891
  updated_at: sql17`now()`
7772
- }).where("session_id", "=", input.session_id).where("turn_id", "=", input.turn_id).where(sql17`state->>'status' = ${expectedSourceStatus}`).returning("turn_id").executeTakeFirst();
7892
+ }).where("session_id", "=", input.session_id).where("turn_id", "=", input.turn_id).where(sql17`state->>'status' = ${expectedSourceStatus}`).returning(["created_at"]).executeTakeFirst();
7773
7893
  if (result === void 0) {
7774
7894
  const existing = await trx.selectFrom("turn").select("state").where("session_id", "=", input.session_id).where("turn_id", "=", input.turn_id).executeTakeFirst();
7775
7895
  if (!existing) {
@@ -7789,6 +7909,12 @@ async function updateTurnNonTerminalState2(db, input) {
7789
7909
  event: json(input.turn_update_event),
7790
7910
  created_at: new Date(input.turn_update_event.created_at)
7791
7911
  }).execute();
7912
+ await applyTurnStateToSession2(trx, {
7913
+ id: input.session_id,
7914
+ turn_id: input.turn_id,
7915
+ turn_created_at: result.created_at,
7916
+ turn_state: input.state
7917
+ });
7792
7918
  });
7793
7919
  }
7794
7920
  async function updateTurnTerminalState2(db, input) {
@@ -7804,8 +7930,9 @@ async function updateTurnTerminalState2(db, input) {
7804
7930
  }
7805
7931
  throw new TurnNotRunningError2(input.turn_id, terminalTurnState2(existing.state, input.turn_id));
7806
7932
  }
7807
- await addSessionCostAndDuration2(trx, {
7808
- session_id: input.session_id,
7933
+ await applyTurnStateToSession2(trx, {
7934
+ id: input.session_id,
7935
+ turn_id: input.turn_id,
7809
7936
  turn_created_at: result.created_at,
7810
7937
  turn_state: input.state
7811
7938
  });
@@ -8057,6 +8184,7 @@ var init_inboundEvents2 = __esm({
8057
8184
  // src/db/postgres/session-store/queries/sessions.ts
8058
8185
  import {
8059
8186
  CreatedBySubjectSchema as CreatedBySubjectSchema9,
8187
+ SessionLastTurnDetailsSchema as SessionLastTurnDetailsSchema4,
8060
8188
  SessionMetadataSchema as SessionMetadataSchema3,
8061
8189
  SessionSourceSchema as SessionSourceSchema2
8062
8190
  } from "@truefoundry/trueforge-core/agent-session";
@@ -8101,6 +8229,7 @@ function mapRowToSessionRecord2(row) {
8101
8229
  title: row.title,
8102
8230
  shared: row.shared,
8103
8231
  last_turn_id: row.last_turn_id,
8232
+ last_turn_details: SessionLastTurnDetailsSchema4.nullable().parse(row.last_turn_details),
8104
8233
  external_id: row.external_id,
8105
8234
  custom: parseSessionCustom2(row.custom),
8106
8235
  metadata: parseSessionMetadata2(row.metadata),
@@ -9285,7 +9414,7 @@ import {
9285
9414
  decodeOffsetPageToken as decodeOffsetPageToken9,
9286
9415
  paginateOffsetRows as paginateOffsetRows7
9287
9416
  } from "@truefoundry/trueforge-core/agent-session/store/OffsetPageToken";
9288
- import { sql as sql25 } from "kysely";
9417
+ import "kysely";
9289
9418
  function toScheduleRecord2(row) {
9290
9419
  return {
9291
9420
  id: row.id,
@@ -9311,6 +9440,7 @@ function toRunRecord2(row) {
9311
9440
  created_by_subject: CreatedBySubjectSchema10.parse(row.created_by_subject),
9312
9441
  triggered_at: row.triggered_at === null ? null : row.triggered_at.toISOString(),
9313
9442
  reason: row.reason,
9443
+ session_id: row.session_id,
9314
9444
  created_at: row.created_at.toISOString(),
9315
9445
  updated_at: row.updated_at.toISOString()
9316
9446
  };
@@ -9439,13 +9569,16 @@ var init_PostgresScheduleStore = __esm({
9439
9569
  const { data, pagination } = paginateOffsetRows7(rows, input.limit, offset);
9440
9570
  return { data: data.map(toScheduleRecord2), pagination };
9441
9571
  }
9442
- async getOwnedIds(input, transaction) {
9572
+ async getSchedulesByIds(input, transaction) {
9443
9573
  if (input.ids.length === 0) {
9444
9574
  return [];
9445
9575
  }
9446
9576
  const db = transaction ?? this.#db;
9447
- const rows = await db.selectFrom("schedule").select("id").where("tenant_id", "=", input.tenant_id).where("id", "in", [...input.ids]).where(sql25`created_by_subject->>'subject_id'`, "=", input.subject_id).execute();
9448
- return rows.map((row) => row.id);
9577
+ const rows = await db.selectFrom("schedule").select(["id", "created_by_subject"]).where("tenant_id", "=", input.tenant_id).where("id", "in", [...input.ids]).execute();
9578
+ return rows.map((row) => ({
9579
+ id: row.id,
9580
+ created_by_subject: CreatedBySubjectSchema10.parse(row.created_by_subject)
9581
+ }));
9449
9582
  }
9450
9583
  async listRuns(input, transaction) {
9451
9584
  const offset = decodeOffsetPageToken9(input.page_token);
@@ -9482,6 +9615,7 @@ var init_PostgresScheduleStore = __esm({
9482
9615
  created_by_subject: json(input.created_by_subject),
9483
9616
  triggered_at: input.triggered_at ?? null,
9484
9617
  reason: input.reason ?? null,
9618
+ session_id: null,
9485
9619
  created_at: now(),
9486
9620
  updated_at: now()
9487
9621
  }).returningAll().executeTakeFirstOrThrow();
@@ -9493,11 +9627,20 @@ var init_PostgresScheduleStore = __esm({
9493
9627
  throw error;
9494
9628
  }
9495
9629
  }
9496
- async updateRunStatus(input, transaction) {
9630
+ async updateRun(input, transaction) {
9497
9631
  const db = transaction ?? this.#db;
9498
9632
  const timestamp = now();
9499
- const reason = input.status === "failed" ? input.reason ?? null : null;
9500
- const patch = input.status === "triggered" ? { status: input.status, triggered_at: timestamp, reason, updated_at: timestamp } : { status: input.status, reason, updated_at: timestamp };
9633
+ const patch = { updated_at: timestamp };
9634
+ if (input.status !== void 0) {
9635
+ patch.status = input.status;
9636
+ patch.reason = input.status === "failed" ? input.reason ?? null : null;
9637
+ if (input.status === "triggered") {
9638
+ patch.triggered_at = timestamp;
9639
+ }
9640
+ }
9641
+ if (input.session_id !== void 0) {
9642
+ patch.session_id = input.session_id;
9643
+ }
9501
9644
  const row = await db.updateTable("schedule_run").set(patch).where("tenant_id", "=", input.tenant_id).where("id", "=", input.id).returningAll().executeTakeFirst();
9502
9645
  return row === void 0 ? void 0 : toRunRecord2(row);
9503
9646
  }
@@ -9520,7 +9663,7 @@ import {
9520
9663
  decodeOffsetPageToken as decodeOffsetPageToken10,
9521
9664
  paginateOffsetRows as paginateOffsetRows8
9522
9665
  } from "@truefoundry/trueforge-core/agent-session/store/OffsetPageToken";
9523
- import { sql as sql26 } from "kysely";
9666
+ import { sql as sql25 } from "kysely";
9524
9667
  function toSecretRecord2(row) {
9525
9668
  return {
9526
9669
  id: row.id,
@@ -9613,7 +9756,7 @@ function latestVersionJoin2(db) {
9613
9756
  "ver.created_at as ver_created_at",
9614
9757
  "ver.updated_at as ver_updated_at"
9615
9758
  ]).where(
9616
- sql26`ver.version = (
9759
+ sql25`ver.version = (
9617
9760
  SELECT MAX(latest.version)
9618
9761
  FROM sandbox_environment_version AS latest
9619
9762
  WHERE latest.environment_id = env.id
@@ -9653,7 +9796,7 @@ var init_PostgresSandboxEnvironmentStore = __esm({
9653
9796
  const db = transaction ?? this.#db;
9654
9797
  let query = latestVersionJoin2(db).where("env.tenant_id", "=", input.tenant_id).where("env.name", "=", input.name).where("env.lifecycle_stage", "=", "active");
9655
9798
  if (input.created_by_subject_id && input.name !== DEFAULT_SANDBOX_ENVIRONMENT_NAME) {
9656
- query = query.where(sql26`env.created_by_subject->>'subject_id'`, "=", input.created_by_subject_id);
9799
+ query = query.where(sql25`env.created_by_subject->>'subject_id'`, "=", input.created_by_subject_id);
9657
9800
  }
9658
9801
  const row = await query.executeTakeFirst();
9659
9802
  if (!row) {
@@ -9661,11 +9804,23 @@ var init_PostgresSandboxEnvironmentStore = __esm({
9661
9804
  }
9662
9805
  return this.#withMountedSecrets(toWithVersion2(row), db);
9663
9806
  }
9807
+ async getEnvironmentsByIds(input, transaction) {
9808
+ if (input.ids.length === 0) {
9809
+ return [];
9810
+ }
9811
+ const db = transaction ?? this.#db;
9812
+ const rows = await db.selectFrom("sandbox_environment").select(["id", "name", "created_by_subject"]).where("tenant_id", "=", input.tenant_id).where("id", "in", [...input.ids]).where("lifecycle_stage", "=", "active").execute();
9813
+ return rows.map((row) => ({
9814
+ id: row.id,
9815
+ name: row.name,
9816
+ created_by_subject: CreatedBySubjectSchema11.parse(row.created_by_subject)
9817
+ }));
9818
+ }
9664
9819
  async getActiveEnvironment(input, transaction) {
9665
9820
  const db = transaction ?? this.#db;
9666
9821
  let query = activeVersionJoin2(db).where("env.tenant_id", "=", input.tenant_id).where("env.name", "=", input.name).where("env.lifecycle_stage", "=", "active");
9667
9822
  if (input.created_by_subject_id && input.name !== DEFAULT_SANDBOX_ENVIRONMENT_NAME) {
9668
- query = query.where(sql26`env.created_by_subject->>'subject_id'`, "=", input.created_by_subject_id);
9823
+ query = query.where(sql25`env.created_by_subject->>'subject_id'`, "=", input.created_by_subject_id);
9669
9824
  }
9670
9825
  const row = await query.executeTakeFirst();
9671
9826
  if (!row) {
@@ -9675,7 +9830,7 @@ var init_PostgresSandboxEnvironmentStore = __esm({
9675
9830
  }
9676
9831
  async listLatestPendingVersions(transaction) {
9677
9832
  const db = transaction ?? this.#db;
9678
- const rows = await sql26`
9833
+ const rows = await sql25`
9679
9834
  SELECT version.id
9680
9835
  FROM sandbox_environment_version AS version
9681
9836
  INNER JOIN sandbox_environment AS environment
@@ -9737,7 +9892,7 @@ var init_PostgresSandboxEnvironmentStore = __esm({
9737
9892
  let environmentQuery = db.selectFrom("sandbox_environment").selectAll().where("tenant_id", "=", input.tenant_id).where("name", "=", input.name).where("lifecycle_stage", "=", "active");
9738
9893
  if (!isDefault) {
9739
9894
  environmentQuery = environmentQuery.where(
9740
- sql26`created_by_subject->>'subject_id'`,
9895
+ sql25`created_by_subject->>'subject_id'`,
9741
9896
  "=",
9742
9897
  input.created_by_subject.subject_id
9743
9898
  );
@@ -9848,7 +10003,7 @@ var init_PostgresSandboxEnvironmentStore = __esm({
9848
10003
  return this.#db.transaction().execute((db) => this.#deleteEnvironment(input, db));
9849
10004
  }
9850
10005
  async #deleteEnvironment(input, db) {
9851
- const environment = await db.selectFrom("sandbox_environment").select("id").where("tenant_id", "=", input.tenant_id).where("name", "=", input.name).where("lifecycle_stage", "=", "active").where(sql26`created_by_subject->>'subject_id'`, "=", input.created_by_subject_id).forUpdate().executeTakeFirst();
10006
+ const environment = await db.selectFrom("sandbox_environment").select("id").where("tenant_id", "=", input.tenant_id).where("name", "=", input.name).where("lifecycle_stage", "=", "active").forUpdate().executeTakeFirst();
9852
10007
  if (environment === void 0) {
9853
10008
  return;
9854
10009
  }
@@ -9988,9 +10143,10 @@ var init_PostgresSandboxEnvironmentStore = __esm({
9988
10143
 
9989
10144
  // src/main.ts
9990
10145
  import {
10146
+ configureOperationMetrics,
9991
10147
  configureOutboundFetches,
9992
10148
  configureOutboundUrlGuard,
9993
- extractErrorLogFields as extractErrorLogFields9
10149
+ extractErrorLogFields as extractErrorLogFields10
9994
10150
  } from "@truefoundry/trueforge-core/core";
9995
10151
  import { mkdir as mkdir5 } from "fs/promises";
9996
10152
  import path6 from "path";
@@ -10055,179 +10211,12 @@ import { HTTPException as HTTPException2 } from "hono/http-exception";
10055
10211
 
10056
10212
  // src/truefoundry/errors.ts
10057
10213
  import { HTTPException } from "hono/http-exception";
10058
-
10059
- // src/sentry/captureCriticalException.ts
10060
- import * as Sentry from "@sentry/node";
10061
- function captureCriticalException(err, options) {
10062
- Sentry.withScope((scope) => {
10063
- if (options?.tags) {
10064
- scope.setTags(options.tags);
10065
- }
10066
- if (options?.extra) {
10067
- scope.setExtras(options.extra);
10068
- }
10069
- Sentry.captureException(err);
10070
- });
10071
- }
10072
-
10073
- // src/sentry/initSentry.ts
10074
- init_config();
10075
- import * as Sentry3 from "@sentry/node";
10076
-
10077
- // src/packageVersion.ts
10078
- import { readFileSync as readFileSync3 } from "fs";
10079
- import path2 from "path";
10080
- import { fileURLToPath as fileURLToPath2 } from "url";
10081
- var PACKAGE_ROOT2 = path2.resolve(path2.dirname(fileURLToPath2(import.meta.url)), "..");
10082
- function readPackageVersion() {
10083
- const packageJsonPath = path2.join(PACKAGE_ROOT2, "package.json");
10084
- const parsed = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
10085
- if (typeof parsed !== "object" || parsed === null || !("version" in parsed)) {
10086
- throw new Error(`${packageJsonPath} is missing a version field`);
10087
- }
10088
- const { version } = parsed;
10089
- if (typeof version !== "string" || version.length === 0) {
10090
- throw new Error(`${packageJsonPath} version must be a non-empty string`);
10091
- }
10092
- return version;
10093
- }
10094
- var PACKAGE_VERSION = readPackageVersion();
10095
-
10096
- // src/truefoundry/initTrueFoundrySentry.ts
10097
- init_config();
10098
- import * as Sentry2 from "@sentry/node";
10099
- import { fetch as undiciFetch } from "undici";
10100
- var SENTRY_SERVICE_NAME = "trueforge";
10101
- async function fetchSentryAuth(input) {
10102
- const url = `${input.authServerUrl}/api/v1/tenants/sentry-auth-data`;
10103
- const urlParamsObj = {
10104
- serviceName: SENTRY_SERVICE_NAME
10105
- };
10106
- if (input.tenantName !== void 0 && input.tenantName !== "") {
10107
- urlParamsObj["tenantName"] = input.tenantName;
10108
- }
10109
- const params = new URLSearchParams(urlParamsObj);
10110
- try {
10111
- const res = await undiciFetch(`${url}?${params.toString()}`, {
10112
- headers: { Authorization: `Bearer ${input.apiKey}` },
10113
- signal: AbortSignal.timeout(input.timeoutMs)
10114
- });
10115
- if (res.status !== 200) {
10116
- return void 0;
10117
- }
10118
- return await res.json();
10119
- } catch (err) {
10120
- if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
10121
- throw new Error(`Timed out fetching sentry auth data after ${String(input.timeoutMs)}ms`, { cause: err });
10122
- }
10123
- throw err;
10124
- }
10125
- }
10126
- async function initTrueFoundrySentry(input) {
10127
- const { logger: logger2, tags } = input;
10128
- if (!isTrueFoundryModeEnabled(config_default)) {
10129
- logger2.error("Sentry TrueFoundry init requires TrueFoundry mode; skipping");
10130
- return false;
10131
- }
10132
- const authServerUrl = config_default.TRUEFOUNDRY_AUTH_SERVER_URL;
10133
- const apiKey = config_default.TRUEFOUNDRY_API_KEY;
10134
- if (authServerUrl === void 0 || authServerUrl.trim() === "") {
10135
- logger2.error("TRUEFOUNDRY_AUTH_SERVER_URL is required when SENTRY_ENABLED in TrueFoundry mode");
10136
- return false;
10137
- }
10138
- if (apiKey === void 0 || apiKey.trim() === "") {
10139
- logger2.error("TRUEFOUNDRY_API_KEY is required when SENTRY_ENABLED in TrueFoundry mode");
10140
- return false;
10141
- }
10142
- try {
10143
- const authData = await fetchSentryAuth({
10144
- authServerUrl,
10145
- apiKey,
10146
- tenantName: config_default.TRUEFOUNDRY_TENANT_NAME,
10147
- timeoutMs: config_default.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS
10148
- });
10149
- if (authData === void 0 || typeof authData !== "object" || authData === null) {
10150
- logger2.error("Failed to fetch sentry config. Skipping initialization");
10151
- return false;
10152
- }
10153
- const sentryInitOptions = {};
10154
- Object.assign(sentryInitOptions, authData);
10155
- sentryInitOptions.includeLocalVariables = false;
10156
- sentryInitOptions.defaultIntegrations = false;
10157
- sentryInitOptions.integrations = [];
10158
- Sentry2.init(sentryInitOptions);
10159
- Sentry2.getGlobalScope().setTag("TRUEFORGE_VERSION", PACKAGE_VERSION);
10160
- if (tags) {
10161
- for (const [key, value] of Object.entries(tags)) {
10162
- Sentry2.getGlobalScope().setTag(key, value);
10163
- }
10164
- }
10165
- logger2.info("Sentry initialised (TrueFoundry auth server)");
10166
- return true;
10167
- } catch (error) {
10168
- logger2.error("Error in fetching sentry auth data; skipping Sentry initialization", {
10169
- error: error instanceof Error ? error.message : error
10170
- });
10171
- return false;
10172
- }
10173
- }
10174
-
10175
- // src/sentry/initSentry.ts
10176
- function isLocalLikeEnv(nodeEnv) {
10177
- return nodeEnv === "development" || nodeEnv === "test" || nodeEnv === "local";
10178
- }
10179
- function applyGlobalTags(tags) {
10180
- const scope = Sentry3.getGlobalScope();
10181
- for (const [key, value] of Object.entries(tags)) {
10182
- scope.setTag(key, value);
10183
- }
10184
- }
10185
- async function initSentry(config, logger2, options) {
10186
- if (!config.SENTRY_ENABLED || isLocalLikeEnv(config.NODE_ENV)) {
10187
- logger2.info("Sentry is not enabled (SENTRY_ENABLED=false or local-like NODE_ENV)");
10188
- return;
10189
- }
10190
- const globalTags = {
10191
- service: "trueforge",
10192
- TRUEFORGE_VERSION: PACKAGE_VERSION,
10193
- ...config.SENTRY_ADDITIONAL_TAGS,
10194
- ...options?.tags
10195
- };
10196
- if (isTrueFoundryModeEnabled(config)) {
10197
- await initTrueFoundrySentry({ logger: logger2, tags: globalTags });
10198
- return;
10199
- }
10200
- const dsn = config.SENTRY_DSN;
10201
- if (dsn === void 0 || dsn.trim() === "") {
10202
- logger2.error("SENTRY_DSN is required when SENTRY_ENABLED=true");
10203
- return;
10204
- }
10205
- Sentry3.init({
10206
- dsn,
10207
- includeLocalVariables: false,
10208
- defaultIntegrations: false,
10209
- integrations: []
10210
- });
10211
- applyGlobalTags(globalTags);
10212
- logger2.info("Sentry initialised");
10213
- }
10214
-
10215
- // src/truefoundry/errors.ts
10216
10214
  var AGENT_EXTERNAL_ID_REQUIRED = "Agent is missing a TrueFoundry external id";
10217
10215
  var TRUEFOUNDRY_MANAGED_STATUS = 424;
10218
10216
  var TRUEFOUNDRY_MANAGED_MESSAGE = "This resource is managed by TrueFoundry";
10219
10217
  function requireTrueFoundryAgentExternalId(agent) {
10220
10218
  if (agent.external_id === null) {
10221
- const error = new HTTPException(500, { message: AGENT_EXTERNAL_ID_REQUIRED });
10222
- captureCriticalException(error, {
10223
- tags: { module: "truefoundry", operation: "requireExternalId" },
10224
- extra: {
10225
- agent_id: agent.id,
10226
- tenant_id: agent.tenant_id,
10227
- agent_name: agent.name
10228
- }
10229
- });
10230
- throw error;
10219
+ throw new HTTPException(500, { message: AGENT_EXTERNAL_ID_REQUIRED });
10231
10220
  }
10232
10221
  return agent.external_id;
10233
10222
  }
@@ -10336,6 +10325,7 @@ function gatewayHeaders(authorization) {
10336
10325
 
10337
10326
  // src/auth/identity.ts
10338
10327
  var STANDALONE_ADMIN_ROLE = "admin";
10328
+ var TRUEFOUNDRY_TENANT_ADMIN_ROLE = "tenant-admin";
10339
10329
  var STANDALONE_REQUEST_CONTEXT = {
10340
10330
  tenant_id: "default",
10341
10331
  subject: {
@@ -10356,7 +10346,7 @@ function resolveRequestContext(c) {
10356
10346
  function hasAdminRole(requestContext) {
10357
10347
  switch (getTrueForgeAuthMode()) {
10358
10348
  case "truefoundry" /* TrueFoundry */:
10359
- return false;
10349
+ return requestContext.roles.includes(TRUEFOUNDRY_TENANT_ADMIN_ROLE);
10360
10350
  case "oidc" /* Oidc */: {
10361
10351
  if (!isOidcConfigured(config_default)) {
10362
10352
  return false;
@@ -10367,6 +10357,18 @@ function hasAdminRole(requestContext) {
10367
10357
  return requestContext.roles.includes(STANDALONE_ADMIN_ROLE);
10368
10358
  }
10369
10359
  }
10360
+ function canAccessSettings(requestContext) {
10361
+ if (getTrueForgeAuthMode() === "truefoundry" /* TrueFoundry */) {
10362
+ return false;
10363
+ }
10364
+ return hasAdminRole(requestContext);
10365
+ }
10366
+ function canCreateOrEdit(requestContext, created_by_subject_id) {
10367
+ return hasAdminRole(requestContext) || created_by_subject_id !== void 0 && requestContext.subject.id === created_by_subject_id;
10368
+ }
10369
+ function canEditSchedule(requestContext, created_by_subject_id) {
10370
+ return hasAdminRole(requestContext) || requestContext.subject.id === created_by_subject_id;
10371
+ }
10370
10372
  function requestSubjectFromCreatedBySubject(subject) {
10371
10373
  return {
10372
10374
  id: subject.subject_id,
@@ -10795,12 +10797,7 @@ function toDaytonaSandboxProvider({
10795
10797
  ...settings,
10796
10798
  tenantName: tenant_id,
10797
10799
  fileMaxBytesForDownload: config_default.SANDBOX_FILE_MAX_BYTES_FOR_DOWNLOAD,
10798
- logger: logger2,
10799
- onCriticalAlert: (error) => {
10800
- captureCriticalException(error, {
10801
- tags: { module: "DaytonaProvider", operation: "sandboxCreate", priority: "P1" }
10802
- });
10803
- }
10800
+ logger: logger2
10804
10801
  });
10805
10802
  }
10806
10803
  function toSandboxProviderFromRecord({
@@ -10870,7 +10867,10 @@ async function resolveWebSearchProvider({
10870
10867
  return void 0;
10871
10868
  }
10872
10869
  const { manifest } = record;
10873
- return new ParallelWebSearchProvider({ apiKey: manifest.auth.api_key, mode: "turbo" });
10870
+ return new ParallelWebSearchProvider({
10871
+ apiKey: manifest.auth.api_key,
10872
+ mode: "turbo"
10873
+ });
10874
10874
  }
10875
10875
 
10876
10876
  // src/runtime/sessionResources.ts
@@ -10940,6 +10940,7 @@ async function getMcpConnection({
10940
10940
  }
10941
10941
  return {
10942
10942
  url: record.manifest.url,
10943
+ server: { name: record.name, description: record.manifest.description },
10943
10944
  headers: store.resolveInvokeHeaders({
10944
10945
  record,
10945
10946
  userRef,
@@ -11511,7 +11512,7 @@ function createAgentsRouter(deps) {
11511
11512
 
11512
11513
  // src/apis/auth.ts
11513
11514
  import { OpenAPIHono as OpenAPIHono2 } from "@hono/zod-openapi";
11514
- import { extractErrorLogFields as extractErrorLogFields2 } from "@truefoundry/trueforge-core/core";
11515
+ import { extractErrorLogFields as extractErrorLogFields2, isReportableError } from "@truefoundry/trueforge-core/core";
11515
11516
 
11516
11517
  // src/auth/cookies.ts
11517
11518
  init_config();
@@ -11676,11 +11677,17 @@ function jsonFormat() {
11676
11677
  winston.format.json()
11677
11678
  );
11678
11679
  }
11680
+ function omitReportableErrorFormat() {
11681
+ return winston.format((info) => {
11682
+ Reflect.deleteProperty(info, "reportable_error");
11683
+ return info;
11684
+ })();
11685
+ }
11679
11686
  function serverLogFormat(options) {
11680
- if (options.standalone) {
11681
- return standaloneFormat(shouldColorize());
11682
- }
11683
- return jsonFormat();
11687
+ return winston.format.combine(
11688
+ omitReportableErrorFormat(),
11689
+ options.standalone ? standaloneFormat(shouldColorize()) : jsonFormat()
11690
+ );
11684
11691
  }
11685
11692
  function createLogger(options) {
11686
11693
  return winston.createLogger({
@@ -11807,8 +11814,9 @@ import {
11807
11814
  // src/auth/safeReturnTo.ts
11808
11815
  init_config();
11809
11816
  var SAFE_RETURN_TO = /^\/(?!\/|api(?:\/|$)).*/;
11817
+ var UNSAFE_RETURN_TO_CHARS = /[\\\t\r\n]/;
11810
11818
  function isSafeReturnTo(value) {
11811
- return SAFE_RETURN_TO.test(value);
11819
+ return !UNSAFE_RETURN_TO_CHARS.test(value) && SAFE_RETURN_TO.test(value);
11812
11820
  }
11813
11821
  function safeReturnTo(value) {
11814
11822
  if (value && isSafeReturnTo(value)) {
@@ -11951,7 +11959,7 @@ function createAdminAuthMiddleware(authenticator) {
11951
11959
  throw new HTTPException5(401, { message: "Authentication required" });
11952
11960
  }
11953
11961
  updateLogContext({ tenant_id: requestContext.tenant_id });
11954
- if (!hasAdminRole(requestContext)) {
11962
+ if (!canAccessSettings(requestContext)) {
11955
11963
  throw new HTTPException5(403, { message: "Admin access required" });
11956
11964
  }
11957
11965
  c.set("request_context", requestContext);
@@ -12141,7 +12149,10 @@ function createAuthRouter(params) {
12141
12149
  });
12142
12150
  return c.redirect(authorizationUrl, 302);
12143
12151
  } catch (error) {
12144
- params.logger.error("Failed to build login authorization", extractErrorLogFields2(error));
12152
+ params.logger.error("Failed to build login authorization", {
12153
+ ...extractErrorLogFields2(error),
12154
+ reportable_error: { error }
12155
+ });
12145
12156
  return c.redirect(oauthErrorRedirect("login_failed"), 302);
12146
12157
  }
12147
12158
  }
@@ -12149,7 +12160,10 @@ function createAuthRouter(params) {
12149
12160
  try {
12150
12161
  return c.redirect(resolveTrueFoundryLoginReturnTo(returnTo), 302);
12151
12162
  } catch (error) {
12152
- params.logger.error("Failed to build TrueFoundry external login URL", extractErrorLogFields2(error));
12163
+ params.logger.error("Failed to build TrueFoundry external login URL", {
12164
+ ...extractErrorLogFields2(error),
12165
+ reportable_error: { error }
12166
+ });
12153
12167
  return c.redirect(oauthErrorRedirect("login_failed"), 302);
12154
12168
  }
12155
12169
  }
@@ -12184,7 +12198,10 @@ function createAuthRouter(params) {
12184
12198
  });
12185
12199
  return c.redirect(safeReturnTo(pending.return_to), 302);
12186
12200
  } catch (error) {
12187
- params.logger.error("Failed to exchange authorization code", extractErrorLogFields2(error));
12201
+ params.logger.error("Failed to exchange authorization code", {
12202
+ ...extractErrorLogFields2(error),
12203
+ ...isReportableError(error) ? { reportable_error: { error } } : {}
12204
+ });
12188
12205
  const soft = await redirectIfAlreadyAuthenticated({
12189
12206
  context: c,
12190
12207
  whenAuthenticated: safeReturnTo(pending.return_to)
@@ -12362,7 +12379,7 @@ function createCapabilitiesRouter(deps) {
12362
12379
  });
12363
12380
  const status = defaultEnv?.version.status;
12364
12381
  const sandboxEnabled = hasTrueFoundrySandboxProviderConfig() || status === "ready" || defaultEnv === void 0 && isLocalSandboxFallbackEnabled();
12365
- const settingsEnabled = hasAdminRole(requestContext);
12382
+ const settingsEnabled = canAccessSettings(requestContext);
12366
12383
  const webSearchEnabled = await hasConfiguredWebSearchProvider({
12367
12384
  tenant_id: requestContext.tenant_id,
12368
12385
  store: deps.resolveWebSearchProviderStore(c)
@@ -12639,7 +12656,8 @@ var AvailableModelSchema = z16.object({
12639
12656
  name: z16.string().describe('Fully qualified name `provider_name/model_name`, e.g. "openai/gpt-5-6-sol". Unique within a tenant.'),
12640
12657
  model_id: z16.string().describe("Upstream, provider-specific identifier sent to the provider API."),
12641
12658
  provider: AvailableModelProviderSchema,
12642
- properties: ModelPropertiesSchema
12659
+ properties: ModelPropertiesSchema,
12660
+ warning: z16.string().min(1).optional().describe("Set when reasoning effort or context length is not configured; may affect TrueForge performance.")
12643
12661
  }).strict().openapi("AvailableModel");
12644
12662
  var ListAvailableModelsResponseSchema = z16.object({
12645
12663
  data: z16.array(AvailableModelSchema)
@@ -13279,7 +13297,10 @@ function createMcpOAuthRouter(deps) {
13279
13297
  deps.logger.warn("MCP OAuth callback token exchange failed", extractErrorLogFields3(err));
13280
13298
  return callbackFailure({ c, pending, message: err.message });
13281
13299
  }
13282
- deps.logger.error("MCP OAuth callback unexpected failure", extractErrorLogFields3(err));
13300
+ deps.logger.error("MCP OAuth callback unexpected failure", {
13301
+ ...extractErrorLogFields3(err),
13302
+ reportable_error: { error: err }
13303
+ });
13283
13304
  return callbackFailure({ c, pending, message: "Internal server error", jsonStatus: 500 });
13284
13305
  }
13285
13306
  return callbackSuccess({ c, pending });
@@ -13296,6 +13317,7 @@ import {
13296
13317
  extractErrorLogFields as extractErrorLogFields4,
13297
13318
  isAuthRequired,
13298
13319
  McpConnectionError as McpConnectionError4,
13320
+ OUTBOUND_URL_BLOCKED,
13299
13321
  RemoteMCP
13300
13322
  } from "@truefoundry/trueforge-core/core";
13301
13323
  import { HTTPException as HTTPException7 } from "hono/http-exception";
@@ -13766,7 +13788,7 @@ function createSettingsMcpServersRouter(deps) {
13766
13788
  try {
13767
13789
  await assertSafeOutboundUrl(incomingManifest.url);
13768
13790
  } catch (error) {
13769
- const message = error instanceof Error ? error.message : "Outbound URL blocked";
13791
+ const message = error instanceof Error ? error.message : OUTBOUND_URL_BLOCKED;
13770
13792
  throw new HTTPException7(400, { message, cause: error });
13771
13793
  }
13772
13794
  let dcrClientToSave;
@@ -13839,7 +13861,7 @@ function createSettingsMcpServersRouter(deps) {
13839
13861
  try {
13840
13862
  await assertSafeOutboundUrl(incomingManifest.url);
13841
13863
  } catch (error) {
13842
- const message = error instanceof Error ? error.message : "Outbound URL blocked";
13864
+ const message = error instanceof Error ? error.message : OUTBOUND_URL_BLOCKED;
13843
13865
  throw new HTTPException7(400, { message, cause: error });
13844
13866
  }
13845
13867
  try {
@@ -13983,7 +14005,10 @@ function createMcpServersRouter(deps) {
13983
14005
  }
13984
14006
  return c.json({ error: { message: error.message } }, 500);
13985
14007
  }
13986
- deps.logger.error(`MCP authorize unexpected failure for "${name}"`, extractErrorLogFields4(error));
14008
+ deps.logger.error(`MCP authorize unexpected failure for "${name}"`, {
14009
+ ...extractErrorLogFields4(error),
14010
+ reportable_error: { error, extra: { mcp_server_name: name } }
14011
+ });
13987
14012
  return c.json({ error: { message: "Internal server error" } }, 500);
13988
14013
  }
13989
14014
  };
@@ -14004,7 +14029,7 @@ function createMcpServersRouter(deps) {
14004
14029
  id: name,
14005
14030
  name,
14006
14031
  url: connection.url,
14007
- headers: connection.headers,
14032
+ headers: connection.headers ?? {},
14008
14033
  requestTimeoutMs: config_default.MCP_REQUEST_TIMEOUT_MS,
14009
14034
  connectTimeoutMs: config_default.MCP_CONNECT_TIMEOUT_MS,
14010
14035
  maxResponseBytes: config_default.MCP_TOOL_CALL_MAX_RESPONSE_BYTES,
@@ -14155,9 +14180,10 @@ import { createRoute as createRoute8 } from "@hono/zod-openapi";
14155
14180
 
14156
14181
  // src/schemas/permissions.ts
14157
14182
  import { z as z24 } from "@hono/zod-openapi";
14158
- var PermissionResourceTypeSchema = z24.enum(["agent", "schedule", "session", "tenant"]).describe("Resource type to evaluate permissions for.").openapi("PermissionResourceType");
14183
+ var PermissionResourceTypeSchema = z24.enum(["agent", "schedule", "session", "tenant", "sandbox_environment"]).describe("Resource type to evaluate permissions for.").openapi("PermissionResourceType");
14159
14184
  var AgentResourcePermissionSchema = z24.enum(["USE", "MANAGE", "DELETE"]).describe("Granted action on an agent.").openapi("AgentResourcePermission");
14160
14185
  var ScheduleResourcePermissionSchema = z24.enum(["MANAGE", "DELETE"]).describe("Granted action on a schedule.").openapi("ScheduleResourcePermission");
14186
+ var SandboxEnvironmentResourcePermissionSchema = z24.enum(["MANAGE", "DELETE"]).describe("Granted action on a sandbox environment.").openapi("SandboxEnvironmentResourcePermission");
14161
14187
  var SessionResourcePermissionSchema = z24.enum(["MANAGE", "DELETE"]).describe("Granted action on a session.").openapi("SessionResourcePermission");
14162
14188
  var TenantScopedResourcePermissionSchema = z24.enum(["CREATE"]).describe("Granted create action on a tenant-scoped entity kind.").openapi("TenantScopedResourcePermission");
14163
14189
  var ResourcePermissionSchema = z24.enum(["USE", "MANAGE", "DELETE", "CREATE"]).describe("Granted action on a resource id or tenant entity kind.").openapi("ResourcePermission");
@@ -14167,9 +14193,7 @@ var ListPermissionsRequestSchema = z24.object({
14167
14193
  }).openapi("ListPermissionsRequest");
14168
14194
  var ListPermissionsDataSchema = z24.object({
14169
14195
  type: PermissionResourceTypeSchema,
14170
- permissions: z24.record(z24.string(), z24.array(ResourcePermissionSchema)).describe(
14171
- "For agent/schedule/session: keyed by resource id. For tenant: keyed by entity kind (e.g. `agent` \u2192 `CREATE`)."
14172
- )
14196
+ permissions: z24.record(z24.string(), z24.array(ResourcePermissionSchema)).describe("Keyed by resource id for resource types, or by entity kind for `tenant` (e.g. `agent` \u2192 `CREATE`).")
14173
14197
  }).openapi("ListPermissionsData");
14174
14198
  var ListPermissionsResponseSchema = z24.object({
14175
14199
  data: ListPermissionsDataSchema
@@ -14177,8 +14201,12 @@ var ListPermissionsResponseSchema = z24.object({
14177
14201
  var AGENT_USE_PERMISSIONS = [AgentResourcePermissionSchema.enum.USE];
14178
14202
  var AGENT_OWNER_PERMISSIONS = AgentResourcePermissionSchema.options;
14179
14203
  var SCHEDULE_OWNER_PERMISSIONS = ScheduleResourcePermissionSchema.options;
14204
+ var SANDBOX_ENVIRONMENT_OWNER_PERMISSIONS = SandboxEnvironmentResourcePermissionSchema.options;
14180
14205
  var SESSION_OWNER_PERMISSIONS = SessionResourcePermissionSchema.options;
14181
14206
  var TENANT_CREATE_AGENT_PERMISSIONS = [TenantScopedResourcePermissionSchema.enum.CREATE];
14207
+ var TENANT_CREATE_SANDBOX_ENVIRONMENT_PERMISSIONS = [
14208
+ TenantScopedResourcePermissionSchema.enum.CREATE
14209
+ ];
14182
14210
  function emptyPermissionsByResourceId(resourceIds) {
14183
14211
  return Object.fromEntries(resourceIds.map((id) => [id, []]));
14184
14212
  }
@@ -14241,6 +14269,13 @@ function createPermissionsRouter(deps) {
14241
14269
  resourceIds,
14242
14270
  store: deps.scheduleStore
14243
14271
  };
14272
+ } else if (resourceType === "sandbox_environment") {
14273
+ input = {
14274
+ resourceType: "sandbox_environment",
14275
+ requestContext,
14276
+ resourceIds,
14277
+ store: deps.sandboxEnvironmentStore
14278
+ };
14244
14279
  } else {
14245
14280
  input = {
14246
14281
  resourceType: "session",
@@ -14332,9 +14367,8 @@ async function progressSandboxEnvironmentVersion({
14332
14367
  const pending = await sandboxEnvironmentStore.getSandboxEnvironmentVersion({ environment_version_id });
14333
14368
  if (pending === void 0) {
14334
14369
  const error = new HTTPException8(404, { message: "Sandbox environment version not found" });
14335
- captureCriticalException(error, {
14336
- tags: { module: "progressSandboxEnvironmentVersion", operation: "notFound" },
14337
- extra: { environment_version_id }
14370
+ logger2.warn("Sandbox environment version not found", {
14371
+ environment_version_id
14338
14372
  });
14339
14373
  throw error;
14340
14374
  }
@@ -14376,16 +14410,8 @@ async function progressSandboxEnvironmentVersion({
14376
14410
  environment_version_id,
14377
14411
  status_reason
14378
14412
  });
14379
- captureCriticalException(error, {
14380
- tags: { module: "progressSandboxEnvironmentVersion", operation: "authz" },
14381
- extra: { environment_version_id, tenant_id: pending.tenant_id, status_reason }
14382
- });
14383
14413
  return;
14384
14414
  }
14385
- captureCriticalException(error, {
14386
- tags: { module: "progressSandboxEnvironmentVersion", operation: "build" },
14387
- extra: { environment_version_id, tenant_id: pending.tenant_id }
14388
- });
14389
14415
  throw error;
14390
14416
  }
14391
14417
  }
@@ -14522,6 +14548,10 @@ var createSandboxEnvironmentRoute = createRoute10({
14522
14548
  content: { "application/json": { schema: RequestErrorResponseSchema } },
14523
14549
  description: "Unauthenticated."
14524
14550
  },
14551
+ 403: {
14552
+ content: { "application/json": { schema: RequestErrorResponseSchema } },
14553
+ description: "User does not have permission to edit Sandbox environment"
14554
+ },
14525
14555
  409: {
14526
14556
  content: { "application/json": { schema: RequestErrorResponseSchema } },
14527
14557
  description: "A sandbox environment with this name already exists."
@@ -14563,6 +14593,10 @@ var putSandboxEnvironmentRoute = createRoute10({
14563
14593
  content: { "application/json": { schema: RequestErrorResponseSchema } },
14564
14594
  description: "Unauthenticated."
14565
14595
  },
14596
+ 403: {
14597
+ content: { "application/json": { schema: RequestErrorResponseSchema } },
14598
+ description: "User does not have permission to edit Sandbox environment"
14599
+ },
14566
14600
  404: {
14567
14601
  content: { "application/json": { schema: RequestErrorResponseSchema } },
14568
14602
  description: "Sandbox environment not found."
@@ -14601,6 +14635,10 @@ var deleteSandboxEnvironmentRoute = createRoute10({
14601
14635
  content: { "application/json": { schema: RequestErrorResponseSchema } },
14602
14636
  description: "Unauthenticated."
14603
14637
  },
14638
+ 403: {
14639
+ content: { "application/json": { schema: RequestErrorResponseSchema } },
14640
+ description: "User does not have permission to edit Sandbox environment"
14641
+ },
14604
14642
  404: {
14605
14643
  content: { "application/json": { schema: RequestErrorResponseSchema } },
14606
14644
  description: "Sandbox environment not found or not owned by the caller."
@@ -14824,6 +14862,7 @@ async function syncSandboxEnvironmentSecrets({
14824
14862
  // src/apis/sandboxEnvironments.ts
14825
14863
  init_sandboxEnvironment();
14826
14864
  init_secretRedaction();
14865
+ var FORBIDDEN_SANDBOX_ENVIRONMENT_WRITE = "User does not have permission to edit Sandbox environment";
14827
14866
  function toSandboxEnvironment2({ environment, version }) {
14828
14867
  const { type, sandbox_provider, ...manifest } = version.manifest;
14829
14868
  void type;
@@ -14897,7 +14936,7 @@ function createSandboxEnvironmentsRouter(deps) {
14897
14936
  }) {
14898
14937
  const requestContext = resolveRequestContext2(c);
14899
14938
  const { manifest } = body;
14900
- const created_by_subject = createdBySubjectFromRequestContext(requestContext);
14939
+ const created_by_subject = existing?.environment.created_by_subject ?? createdBySubjectFromRequestContext(requestContext);
14901
14940
  try {
14902
14941
  const provider = await resolveSandboxProviderRecord(
14903
14942
  deps.resolveSandboxProviderStore(c),
@@ -14959,9 +14998,12 @@ function createSandboxEnvironmentsRouter(deps) {
14959
14998
  }
14960
14999
  }
14961
15000
  const createHandler = async (c) => {
15001
+ const requestContext = resolveRequestContext2(c);
15002
+ if (!canCreateOrEdit(requestContext)) {
15003
+ return c.json({ error: { message: FORBIDDEN_SANDBOX_ENVIRONMENT_WRITE } }, 403);
15004
+ }
14962
15005
  const body = c.req.valid("json");
14963
- const { tenant_id } = resolveRequestContext2(c);
14964
- const existing = await store.getEnvironment({ tenant_id, name: body.manifest.name });
15006
+ const existing = await store.getEnvironment({ tenant_id: requestContext.tenant_id, name: body.manifest.name });
14965
15007
  if (existing) {
14966
15008
  return c.json({ error: { message: `Sandbox environment with name ${body.manifest.name} already exists` } }, 409);
14967
15009
  }
@@ -14973,10 +15015,13 @@ function createSandboxEnvironmentsRouter(deps) {
14973
15015
  };
14974
15016
  const putHandler = async (c) => {
14975
15017
  const body = c.req.valid("json");
14976
- const { tenant_id, subject } = resolveRequestContext2(c);
14977
- const existing = await store.getEnvironment({ tenant_id, name: body.manifest.name });
14978
- if (existing && existing.environment.created_by_subject.subject_id !== subject.id) {
14979
- return c.json({ error: { message: `Sandbox environment not found: ${body.manifest.name}` } }, 404);
15018
+ const requestContext = resolveRequestContext2(c);
15019
+ const existing = await store.getEnvironment({
15020
+ tenant_id: requestContext.tenant_id,
15021
+ name: body.manifest.name
15022
+ });
15023
+ if (!canCreateOrEdit(requestContext, existing?.environment.created_by_subject.subject_id)) {
15024
+ return c.json({ error: { message: FORBIDDEN_SANDBOX_ENVIRONMENT_WRITE } }, 403);
14980
15025
  }
14981
15026
  const outcome = await writeSandboxEnvironment({ c, body, mode: "upsert", existing });
14982
15027
  if (outcome.kind === "error") {
@@ -14985,7 +15030,8 @@ function createSandboxEnvironmentsRouter(deps) {
14985
15030
  return c.json({ data: outcome.environment }, 200);
14986
15031
  };
14987
15032
  const deleteHandler = async (c) => {
14988
- const { tenant_id, subject } = resolveRequestContext2(c);
15033
+ const requestContext = resolveRequestContext2(c);
15034
+ const { tenant_id } = requestContext;
14989
15035
  const { name } = c.req.valid("param");
14990
15036
  if (name === DEFAULT_SANDBOX_ENVIRONMENT_NAME) {
14991
15037
  return c.json({ error: { message: 'Sandbox environment "default" cannot be deleted' } }, 409);
@@ -14997,8 +15043,8 @@ function createSandboxEnvironmentsRouter(deps) {
14997
15043
  if (!existing) {
14998
15044
  return c.json({ error: { message: `Sandbox environment not found: ${name}` } }, 404);
14999
15045
  }
15000
- if (existing.environment.created_by_subject.subject_id !== subject.id) {
15001
- return c.json({ error: { message: `Sandbox environment not found: ${name}` } }, 404);
15046
+ if (!canCreateOrEdit(requestContext, existing.environment.created_by_subject.subject_id)) {
15047
+ return c.json({ error: { message: FORBIDDEN_SANDBOX_ENVIRONMENT_WRITE } }, 403);
15002
15048
  }
15003
15049
  const agentNames = await resolveAgentStore(c).listAgentNamesUsingSandboxEnvironment({
15004
15050
  tenant_id,
@@ -15028,8 +15074,7 @@ function createSandboxEnvironmentsRouter(deps) {
15028
15074
  }
15029
15075
  await store.deleteEnvironment({
15030
15076
  tenant_id,
15031
- name,
15032
- created_by_subject_id: subject.id
15077
+ name
15033
15078
  });
15034
15079
  return c.json({}, 200);
15035
15080
  } catch (error) {
@@ -15066,18 +15111,18 @@ init_config();
15066
15111
  import { TrueForge } from "@truefoundry/trueforge-sdk";
15067
15112
 
15068
15113
  // src/http/tls.ts
15069
- import { readFileSync as readFileSync4 } from "fs";
15114
+ import { readFileSync as readFileSync3 } from "fs";
15070
15115
  import { createServer as createHttpsServer } from "https";
15071
15116
  import { join as join5 } from "path";
15072
15117
  import { rootCertificates, TLSSocket } from "tls";
15073
- import { Agent, fetch as undiciFetch2 } from "undici";
15118
+ import { Agent, fetch as undiciFetch } from "undici";
15074
15119
  var TLS_CERT_FILE = "tls.crt";
15075
15120
  var TLS_KEY_FILE = "tls.key";
15076
15121
  var TLS_CA_FILE = "ca.crt";
15077
15122
  function readTlsFile(input) {
15078
15123
  const filePath = join5(input.dir, input.fileName);
15079
15124
  try {
15080
- return readFileSync4(filePath, "utf8");
15125
+ return readFileSync3(filePath, "utf8");
15081
15126
  } catch (error) {
15082
15127
  throw new Error(
15083
15128
  `${input.enabledEnvKey} is true but ${filePath} could not be read. Check that the mTLS secret is mounted at the configured certs directory, or set ${input.enabledEnvKey}=false.`,
@@ -15133,7 +15178,7 @@ function createTlsFetch(options) {
15133
15178
  if (dispatcher === void 0) {
15134
15179
  return void 0;
15135
15180
  }
15136
- return (input, init3) => undiciFetch2(requestUrlFromFetchInput(input), { ...init3, dispatcher });
15181
+ return (input, init3) => undiciFetch(requestUrlFromFetchInput(input), { ...init3, dispatcher });
15137
15182
  }
15138
15183
  function serverTlsServeOptions(options) {
15139
15184
  if (!options.enabled) {
@@ -15227,7 +15272,8 @@ async function startScheduleRun(params) {
15227
15272
  const {
15228
15273
  item: { run, schedule },
15229
15274
  sessions,
15230
- agentStore
15275
+ agentStore,
15276
+ scheduleStore
15231
15277
  } = params;
15232
15278
  const named = await agentStore.getAgent({ tenant_id: schedule.tenant_id, name: schedule.agent_name });
15233
15279
  if (named === void 0) {
@@ -15240,6 +15286,11 @@ async function startScheduleRun(params) {
15240
15286
  agent: { type: "reference", id: named.id, name: named.name },
15241
15287
  source: { type: "schedule", id: schedule.id, run_id: run.id }
15242
15288
  });
15289
+ await scheduleStore.updateRun({
15290
+ tenant_id: schedule.tenant_id,
15291
+ id: run.id,
15292
+ session_id: session.session_id
15293
+ });
15243
15294
  const { data: turns } = await session.listTurns({ limit: 1 });
15244
15295
  if (turns.length > 0) {
15245
15296
  return void 0;
@@ -15268,7 +15319,7 @@ async function finishScheduledRun(params) {
15268
15319
  const { store, withTransaction, run, status, reason, now: now2 } = params;
15269
15320
  await withTransaction(async (txn) => {
15270
15321
  const latest = await store.getScheduleForUpdate({ tenant_id: run.tenant_id, id: run.schedule_id }, txn);
15271
- const updated = await store.updateRunStatus(
15322
+ const updated = await store.updateRun(
15272
15323
  { tenant_id: run.tenant_id, id: run.id, status, reason: reason ?? null },
15273
15324
  txn
15274
15325
  );
@@ -15329,14 +15380,14 @@ async function dispatchScheduledRuns(params) {
15329
15380
  logger2.error("Failed to hand off triggered run", {
15330
15381
  schedule_id: schedule.id,
15331
15382
  run_id: run.id,
15332
- error
15333
- });
15334
- captureCriticalException(error, {
15335
- tags: { module: "scheduleDispatch", operation: "handoff" },
15336
- extra: {
15337
- tenant_id: run.tenant_id,
15338
- schedule_id: schedule.id,
15339
- run_id: run.id
15383
+ error,
15384
+ reportable_error: {
15385
+ error,
15386
+ extra: {
15387
+ tenant_id: run.tenant_id,
15388
+ schedule_id: schedule.id,
15389
+ run_id: run.id
15390
+ }
15340
15391
  }
15341
15392
  });
15342
15393
  await finishScheduledRun({
@@ -15362,14 +15413,14 @@ async function dispatchScheduledRuns(params) {
15362
15413
  logger2.error("Failed to process scheduled run", {
15363
15414
  schedule_id: run.schedule_id,
15364
15415
  run_id: run.id,
15365
- error
15366
- });
15367
- captureCriticalException(error, {
15368
- tags: { module: "scheduleDispatch", operation: "processRun" },
15369
- extra: {
15370
- tenant_id: run.tenant_id,
15371
- schedule_id: run.schedule_id,
15372
- run_id: run.id
15416
+ error,
15417
+ reportable_error: {
15418
+ error,
15419
+ extra: {
15420
+ tenant_id: run.tenant_id,
15421
+ schedule_id: run.schedule_id,
15422
+ run_id: run.id
15423
+ }
15373
15424
  }
15374
15425
  });
15375
15426
  }
@@ -15693,6 +15744,7 @@ import {
15693
15744
  AgentHarnessError,
15694
15745
  existingSandboxIdForProvider,
15695
15746
  extractErrorLogFields as extractErrorLogFields5,
15747
+ getOperationMetrics,
15696
15748
  isAgentInputUserMessage,
15697
15749
  isFileContentPart,
15698
15750
  McpConnectionError as McpConnectionError5,
@@ -15728,6 +15780,8 @@ import {
15728
15780
  ModelMessageDeltaEventSchema,
15729
15781
  ModelMessageEventSchema,
15730
15782
  SandboxCreatedEventSchema,
15783
+ ThreadContextCompactionFinishedEventSchema,
15784
+ ThreadContextCompactionStartedEventSchema,
15731
15785
  ThreadCreatedEventSchema,
15732
15786
  ThreadDoneEventSchema,
15733
15787
  ToolApprovalRequiredEventSchema,
@@ -15757,6 +15811,8 @@ var TurnStreamingEventSchema = z29.discriminatedUnion("type", [
15757
15811
  ToolResponseEventSchema,
15758
15812
  ThreadCreatedEventSchema,
15759
15813
  ThreadDoneEventSchema,
15814
+ ThreadContextCompactionStartedEventSchema,
15815
+ ThreadContextCompactionFinishedEventSchema,
15760
15816
  MCPAuthRequiredEventSchema,
15761
15817
  MCPInitializeEventSchema,
15762
15818
  SandboxCreatedEventSchema,
@@ -16947,7 +17003,8 @@ function createTurnResolver(deps) {
16947
17003
  signal
16948
17004
  }),
16949
17005
  defaultModelParams: resolved.defaultModelParams,
16950
- modelProperties: resolved.modelProperties
17006
+ modelProperties: resolved.modelProperties,
17007
+ providerType: resolved.providerConfig.provider.type
16951
17008
  };
16952
17009
  },
16953
17010
  mcp: async (name) => {
@@ -16963,10 +17020,7 @@ function createTurnResolver(deps) {
16963
17020
  message: `Unknown MCP server "${name}" \u2014 not configured`
16964
17021
  });
16965
17022
  }
16966
- return {
16967
- url: connection.url,
16968
- headers: connection.headers
16969
- };
17023
+ return connection;
16970
17024
  },
16971
17025
  mcpRequestTimeoutMs: config_default.MCP_REQUEST_TIMEOUT_MS,
16972
17026
  mcpConnectTimeoutMs: config_default.MCP_CONNECT_TIMEOUT_MS,
@@ -17075,10 +17129,28 @@ function streamTTLSecondsFor(event) {
17075
17129
  function turnStreamId(tenantId, sessionId, turnId) {
17076
17130
  return redisKey("agent", "turn", tenantId, sessionId, turnId, "stream");
17077
17131
  }
17132
+ function reportUnexpectedTurnDone({ event, logger: logger2 }) {
17133
+ if (event.type !== EventType2.TURN_DONE) {
17134
+ return;
17135
+ }
17136
+ const { state } = event;
17137
+ if (state.status === "error") {
17138
+ logger2.error("turn.done error", extractErrorLogFields5(new Error(state.message)));
17139
+ return;
17140
+ }
17141
+ if (state.status === "cancelled" && (state.reason === CancellationReason.Abandoned || state.reason === CancellationReason.ServerExecutionTimeout)) {
17142
+ const error = new Error(state.reason);
17143
+ logger2.error("turn.done cancelled", {
17144
+ ...extractErrorLogFields5(error),
17145
+ reportable_error: { error, extra: { reason: state.reason } }
17146
+ });
17147
+ }
17148
+ }
17078
17149
  async function drainTurnEvents(input) {
17079
17150
  const { trackedStream, turnEventStream, maxExecutionTimer, logger: logger2, onEvent } = input;
17080
17151
  try {
17081
17152
  for await (const event of trackedStream) {
17153
+ reportUnexpectedTurnDone({ event, logger: logger2 });
17082
17154
  const sequenceNumber = await turnEventStream.put(event, {
17083
17155
  streamTTLSeconds: streamTTLSecondsFor(event)
17084
17156
  });
@@ -17088,7 +17160,10 @@ async function drainTurnEvents(input) {
17088
17160
  if (error instanceof SessionStoreNotFoundError) {
17089
17161
  logger2.warn("Turn stream ended after session/turn was removed", extractErrorLogFields5(error));
17090
17162
  } else {
17091
- logger2.error("Unexpected error in turn event drain", extractErrorLogFields5(error));
17163
+ logger2.error("Unexpected error in turn event drain", {
17164
+ ...extractErrorLogFields5(error),
17165
+ reportable_error: { error }
17166
+ });
17092
17167
  }
17093
17168
  } finally {
17094
17169
  clearTimeout(maxExecutionTimer);
@@ -17142,6 +17217,7 @@ async function beginTurnExecution(params) {
17142
17217
  });
17143
17218
  const maxExecutionTimer = setTimeout(() => {
17144
17219
  if (!abortController.signal.aborted) {
17220
+ getOperationMetrics()?.recordTurnTimeout({ phase: "execution" });
17145
17221
  abortController.abort(CancellationReason.ServerExecutionTimeout);
17146
17222
  }
17147
17223
  }, config_default.SERVER_EXECUTION_TIMEOUT_SECONDS * 1e3);
@@ -17336,7 +17412,8 @@ function createTurnsRouter(deps) {
17336
17412
  deps.logger.error("Sandbox file download failed", {
17337
17413
  ...extractErrorLogFields5(error),
17338
17414
  sandboxId,
17339
- path: path7
17415
+ path: path7,
17416
+ reportable_error: { error, extra: { sandboxId, path: path7 } }
17340
17417
  });
17341
17418
  return c.json({ error: { message: "Failed to download file from sandbox" } }, 424);
17342
17419
  }
@@ -17456,8 +17533,13 @@ function createTurnsRouter(deps) {
17456
17533
  turn_id: turn.id
17457
17534
  };
17458
17535
  let shouldWriteToSSEStream = true;
17536
+ let closedByServer = false;
17459
17537
  return streamSSE(c, async (stream) => {
17460
17538
  stream.onAbort(() => {
17539
+ if (closedByServer) {
17540
+ return;
17541
+ }
17542
+ getOperationMetrics()?.recordTurnSseDisconnect({ path: "create" });
17461
17543
  shouldWriteToSSEStream = false;
17462
17544
  deps.logger.info(
17463
17545
  "Create-turn SSE client disconnected, continuing drain without writing",
@@ -17475,6 +17557,7 @@ function createTurnsRouter(deps) {
17475
17557
  );
17476
17558
  } catch (error) {
17477
17559
  if (error instanceof PromiseTimeoutError) {
17560
+ getOperationMetrics()?.recordTurnTimeout({ phase: "sse_write" });
17478
17561
  deps.logger.error("SSE stream write timed out", extractErrorLogFields5(error));
17479
17562
  } else {
17480
17563
  deps.logger.error("SSE stream write error", extractErrorLogFields5(error));
@@ -17485,6 +17568,7 @@ function createTurnsRouter(deps) {
17485
17568
  }
17486
17569
  });
17487
17570
  if (!shouldWriteToSSEStream && !stream.closed) {
17571
+ closedByServer = true;
17488
17572
  stream.abort();
17489
17573
  }
17490
17574
  await stream.close();
@@ -17535,6 +17619,7 @@ function createTurnsRouter(deps) {
17535
17619
  const subscribeAbort = new AbortController();
17536
17620
  const timeoutMs = config_default.TURN_SUBSCRIBE_TIMEOUT_MS;
17537
17621
  const timeoutHandler = setTimeout(() => {
17622
+ getOperationMetrics()?.recordTurnTimeout({ phase: "subscribe" });
17538
17623
  deps.logger.info("Subscribe turn stream server-side timeout reached, closing stream", {
17539
17624
  afterSequenceNumber,
17540
17625
  timeoutMs
@@ -17543,6 +17628,7 @@ function createTurnsRouter(deps) {
17543
17628
  }, timeoutMs);
17544
17629
  return streamSSE(c, async (stream) => {
17545
17630
  stream.onAbort(() => {
17631
+ getOperationMetrics()?.recordTurnSseDisconnect({ path: "subscribe" });
17546
17632
  subscribeAbort.abort(new Error("client-disconnected"));
17547
17633
  });
17548
17634
  const generator = turnEventStream.poll(afterSequenceNumber, { signal: subscribeAbort.signal });
@@ -17555,7 +17641,10 @@ function createTurnsRouter(deps) {
17555
17641
  }
17556
17642
  } catch (error) {
17557
17643
  if (!subscribeAbort.signal.aborted) {
17558
- deps.logger.error("Unexpected error in turn subscribe SSE loop", extractErrorLogFields5(error));
17644
+ deps.logger.error("Unexpected error in turn subscribe SSE loop", {
17645
+ ...extractErrorLogFields5(error),
17646
+ reportable_error: { error }
17647
+ });
17559
17648
  }
17560
17649
  } finally {
17561
17650
  clearTimeout(timeoutHandler);
@@ -17611,7 +17700,8 @@ async function startScheduleRunOnRequest(params) {
17611
17700
  const prepared = await startScheduleRun({
17612
17701
  item,
17613
17702
  sessions: deps.sessions,
17614
- agentStore: deps.agentStore
17703
+ agentStore: deps.agentStore,
17704
+ scheduleStore: deps.scheduleStore
17615
17705
  });
17616
17706
  if (prepared === void 0) {
17617
17707
  return;
@@ -17656,6 +17746,7 @@ function toWireScheduleRun(record) {
17656
17746
  created_by_subject: record.created_by_subject,
17657
17747
  triggered_at: record.triggered_at,
17658
17748
  reason: record.reason,
17749
+ session_id: record.session_id,
17659
17750
  created_at: record.created_at,
17660
17751
  updated_at: record.updated_at
17661
17752
  };
@@ -17684,10 +17775,7 @@ function validateManifest2(manifest, from = /* @__PURE__ */ new Date()) {
17684
17775
  );
17685
17776
  }
17686
17777
  }
17687
- var FORBIDDEN_SCHEDULE_ACCESS = "Only the schedule creator can access this schedule";
17688
- function isScheduleOwner(requestContext, created_by_subject_id) {
17689
- return requestContext.subject.id === created_by_subject_id;
17690
- }
17778
+ var FORBIDDEN_SCHEDULE_ACCESS = "Only the schedule creator or an admin can access this schedule";
17691
17779
  function createScheduleExecutionRouter(deps) {
17692
17780
  const handler = async (c) => {
17693
17781
  const { schedule_run_id: scheduleRunId } = c.req.valid("json");
@@ -17722,20 +17810,20 @@ function createSchedulesRouter(deps) {
17722
17810
  const { agent_names: agentNames, limit, page_token: pageToken, created_by_me: createdByMe } = c.req.valid("query");
17723
17811
  const requestContext = deps.resolveRequestContext(c);
17724
17812
  try {
17725
- const managedAgentIds = createdByMe ? [] : await resolveManagedAgentIds({
17726
- store: deps.resolveAgentStore(c),
17727
- context: requestContext,
17728
- authorizer: deps.authorizer
17729
- });
17813
+ const created_by_or_agent_ids = !createdByMe && hasAdminRole(requestContext) ? void 0 : {
17814
+ created_by_subject_id: requestContext.subject.id,
17815
+ agent_ids: createdByMe ? [] : await resolveManagedAgentIds({
17816
+ store: deps.resolveAgentStore(c),
17817
+ context: requestContext,
17818
+ authorizer: deps.authorizer
17819
+ })
17820
+ };
17730
17821
  const { data, pagination } = await deps.scheduleStore.listSchedules({
17731
17822
  tenant_id: requestContext.tenant_id,
17732
17823
  limit,
17733
17824
  page_token: pageToken,
17734
17825
  agent_names: agentNames,
17735
- created_by_or_agent_ids: {
17736
- created_by_subject_id: requestContext.subject.id,
17737
- agent_ids: managedAgentIds
17738
- }
17826
+ created_by_or_agent_ids
17739
17827
  });
17740
17828
  return c.json({ data: data.map(toWireSchedule), pagination }, 200);
17741
17829
  } catch (error) {
@@ -17756,7 +17844,7 @@ function createSchedulesRouter(deps) {
17756
17844
  if (schedule === void 0) {
17757
17845
  return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
17758
17846
  }
17759
- if (!await canReadAgentBoundResource({
17847
+ if (!canEditSchedule(requestContext, schedule.created_by_subject.subject_id) && !await canReadAgentBoundResource({
17760
17848
  store: deps.resolveAgentStore(c),
17761
17849
  context: requestContext,
17762
17850
  authorizer: deps.authorizer,
@@ -17790,7 +17878,7 @@ function createSchedulesRouter(deps) {
17790
17878
  if (schedule === void 0) {
17791
17879
  return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
17792
17880
  }
17793
- if (!isScheduleOwner(requestContext, schedule.created_by_subject.subject_id)) {
17881
+ if (!canEditSchedule(requestContext, schedule.created_by_subject.subject_id)) {
17794
17882
  return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
17795
17883
  }
17796
17884
  const agent = await agentIfAccessible({
@@ -17826,7 +17914,7 @@ function createSchedulesRouter(deps) {
17826
17914
  try {
17827
17915
  await startScheduleRunOnRequest({ c, item: { run, schedule }, deps });
17828
17916
  } catch (error) {
17829
- await deps.scheduleStore.updateRunStatus({
17917
+ await deps.scheduleStore.updateRun({
17830
17918
  tenant_id: requestContext.tenant_id,
17831
17919
  id: run.id,
17832
17920
  status: "failed",
@@ -17898,7 +17986,7 @@ function createSchedulesRouter(deps) {
17898
17986
  if (record === void 0) {
17899
17987
  return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
17900
17988
  }
17901
- if (!await canReadAgentBoundResource({
17989
+ if (!canEditSchedule(requestContext, record.created_by_subject.subject_id) && !await canReadAgentBoundResource({
17902
17990
  store: deps.resolveAgentStore(c),
17903
17991
  context: requestContext,
17904
17992
  authorizer: deps.authorizer,
@@ -17921,7 +18009,7 @@ function createSchedulesRouter(deps) {
17921
18009
  if (existing === void 0) {
17922
18010
  return c.json({ error: { message: `Schedule not found: ${scheduleId}` } }, 404);
17923
18011
  }
17924
- if (!isScheduleOwner(requestContext, existing.created_by_subject.subject_id)) {
18012
+ if (!canEditSchedule(requestContext, existing.created_by_subject.subject_id)) {
17925
18013
  return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
17926
18014
  }
17927
18015
  let record;
@@ -17963,7 +18051,7 @@ function createSchedulesRouter(deps) {
17963
18051
  if (record === void 0) {
17964
18052
  return c.json({}, 200);
17965
18053
  }
17966
- if (!isScheduleOwner(requestContext, record.created_by_subject.subject_id)) {
18054
+ if (!canEditSchedule(requestContext, record.created_by_subject.subject_id)) {
17967
18055
  return c.json({ error: { message: FORBIDDEN_SCHEDULE_ACCESS } }, 403);
17968
18056
  }
17969
18057
  await deps.scheduleStore.deleteSchedule({
@@ -18168,14 +18256,14 @@ function createInternalMetricsRouter(deps) {
18168
18256
  context: requestContext,
18169
18257
  authorizer: deps.authorizer
18170
18258
  });
18171
- const metrics = await deps.sessionMetricsStore.getSessionMetricsMeters({
18259
+ const metrics2 = await deps.sessionMetricsStore.getSessionMetricsMeters({
18172
18260
  tenant_id: requestContext.tenant_id,
18173
18261
  agent_id: query.agent_id,
18174
18262
  created_by_subject_id: managedAgentIds.includes(query.agent_id) ? void 0 : requestContext.subject.id,
18175
18263
  start_timestamp: query.start_timestamp,
18176
18264
  end_timestamp: query.end_timestamp
18177
18265
  });
18178
- return c.json({ data: metrics }, 200);
18266
+ return c.json({ data: metrics2 }, 200);
18179
18267
  };
18180
18268
  const getSessionMetricsChartsHandler = (c) => {
18181
18269
  return c.json({ data: buildSessionMetricsCharts() }, 200);
@@ -18239,7 +18327,8 @@ function toWireSession(record) {
18239
18327
  updated_at: record.updated_at.toISOString(),
18240
18328
  metrics: record.metrics,
18241
18329
  metadata: record.metadata,
18242
- source: record.source
18330
+ source: record.source,
18331
+ last_turn_details: record.last_turn_details
18243
18332
  };
18244
18333
  }
18245
18334
  function cancelTurnOnThisExecutor(activeTurns, input) {
@@ -18301,9 +18390,15 @@ async function cancelSessionTurn(deps, input) {
18301
18390
  ...extractErrorLogFields6(error)
18302
18391
  };
18303
18392
  if (error instanceof RequestTimeoutError) {
18304
- deps.logger.warn("Timed out waiting for owning executor to cancel; freezing the running turn", fields);
18393
+ deps.logger.warn("Timed out waiting for owning executor to cancel; freezing the running turn", {
18394
+ ...fields,
18395
+ reportable_error: { error, extra: { turn_id: turnId, owner } }
18396
+ });
18305
18397
  } else {
18306
- deps.logger.warn("Failed to reach owning executor over Redis; freezing the running turn", fields);
18398
+ deps.logger.warn("Failed to reach owning executor over Redis; freezing the running turn", {
18399
+ ...fields,
18400
+ reportable_error: { error, extra: { turn_id: turnId, owner } }
18401
+ });
18307
18402
  }
18308
18403
  }
18309
18404
  await freezeTurnIgnoringMissing(deps.session, { turnId, reason });
@@ -18683,7 +18778,7 @@ import { OpenAPIHono as OpenAPIHono19 } from "@hono/zod-openapi";
18683
18778
  // src/apis/modelProviders.ts
18684
18779
  init_modelProviderStore();
18685
18780
  import { OpenAPIHono as OpenAPIHono15 } from "@hono/zod-openapi";
18686
- import { assertSafeOutboundUrl as assertSafeOutboundUrl2 } from "@truefoundry/trueforge-core/core";
18781
+ import { assertSafeOutboundUrl as assertSafeOutboundUrl2, OUTBOUND_URL_BLOCKED as OUTBOUND_URL_BLOCKED2 } from "@truefoundry/trueforge-core/core";
18687
18782
  import { HTTPException as HTTPException15 } from "hono/http-exception";
18688
18783
 
18689
18784
  // src/routes/modelProviderRoutes.ts
@@ -18871,7 +18966,7 @@ function createModelProvidersRouter(deps) {
18871
18966
  try {
18872
18967
  await assertSafeOutboundUrl2(provider.base_url);
18873
18968
  } catch (error) {
18874
- const message = error instanceof Error ? error.message : "Outbound URL blocked";
18969
+ const message = error instanceof Error ? error.message : OUTBOUND_URL_BLOCKED2;
18875
18970
  throw new HTTPException15(400, { message, cause: error });
18876
18971
  }
18877
18972
  try {
@@ -18901,7 +18996,7 @@ function createModelProvidersRouter(deps) {
18901
18996
  try {
18902
18997
  await assertSafeOutboundUrl2(provider.base_url);
18903
18998
  } catch (error) {
18904
- const message = error instanceof Error ? error.message : "Outbound URL blocked";
18999
+ const message = error instanceof Error ? error.message : OUTBOUND_URL_BLOCKED2;
18905
19000
  throw new HTTPException15(400, { message, cause: error });
18906
19001
  }
18907
19002
  try {
@@ -19645,22 +19740,24 @@ function createSettingsRouter(deps) {
19645
19740
  // src/app.ts
19646
19741
  init_config();
19647
19742
 
19648
- // src/http/prometheus.ts
19649
- import { prometheus } from "@hono/prometheus";
19650
- var DURATION_BUCKETS_SECONDS = [0.01, 0.05, 0.1, 0.2, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300];
19651
- var requestDuration = {
19652
- help: "Duration of HTTP requests in seconds",
19653
- buckets: DURATION_BUCKETS_SECONDS
19654
- };
19655
- function createHttpMetrics() {
19656
- const { printMetrics, registerMetrics } = prometheus({
19657
- collectDefaultMetrics: true,
19658
- metricOptions: {
19659
- requestDuration
19660
- }
19661
- });
19662
- return { middleware: registerMetrics, handler: printMetrics };
19743
+ // src/packageVersion.ts
19744
+ import { readFileSync as readFileSync4 } from "fs";
19745
+ import path2 from "path";
19746
+ import { fileURLToPath as fileURLToPath2 } from "url";
19747
+ var PACKAGE_ROOT2 = path2.resolve(path2.dirname(fileURLToPath2(import.meta.url)), "..");
19748
+ function readPackageVersion() {
19749
+ const packageJsonPath = path2.join(PACKAGE_ROOT2, "package.json");
19750
+ const parsed = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
19751
+ if (typeof parsed !== "object" || parsed === null || !("version" in parsed)) {
19752
+ throw new Error(`${packageJsonPath} is missing a version field`);
19753
+ }
19754
+ const { version } = parsed;
19755
+ if (typeof version !== "string" || version.length === 0) {
19756
+ throw new Error(`${packageJsonPath} version must be a non-empty string`);
19757
+ }
19758
+ return version;
19663
19759
  }
19760
+ var PACKAGE_VERSION = readPackageVersion();
19664
19761
 
19665
19762
  // src/app.ts
19666
19763
  init_schedule();
@@ -19752,7 +19849,8 @@ function createAppErrorHandler(params) {
19752
19849
  method: c.req.method,
19753
19850
  path: c.req.path,
19754
19851
  status,
19755
- ...extractErrorLogFields7(error)
19852
+ ...extractErrorLogFields7(error),
19853
+ ...status >= 500 ? { reportable_error: { error } } : {}
19756
19854
  };
19757
19855
  if (status >= 500) {
19758
19856
  params.logger.error(message, fields);
@@ -19832,7 +19930,7 @@ function createServerApp(deps) {
19832
19930
  activeTurns: deps.activeTurns,
19833
19931
  resolveTurnSkillsStore: deps.resolveTurnSkillsStore
19834
19932
  };
19835
- const httpMetrics = createHttpMetrics();
19933
+ const httpMetrics = deps.httpMetrics;
19836
19934
  app.use("*", createRequestLogContextMiddleware());
19837
19935
  app.use("/api/v1/sessions/:session_id/*", createSessionPathLogContextMiddleware());
19838
19936
  app.use("/api/v1/sessions/:session_id/turns/:turn_id/*", createSessionPathLogContextMiddleware());
@@ -20039,6 +20137,7 @@ function createServerApp(deps) {
20039
20137
  authorizer: deps.authorizer,
20040
20138
  resolveAgentStore: deps.resolveAgentStore,
20041
20139
  scheduleStore: deps.scheduleStore,
20140
+ sandboxEnvironmentStore: deps.sandboxEnvironmentStore,
20042
20141
  sessionStore: deps.sessionStore,
20043
20142
  resolveRequestContext
20044
20143
  }),
@@ -20111,6 +20210,42 @@ function createServerApp(deps) {
20111
20210
  }
20112
20211
 
20113
20212
  // src/auth/authorizer.ts
20213
+ init_sandboxEnvironment();
20214
+ async function resolveSchedulePermissions(input) {
20215
+ const data = emptyPermissionsByResourceId(input.resourceIds);
20216
+ const schedules = await input.store.getSchedulesByIds({
20217
+ tenant_id: input.requestContext.tenant_id,
20218
+ ids: [...new Set(input.resourceIds)]
20219
+ });
20220
+ for (const schedule of schedules) {
20221
+ if (canEditSchedule(input.requestContext, schedule.created_by_subject.subject_id)) {
20222
+ data[schedule.id] = [...SCHEDULE_OWNER_PERMISSIONS];
20223
+ }
20224
+ }
20225
+ return listPermissionsData("schedule", data);
20226
+ }
20227
+ async function resolveSandboxEnvironmentPermissions(input) {
20228
+ const data = emptyPermissionsByResourceId(input.resourceIds);
20229
+ const environments = await input.store.getEnvironmentsByIds({
20230
+ tenant_id: input.requestContext.tenant_id,
20231
+ ids: [...new Set(input.resourceIds)]
20232
+ });
20233
+ for (const environment of environments) {
20234
+ if (environment.name === DEFAULT_SANDBOX_ENVIRONMENT_NAME) {
20235
+ continue;
20236
+ }
20237
+ if (canCreateOrEdit(input.requestContext, environment.created_by_subject.subject_id)) {
20238
+ data[environment.id] = [...SANDBOX_ENVIRONMENT_OWNER_PERMISSIONS];
20239
+ }
20240
+ }
20241
+ return listPermissionsData("sandbox_environment", data);
20242
+ }
20243
+ function tenantCreatePermissions(requestContext) {
20244
+ return listPermissionsData("tenant", {
20245
+ agent: [...TENANT_CREATE_AGENT_PERMISSIONS],
20246
+ sandbox_environment: canCreateOrEdit(requestContext) ? [...TENANT_CREATE_SANDBOX_ENVIRONMENT_PERMISSIONS] : []
20247
+ });
20248
+ }
20114
20249
  var TrueForgeAuthorizer = class {
20115
20250
  listAgentAccess() {
20116
20251
  return Promise.resolve({ kind: "all" });
@@ -20123,7 +20258,7 @@ var TrueForgeAuthorizer = class {
20123
20258
  }
20124
20259
  async getPermissions(input) {
20125
20260
  if (input.resourceType === "tenant") {
20126
- return listPermissionsData("tenant", { agent: [...TENANT_CREATE_AGENT_PERMISSIONS] });
20261
+ return tenantCreatePermissions(input.requestContext);
20127
20262
  }
20128
20263
  const data = emptyPermissionsByResourceId(input.resourceIds);
20129
20264
  if (input.resourceType === "agent") {
@@ -20139,15 +20274,10 @@ var TrueForgeAuthorizer = class {
20139
20274
  return listPermissionsData("agent", data);
20140
20275
  }
20141
20276
  if (input.resourceType === "schedule") {
20142
- const ownedIds2 = await input.store.getOwnedIds({
20143
- tenant_id: input.requestContext.tenant_id,
20144
- ids: input.resourceIds,
20145
- subject_id: input.requestContext.subject.id
20146
- });
20147
- for (const id of ownedIds2) {
20148
- data[id] = [...SCHEDULE_OWNER_PERMISSIONS];
20149
- }
20150
- return listPermissionsData("schedule", data);
20277
+ return resolveSchedulePermissions(input);
20278
+ }
20279
+ if (input.resourceType === "sandbox_environment") {
20280
+ return resolveSandboxEnvironmentPermissions(input);
20151
20281
  }
20152
20282
  const ownedIds = await input.store.getOwnedIds({
20153
20283
  tenant_id: input.requestContext.tenant_id,
@@ -20282,7 +20412,7 @@ function loadYamlAtPath(filePath, schema) {
20282
20412
  }
20283
20413
 
20284
20414
  // src/catalog/mcpCatalog.gen.ts
20285
- var shippedMcpCatalogYaml = "# Shipped MCP catalog: server presets offered by\n# GET /api/v1/catalog/mcp-servers for the UI to copy into\n# PUT /api/v1/settings/mcp-servers bodies. Discovery-only \u2014 never executed against.\nmcp_servers:\n - type: remote\n name: linear\n logo: https://assets.production.truefoundry.com/linear.svg\n url: https://mcp.linear.app/mcp\n description: Search, read, and create Linear issues.\n auth:\n type: dcr\n - type: remote\n name: notion\n logo: https://assets.production.truefoundry.com/notion.svg\n url: https://mcp.notion.com/mcp\n description: Search pages, read content, query databases, create pages.\n auth:\n type: dcr\n - type: remote\n name: sentry\n logo: https://assets.production.truefoundry.com/sentry.svg\n url: https://mcp.sentry.dev/mcp\n description: Search errors, read stack traces, and check releases.\n auth:\n type: dcr\n - type: remote\n name: deepwiki\n logo: https://assets.production.truefoundry.com/deepwiki.png\n url: https://mcp.deepwiki.com/mcp\n description: Read documentation and ask questions about any public GitHub repository.\n - type: remote\n name: exa\n logo: https://assets.production.truefoundry.com/exa.svg\n url: https://mcp.exa.ai/mcp\n description: Search the web, fetch page contents, and find similar pages.\n - type: remote\n name: parallel-web\n logo: https://assets.production.truefoundry.com/parallel-web.svg\n url: https://search.parallel.ai/mcp\n description: Search the web and get ranked results with extracted content.\n - type: remote\n name: github\n logo: https://assets.production.truefoundry.com/github.svg\n url: https://api.githubcopilot.com/mcp/\n description: Work with issues, pull requests, repository files, and CI status.\n auth:\n type: header\n headers:\n Authorization: Bearer YOUR_GITHUB_PAT\n - type: remote\n name: tavily\n logo: https://assets.production.truefoundry.com/tavily.svg\n url: https://mcp.tavily.com/mcp\n description: Search the web, extract page content, and crawl sites.\n auth:\n type: header\n headers:\n Authorization: Bearer YOUR_TAVILY_API_KEY\n - type: remote\n name: bright-data\n logo: https://assets.production.truefoundry.com/bright-data.png\n url: https://mcp.brightdata.com/mcp\n description: Search the web and scrape pages, including sites behind bot protection.\n auth:\n type: header\n headers:\n Authorization: Bearer YOUR_BRIGHT_DATA_API_TOKEN\n - type: remote\n name: supabase\n logo: https://assets.production.truefoundry.com/supabase.svg\n url: https://mcp.supabase.com/mcp\n description: Run SQL queries, manage tables, and inspect Supabase projects.\n auth:\n type: dcr\n - type: remote\n name: stripe\n logo: https://assets.production.truefoundry.com/stripe.svg\n url: https://mcp.stripe.com\n description: Create and manage customers, payments, invoices, and subscriptions.\n auth:\n type: dcr\n - type: remote\n name: confluence\n logo: https://assets.production.truefoundry.com/confluence.svg\n url: https://mcp.atlassian.com/v1/mcp\n description: Search spaces, read pages, and create or update content.\n auth:\n type: dcr\n - type: remote\n name: jira\n logo: https://assets.production.truefoundry.com/jira.png\n url: https://mcp.atlassian.com/v1/mcp\n description: Search, read, create, and update Jira issues.\n auth:\n type: dcr\n - type: remote\n name: posthog\n logo: https://assets.production.truefoundry.com/posthog.svg\n url: https://mcp.posthog.com/mcp\n description: Query product analytics, run SQL, and manage feature flags.\n auth:\n type: dcr\n - type: remote\n logo: https://assets.production.truefoundry.com/you.svg\n name: you\n url: https://api.you.com/mcp?profile=free\n description: Search the web, fetch page content, and run multi-step research using You.com. Keyless free profile; pass a You.com API key at https://api.you.com/mcp for full-rate access.\n";
20415
+ var shippedMcpCatalogYaml = "# Shipped MCP catalog: server presets offered by\n# GET /api/v1/catalog/mcp-servers for the UI to copy into\n# PUT /api/v1/settings/mcp-servers bodies. Discovery-only \u2014 never executed against.\nmcp_servers:\n - type: remote\n name: linear\n logo: https://assets.production.truefoundry.com/linear.svg\n url: https://mcp.linear.app/mcp\n description: Search, read, and create Linear issues.\n auth:\n type: dcr\n - type: remote\n name: notion\n logo: https://assets.production.truefoundry.com/notion.svg\n url: https://mcp.notion.com/mcp\n description: Search pages, read content, query databases, create pages.\n auth:\n type: dcr\n - type: remote\n name: sentry\n logo: https://assets.production.truefoundry.com/sentry.svg\n url: https://mcp.sentry.dev/mcp\n description: Search errors, read stack traces, and check releases.\n auth:\n type: dcr\n - type: remote\n name: deepwiki\n logo: https://assets.production.truefoundry.com/deepwiki.png\n url: https://mcp.deepwiki.com/mcp\n description: Read documentation and ask questions about any public GitHub repository.\n - type: remote\n name: exa\n logo: https://assets.production.truefoundry.com/exa.svg\n url: https://mcp.exa.ai/mcp\n description: Search the web, fetch page contents, and find similar pages.\n - type: remote\n name: parallel-web\n logo: https://assets.production.truefoundry.com/parallel-web.svg\n url: https://search.parallel.ai/mcp\n description: Search the web and get ranked results with extracted content.\n - type: remote\n name: github\n logo: https://assets.production.truefoundry.com/github.svg\n url: https://api.githubcopilot.com/mcp/\n description: Work with issues, pull requests, repository files, and CI status.\n auth:\n type: header\n headers:\n Authorization: Bearer YOUR_GITHUB_PAT\n - type: remote\n name: tavily\n logo: https://assets.production.truefoundry.com/tavily.svg\n url: https://mcp.tavily.com/mcp\n description: Search the web, extract page content, and crawl sites.\n auth:\n type: header\n headers:\n Authorization: Bearer YOUR_TAVILY_API_KEY\n - type: remote\n name: bright-data\n logo: https://assets.production.truefoundry.com/bright-data.png\n url: https://mcp.brightdata.com/mcp\n description: Search the web and scrape pages, including sites behind bot protection.\n auth:\n type: header\n headers:\n Authorization: Bearer YOUR_BRIGHT_DATA_API_TOKEN\n - type: remote\n name: supabase\n logo: https://assets.production.truefoundry.com/supabase.svg\n url: https://mcp.supabase.com/mcp\n description: Run SQL queries, manage tables, and inspect Supabase projects.\n auth:\n type: dcr\n - type: remote\n name: stripe\n logo: https://assets.production.truefoundry.com/stripe.svg\n url: https://mcp.stripe.com\n description: Create and manage customers, payments, invoices, and subscriptions.\n auth:\n type: dcr\n - type: remote\n name: confluence\n logo: https://assets.production.truefoundry.com/confluence.svg\n url: https://mcp.atlassian.com/v1/mcp\n description: Search spaces, read pages, and create or update content.\n auth:\n type: dcr\n - type: remote\n name: jira\n logo: https://assets.production.truefoundry.com/jira.png\n url: https://mcp.atlassian.com/v1/mcp\n description: Search, read, create, and update Jira issues.\n auth:\n type: dcr\n - type: remote\n name: posthog\n logo: https://assets.production.truefoundry.com/posthog.svg\n url: https://mcp.posthog.com/mcp\n description: Query product analytics, run SQL, and manage feature flags.\n auth:\n type: dcr\n - type: remote\n logo: https://assets.production.truefoundry.com/you.svg\n name: you\n url: https://api.you.com/mcp?profile=free\n description: Search the web, fetch page content, and run multi-step research using You.com. Keyless free profile; pass a You.com API key at https://api.you.com/mcp for full-rate access.\n - type: remote\n logo: https://assets.production.truefoundry.com/keenable.svg\n name: keenable\n url: https://api.keenable.ai/mcp?keenable_title=trueforge\n description: Search the web and fetch page content as markdown using Keenable. Keyless; add a Keenable API key as an X-API-Key header for higher rate limits.\n";
20286
20416
 
20287
20417
  // src/catalog/McpCatalog.ts
20288
20418
  var McpCatalog = class _McpCatalog {
@@ -20308,7 +20438,7 @@ var McpCatalog = class _McpCatalog {
20308
20438
  init_config();
20309
20439
 
20310
20440
  // src/catalog/modelCatalog.gen.ts
20311
- var shippedModelCatalogYaml = "# Shipped model catalog: provider/model presets offered by\n# GET /api/v1/catalog/model-providers for the UI to copy into\n# PUT /api/v1/settings/model-providers bodies. Discovery-only \u2014 never executed against.\nproviders:\n - type: openai\n logo: https://assets.production.truefoundry.com/openai.svg\n models:\n - model_id: gpt-5.4\n name: gpt-5-4\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.4-mini\n name: gpt-5-4-mini\n properties:\n context_length: 400000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.4-nano\n name: gpt-5-4-nano\n properties:\n context_length: 400000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.4-pro\n name: gpt-5-4-pro\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - medium\n - high\n - xhigh\n - model_id: gpt-5.5\n name: gpt-5-5\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.5-pro\n name: gpt-5-5-pro\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - medium\n - high\n - xhigh\n - model_id: gpt-5.6-luna\n name: gpt-5-6-luna\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-5.6-sol\n name: gpt-5-6-sol\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-5.6-terra\n name: gpt-5-6-terra\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-6-astra\n name: gpt-6-astra\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-6-luna\n name: gpt-6-luna\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-6-sol\n name: gpt-6-sol\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-6.1-sol\n name: gpt-6-1-sol\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - type: anthropic\n logo: https://assets.production.truefoundry.com/anthropic.svg\n models:\n - model_id: claude-fable-5\n name: claude-fable-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-fable-5-1\n name: claude-fable-5-1\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-haiku-4-5\n name: claude-haiku-4-5\n properties:\n context_length: 200000\n max_output_tokens: 64000\n - model_id: claude-haiku-5-5\n name: claude-haiku-5-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-opus-4-8\n name: claude-opus-4-8\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-opus-5\n name: claude-opus-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-opus-5-5\n name: claude-opus-5-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-sonnet-4-6\n name: claude-sonnet-4-6\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - max\n - model_id: claude-sonnet-5\n name: claude-sonnet-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-sonnet-5-5\n name: claude-sonnet-5-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - type: google-gemini\n logo: https://assets.production.truefoundry.com/google-gemini.svg\n models:\n - model_id: gemini-3.1-flash-lite\n name: gemini-3-1-flash-lite\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - minimal\n - low\n - medium\n - high\n - model_id: gemini-3.1-pro-preview\n name: gemini-3-1-pro-preview\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - low\n - medium\n - high\n - model_id: gemini-3.5-flash\n name: gemini-3-5-flash\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n - model_id: gemini-3.5-flash-lite\n name: gemini-3-5-flash-lite\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - minimal\n - low\n - medium\n - high\n - model_id: gemini-3.6-flash\n name: gemini-3-6-flash\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - minimal\n - low\n - medium\n - high\n - model_id: gemini-3.7-flash\n name: gemini-3-7-flash\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - low\n - medium\n - high\n - model_id: gemini-3.8-flash\n name: gemini-3-8-flash\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - low\n - medium\n - high\n - type: fireworks\n logo: https://assets.production.truefoundry.com/fireworks.svg\n models:\n - model_id: accounts/fireworks/models/deepseek-v4-pro\n name: deepseek-v4-pro\n properties:\n context_length: 1048576\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: accounts/fireworks/models/deepseek-v4p1-flash\n name: deepseek-v4p1-flash\n properties:\n context_length: 1000000\n - model_id: accounts/fireworks/models/ember-1\n name: ember-1\n properties:\n context_length: 1048576\n max_output_tokens: 943718\n - model_id: accounts/fireworks/models/glm-5p2\n name: glm-5p2\n properties:\n context_length: 1048576\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: accounts/fireworks/models/glm-5p3\n name: glm-5p3\n properties:\n context_length: 1048576\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: accounts/fireworks/models/glm-5p3-flash\n name: glm-5p3-flash\n properties:\n context_length: 1048576\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: accounts/fireworks/models/kimi-k2p7-code\n name: kimi-k2p7-code\n properties:\n context_length: 262144\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: accounts/fireworks/models/kimi-k3\n name: kimi-k3\n properties:\n context_length: 1048576\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: accounts/fireworks/models/minimax-m3\n name: minimax-m3\n properties:\n context_length: 512000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - type: zai\n logo: https://assets.production.truefoundry.com/zai.svg\n models:\n - model_id: glm-5-turbo\n name: glm-5-turbo\n properties:\n context_length: 200000\n max_output_tokens: 131072\n - model_id: glm-5.1\n name: glm-5-1\n properties:\n context_length: 200000\n max_output_tokens: 131072\n - model_id: glm-5.2\n name: glm-5-2\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: glm-5.3\n name: glm-5-3\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: glm-5.3-flash\n name: glm-5-3-flash\n properties:\n context_length: 1048576\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: glm-5.3-flashx\n name: glm-5-3-flashx\n properties:\n context_length: 1048576\n max_output_tokens: 131072\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: glm-5.3-prime\n name: glm-5-3-prime\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: glm-5v-turbo\n name: glm-5v-turbo\n properties:\n context_length: 202752\n max_output_tokens: 131072\n - type: moonshot\n logo: https://assets.production.truefoundry.com/moonshot.png\n models:\n - model_id: kimi-k2.7-code\n name: kimi-k2-7-code\n properties:\n context_length: 262144\n - model_id: kimi-k3\n name: kimi-k3\n properties:\n context_length: 1048576\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: kimi-k3-fast\n name: kimi-k3-fast\n properties:\n context_length: 1048576\n - type: alibaba\n logo: https://assets.production.truefoundry.com/alibaba.png\n models:\n - model_id: qwen3.7-flash\n name: qwen3-7-flash\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: qwen3.7-max\n name: qwen3-7-max\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: qwen3.7-plus\n name: qwen3-7-plus\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: qwen3.8-flash\n name: qwen3-8-flash\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - low\n - medium\n - xhigh\n - model_id: qwen3.8-max\n name: qwen3-8-max\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: qwen3.8-omni-flash\n name: qwen3-8-omni-flash\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n - type: together\n logo: https://assets.production.truefoundry.com/togetherai.svg\n models:\n - model_id: deepseek-ai/DeepSeek-V4-Flash-0731\n name: deepseek-v4-flash-0731\n properties:\n context_length: 1000000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: deepseek-ai/DeepSeek-V4-Pro\n name: deepseek-v4-pro\n properties:\n context_length: 512000\n reasoning_efforts:\n - high\n - max\n - model_id: deepseek-ai/DeepSeek-V4-Pro-0813\n name: deepseek-v4-pro-0813\n properties:\n context_length: 1048576\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: deepseek-ai/DeepSeek-V4.1-Flash\n name: deepseek-v4-1-flash\n properties:\n context_length: 1000000\n - model_id: MiniMaxAI/MiniMax-M3\n name: minimax-m3\n properties:\n context_length: 524288\n - model_id: moonshotai/Kimi-K2.7-Code\n name: kimi-k2-7-code\n properties:\n context_length: 262144\n - model_id: moonshotai/Kimi-K3\n name: kimi-k3\n properties:\n context_length: 1048576\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - max\n - model_id: Qwen/Qwen3.7-Max\n name: qwen3-7-max\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: Qwen/Qwen3.7-Plus\n name: qwen3-7-plus\n properties:\n context_length: 1000000\n max_output_tokens: 65536\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: Qwen/Qwen3.8-2.4T-A95B\n name: qwen3-8-2-4t-a95b\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - xhigh\n - model_id: Qwen/Qwen3.8-Flash\n name: qwen3-8-flash\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - low\n - medium\n - xhigh\n - model_id: zai-org/GLM-5.2\n name: glm-5-2\n properties:\n context_length: 1048576\n max_output_tokens: 131072\n reasoning_efforts:\n - high\n - max\n - model_id: zai-org/GLM-5.3\n name: glm-5-3\n properties:\n context_length: 1048575\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: zai-org/GLM-5.3-Flash\n name: glm-5-3-flash\n properties:\n context_length: 1048576\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n";
20441
+ var shippedModelCatalogYaml = "# Shipped model catalog: provider/model presets offered by\n# GET /api/v1/catalog/model-providers for the UI to copy into\n# PUT /api/v1/settings/model-providers bodies. Discovery-only \u2014 never executed against.\nproviders:\n - type: openai\n logo: https://assets.production.truefoundry.com/openai.svg\n models:\n - model_id: chat-latest\n name: chat-latest\n properties:\n context_length: 400000\n max_output_tokens: 128000\n reasoning_efforts:\n - medium\n - model_id: gpt-5.3-codex\n name: gpt-5-3-codex\n properties:\n context_length: 400000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.4\n name: gpt-5-4\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.4-mini\n name: gpt-5-4-mini\n properties:\n context_length: 400000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.4-nano\n name: gpt-5-4-nano\n properties:\n context_length: 400000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.4-pro\n name: gpt-5-4-pro\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - medium\n - high\n - xhigh\n - model_id: gpt-5.5\n name: gpt-5-5\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - model_id: gpt-5.5-pro\n name: gpt-5-5-pro\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - medium\n - high\n - xhigh\n - model_id: gpt-5.6-luna\n name: gpt-5-6-luna\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-5.6-sol\n name: gpt-5-6-sol\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-5.6-terra\n name: gpt-5-6-terra\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-6-astra\n name: gpt-6-astra\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-6-luna\n name: gpt-6-luna\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-6-sol\n name: gpt-6-sol\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: gpt-6.1-sol\n name: gpt-6-1-sol\n properties:\n context_length: 1050000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - type: anthropic\n logo: https://assets.production.truefoundry.com/anthropic.svg\n models:\n - model_id: claude-fable-5\n name: claude-fable-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-fable-5-1\n name: claude-fable-5-1\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-haiku-4-5\n name: claude-haiku-4-5\n properties:\n context_length: 200000\n max_output_tokens: 64000\n - model_id: claude-haiku-5-5\n name: claude-haiku-5-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-opus-4-8\n name: claude-opus-4-8\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-opus-5\n name: claude-opus-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-opus-5-5\n name: claude-opus-5-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-sonnet-4-6\n name: claude-sonnet-4-6\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - max\n - model_id: claude-sonnet-5\n name: claude-sonnet-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: claude-sonnet-5-5\n name: claude-sonnet-5-5\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - medium\n - high\n - xhigh\n - max\n - type: google-gemini\n logo: https://assets.production.truefoundry.com/google-gemini.svg\n models:\n - model_id: gemini-3.1-flash-lite\n name: gemini-3-1-flash-lite\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - minimal\n - low\n - medium\n - high\n - model_id: gemini-3.1-pro-preview\n name: gemini-3-1-pro-preview\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - low\n - medium\n - high\n - model_id: gemini-3.5-flash\n name: gemini-3-5-flash\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n - model_id: gemini-3.5-flash-lite\n name: gemini-3-5-flash-lite\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - minimal\n - low\n - medium\n - high\n - model_id: gemini-3.6-flash\n name: gemini-3-6-flash\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - minimal\n - low\n - medium\n - high\n - model_id: gemini-3.7-flash\n name: gemini-3-7-flash\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - low\n - medium\n - high\n - model_id: gemini-3.8-flash\n name: gemini-3-8-flash\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - low\n - medium\n - high\n - model_id: gemini-flash-latest\n name: gemini-flash-latest\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n reasoning_efforts:\n - low\n - medium\n - high\n - model_id: gemini-flash-lite-latest\n name: gemini-flash-lite-latest\n properties:\n context_length: 1048576\n max_output_tokens: 65536\n - model_id: gemma-4-26b-a4b-it\n name: gemma-4-26b-a4b-it\n properties:\n context_length: 262144\n max_output_tokens: 32768\n - model_id: gemma-4-31b-it\n name: gemma-4-31b-it\n properties:\n context_length: 256000\n - type: fireworks\n logo: https://assets.production.truefoundry.com/fireworks.svg\n models:\n - model_id: accounts/fireworks/models/deepseek-v4-pro\n name: deepseek-v4-pro\n properties:\n context_length: 1048576\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: accounts/fireworks/models/deepseek-v4p1-flash\n name: deepseek-v4p1-flash\n properties:\n context_length: 1000000\n - model_id: accounts/fireworks/models/ember-1\n name: ember-1\n properties:\n context_length: 1048576\n max_output_tokens: 943718\n - model_id: accounts/fireworks/models/glm-5p2\n name: glm-5p2\n properties:\n context_length: 1048576\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: accounts/fireworks/models/glm-5p3\n name: glm-5p3\n properties:\n context_length: 1048576\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: accounts/fireworks/models/glm-5p3-flash\n name: glm-5p3-flash\n properties:\n context_length: 1048576\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: accounts/fireworks/models/kimi-k2p7-code\n name: kimi-k2p7-code\n properties:\n context_length: 262144\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: accounts/fireworks/models/kimi-k3\n name: kimi-k3\n properties:\n context_length: 1048576\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: accounts/fireworks/models/minimax-m3\n name: minimax-m3\n properties:\n context_length: 512000\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - xhigh\n - max\n - type: zai\n logo: https://assets.production.truefoundry.com/zai.svg\n models:\n - model_id: glm-5-turbo\n name: glm-5-turbo\n properties:\n context_length: 200000\n max_output_tokens: 131072\n - model_id: glm-5.1\n name: glm-5-1\n properties:\n context_length: 200000\n max_output_tokens: 131072\n - model_id: glm-5.2\n name: glm-5-2\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: glm-5.3\n name: glm-5-3\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: glm-5.3-flash\n name: glm-5-3-flash\n properties:\n context_length: 1048576\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: glm-5.3-flashx\n name: glm-5-3-flashx\n properties:\n context_length: 1048576\n max_output_tokens: 131072\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: glm-5.3-prime\n name: glm-5-3-prime\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: glm-5v-turbo\n name: glm-5v-turbo\n properties:\n context_length: 202752\n max_output_tokens: 131072\n - type: moonshot\n logo: https://assets.production.truefoundry.com/moonshot.png\n models:\n - model_id: kimi-k2.7-code\n name: kimi-k2-7-code\n properties:\n context_length: 262144\n - model_id: kimi-k3\n name: kimi-k3\n properties:\n context_length: 1048576\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: kimi-k3-fast\n name: kimi-k3-fast\n properties:\n context_length: 1048576\n - type: alibaba\n logo: https://assets.production.truefoundry.com/alibaba.png\n models:\n - model_id: qwen3.7-flash\n name: qwen3-7-flash\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: qwen3.7-max\n name: qwen3-7-max\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: qwen3.7-plus\n name: qwen3-7-plus\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: qwen3.8-flash\n name: qwen3-8-flash\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - low\n - medium\n - xhigh\n - model_id: qwen3.8-max\n name: qwen3-8-max\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - max\n - model_id: qwen3.8-omni-flash\n name: qwen3-8-omni-flash\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n - type: together\n logo: https://assets.production.truefoundry.com/togetherai.svg\n models:\n - model_id: deepseek-ai/DeepSeek-V4-Flash-0731\n name: deepseek-v4-flash-0731\n properties:\n context_length: 1000000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: deepseek-ai/DeepSeek-V4-Pro\n name: deepseek-v4-pro\n properties:\n context_length: 512000\n reasoning_efforts:\n - high\n - max\n - model_id: deepseek-ai/DeepSeek-V4-Pro-0813\n name: deepseek-v4-pro-0813\n properties:\n context_length: 1048576\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: deepseek-ai/DeepSeek-V4.1-Flash\n name: deepseek-v4-1-flash\n properties:\n context_length: 1000000\n - model_id: MiniMaxAI/MiniMax-M2.7\n name: minimax-m2-7\n properties:\n context_length: 228700\n - model_id: MiniMaxAI/MiniMax-M3\n name: minimax-m3\n properties:\n context_length: 524288\n - model_id: moonshotai/Kimi-K2.6\n name: kimi-k2-6\n properties:\n context_length: 262144\n - model_id: moonshotai/Kimi-K2.7-Code\n name: kimi-k2-7-code\n properties:\n context_length: 262144\n - model_id: moonshotai/Kimi-K3\n name: kimi-k3\n properties:\n context_length: 1048576\n reasoning_efforts:\n - none\n - low\n - medium\n - high\n - max\n - model_id: nvidia/nemotron-3-ultra-550b-a55b\n name: nemotron-3-ultra-550b-a55b\n properties:\n context_length: 1000000\n - model_id: openai/gpt-oss-120b\n name: gpt-oss-120b\n properties:\n context_length: 131072\n reasoning_efforts:\n - low\n - medium\n - high\n - model_id: Qwen/Qwen3.6-Plus\n name: qwen3-6-plus\n properties:\n context_length: 1000000\n - model_id: Qwen/Qwen3.7-Max\n name: qwen3-7-max\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: Qwen/Qwen3.7-Plus\n name: qwen3-7-plus\n properties:\n context_length: 1000000\n max_output_tokens: 65536\n reasoning_efforts:\n - none\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: Qwen/Qwen3.8-2.4T-A95B\n name: qwen3-8-2-4t-a95b\n properties:\n context_length: 1000000\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - xhigh\n - model_id: Qwen/Qwen3.8-Flash\n name: qwen3-8-flash\n properties:\n context_length: 1000000\n max_output_tokens: 131072\n reasoning_efforts:\n - low\n - medium\n - xhigh\n - model_id: thinkingmachines/Inkling\n name: inkling\n properties:\n context_length: 524288\n - model_id: thinkingmachines/Inkling-Small\n name: inkling-small\n properties:\n context_length: 524288\n reasoning_efforts:\n - minimal\n - low\n - medium\n - high\n - xhigh\n - model_id: zai-org/GLM-5.2\n name: glm-5-2\n properties:\n context_length: 1048576\n max_output_tokens: 131072\n reasoning_efforts:\n - high\n - max\n - model_id: zai-org/GLM-5.2-FP8\n name: glm-5-2-fp8\n properties:\n context_length: 1048576\n max_output_tokens: 131072\n - model_id: zai-org/GLM-5.3\n name: glm-5-3\n properties:\n context_length: 1048575\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: zai-org/GLM-5.3-Flash\n name: glm-5-3-flash\n properties:\n context_length: 1048576\n max_output_tokens: 128000\n reasoning_efforts:\n - low\n - high\n - max\n - model_id: zai-org/GLM-5.3-FP8\n name: glm-5-3-fp8\n properties:\n context_length: 1048576\n reasoning_efforts:\n - low\n - high\n - max\n";
20312
20442
 
20313
20443
  // src/catalog/ModelCatalog.ts
20314
20444
  var ModelCatalog = class _ModelCatalog {
@@ -20606,7 +20736,11 @@ var Controller = class {
20606
20736
  if (signal.aborted) {
20607
20737
  return;
20608
20738
  }
20609
- this.#logger.error("Control loop pass failed", { loop: loop.name, error });
20739
+ this.#logger.error("Control loop pass failed", {
20740
+ loop: loop.name,
20741
+ error,
20742
+ reportable_error: { error, extra: { loop: loop.name } }
20743
+ });
20610
20744
  }
20611
20745
  })();
20612
20746
  state.pass = pass;
@@ -20619,7 +20753,7 @@ var Controller = class {
20619
20753
  };
20620
20754
 
20621
20755
  // src/controller/sandboxEnvBuild.ts
20622
- import { TrueForgeApi } from "@truefoundry/trueforge-sdk";
20756
+ import { TrueForgeApi, TrueForgeError } from "@truefoundry/trueforge-sdk";
20623
20757
  var SANDBOX_ENV_BUILD_INTERVAL_MS = 5e3;
20624
20758
  var SANDBOX_ENV_BUILD_LOOP_NAME = "sandbox-env-build";
20625
20759
  async function dispatchSandboxEnvBuilds({ logger: logger2 }) {
@@ -20637,19 +20771,18 @@ async function dispatchSandboxEnvBuilds({ logger: logger2 }) {
20637
20771
  logger2.warn("Sandbox environment version not found; skipping", {
20638
20772
  environment_version_id: environmentVersionId
20639
20773
  });
20640
- captureCriticalException(error, {
20641
- tags: { module: "sandboxEnvBuild", operation: "progressNotFound" },
20642
- extra: { environment_version_id: environmentVersionId }
20643
- });
20644
20774
  continue;
20645
20775
  }
20776
+ const serverResponded = error instanceof TrueForgeError && typeof error.statusCode === "number";
20646
20777
  logger2.error("Sandbox environment version progress failed", {
20647
20778
  environment_version_id: environmentVersionId,
20648
- error: error instanceof Error ? error.message : String(error)
20649
- });
20650
- captureCriticalException(error, {
20651
- tags: { module: "sandboxEnvBuild", operation: "progress" },
20652
- extra: { environment_version_id: environmentVersionId }
20779
+ error: error instanceof Error ? error.message : String(error),
20780
+ ...serverResponded ? {} : {
20781
+ reportable_error: {
20782
+ error,
20783
+ extra: { environment_version_id: environmentVersionId }
20784
+ }
20785
+ }
20653
20786
  });
20654
20787
  }
20655
20788
  }
@@ -20872,8 +21005,330 @@ function mountFrontend(app, options) {
20872
21005
  return true;
20873
21006
  }
20874
21007
 
21008
+ // src/http/prometheus.ts
21009
+ import { prometheus } from "@hono/prometheus";
21010
+ import { Registry } from "prom-client";
21011
+ var HTTP_REQUEST_DURATION_BUCKETS_SECONDS = [0.01, 0.05, 0.1, 0.2, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300];
21012
+ var requestDuration = {
21013
+ help: "Duration of HTTP requests in seconds",
21014
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS
21015
+ };
21016
+ var metricsScrapeAppendix;
21017
+ var metricsScrapeOnError;
21018
+ function setMetricsScrapeAppendix(options) {
21019
+ metricsScrapeAppendix = options.scrape;
21020
+ metricsScrapeOnError = options.onError;
21021
+ }
21022
+ async function readMetricsScrapeAppendix() {
21023
+ if (metricsScrapeAppendix === void 0) {
21024
+ return "";
21025
+ }
21026
+ try {
21027
+ return await metricsScrapeAppendix();
21028
+ } catch (error) {
21029
+ metricsScrapeOnError?.(error);
21030
+ return "";
21031
+ }
21032
+ }
21033
+ function createHttpMetrics() {
21034
+ const registry = new Registry();
21035
+ const { registerMetrics } = prometheus({
21036
+ registry,
21037
+ collectDefaultMetrics: true,
21038
+ metricOptions: {
21039
+ requestDuration
21040
+ }
21041
+ });
21042
+ const handler = async (c) => {
21043
+ const body = await registry.metrics();
21044
+ const extra = await readMetricsScrapeAppendix();
21045
+ return c.text(extra.length === 0 ? body : `${body}${extra}`);
21046
+ };
21047
+ return { middleware: registerMetrics, handler, registry };
21048
+ }
21049
+
21050
+ // src/observability/agentMetrics.ts
21051
+ import { Counter, Gauge, Histogram } from "prom-client";
21052
+ var TURN_DURATION_BUCKETS_SECONDS = [...HTTP_REQUEST_DURATION_BUCKETS_SECONDS, 600];
21053
+ function createOperationMetrics(registry) {
21054
+ const requests = new Counter({
21055
+ name: "tfg_outbound_http_requests_total",
21056
+ help: "Outbound HTTP requests",
21057
+ labelNames: ["module", "outcome", "status_class"],
21058
+ registers: [registry]
21059
+ });
21060
+ const duration = new Histogram({
21061
+ name: "tfg_outbound_http_request_duration_seconds",
21062
+ help: "Outbound HTTP request duration in seconds",
21063
+ labelNames: ["module", "outcome"],
21064
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21065
+ registers: [registry]
21066
+ });
21067
+ const retries = new Counter({
21068
+ name: "tfg_outbound_http_retries_total",
21069
+ help: "Outbound HTTP retries",
21070
+ labelNames: ["module", "reason"],
21071
+ registers: [registry]
21072
+ });
21073
+ const llmRequests = new Counter({
21074
+ name: "tfg_agent_llm_requests_total",
21075
+ help: "Model calls from an agent step",
21076
+ labelNames: ["provider_type", "outcome"],
21077
+ registers: [registry]
21078
+ });
21079
+ const llmDuration = new Histogram({
21080
+ name: "tfg_agent_llm_request_duration_seconds",
21081
+ help: "Model call duration in seconds, including the provider stream",
21082
+ labelNames: ["provider_type", "outcome", "finish_reason"],
21083
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21084
+ registers: [registry]
21085
+ });
21086
+ const llmTimeToFirstToken = new Histogram({
21087
+ name: "tfg_agent_llm_time_to_first_token_seconds",
21088
+ help: "Seconds until the first model token",
21089
+ labelNames: ["provider_type"],
21090
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21091
+ registers: [registry]
21092
+ });
21093
+ const llmStreamErrors = new Counter({
21094
+ name: "tfg_agent_llm_stream_errors_total",
21095
+ help: "Model stream create and read failures",
21096
+ labelNames: ["provider_type", "error_kind", "status_class"],
21097
+ registers: [registry]
21098
+ });
21099
+ const mcpConnects = new Counter({
21100
+ name: "tfg_agent_mcp_connect_attempts_total",
21101
+ help: "MCP transport connect attempts",
21102
+ labelNames: ["transport", "outcome"],
21103
+ registers: [registry]
21104
+ });
21105
+ const mcpConnectDuration = new Histogram({
21106
+ name: "tfg_agent_mcp_connect_duration_seconds",
21107
+ help: "MCP transport connect duration in seconds",
21108
+ labelNames: ["transport", "outcome"],
21109
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21110
+ registers: [registry]
21111
+ });
21112
+ const mcpOperations = new Counter({
21113
+ name: "tfg_agent_mcp_operations_total",
21114
+ help: "MCP initialize, list, and call operations",
21115
+ labelNames: ["method", "server_class", "outcome"],
21116
+ registers: [registry]
21117
+ });
21118
+ const mcpOperationDuration = new Histogram({
21119
+ name: "tfg_agent_mcp_operation_duration_seconds",
21120
+ help: "MCP operation duration in seconds",
21121
+ labelNames: ["method", "server_class", "outcome"],
21122
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21123
+ registers: [registry]
21124
+ });
21125
+ const mcpSessionRetries = new Counter({
21126
+ name: "tfg_agent_mcp_session_retries_total",
21127
+ help: "MCP session reconnects after expiry",
21128
+ labelNames: ["reason"],
21129
+ registers: [registry]
21130
+ });
21131
+ const mcpDisconnects = new Counter({
21132
+ name: "tfg_agent_mcp_disconnects_total",
21133
+ help: "MCP transport disconnect signals",
21134
+ labelNames: ["via"],
21135
+ registers: [registry]
21136
+ });
21137
+ const harnessLimits = new Counter({
21138
+ name: "tfg_agent_harness_limits_total",
21139
+ help: "Times a configured harness cap fired",
21140
+ labelNames: ["limit"],
21141
+ registers: [registry]
21142
+ });
21143
+ const toolCallDuration = new Histogram({
21144
+ name: "tfg_agent_tool_call_duration_seconds",
21145
+ help: "Tool call duration in seconds",
21146
+ labelNames: ["server_class", "outcome"],
21147
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21148
+ registers: [registry]
21149
+ });
21150
+ const activeThreads = new Counter({
21151
+ name: "tfg_agent_active_threads_total",
21152
+ help: "Agent threads started in this process",
21153
+ registers: [registry]
21154
+ });
21155
+ const turnDuration = new Histogram({
21156
+ name: "tfg_agent_turn_duration_seconds",
21157
+ help: "Turn duration in seconds",
21158
+ labelNames: ["terminal_status"],
21159
+ buckets: TURN_DURATION_BUCKETS_SECONDS,
21160
+ registers: [registry]
21161
+ });
21162
+ const activeTurns = new Gauge({
21163
+ name: "tfg_agent_active_turns",
21164
+ help: "Turns running in this process",
21165
+ registers: [registry]
21166
+ });
21167
+ const turnTimeouts = new Counter({
21168
+ name: "tfg_agent_turn_timeouts_total",
21169
+ help: "Turn execution, subscribe, and SSE write timeouts",
21170
+ labelNames: ["phase"],
21171
+ registers: [registry]
21172
+ });
21173
+ const turnSseDisconnects = new Counter({
21174
+ name: "tfg_agent_turn_sse_disconnects_total",
21175
+ help: "SSE client disconnects during a turn",
21176
+ labelNames: ["path"],
21177
+ registers: [registry]
21178
+ });
21179
+ const turnPersistErrors = new Counter({
21180
+ name: "tfg_agent_turn_persist_errors_total",
21181
+ help: "Turn store write failures",
21182
+ labelNames: ["phase"],
21183
+ registers: [registry]
21184
+ });
21185
+ const parallelRequests = new Counter({
21186
+ name: "tfg_parallel_web_requests_total",
21187
+ help: "Parallel search and extract requests",
21188
+ labelNames: ["operation", "outcome"],
21189
+ registers: [registry]
21190
+ });
21191
+ const parallelDuration = new Histogram({
21192
+ name: "tfg_parallel_web_request_duration_seconds",
21193
+ help: "Parallel search and extract duration in seconds",
21194
+ labelNames: ["operation", "outcome"],
21195
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21196
+ registers: [registry]
21197
+ });
21198
+ const parallelPartialErrors = new Counter({
21199
+ name: "tfg_parallel_web_partial_errors_total",
21200
+ help: "Page errors returned by a successful Parallel extract",
21201
+ registers: [registry]
21202
+ });
21203
+ const serviceFoundryRequests = new Counter({
21204
+ name: "tfg_servicefoundry_requests_total",
21205
+ help: "ServiceFoundry control-plane requests",
21206
+ labelNames: ["operation", "outcome", "status_class"],
21207
+ registers: [registry]
21208
+ });
21209
+ const serviceFoundryDuration = new Histogram({
21210
+ name: "tfg_servicefoundry_request_duration_seconds",
21211
+ help: "ServiceFoundry request duration in seconds",
21212
+ labelNames: ["operation", "outcome"],
21213
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21214
+ registers: [registry]
21215
+ });
21216
+ const postgresQueryDuration = new Histogram({
21217
+ name: "tfg_postgres_query_duration_seconds",
21218
+ help: "Postgres query duration in seconds",
21219
+ labelNames: ["outcome"],
21220
+ buckets: HTTP_REQUEST_DURATION_BUCKETS_SECONDS,
21221
+ registers: [registry]
21222
+ });
21223
+ return {
21224
+ recordOutboundHttpRequest({ module, outcome, statusClass, durationSeconds }) {
21225
+ requests.inc({ module, outcome, status_class: statusClass });
21226
+ duration.observe({ module, outcome }, durationSeconds);
21227
+ },
21228
+ recordOutboundHttpRetry({ module, reason }) {
21229
+ retries.inc({ module, reason });
21230
+ },
21231
+ recordLlmRequest({ providerType, outcome, finishReason, durationSeconds }) {
21232
+ llmRequests.inc({ provider_type: providerType, outcome });
21233
+ llmDuration.observe({ provider_type: providerType, outcome, finish_reason: finishReason }, durationSeconds);
21234
+ },
21235
+ recordLlmTimeToFirstToken({ providerType, durationSeconds }) {
21236
+ llmTimeToFirstToken.observe({ provider_type: providerType }, durationSeconds);
21237
+ },
21238
+ recordLlmStreamError({ providerType, errorKind, statusClass }) {
21239
+ llmStreamErrors.inc({ provider_type: providerType, error_kind: errorKind, status_class: statusClass });
21240
+ },
21241
+ recordMcpConnect({ transport, outcome, durationSeconds }) {
21242
+ mcpConnects.inc({ transport, outcome });
21243
+ mcpConnectDuration.observe({ transport, outcome }, durationSeconds);
21244
+ },
21245
+ recordMcpOperation({ method, serverClass, outcome, durationSeconds }) {
21246
+ mcpOperations.inc({ method, server_class: serverClass, outcome });
21247
+ mcpOperationDuration.observe({ method, server_class: serverClass, outcome }, durationSeconds);
21248
+ },
21249
+ recordMcpSessionRetry({ reason }) {
21250
+ mcpSessionRetries.inc({ reason });
21251
+ },
21252
+ recordMcpDisconnect({ via }) {
21253
+ mcpDisconnects.inc({ via });
21254
+ },
21255
+ recordHarnessLimit({ limit }) {
21256
+ harnessLimits.inc({ limit });
21257
+ },
21258
+ recordToolCall({ serverClass, outcome, durationSeconds }) {
21259
+ toolCallDuration.observe({ server_class: serverClass, outcome }, durationSeconds);
21260
+ },
21261
+ recordActiveThreads({ count }) {
21262
+ activeThreads.inc(count);
21263
+ },
21264
+ recordTurnDuration({ terminalStatus, durationSeconds }) {
21265
+ turnDuration.observe({ terminal_status: terminalStatus }, durationSeconds);
21266
+ },
21267
+ recordActiveTurns({ delta }) {
21268
+ if (delta === 1) {
21269
+ activeTurns.inc();
21270
+ return;
21271
+ }
21272
+ activeTurns.dec();
21273
+ },
21274
+ recordTurnTimeout({ phase }) {
21275
+ turnTimeouts.inc({ phase });
21276
+ },
21277
+ recordTurnSseDisconnect({ path: path7 }) {
21278
+ turnSseDisconnects.inc({ path: path7 });
21279
+ },
21280
+ recordTurnPersistError({ phase }) {
21281
+ turnPersistErrors.inc({ phase });
21282
+ },
21283
+ recordParallelWebRequest({ operation, outcome, durationSeconds }) {
21284
+ parallelRequests.inc({ operation, outcome });
21285
+ parallelDuration.observe({ operation, outcome }, durationSeconds);
21286
+ },
21287
+ recordParallelWebPartialErrors({ count }) {
21288
+ parallelPartialErrors.inc(count);
21289
+ },
21290
+ recordServiceFoundryRequest({ operation, outcome, statusClass, durationSeconds }) {
21291
+ serviceFoundryRequests.inc({ operation, outcome, status_class: statusClass });
21292
+ serviceFoundryDuration.observe({ operation, outcome }, durationSeconds);
21293
+ },
21294
+ recordPostgresQuery({ outcome, durationSeconds }) {
21295
+ postgresQueryDuration.observe({ outcome }, durationSeconds);
21296
+ }
21297
+ };
21298
+ }
21299
+
21300
+ // src/observability/sdkMetrics.ts
21301
+ import { metrics } from "@opentelemetry/api";
21302
+ import { PrometheusExporter, PrometheusSerializer } from "@opentelemetry/exporter-prometheus";
21303
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
21304
+ var scrapeSdkMetrics;
21305
+ function startSdkMetrics() {
21306
+ if (scrapeSdkMetrics !== void 0) {
21307
+ return scrapeSdkMetrics;
21308
+ }
21309
+ const exporter = new PrometheusExporter({
21310
+ preventServerStart: true,
21311
+ withoutTargetInfo: true,
21312
+ withoutScopeInfo: true
21313
+ });
21314
+ const provider = new MeterProvider({ readers: [exporter] });
21315
+ metrics.setGlobalMeterProvider(provider);
21316
+ const serializer = new PrometheusSerializer(void 0, false, void 0, true, true);
21317
+ scrapeSdkMetrics = async () => {
21318
+ const { resourceMetrics, errors } = await exporter.collect();
21319
+ if (errors.length > 0) {
21320
+ const message = errors.map((error) => error instanceof Error ? error.message : String(error)).join("; ");
21321
+ const [first] = errors;
21322
+ throw new Error(`SDK metrics collection failed: ${message}`, first === void 0 ? void 0 : { cause: first });
21323
+ }
21324
+ return serializer.serialize(resourceMetrics);
21325
+ };
21326
+ return scrapeSdkMetrics;
21327
+ }
21328
+
20875
21329
  // src/runtime/activeTurns.ts
20876
21330
  import "@truefoundry/trueforge-core/agent-session";
21331
+ import { getOperationMetrics as getOperationMetrics2 } from "@truefoundry/trueforge-core/core";
20877
21332
  function activeTurnKey(sessionId, turnId) {
20878
21333
  return `${sessionId}:${turnId}`;
20879
21334
  }
@@ -20898,6 +21353,7 @@ var ActiveTurnRegistry = class {
20898
21353
  markCompleted
20899
21354
  };
20900
21355
  this.runs.set(key, run);
21356
+ getOperationMetrics2()?.recordActiveTurns({ delta: 1 });
20901
21357
  if (this.alreadyShutDownAbortReason !== void 0) {
20902
21358
  if (!input.abortController.signal.aborted) {
20903
21359
  input.abortController.abort(this.alreadyShutDownAbortReason);
@@ -20905,6 +21361,7 @@ var ActiveTurnRegistry = class {
20905
21361
  }
20906
21362
  const complete = () => {
20907
21363
  run.markCompleted();
21364
+ getOperationMetrics2()?.recordActiveTurns({ delta: -1 });
20908
21365
  if (this.runs.get(key) === run) {
20909
21366
  this.runs.delete(key);
20910
21367
  }
@@ -20954,6 +21411,246 @@ var ActiveTurnRegistry = class {
20954
21411
  }
20955
21412
  };
20956
21413
 
21414
+ // src/main.ts
21415
+ init_redis();
21416
+
21417
+ // src/sentry/captureCriticalException.ts
21418
+ import * as Sentry from "@sentry/node";
21419
+ var LOG_CONTEXT_TAG_KEYS = ["tenant_id", "request_id", "session_id", "turn_id"];
21420
+ function logContextTags() {
21421
+ const context = currentLogContext();
21422
+ if (context === void 0) {
21423
+ return {};
21424
+ }
21425
+ const tags = {};
21426
+ for (const key of LOG_CONTEXT_TAG_KEYS) {
21427
+ const value = context[key];
21428
+ if (value !== void 0) {
21429
+ tags[key] = value;
21430
+ }
21431
+ }
21432
+ return tags;
21433
+ }
21434
+ function captureCriticalException(err, options) {
21435
+ const tags = { ...logContextTags(), ...options?.tags };
21436
+ Sentry.withScope((scope) => {
21437
+ if (Object.keys(tags).length > 0) {
21438
+ scope.setTags(tags);
21439
+ }
21440
+ if (options?.extra) {
21441
+ scope.setExtras(options.extra);
21442
+ }
21443
+ Sentry.captureException(err);
21444
+ });
21445
+ }
21446
+
21447
+ // src/sentry/initSentry.ts
21448
+ init_config();
21449
+ import * as Sentry3 from "@sentry/node";
21450
+ import winston3 from "winston";
21451
+
21452
+ // src/truefoundry/initTrueFoundrySentry.ts
21453
+ init_config();
21454
+ import * as Sentry2 from "@sentry/node";
21455
+ import { fetch as undiciFetch2 } from "undici";
21456
+ var SENTRY_SERVICE_NAME = "trueforge";
21457
+ async function fetchSentryAuth(input) {
21458
+ const url = `${input.authServerUrl}/api/v1/tenants/sentry-auth-data`;
21459
+ const urlParamsObj = {
21460
+ serviceName: SENTRY_SERVICE_NAME
21461
+ };
21462
+ if (input.tenantName !== void 0 && input.tenantName !== "") {
21463
+ urlParamsObj["tenantName"] = input.tenantName;
21464
+ }
21465
+ const params = new URLSearchParams(urlParamsObj);
21466
+ try {
21467
+ const res = await undiciFetch2(`${url}?${params.toString()}`, {
21468
+ headers: { Authorization: `Bearer ${input.apiKey}` },
21469
+ signal: AbortSignal.timeout(input.timeoutMs)
21470
+ });
21471
+ if (res.status !== 200) {
21472
+ return void 0;
21473
+ }
21474
+ return await res.json();
21475
+ } catch (err) {
21476
+ if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
21477
+ throw new Error(`Timed out fetching sentry auth data after ${String(input.timeoutMs)}ms`, { cause: err });
21478
+ }
21479
+ throw err;
21480
+ }
21481
+ }
21482
+ async function initTrueFoundrySentry(input) {
21483
+ const { logger: logger2, tags } = input;
21484
+ if (!isTrueFoundryModeEnabled(config_default)) {
21485
+ logger2.error("Sentry TrueFoundry init requires TrueFoundry mode; skipping");
21486
+ return false;
21487
+ }
21488
+ const authServerUrl = config_default.TRUEFOUNDRY_AUTH_SERVER_URL;
21489
+ const apiKey = config_default.TRUEFOUNDRY_API_KEY;
21490
+ if (authServerUrl === void 0 || authServerUrl.trim() === "") {
21491
+ logger2.error("TRUEFOUNDRY_AUTH_SERVER_URL is required when SENTRY_ENABLED in TrueFoundry mode");
21492
+ return false;
21493
+ }
21494
+ if (apiKey === void 0 || apiKey.trim() === "") {
21495
+ logger2.error("TRUEFOUNDRY_API_KEY is required when SENTRY_ENABLED in TrueFoundry mode");
21496
+ return false;
21497
+ }
21498
+ try {
21499
+ const authData = await fetchSentryAuth({
21500
+ authServerUrl,
21501
+ apiKey,
21502
+ tenantName: config_default.TRUEFOUNDRY_TENANT_NAME,
21503
+ timeoutMs: config_default.TRUEFOUNDRY_SERVICEFOUNDRY_HTTP_TIMEOUT_MS
21504
+ });
21505
+ if (authData === void 0 || typeof authData !== "object" || authData === null) {
21506
+ logger2.error("Failed to fetch sentry config. Skipping initialization");
21507
+ return false;
21508
+ }
21509
+ const sentryInitOptions = {};
21510
+ Object.assign(sentryInitOptions, authData);
21511
+ sentryInitOptions.includeLocalVariables = false;
21512
+ sentryInitOptions.defaultIntegrations = false;
21513
+ sentryInitOptions.integrations = [Sentry2.linkedErrorsIntegration()];
21514
+ Sentry2.init(sentryInitOptions);
21515
+ Sentry2.getGlobalScope().setTag("TRUEFORGE_VERSION", PACKAGE_VERSION);
21516
+ if (tags) {
21517
+ for (const [key, value] of Object.entries(tags)) {
21518
+ Sentry2.getGlobalScope().setTag(key, value);
21519
+ }
21520
+ }
21521
+ logger2.info("Sentry initialised (TrueFoundry auth server)");
21522
+ return true;
21523
+ } catch (error) {
21524
+ logger2.error("Error in fetching sentry auth data; skipping Sentry initialization", {
21525
+ error: error instanceof Error ? error.message : error
21526
+ });
21527
+ return false;
21528
+ }
21529
+ }
21530
+
21531
+ // src/sentry/reportMarkedLog.ts
21532
+ import winston2 from "winston";
21533
+ function readExtra(value) {
21534
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
21535
+ return void 0;
21536
+ }
21537
+ const extra = {};
21538
+ for (const key of Object.keys(value)) {
21539
+ extra[key] = Reflect.get(value, key);
21540
+ }
21541
+ return extra;
21542
+ }
21543
+ function readFilePath(value) {
21544
+ if (typeof value !== "object" || value === null || !("filepath" in value)) {
21545
+ return void 0;
21546
+ }
21547
+ const filepath = Reflect.get(value, "filepath");
21548
+ if (typeof filepath !== "string" || filepath.length === 0) {
21549
+ return void 0;
21550
+ }
21551
+ return filepath;
21552
+ }
21553
+ function readReportableError(value) {
21554
+ if (typeof value !== "object" || value === null || !("error" in value)) {
21555
+ return void 0;
21556
+ }
21557
+ return {
21558
+ error: Reflect.get(value, "error"),
21559
+ extra: readExtra(Reflect.get(value, "extra")),
21560
+ filepath: readFilePath(value)
21561
+ };
21562
+ }
21563
+ function toError(value) {
21564
+ if (value instanceof Error) {
21565
+ return value;
21566
+ }
21567
+ if (typeof value !== "string" || value.length === 0) {
21568
+ return void 0;
21569
+ }
21570
+ return new Error(value, { cause: value });
21571
+ }
21572
+ function errorWithLogTitle({ message, cause }) {
21573
+ const titled = new Error(message, { cause });
21574
+ const causeStack = cause.stack;
21575
+ if (causeStack === void 0) {
21576
+ titled.stack = `${titled.name}: ${message}`;
21577
+ return titled;
21578
+ }
21579
+ const frameStart = causeStack.indexOf("\n");
21580
+ const frames = frameStart === -1 ? "" : causeStack.slice(frameStart);
21581
+ titled.stack = `${titled.name}: ${message}${frames}`;
21582
+ return titled;
21583
+ }
21584
+ function reportedError({ message, cause }) {
21585
+ if (typeof message === "string" && message.length > 0) {
21586
+ return errorWithLogTitle({ message, cause });
21587
+ }
21588
+ return cause;
21589
+ }
21590
+ function reportMarkedLogFormat() {
21591
+ return winston2.format((info) => {
21592
+ const marked = readReportableError(info["reportable_error"]);
21593
+ if (marked !== void 0) {
21594
+ const cause = toError(marked.error);
21595
+ if (cause !== void 0) {
21596
+ captureCriticalException(reportedError({ message: info.message, cause }), {
21597
+ ...marked.filepath !== void 0 ? { tags: { filepath: marked.filepath } } : {},
21598
+ ...marked.extra !== void 0 ? { extra: marked.extra } : {}
21599
+ });
21600
+ }
21601
+ }
21602
+ Reflect.deleteProperty(info, "reportable_error");
21603
+ return info;
21604
+ })();
21605
+ }
21606
+
21607
+ // src/sentry/initSentry.ts
21608
+ function isLocalLikeEnv(nodeEnv) {
21609
+ return nodeEnv === "development" || nodeEnv === "test" || nodeEnv === "local";
21610
+ }
21611
+ function applyGlobalTags(tags) {
21612
+ const scope = Sentry3.getGlobalScope();
21613
+ for (const [key, value] of Object.entries(tags)) {
21614
+ scope.setTag(key, value);
21615
+ }
21616
+ }
21617
+ function attachMarkedLogReporting(logger2) {
21618
+ logger2.format = winston3.format.combine(reportMarkedLogFormat(), logger2.format);
21619
+ }
21620
+ async function initSentry(config, logger2, options) {
21621
+ if (!config.SENTRY_ENABLED || isLocalLikeEnv(config.NODE_ENV)) {
21622
+ logger2.info("Sentry is not enabled (SENTRY_ENABLED=false or local-like NODE_ENV)");
21623
+ return;
21624
+ }
21625
+ const globalTags = {
21626
+ service: "trueforge",
21627
+ TRUEFORGE_VERSION: PACKAGE_VERSION,
21628
+ ...config.SENTRY_ADDITIONAL_TAGS,
21629
+ ...options?.tags
21630
+ };
21631
+ if (isTrueFoundryModeEnabled(config)) {
21632
+ const ready = await initTrueFoundrySentry({ logger: logger2, tags: globalTags });
21633
+ if (ready) {
21634
+ attachMarkedLogReporting(logger2);
21635
+ }
21636
+ return;
21637
+ }
21638
+ const dsn = config.SENTRY_DSN;
21639
+ if (dsn === void 0 || dsn.trim() === "") {
21640
+ logger2.error("SENTRY_DSN is required when SENTRY_ENABLED=true");
21641
+ return;
21642
+ }
21643
+ Sentry3.init({
21644
+ dsn,
21645
+ includeLocalVariables: false,
21646
+ defaultIntegrations: false,
21647
+ integrations: [Sentry3.linkedErrorsIntegration()]
21648
+ });
21649
+ applyGlobalTags(globalTags);
21650
+ attachMarkedLogReporting(logger2);
21651
+ logger2.info("Sentry initialised");
21652
+ }
21653
+
20957
21654
  // src/startupBanner.ts
20958
21655
  var STANDALONE_MODE_DISCLAIMER = "Standalone mode is intended for local use on your own machine. It is not hardened for production or shared internet access \u2014 please keep it on localhost. We cannot take responsibility for data loss or unauthorized access if this mode is used beyond that.";
20959
21656
  var ANSI_SHADOW = {
@@ -21406,10 +22103,16 @@ function parsePerServerMcpHeaders(raw) {
21406
22103
  // src/truefoundry/TrueFoundryAgentStore.ts
21407
22104
  init_agentStore();
21408
22105
  init_PostgresAgentStore();
22106
+ import { extractErrorLogFields as extractErrorLogFields9 } from "@truefoundry/trueforge-core/core";
21409
22107
  import { sql as sql3 } from "kysely";
21410
22108
 
21411
22109
  // src/truefoundry/TrueFoundryServiceFoundryServerClient.ts
21412
- import { extractErrorLogFields as extractErrorLogFields8 } from "@truefoundry/trueforge-core/core";
22110
+ import {
22111
+ elapsedSeconds,
22112
+ extractErrorLogFields as extractErrorLogFields8,
22113
+ getOperationMetrics as getOperationMetrics4,
22114
+ httpStatusClass
22115
+ } from "@truefoundry/trueforge-core/core";
21413
22116
  import { HTTPException as HTTPException25 } from "hono/http-exception";
21414
22117
  import { LRUCache } from "lru-cache";
21415
22118
  import { fetch as undiciFetch3 } from "undici";
@@ -21630,6 +22333,25 @@ var ListResponseSchema = z45.union([
21630
22333
  pagination: z45.object({ total: z45.number().optional() }).optional()
21631
22334
  })
21632
22335
  ]);
22336
+ var SERVICE_FOUNDRY_OPERATIONS = {
22337
+ listProviderIntegrations: "model_providers",
22338
+ listGatewayInstallations: "gateway_installations",
22339
+ listMcpServers: "mcp_servers",
22340
+ getMcpServerByName: "mcp_servers",
22341
+ putRemoteAgent: "agents",
22342
+ deleteRemoteAgent: "agents",
22343
+ listAgentSkills: "skills",
22344
+ listAgentSkillVersions: "skills",
22345
+ resolveAgentSkillVersions: "skills",
22346
+ getMcpAuthorize: "mcp_servers",
22347
+ getMcpAuthStatus: "mcp_servers",
22348
+ deleteMcpAuth: "mcp_servers",
22349
+ getSession: "get_session",
22350
+ getTenantControlPlaneUrl: "get_session",
22351
+ getAgentPermissions: "agent_permissions",
22352
+ getTenantPermissions: "tenant_permissions",
22353
+ vendToken: "vend_token"
22354
+ };
21633
22355
  var ServiceFoundryErrorSchema = z45.object({
21634
22356
  message: z45.union([z45.string(), z45.array(z45.string())]).optional()
21635
22357
  });
@@ -21702,6 +22424,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21702
22424
  };
21703
22425
  const query = { type: "model", mergeParams: "true", ...filterQuery };
21704
22426
  const payload = await this.#requestJson({
22427
+ operation: SERVICE_FOUNDRY_OPERATIONS.listProviderIntegrations,
21705
22428
  url: this.#url(INTEGRATIONS_PATH, query),
21706
22429
  accessToken: input.accessToken,
21707
22430
  method: "GET"
@@ -21710,6 +22433,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21710
22433
  }
21711
22434
  listGatewayInstallations(accessToken) {
21712
22435
  return this.#requestJson({
22436
+ operation: SERVICE_FOUNDRY_OPERATIONS.listGatewayInstallations,
21713
22437
  url: this.#url(INSTALLATIONS_PATH),
21714
22438
  accessToken,
21715
22439
  method: "GET"
@@ -21723,6 +22447,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21723
22447
  })
21724
22448
  };
21725
22449
  const payload = await this.#requestJson({
22450
+ operation: SERVICE_FOUNDRY_OPERATIONS.listMcpServers,
21726
22451
  url: this.#url(MCP_SERVERS_PATH, query),
21727
22452
  accessToken: input.accessToken,
21728
22453
  method: "GET"
@@ -21736,6 +22461,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21736
22461
  values: [{ field: "name", op: "EQUAL", value: input.name }]
21737
22462
  });
21738
22463
  const payload = await this.#requestJson({
22464
+ operation: SERVICE_FOUNDRY_OPERATIONS.getMcpServerByName,
21739
22465
  url: this.#url(MCP_SERVERS_PATH, { filter, limit: "1", offset: "0" }),
21740
22466
  accessToken: input.accessToken,
21741
22467
  method: "GET"
@@ -21752,6 +22478,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21752
22478
  /** PUT `/internal/tfg/agents` — create/reuse remote agent + sync model/MCP grants. */
21753
22479
  async putRemoteAgent(input) {
21754
22480
  const payload = await this.#requestJson({
22481
+ operation: SERVICE_FOUNDRY_OPERATIONS.putRemoteAgent,
21755
22482
  url: this.#url(TFG_AGENTS_PATH),
21756
22483
  accessToken: input.accessToken,
21757
22484
  method: "PUT",
@@ -21766,7 +22493,8 @@ var TrueFoundryServiceFoundryServerClient = class {
21766
22493
  const parsed = PutRemoteAgentResponseSchema.safeParse(payload);
21767
22494
  if (!parsed.success) {
21768
22495
  this.#logger.error("TrueFoundry ServiceFoundry put remote agent returned an unexpected response", {
21769
- ...extractErrorLogFields8(parsed.error)
22496
+ ...extractErrorLogFields8(parsed.error),
22497
+ reportable_error: { error: parsed.error }
21770
22498
  });
21771
22499
  throw new HTTPException25(424, {
21772
22500
  message: "TrueFoundry ServiceFoundry put remote agent returned an unexpected response",
@@ -21778,6 +22506,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21778
22506
  /** DELETE `/internal/tfg/agents/:id` — remove remote agent. Missing agent (404) is success. */
21779
22507
  async deleteRemoteAgent(input) {
21780
22508
  await this.#requestJson({
22509
+ operation: SERVICE_FOUNDRY_OPERATIONS.deleteRemoteAgent,
21781
22510
  url: this.#url(`${TFG_AGENTS_PATH}/${encodeURIComponent(input.externalId)}`),
21782
22511
  accessToken: input.accessToken,
21783
22512
  method: "DELETE",
@@ -21788,6 +22517,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21788
22517
  /** `GET /v1/agent-skills` with empty skills excluded. */
21789
22518
  async listAgentSkills(input) {
21790
22519
  return this.#listAllPages({
22520
+ operation: SERVICE_FOUNDRY_OPERATIONS.listAgentSkills,
21791
22521
  path: AGENT_SKILLS_PATH,
21792
22522
  accessToken: input.accessToken,
21793
22523
  query: { include_empty_agent_skills: "false" },
@@ -21804,6 +22534,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21804
22534
  query["agent_skill_id"] = input.agent_skill_id;
21805
22535
  }
21806
22536
  return this.#listAllPages({
22537
+ operation: SERVICE_FOUNDRY_OPERATIONS.listAgentSkillVersions,
21807
22538
  path: AGENT_SKILL_VERSIONS_PATH,
21808
22539
  accessToken: input.accessToken,
21809
22540
  query,
@@ -21823,6 +22554,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21823
22554
  for (let i = 0; i < input.skills.length; i += AGENT_SKILL_RESOLVE_CHUNK_SIZE) {
21824
22555
  const chunk = input.skills.slice(i, i + AGENT_SKILL_RESOLVE_CHUNK_SIZE);
21825
22556
  const payload = await this.#requestJson({
22557
+ operation: SERVICE_FOUNDRY_OPERATIONS.resolveAgentSkillVersions,
21826
22558
  url: this.#url(TFG_AGENT_SKILL_VERSIONS_RESOLVE_PATH),
21827
22559
  accessToken: input.accessToken,
21828
22560
  method: "POST",
@@ -21853,6 +22585,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21853
22585
  const items = [];
21854
22586
  for (; ; ) {
21855
22587
  const payload = await this.#requestJson({
22588
+ operation: input.operation,
21856
22589
  url: this.#url(input.path, {
21857
22590
  ...input.query,
21858
22591
  offset: String(items.length),
@@ -21880,6 +22613,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21880
22613
  search["gatewayBaseURL"] = input.gatewayBaseURL;
21881
22614
  }
21882
22615
  const payload = await this.#requestJson({
22616
+ operation: SERVICE_FOUNDRY_OPERATIONS.getMcpAuthorize,
21883
22617
  url: this.#url(`${MCP_SERVERS_PATH}/${encodeURIComponent(input.mcpServerId)}/authorize`, search),
21884
22618
  accessToken: input.accessToken,
21885
22619
  method: "GET"
@@ -21889,7 +22623,8 @@ var TrueFoundryServiceFoundryServerClient = class {
21889
22623
  } catch (error) {
21890
22624
  this.#logger.error("TrueFoundry ServiceFoundry MCP authorize returned an unexpected response", {
21891
22625
  mcpServerId: input.mcpServerId,
21892
- ...extractErrorLogFields8(error)
22626
+ ...extractErrorLogFields8(error),
22627
+ reportable_error: { error, extra: { mcp_server_id: input.mcpServerId } }
21893
22628
  });
21894
22629
  throw new HTTPException25(424, {
21895
22630
  message: "TrueFoundry ServiceFoundry MCP authorize returned an unexpected response",
@@ -21900,6 +22635,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21900
22635
  /** Per-subject auth status without seeding a consent URL. */
21901
22636
  async getMcpAuthStatus(input) {
21902
22637
  const payload = await this.#requestJson({
22638
+ operation: SERVICE_FOUNDRY_OPERATIONS.getMcpAuthStatus,
21903
22639
  url: this.#url(`${MCP_SERVERS_PATH}/${encodeURIComponent(input.mcpServerId)}/auth/status`, {
21904
22640
  subjectId: input.subjectId,
21905
22641
  subjectType: input.subjectType
@@ -21912,7 +22648,8 @@ var TrueFoundryServiceFoundryServerClient = class {
21912
22648
  } catch (error) {
21913
22649
  this.#logger.error("TrueFoundry ServiceFoundry MCP auth status returned an unexpected response", {
21914
22650
  mcpServerId: input.mcpServerId,
21915
- ...extractErrorLogFields8(error)
22651
+ ...extractErrorLogFields8(error),
22652
+ reportable_error: { error, extra: { mcp_server_id: input.mcpServerId } }
21916
22653
  });
21917
22654
  throw new HTTPException25(424, {
21918
22655
  message: "TrueFoundry ServiceFoundry MCP auth status returned an unexpected response",
@@ -21923,6 +22660,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21923
22660
  /** Revoke the subject's OAuth token or auth-override. */
21924
22661
  async deleteMcpAuth(input) {
21925
22662
  await this.#requestJson({
22663
+ operation: SERVICE_FOUNDRY_OPERATIONS.deleteMcpAuth,
21926
22664
  url: this.#url(`${MCP_SERVERS_PATH}/${encodeURIComponent(input.mcpServerId)}/auth`),
21927
22665
  accessToken: input.accessToken,
21928
22666
  method: "DELETE",
@@ -21941,6 +22679,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21941
22679
  let payload;
21942
22680
  try {
21943
22681
  payload = await this.#requestJson({
22682
+ operation: SERVICE_FOUNDRY_OPERATIONS.getSession,
21944
22683
  url: this.#url(SESSION_PATH),
21945
22684
  accessToken,
21946
22685
  method: "GET"
@@ -21978,6 +22717,7 @@ var TrueFoundryServiceFoundryServerClient = class {
21978
22717
  let payload;
21979
22718
  try {
21980
22719
  payload = await this.#requestJson({
22720
+ operation: SERVICE_FOUNDRY_OPERATIONS.getTenantControlPlaneUrl,
21981
22721
  url: this.#url(SESSION_PATH, { tenantName: input.tenantName }),
21982
22722
  accessToken: this.#apiKey,
21983
22723
  method: "GET"
@@ -22002,6 +22742,7 @@ var TrueFoundryServiceFoundryServerClient = class {
22002
22742
  }
22003
22743
  async getAgentPermissions(input) {
22004
22744
  const payload = await this.#requestJson({
22745
+ operation: SERVICE_FOUNDRY_OPERATIONS.getAgentPermissions,
22005
22746
  url: this.#url(AGENT_PERMISSIONS_PATH, {
22006
22747
  resourceType: "agent",
22007
22748
  v2: "true",
@@ -22013,7 +22754,8 @@ var TrueFoundryServiceFoundryServerClient = class {
22013
22754
  const parsed = AgentPermissionsSchema.safeParse(payload);
22014
22755
  if (!parsed.success) {
22015
22756
  this.#logger.error("TrueFoundry ServiceFoundry agent permissions response was malformed", {
22016
- ...extractErrorLogFields8(parsed.error)
22757
+ ...extractErrorLogFields8(parsed.error),
22758
+ reportable_error: { error: parsed.error }
22017
22759
  });
22018
22760
  throw new HTTPException25(424, {
22019
22761
  message: "TrueFoundry ServiceFoundry agent permissions response was malformed",
@@ -22028,6 +22770,7 @@ var TrueFoundryServiceFoundryServerClient = class {
22028
22770
  */
22029
22771
  async getTenantPermissions(input) {
22030
22772
  const payload = await this.#requestJson({
22773
+ operation: SERVICE_FOUNDRY_OPERATIONS.getTenantPermissions,
22031
22774
  url: this.#url(AGENT_PERMISSIONS_PATH, { resourceType: "tenant", v2: "true" }),
22032
22775
  accessToken: input.accessToken,
22033
22776
  method: "GET"
@@ -22035,7 +22778,8 @@ var TrueFoundryServiceFoundryServerClient = class {
22035
22778
  const parsed = z45.array(z45.string()).safeParse(payload);
22036
22779
  if (!parsed.success) {
22037
22780
  this.#logger.error("TrueFoundry ServiceFoundry tenant permissions response was malformed", {
22038
- ...extractErrorLogFields8(parsed.error)
22781
+ ...extractErrorLogFields8(parsed.error),
22782
+ reportable_error: { error: parsed.error }
22039
22783
  });
22040
22784
  throw new HTTPException25(424, {
22041
22785
  message: "TrueFoundry ServiceFoundry tenant permissions response was malformed",
@@ -22051,6 +22795,7 @@ var TrueFoundryServiceFoundryServerClient = class {
22051
22795
  */
22052
22796
  async vendToken(input) {
22053
22797
  const payload = await this.#requestJson({
22798
+ operation: SERVICE_FOUNDRY_OPERATIONS.vendToken,
22054
22799
  url: this.#url(VEND_TOKEN_PATH),
22055
22800
  accessToken: this.#apiKey,
22056
22801
  method: "POST",
@@ -22065,7 +22810,8 @@ var TrueFoundryServiceFoundryServerClient = class {
22065
22810
  const parsed = VendTokenResponseSchema.safeParse(payload);
22066
22811
  if (!parsed.success) {
22067
22812
  this.#logger.error("TrueFoundry ServiceFoundry vend-token response was malformed", {
22068
- ...extractErrorLogFields8(parsed.error)
22813
+ ...extractErrorLogFields8(parsed.error),
22814
+ reportable_error: { error: parsed.error }
22069
22815
  });
22070
22816
  throw new HTTPException25(424, {
22071
22817
  message: "TrueFoundry ServiceFoundry vend-token response was malformed",
@@ -22078,7 +22824,8 @@ var TrueFoundryServiceFoundryServerClient = class {
22078
22824
  const parsed = ListResponseSchema.safeParse(payload);
22079
22825
  if (!parsed.success) {
22080
22826
  this.#logger.error("TrueFoundry ServiceFoundry server returned an unexpected list response", {
22081
- ...extractErrorLogFields8(parsed.error)
22827
+ ...extractErrorLogFields8(parsed.error),
22828
+ reportable_error: { error: parsed.error }
22082
22829
  });
22083
22830
  throw new HTTPException25(424, {
22084
22831
  message: "TrueFoundry ServiceFoundry server returned an unexpected list response",
@@ -22098,6 +22845,16 @@ var TrueFoundryServiceFoundryServerClient = class {
22098
22845
  }
22099
22846
  async #requestJson(input) {
22100
22847
  const startedAt = Date.now();
22848
+ const startedMs = performance.now();
22849
+ const metrics2 = getOperationMetrics4();
22850
+ const record = (outcome, status) => {
22851
+ metrics2?.recordServiceFoundryRequest({
22852
+ operation: input.operation,
22853
+ outcome,
22854
+ statusClass: httpStatusClass(status),
22855
+ durationSeconds: elapsedSeconds(startedMs)
22856
+ });
22857
+ };
22101
22858
  const timeoutMs = input.timeoutMs ?? this.#httpTimeoutMs;
22102
22859
  const headers = {
22103
22860
  accept: "application/json",
@@ -22119,6 +22876,7 @@ var TrueFoundryServiceFoundryServerClient = class {
22119
22876
  });
22120
22877
  } catch (error) {
22121
22878
  const timedOut = error instanceof Error && error.name === "TimeoutError";
22879
+ record(timedOut ? "timeout" : "error");
22122
22880
  this.#logger.error("TrueFoundry ServiceFoundry server request failed", {
22123
22881
  url: input.url.href,
22124
22882
  method: input.method,
@@ -22138,33 +22896,42 @@ var TrueFoundryServiceFoundryServerClient = class {
22138
22896
  durationMs: Date.now() - startedAt
22139
22897
  });
22140
22898
  if (response.status === 401 || response.status === 403) {
22899
+ record("error", response.status);
22141
22900
  const detail = await readServiceFoundryErrorMessage(response);
22142
22901
  throw new HTTPException25(response.status, {
22143
22902
  message: `TrueFoundry ServiceFoundry server rejected the request: ${detail ?? `HTTP ${String(response.status)}`}`
22144
22903
  });
22145
22904
  }
22146
22905
  if (response.status === 404 && input.notFoundOk) {
22906
+ record("success", response.status);
22147
22907
  return void 0;
22148
22908
  }
22149
22909
  if (!response.ok) {
22910
+ record("error", response.status);
22150
22911
  const detail = await readServiceFoundryErrorMessage(response);
22151
22912
  throw new HTTPException25(424, {
22152
22913
  message: `TrueFoundry ServiceFoundry server request failed: ${detail ?? `HTTP ${String(response.status)}`}`
22153
22914
  });
22154
22915
  }
22155
22916
  if (response.status === 204) {
22917
+ record("success", response.status);
22156
22918
  return void 0;
22157
22919
  }
22158
22920
  const text = await response.text();
22159
22921
  if (text.length === 0) {
22922
+ record("success", response.status);
22160
22923
  return void 0;
22161
22924
  }
22162
22925
  try {
22163
- return JSON.parse(text);
22926
+ const parsed = JSON.parse(text);
22927
+ record("success", response.status);
22928
+ return parsed;
22164
22929
  } catch (error) {
22930
+ record("error", response.status);
22165
22931
  this.#logger.error("TrueFoundry ServiceFoundry server returned non-JSON", {
22166
22932
  url: input.url.href,
22167
- ...extractErrorLogFields8(error)
22933
+ ...extractErrorLogFields8(error),
22934
+ reportable_error: { error }
22168
22935
  });
22169
22936
  throw new HTTPException25(424, {
22170
22937
  message: "TrueFoundry ServiceFoundry server returned non-JSON",
@@ -22195,11 +22962,13 @@ var TrueFoundryAgentStore = class {
22195
22962
  #client;
22196
22963
  #resolveAccessToken;
22197
22964
  #db;
22965
+ #logger;
22198
22966
  constructor(input) {
22199
22967
  this.#inner = input.inner;
22200
22968
  this.#client = input.client;
22201
22969
  this.#resolveAccessToken = callerAccessToken(input.context);
22202
22970
  this.#db = input.db;
22971
+ this.#logger = input.logger;
22203
22972
  }
22204
22973
  listAgents(input, transaction) {
22205
22974
  return this.#inner.listAgents(input, transaction);
@@ -22272,13 +23041,20 @@ var TrueFoundryAgentStore = class {
22272
23041
  const aggregate = new AggregateError(failures, "createAgent failed and cleanup also failed", {
22273
23042
  cause: error
22274
23043
  });
22275
- captureCriticalException(aggregate, {
22276
- tags: { module: "TrueFoundryAgentStore", operation: "dualWrite" },
22277
- extra: {
22278
- agent_id: created.id,
22279
- agent_name: created.name,
22280
- tenant_id: input.tenant_id,
22281
- external_id: externalId
23044
+ this.#logger.error("createAgent failed and cleanup also failed", {
23045
+ ...extractErrorLogFields9(aggregate),
23046
+ agent_id: created.id,
23047
+ agent_name: created.name,
23048
+ tenant_id: input.tenant_id,
23049
+ external_id: externalId,
23050
+ reportable_error: {
23051
+ error: aggregate,
23052
+ extra: {
23053
+ agent_id: created.id,
23054
+ agent_name: created.name,
23055
+ tenant_id: input.tenant_id,
23056
+ external_id: externalId
23057
+ }
22282
23058
  }
22283
23059
  });
22284
23060
  throw aggregate;
@@ -22332,13 +23108,20 @@ var TrueFoundryAgentStore = class {
22332
23108
  "updateAgent failed and ServiceFoundry restore also failed",
22333
23109
  { cause: restoreError }
22334
23110
  );
22335
- captureCriticalException(aggregate, {
22336
- tags: { module: "TrueFoundryAgentStore", operation: "dualWrite" },
22337
- extra: {
22338
- agent_id: input.id,
22339
- agent_name: previous.name,
22340
- tenant_id: input.tenant_id,
22341
- external_id: previous.external_id
23111
+ this.#logger.error("updateAgent failed and ServiceFoundry restore also failed", {
23112
+ ...extractErrorLogFields9(aggregate),
23113
+ agent_id: input.id,
23114
+ agent_name: previous.name,
23115
+ tenant_id: input.tenant_id,
23116
+ external_id: previous.external_id,
23117
+ reportable_error: {
23118
+ error: aggregate,
23119
+ extra: {
23120
+ agent_id: input.id,
23121
+ agent_name: previous.name,
23122
+ tenant_id: input.tenant_id,
23123
+ external_id: previous.external_id
23124
+ }
22342
23125
  }
22343
23126
  });
22344
23127
  throw aggregate;
@@ -22418,7 +23201,8 @@ var TrueFoundryAuthorizer = class {
22418
23201
  accessToken: requireUserCredential(requestContext)
22419
23202
  });
22420
23203
  const agent = tenantPermissions.includes("CREATE_AGENT") ? [...TENANT_CREATE_AGENT_PERMISSIONS] : [];
22421
- return listPermissionsData("tenant", { agent });
23204
+ const sandbox_environment = canCreateOrEdit(requestContext) ? [...TENANT_CREATE_SANDBOX_ENVIRONMENT_PERMISSIONS] : [];
23205
+ return listPermissionsData("tenant", { agent, sandbox_environment });
22422
23206
  }
22423
23207
  const data = emptyPermissionsByResourceId(resourceIds);
22424
23208
  if (input.resourceType === "agent") {
@@ -22439,15 +23223,10 @@ var TrueFoundryAuthorizer = class {
22439
23223
  return listPermissionsData("agent", data);
22440
23224
  }
22441
23225
  if (input.resourceType === "schedule") {
22442
- const ownedIds2 = await input.store.getOwnedIds({
22443
- tenant_id: requestContext.tenant_id,
22444
- ids: resourceIds,
22445
- subject_id: requestContext.subject.id
22446
- });
22447
- for (const id of ownedIds2) {
22448
- data[id] = [...SCHEDULE_OWNER_PERMISSIONS];
22449
- }
22450
- return listPermissionsData("schedule", data);
23226
+ return resolveSchedulePermissions(input);
23227
+ }
23228
+ if (input.resourceType === "sandbox_environment") {
23229
+ return resolveSandboxEnvironmentPermissions(input);
22451
23230
  }
22452
23231
  const ownedIds = await input.store.getOwnedIds({
22453
23232
  tenant_id: requestContext.tenant_id,
@@ -22989,6 +23768,29 @@ var TrueFoundrySandboxEnvironmentStore = class {
22989
23768
  }
22990
23769
  return this.#persistence.getEnvironment(input, transaction);
22991
23770
  }
23771
+ async getEnvironmentsByIds(input, transaction) {
23772
+ if (!this.#envSupported) {
23773
+ return this.#persistence.getEnvironmentsByIds(input, transaction);
23774
+ }
23775
+ const includesDefault = input.ids.includes(DEFAULT_ENVIRONMENT_ID);
23776
+ const persistenceIds = includesDefault ? input.ids.filter((id) => id !== DEFAULT_ENVIRONMENT_ID) : input.ids;
23777
+ let rows = await this.#persistence.getEnvironmentsByIds(
23778
+ { tenant_id: input.tenant_id, ids: persistenceIds },
23779
+ transaction
23780
+ );
23781
+ if (includesDefault) {
23782
+ const synthesized = synthesizeTrueFoundryDefaultSandboxEnvironment(input.tenant_id);
23783
+ rows = [
23784
+ {
23785
+ id: synthesized.environment.id,
23786
+ name: synthesized.environment.name,
23787
+ created_by_subject: synthesized.environment.created_by_subject
23788
+ },
23789
+ ...rows
23790
+ ];
23791
+ }
23792
+ return rows;
23793
+ }
22992
23794
  getActiveEnvironment(input, transaction) {
22993
23795
  if (!this.#envSupported) {
22994
23796
  logger.info("Skipping active sandbox environment get (provider does not support environments)", {
@@ -23343,6 +24145,7 @@ var isTrueFoundryModeEnabled2;
23343
24145
  var getTrueForgeAuthMode2;
23344
24146
  var getPublicUiBasePath2;
23345
24147
  var TrueForgeAuthMode2;
24148
+ var serverHttpMetrics;
23346
24149
  try {
23347
24150
  ({
23348
24151
  default: configuration2,
@@ -23357,27 +24160,32 @@ try {
23357
24160
  allowedHosts: configuration2.OUTBOUND_URL_ALLOWED_HOSTS,
23358
24161
  blockedHosts: configuration2.OUTBOUND_URL_BLOCKED_HOSTS
23359
24162
  });
24163
+ serverHttpMetrics = createHttpMetrics();
24164
+ configureOperationMetrics(createOperationMetrics(serverHttpMetrics.registry));
23360
24165
  configureOutboundFetches({
23361
24166
  outbound: {
23362
24167
  connectTimeoutMs: configuration2.OUTBOUND_HTTP_CONNECT_TIMEOUT_MS,
23363
24168
  headersTimeoutMs: configuration2.OUTBOUND_HTTP_HEADERS_TIMEOUT_MS,
23364
24169
  bodyTimeoutMs: configuration2.OUTBOUND_HTTP_BODY_TIMEOUT_MS,
23365
24170
  maxRetries: configuration2.OUTBOUND_HTTP_MAX_RETRIES,
23366
- idempotent: true
24171
+ idempotent: true,
24172
+ metrics: { module: "generic" }
23367
24173
  },
23368
24174
  model: {
23369
24175
  connectTimeoutMs: configuration2.MODEL_HTTP_CONNECT_TIMEOUT_MS,
23370
24176
  headersTimeoutMs: configuration2.MODEL_HTTP_HEADERS_TIMEOUT_MS,
23371
24177
  bodyTimeoutMs: configuration2.MODEL_HTTP_BODY_TIMEOUT_MS,
23372
24178
  maxRetries: configuration2.MODEL_HTTP_MAX_RETRIES,
23373
- idempotent: true
24179
+ idempotent: true,
24180
+ metrics: { module: "model" }
23374
24181
  },
23375
24182
  mcp: {
23376
24183
  connectTimeoutMs: configuration2.MCP_HTTP_CONNECT_TIMEOUT_MS,
23377
24184
  headersTimeoutMs: configuration2.MCP_HTTP_HEADERS_TIMEOUT_MS,
23378
24185
  bodyTimeoutMs: configuration2.MCP_HTTP_BODY_TIMEOUT_MS,
23379
24186
  maxRetries: configuration2.MCP_HTTP_MAX_RETRIES,
23380
- idempotent: false
24187
+ idempotent: false,
24188
+ metrics: { module: "mcp" }
23381
24189
  }
23382
24190
  });
23383
24191
  } catch (error) {
@@ -23467,14 +24275,15 @@ function buildResolveMcpServerStore(options) {
23467
24275
  };
23468
24276
  }
23469
24277
  function buildResolveAgentStore(options) {
23470
- const { persistenceStore, client: client2, db } = options;
24278
+ const { persistenceStore, client: client2, db, logger: logger2 } = options;
23471
24279
  return (rc) => {
23472
24280
  if (client2) {
23473
24281
  return new TrueFoundryAgentStore({
23474
24282
  inner: persistenceStore,
23475
24283
  client: client2,
23476
24284
  context: rc,
23477
- db
24285
+ db,
24286
+ logger: logger2
23478
24287
  });
23479
24288
  }
23480
24289
  return persistenceStore;
@@ -23674,7 +24483,8 @@ async function createDistributedPersistence(options) {
23674
24483
  const resolveAgentStore = buildResolveAgentStore({
23675
24484
  persistenceStore: agentStore,
23676
24485
  db,
23677
- client: serviceFoundryClient
24486
+ client: serviceFoundryClient,
24487
+ logger: logger2
23678
24488
  });
23679
24489
  const resolveSandboxProviderStore = buildResolveSandboxProviderStore({
23680
24490
  persistenceStore: sandboxProviderStore
@@ -23872,7 +24682,8 @@ async function createServerRuntime(persistence, logger2) {
23872
24682
  logger: logger2,
23873
24683
  oidcClient,
23874
24684
  authenticator,
23875
- authorizer
24685
+ authorizer,
24686
+ httpMetrics: serverHttpMetrics
23876
24687
  });
23877
24688
  return { activeTurns, app, controller, destroyDb, redis, requestReplyRouter };
23878
24689
  }
@@ -23882,6 +24693,13 @@ try {
23882
24693
  standalone: configuration2.STANDALONE
23883
24694
  });
23884
24695
  await initSentry(configuration2, logger2, { tags: { component: "server" } });
24696
+ setMetricsScrapeAppendix({
24697
+ scrape: startSdkMetrics(),
24698
+ onError(error) {
24699
+ logger2.error("SDK metrics scrape failed", extractErrorLogFields10(error));
24700
+ }
24701
+ });
24702
+ enableRedisOpenTelemetry();
23885
24703
  if (configuration2.STANDALONE) {
23886
24704
  printStandaloneStartupBanner({ version: PACKAGE_VERSION, color: shouldColorize() });
23887
24705
  await prepareCodeModeSocketParent({ path: configuration2.CODE_MODE_SOCKET_PARENT, logger: logger2 });
@@ -23927,7 +24745,10 @@ try {
23927
24745
  if (redis.mode !== "sentinel") {
23928
24746
  requestReplySubscriber = redis.client.duplicate();
23929
24747
  requestReplySubscriber.on("error", (error) => {
23930
- logger2.error("[RedisSubscriber] Client error", extractErrorLogFields9(error));
24748
+ logger2.error("[RedisSubscriber] Client error", {
24749
+ ...extractErrorLogFields10(error),
24750
+ reportable_error: { error }
24751
+ });
23931
24752
  });
23932
24753
  await requestReplySubscriber.connect();
23933
24754
  } else {
@@ -23978,7 +24799,11 @@ try {
23978
24799
  shuttingDown = true;
23979
24800
  logger2.info(`Received ${signal}, draining connections before shutdown`);
23980
24801
  setTimeout(() => {
23981
- logger2.warn(`Drain timed out after ${String(configuration2.GRACEFUL_TIMEOUT_SECONDS)}s, exiting`);
24802
+ logger2.warn(`Drain timed out after ${String(configuration2.GRACEFUL_TIMEOUT_SECONDS)}s, exiting`, {
24803
+ reportable_error: {
24804
+ error: new Error(`Drain timed out after ${String(configuration2.GRACEFUL_TIMEOUT_SECONDS)}s, exiting`)
24805
+ }
24806
+ });
23982
24807
  process.exit(1);
23983
24808
  }, configuration2.GRACEFUL_TIMEOUT_SECONDS * 1e3).unref();
23984
24809
  const closed = new Promise((resolve3) => {
@@ -23999,12 +24824,12 @@ try {
23999
24824
  }
24000
24825
  for (const client2 of redisClients) {
24001
24826
  await client2.close().catch((error) => {
24002
- logger2.warn("[Redis] Error closing client during shutdown", extractErrorLogFields9(error));
24827
+ logger2.warn("[Redis] Error closing client during shutdown", extractErrorLogFields10(error));
24003
24828
  });
24004
24829
  }
24005
24830
  if (configuration2.STANDALONE) {
24006
24831
  await removeCodeModeSocketParent(configuration2.CODE_MODE_SOCKET_PARENT).catch((error) => {
24007
- logger2.warn("Error removing Code Mode socket parent during shutdown", extractErrorLogFields9(error));
24832
+ logger2.warn("Error removing Code Mode socket parent during shutdown", extractErrorLogFields10(error));
24008
24833
  });
24009
24834
  }
24010
24835
  await destroyDb();