bazilion 0.25.0 → 0.26.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 (382) hide show
  1. package/README.md +41 -140
  2. package/dist/cli.js +5001 -2
  3. package/dist/cli.js.map +1 -0
  4. package/dist/daemon.js +17836 -2
  5. package/dist/daemon.js.map +1 -0
  6. package/dist/schema.sql +382 -0
  7. package/dist/web/client/assets/{AgentAvatar-JYijLvZ2.js → AgentAvatar-DWx-bM6n.js} +1 -1
  8. package/dist/web/client/assets/ChatPane-DOV_HJg-.js +72 -0
  9. package/dist/web/client/assets/ConfigPage-Dfu9DzFX.js +1 -0
  10. package/dist/web/client/assets/ConfirmDialog-536ziJ5P.js +1 -0
  11. package/dist/web/client/assets/FieldRow-z1JqCdqn.js +1 -0
  12. package/dist/web/client/assets/ModelSelect-CvOHjUyB.js +1 -0
  13. package/dist/web/client/assets/ResultCard-X4nTbjYY.js +1 -0
  14. package/dist/web/client/assets/SectionTabs-DXHzXmmb.js +1 -0
  15. package/dist/web/client/assets/SkillFindings-8LX6bYf_.js +1 -0
  16. package/dist/web/client/assets/SkillsPicker-Cr87y_W-.js +1 -0
  17. package/dist/web/client/assets/SpawnDialog-DoZl-yes.js +1 -0
  18. package/dist/web/client/assets/SpawnTeamModal-C638hEoN.js +1 -0
  19. package/dist/web/client/assets/Tabs-D0LgBNIk.js +1 -0
  20. package/dist/web/client/assets/TeamForm-C-WzvOl4.js +1 -0
  21. package/dist/web/client/assets/TeamPolicyEditor-CSKBx0oK.js +7 -0
  22. package/dist/web/client/assets/UnsavedChangesGuard-GC-vzw7h.js +1 -0
  23. package/dist/web/client/assets/_id-BKLynswT.js +1 -0
  24. package/dist/web/client/assets/_id-BYM_NORr.js +1 -0
  25. package/dist/web/client/assets/_id-Cxa98a9m.js +1 -0
  26. package/dist/web/client/assets/_id-D4hV1U1t.js +1 -0
  27. package/dist/web/client/assets/agent-actions-CXQCoxKO.js +1 -0
  28. package/dist/web/client/assets/agents-BxPS1_Bp.js +1 -0
  29. package/dist/web/client/assets/agents-GozAWW-l.js +1 -0
  30. package/dist/web/client/assets/attention-Cz9rZcrr.js +1 -0
  31. package/dist/web/client/assets/chevron-right-CPAb1zac.js +1 -0
  32. package/dist/web/client/assets/config-9vv9Lipb.js +3 -0
  33. package/dist/web/client/assets/entities-xVoB-p2j.js +1 -0
  34. package/dist/web/client/assets/inbox-DHLArXxl.js +1 -0
  35. package/dist/web/client/assets/index-1YXquAq8.js +52 -0
  36. package/dist/web/client/assets/jsx-runtime-bzQ4Vb5N.js +1 -0
  37. package/dist/web/client/assets/learning-PvtXm8Ne.js +1 -0
  38. package/dist/web/client/assets/login-DIJpNQFo.js +1 -0
  39. package/dist/web/client/assets/mcp-pKBL0xIf.js +1 -0
  40. package/dist/web/client/assets/members-DHWsgsEs.js +1 -0
  41. package/dist/web/client/assets/memory-CEVppPyU.js +1 -0
  42. package/dist/web/client/assets/plus-BaIRdB10.js +1 -0
  43. package/dist/web/client/assets/policy-DEh4BLSw.js +1 -0
  44. package/dist/web/client/assets/preload-helper-eUUcpe2S.js +1 -0
  45. package/dist/web/client/assets/results-DgJPjEZF.js +1 -0
  46. package/dist/web/client/assets/review-BbshafTQ.js +1 -0
  47. package/dist/web/client/assets/route-Ccb8v41z.js +1 -0
  48. package/dist/web/client/assets/route-D1d6kCEV.js +1 -0
  49. package/dist/web/client/assets/routes-g7V4ru7T.js +1 -0
  50. package/dist/web/client/assets/services-B2f7e5jV.js +1 -0
  51. package/dist/web/client/assets/settings-B6elpcYm.js +1 -0
  52. package/dist/web/client/assets/skills-CngE7TF8.js +1 -0
  53. package/dist/web/client/assets/styles-xUnZ-ep_.css +2 -0
  54. package/dist/web/client/assets/teams-BdJZXOan.js +1 -0
  55. package/dist/web/client/assets/teams-c496ISsT.js +1 -0
  56. package/dist/web/client/assets/telegram-B_-hK6EC.js +1 -0
  57. package/dist/web/client/assets/tokens-CKz8gx4-.js +1 -0
  58. package/dist/web/client/assets/triggers-DCEPciGW.js +1 -0
  59. package/dist/web/client/assets/welcome-D-zVOLGA.js +1 -0
  60. package/dist/web/client/baziu.svg +176 -7
  61. package/dist/web/server/assets/ChatPane-De_FPEoD.js +1887 -0
  62. package/dist/web/server/assets/ConfigPage-CGld_wCK.js +28 -0
  63. package/dist/web/server/assets/ConfirmDialog-LdVlEanK.js +132 -0
  64. package/dist/web/server/assets/{FieldRow-DPO8x_le.js → FieldRow-Dah2KKqo.js} +8 -15
  65. package/dist/web/server/assets/ModelSelect-Vwro6OkL.js +43 -0
  66. package/dist/web/server/assets/{Page-DJNoI4Gn.js → Page-CMSYKXWJ.js} +51 -2
  67. package/dist/web/server/assets/ResultCard-CZn1w4KA.js +97 -0
  68. package/dist/web/server/assets/SectionTabs-CqFg9Vwx.js +53 -0
  69. package/dist/web/server/assets/Sidebar-puq47KyR.js +430 -0
  70. package/dist/web/server/assets/SkillFindings-Bd6e81Wu.js +46 -0
  71. package/dist/web/server/assets/SkillsPicker-DlqEfRWh.js +67 -0
  72. package/dist/web/server/assets/SpawnDialog-BGNaMfFb.js +111 -0
  73. package/dist/web/server/assets/SpawnTeamModal-C6GbfScI.js +97 -0
  74. package/dist/web/server/assets/Tabs-BhF41MfQ.js +20 -0
  75. package/dist/web/server/assets/TeamForm-C93tpn9r.js +96 -0
  76. package/dist/web/server/assets/TeamPolicyEditor-BHS3J0R9.js +738 -0
  77. package/dist/web/server/assets/{UnsavedChangesGuard-BfSyMhiD.js → UnsavedChangesGuard-Dm4a27_5.js} +1 -1
  78. package/dist/web/server/assets/_id-B0x1ffz3.js +12 -0
  79. package/dist/web/server/assets/_id-BR6tnR6I.js +23 -0
  80. package/dist/web/server/assets/_id-Bdf_Rg62.js +19 -0
  81. package/dist/web/server/assets/_id-Bm611NQz.js +13 -0
  82. package/dist/web/server/assets/{_id-4fEeAcp0.js → _id-ByiXeIPS.js} +9 -8
  83. package/dist/web/server/assets/_id-D5UCoyES.js +359 -0
  84. package/dist/web/server/assets/_id-DHx5UmmL.js +12 -0
  85. package/dist/web/server/assets/_id-DLpGmOVm.js +19 -0
  86. package/dist/web/server/assets/_id-Y5ctILG2.js +13 -0
  87. package/dist/web/server/assets/_id-dDA0pdVo.js +54 -0
  88. package/dist/web/server/assets/_id-lOVnT5sS.js +383 -0
  89. package/dist/web/server/assets/{_id-BhJCnRR1.js → _id-sW6zXrTP.js} +4 -4
  90. package/dist/web/server/assets/_tanstack-start-manifest_v-B8u80HjK.js +292 -0
  91. package/dist/web/server/assets/agent-actions-BBdFVdoa.js +20 -0
  92. package/dist/web/server/assets/{agents-Cmw-sUUD.js → agents-BK8OmB8g.js} +7 -6
  93. package/dist/web/server/assets/{agents-DOrzqCXg.js → agents-BNPkidbH.js} +8 -10
  94. package/dist/web/server/assets/{agents-BitDk_C5.js → agents-Cn9GkXFX.js} +1 -3
  95. package/dist/web/server/assets/agents-D4tqK1kH.js +131 -0
  96. package/dist/web/server/assets/agents-DycxHDt8.js +327 -0
  97. package/dist/web/server/assets/{agents-DmmuOHw8.js → agents-lOqc6VGd.js} +4 -4
  98. package/dist/web/server/assets/api-WWxPqx67.js +85 -0
  99. package/dist/web/server/assets/attention-BIm455bC.js +216 -0
  100. package/dist/web/server/assets/{attention-Cy3Xu-Su.js → attention-DULVjdmF.js} +2 -4
  101. package/dist/web/server/assets/{attention-CsYqmV0L.js → attention-YWnLKA2E.js} +4 -2
  102. package/dist/web/server/assets/{auth-DChuQIh4.js → auth-DiN92ydD.js} +7 -8
  103. package/dist/web/server/assets/{config-0_5yhRKg.js → config-BNEgu7WG.js} +141 -432
  104. package/dist/web/server/assets/{config-VsmvCulS.js → config-C1VB28se.js} +1 -1
  105. package/dist/web/server/assets/{config-CpHD812q.js → config-TdVqnqNL.js} +3 -7
  106. package/dist/web/server/assets/cookies-HnTYjKRp.js +17 -0
  107. package/dist/web/server/assets/daemon-client-DL2ik2Em.js +146 -0
  108. package/dist/web/server/assets/entities-Dn2xzKIw.js +16 -0
  109. package/dist/web/server/assets/inbox-4Vj5jTT8.js +245 -0
  110. package/dist/web/server/assets/inbox-D4IqUv3l.js +38 -0
  111. package/dist/web/server/assets/inbox-Dle24AfV.js +23 -0
  112. package/dist/web/server/assets/learning-BScq7VbO.js +12 -0
  113. package/dist/web/server/assets/learning-CBWFEnhg.js +263 -0
  114. package/dist/web/server/assets/{learning-BuL0c1vH.js → learning-DWAKevhF.js} +6 -14
  115. package/dist/web/server/assets/{login-rDox7PRD.js → login-JoIjlcmu.js} +2 -5
  116. package/dist/web/server/assets/{login-B_-9L8TU.js → login-VV10kZBl.js} +15 -17
  117. package/dist/web/server/assets/mcp-B09_O05r.js +250 -0
  118. package/dist/web/server/assets/{mcp-B8ErRiR_.js → mcp-BwmpNQPN.js} +1 -1
  119. package/dist/web/server/assets/{mcp-BEdnl_TT.js → mcp-CqdTfXcn.js} +1 -3
  120. package/dist/web/server/assets/members-B8QBF6TF.js +12 -0
  121. package/dist/web/server/assets/{members-DFLi2nQg.js → members-DsF02Wp7.js} +2 -2
  122. package/dist/web/server/assets/members-tWZA9b15.js +36 -0
  123. package/dist/web/server/assets/memory-BNN0b-0x.js +12 -0
  124. package/dist/web/server/assets/memory-CTl1E1Rm.js +267 -0
  125. package/dist/web/server/assets/memory-CV5uCBb2.js +12 -0
  126. package/dist/web/server/assets/policy-C9M6zV6w.js +79 -0
  127. package/dist/web/server/assets/policy-h-6NpU3m.js +19 -0
  128. package/dist/web/server/assets/policy-xEw9X0DK.js +12 -0
  129. package/dist/web/server/assets/public-origin-BpDkdS5Q.js +34 -0
  130. package/dist/web/server/assets/results-D3A3UA4d.js +182 -0
  131. package/dist/web/server/assets/results-D6Ui5S8D.js +12 -0
  132. package/dist/web/server/assets/results-DWmxvfyn.js +15 -0
  133. package/dist/web/server/assets/review-CyQky-WQ.js +40 -0
  134. package/dist/web/server/assets/review-Sq0GGcPV.js +322 -0
  135. package/dist/web/server/assets/review-XWbSF8cF.js +12 -0
  136. package/dist/web/server/assets/route-BErtkz6t.js +19 -0
  137. package/dist/web/server/assets/route-CLoV-An_.js +48 -0
  138. package/dist/web/server/assets/route-WQ19JkBa.js +19 -0
  139. package/dist/web/server/assets/route-dEK_2GLj.js +203 -0
  140. package/dist/web/server/assets/route-iHTkhO81.js +16 -0
  141. package/dist/web/server/assets/route-zs8uUQtB.js +16 -0
  142. package/dist/web/server/assets/router-BI9gmY3S.js +751 -0
  143. package/dist/web/server/assets/routes-081s4n24.js +45 -0
  144. package/dist/web/server/assets/routes-CWo5WPsr.js +15 -0
  145. package/dist/web/server/assets/routes-Cqp1ufHm.js +56 -0
  146. package/dist/web/server/assets/{services-ZeEIgTn0.js → services-BLvAvb8g.js} +1 -1
  147. package/dist/web/server/assets/{services-UL_2b8PP.js → services-Q9HYQXXB.js} +2 -8
  148. package/dist/web/server/assets/{services-T8adll3y.js → services-tCfB1B83.js} +21 -38
  149. package/dist/web/server/assets/settings-CVaGv-xF.js +12 -0
  150. package/dist/web/server/assets/settings-D9viV-86.js +561 -0
  151. package/dist/web/server/assets/settings-DaZNZ_CC.js +27 -0
  152. package/dist/web/server/assets/{skills-D1oy3JAH.js → skills-BZg_txbf.js} +1 -3
  153. package/dist/web/server/assets/skills-C7fqRPna.js +275 -0
  154. package/dist/web/server/assets/{skills-kfqhxYmf.js → skills-C_g8IKag.js} +1 -1
  155. package/dist/web/server/assets/start-DTX6aKCi.js +100 -0
  156. package/dist/web/server/assets/teams-BHkhnt6b.js +12 -0
  157. package/dist/web/server/assets/teams-BS-oweRl.js +80 -0
  158. package/dist/web/server/assets/teams-BSflKBP8.js +108 -0
  159. package/dist/web/server/assets/teams-CNyB5nM9.js +12 -0
  160. package/dist/web/server/assets/{teams-BW2ARIvk.js → teams-D4CaU76n.js} +3 -5
  161. package/dist/web/server/assets/teams-DX2HmKqi.js +21 -0
  162. package/dist/web/server/assets/{telegram-U9UAdUEx.js → telegram-BUdnc8oF.js} +1 -1
  163. package/dist/web/server/assets/{telegram-ByHqeAGC.js → telegram-C4v1HhyJ.js} +1 -1
  164. package/dist/web/server/assets/{telegram-IMfV34-w.js → telegram-CrJiygCX.js} +223 -471
  165. package/dist/web/server/assets/{tokens-CiThDMwM.js → tokens-B1twAJdd.js} +5 -5
  166. package/dist/web/server/assets/tokens-DdjEyALj.js +232 -0
  167. package/dist/web/server/assets/tokens-DqldzPUq.js +14 -0
  168. package/dist/web/server/assets/triggers-B7LW784F.js +214 -0
  169. package/dist/web/server/assets/triggers-C5sMCZXv2.js +12 -0
  170. package/dist/web/server/assets/triggers-DMfVdImD.js +12 -0
  171. package/dist/web/server/assets/{welcome-BFWKx138.js → welcome-D0d38Pzx.js} +5 -6
  172. package/dist/web/server/server.js +55 -159
  173. package/dist/web-server.js +3 -3
  174. package/dist/worker.js +1692 -6375
  175. package/dist/worker.js.map +1 -1
  176. package/package.json +8 -18
  177. package/dist/browser-keychain.js +0 -83
  178. package/dist/browser-keychain.js.map +0 -1
  179. package/dist/cli-main.js +0 -9211
  180. package/dist/cli-main.js.map +0 -1
  181. package/dist/daemon-main.js +0 -50664
  182. package/dist/daemon-main.js.map +0 -1
  183. package/dist/migrations/0001_init.sql +0 -1103
  184. package/dist/migrations/0002_device_token_scopes.sql +0 -8
  185. package/dist/migrations/0003_web_pairing_tokens.sql +0 -18
  186. package/dist/migrations/0004_image_generation.sql +0 -25
  187. package/dist/native-darwin-entry.js +0 -692
  188. package/dist/native-darwin-entry.js.map +0 -1
  189. package/dist/native-linux-entry.js +0 -60
  190. package/dist/native-linux-entry.js.map +0 -1
  191. package/dist/runtime-version.js +0 -28
  192. package/dist/runtime-version.js.map +0 -1
  193. package/dist/web/client/assets/AgentTabs-kEd-oDRM.js +0 -1
  194. package/dist/web/client/assets/ChatPane-DhvlzNPJ.js +0 -76
  195. package/dist/web/client/assets/ConfigPage-CMKsWDjh.js +0 -1
  196. package/dist/web/client/assets/ConfirmDialog-DpAzoNG8.js +0 -1
  197. package/dist/web/client/assets/FieldRow-OQ-Ezw5t.js +0 -1
  198. package/dist/web/client/assets/ProductionTeamPolicyEditor-DhT-Q13a.js +0 -7
  199. package/dist/web/client/assets/ProfileCommunicationEditor-CnQIp4e6.js +0 -1
  200. package/dist/web/client/assets/RecoveryState-B4Rne9N_.js +0 -1
  201. package/dist/web/client/assets/ResultCard-BxAlMky1.js +0 -1
  202. package/dist/web/client/assets/ResultSourceConversation-BzIw43-r.js +0 -1
  203. package/dist/web/client/assets/SectionTabs-D3M6F_HR.js +0 -1
  204. package/dist/web/client/assets/TeamTabs-BZbg-UFx.js +0 -1
  205. package/dist/web/client/assets/TemplatesTabs-D8geEOte.js +0 -1
  206. package/dist/web/client/assets/UnsavedChangesGuard-CPQe9VLw.js +0 -1
  207. package/dist/web/client/assets/_id-1RIodFdi.js +0 -1
  208. package/dist/web/client/assets/_id-BV3w2kDj.js +0 -1
  209. package/dist/web/client/assets/_id-C9zxKqvQ.js +0 -1
  210. package/dist/web/client/assets/_id-CLG_POnZ.js +0 -1
  211. package/dist/web/client/assets/_id-Cha845UH.js +0 -1
  212. package/dist/web/client/assets/_id-DssxcwBl.js +0 -1
  213. package/dist/web/client/assets/_id-IDHR-MEm.js +0 -1
  214. package/dist/web/client/assets/_id-SGs5zOcT.js +0 -1
  215. package/dist/web/client/assets/activity-0srO4qbd.js +0 -1
  216. package/dist/web/client/assets/activity-DxQGr6eP.js +0 -1
  217. package/dist/web/client/assets/agents-CVTYoXKu.js +0 -1
  218. package/dist/web/client/assets/agents-DPTu6Sm_.js +0 -1
  219. package/dist/web/client/assets/agents-nHiIbumu.js +0 -1
  220. package/dist/web/client/assets/approvals-Di_Bux_Q.js +0 -1
  221. package/dist/web/client/assets/approvals-ScNrQg7q.js +0 -1
  222. package/dist/web/client/assets/attention-BF-Llt9z.js +0 -1
  223. package/dist/web/client/assets/attention-D7xB17sN.js +0 -1
  224. package/dist/web/client/assets/chevron-right-CJ2wat15.js +0 -1
  225. package/dist/web/client/assets/config-BOuIcP1T.js +0 -3
  226. package/dist/web/client/assets/context-wo9lNjHx.js +0 -1
  227. package/dist/web/client/assets/git-review-presentation-CzHQulDk.js +0 -1
  228. package/dist/web/client/assets/inbox-CNLmz0Jp.js +0 -1
  229. package/dist/web/client/assets/inbox-De6HOll3.js +0 -1
  230. package/dist/web/client/assets/index-CjI7_vB3.js +0 -52
  231. package/dist/web/client/assets/jsx-runtime-DGeXAQPT.js +0 -1
  232. package/dist/web/client/assets/learning-591SFAKg.js +0 -1
  233. package/dist/web/client/assets/learning-D6bO0NeB.js +0 -1
  234. package/dist/web/client/assets/login-Q7uP-v0M.js +0 -1
  235. package/dist/web/client/assets/mcp-BGy64VOv.js +0 -1
  236. package/dist/web/client/assets/mcp-DSCjhc5I.js +0 -1
  237. package/dist/web/client/assets/members-CBVor-P4.js +0 -1
  238. package/dist/web/client/assets/members-CCcecjC3.js +0 -1
  239. package/dist/web/client/assets/memory-CSE8EQ48.js +0 -1
  240. package/dist/web/client/assets/memory-DgGz0wh4.js +0 -1
  241. package/dist/web/client/assets/policy-6j-NQvBj.js +0 -1
  242. package/dist/web/client/assets/policy-Do0TvNWc.js +0 -1
  243. package/dist/web/client/assets/preload-helper-bztXdkDj.js +0 -1
  244. package/dist/web/client/assets/react-3W8R1pOO.js +0 -1
  245. package/dist/web/client/assets/results-CCQGn0dE.js +0 -1
  246. package/dist/web/client/assets/results-Cx6_ChIY.js +0 -1
  247. package/dist/web/client/assets/review-CyS5b0fz.js +0 -1
  248. package/dist/web/client/assets/review-qG-2gqEp.js +0 -1
  249. package/dist/web/client/assets/routes-DRic0xNy.js +0 -1
  250. package/dist/web/client/assets/services-B_7lf-mx.js +0 -1
  251. package/dist/web/client/assets/services-ByBA_yA-.js +0 -1
  252. package/dist/web/client/assets/skills--lnDzPWe.js +0 -1
  253. package/dist/web/client/assets/skills-C70btgIg.js +0 -1
  254. package/dist/web/client/assets/styles-e_ADuRbs.css +0 -2
  255. package/dist/web/client/assets/team-policy-D0jpnn2b.js +0 -1
  256. package/dist/web/client/assets/teams-BL-Fr2xF.js +0 -1
  257. package/dist/web/client/assets/teams-BeoxArzy.js +0 -1
  258. package/dist/web/client/assets/teams-C4mb790r.js +0 -1
  259. package/dist/web/client/assets/teams-DHStw3OS.js +0 -1
  260. package/dist/web/client/assets/telegram-BIMiebJl.js +0 -1
  261. package/dist/web/client/assets/templates-CzHXXiA_.js +0 -1
  262. package/dist/web/client/assets/tokens-B9ehOc1o.js +0 -1
  263. package/dist/web/client/assets/tokens-DhaMzFWK.js +0 -1
  264. package/dist/web/client/assets/triggers--xMpHFW7.js +0 -1
  265. package/dist/web/client/assets/triggers-DLzZu8bB.js +0 -1
  266. package/dist/web/client/assets/verifications-FzypGVwW.js +0 -2
  267. package/dist/web/client/assets/verifications-fR9W-adv.js +0 -1
  268. package/dist/web/client/assets/welcome-pjZD7pq4.js +0 -1
  269. package/dist/web/client/assets/wire-constants-CBD-lTaa.js +0 -1
  270. package/dist/web/client/assets/x-CZxV4X-6.js +0 -1
  271. package/dist/web/server/assets/AgentTabs-DVVkxBks.js +0 -49
  272. package/dist/web/server/assets/ChatPane-CeDUEjmn.js +0 -2962
  273. package/dist/web/server/assets/ConfigPage-J3s_PX4o.js +0 -69
  274. package/dist/web/server/assets/ConfirmDialog-C-2cbcmQ.js +0 -99
  275. package/dist/web/server/assets/ProductionTeamPolicyEditor-DNtdMn2a.js +0 -1026
  276. package/dist/web/server/assets/ProfileCommunicationEditor-C2RU-2QB.js +0 -107
  277. package/dist/web/server/assets/RecoveryState-DFPWxMIo.js +0 -37
  278. package/dist/web/server/assets/ResultCard-BtVFqdRU.js +0 -162
  279. package/dist/web/server/assets/ResultSourceConversation-xn4EKjaP.js +0 -64
  280. package/dist/web/server/assets/SectionTabs-DQWPEk1x.js +0 -8
  281. package/dist/web/server/assets/Sidebar-Dk9bErQV.js +0 -1243
  282. package/dist/web/server/assets/TeamTabs-XybMRm3w.js +0 -59
  283. package/dist/web/server/assets/TemplatesTabs-BiJt7Fjx.js +0 -31
  284. package/dist/web/server/assets/WorkspaceRecoveryCard-B-6gfg0D.js +0 -18
  285. package/dist/web/server/assets/_id-6aGxCNlp.js +0 -37
  286. package/dist/web/server/assets/_id-BJeSZ4DF.js +0 -11
  287. package/dist/web/server/assets/_id-BSkg6FJC.js +0 -45
  288. package/dist/web/server/assets/_id-BfT3umhN.js +0 -14
  289. package/dist/web/server/assets/_id-Bk4SHXs4.js +0 -626
  290. package/dist/web/server/assets/_id-C0C6wOt8.js +0 -42
  291. package/dist/web/server/assets/_id-CAxK6pln.js +0 -6
  292. package/dist/web/server/assets/_id-CGMvV1p5.js +0 -1183
  293. package/dist/web/server/assets/_id-CI33J2xv.js +0 -11
  294. package/dist/web/server/assets/_id-C_FnWQ61.js +0 -11
  295. package/dist/web/server/assets/_id-CmS2d0me.js +0 -17
  296. package/dist/web/server/assets/_id-D9VWEfdp.js +0 -28
  297. package/dist/web/server/assets/_id-DhheAcWL.js +0 -1035
  298. package/dist/web/server/assets/_id-t8AepTB2.js +0 -26
  299. package/dist/web/server/assets/_id-ujm4R5OF.js +0 -18
  300. package/dist/web/server/assets/_tanstack-start-manifest_v-CXwNJhX2.js +0 -376
  301. package/dist/web/server/assets/activity-BKb_BIx7.js +0 -168
  302. package/dist/web/server/assets/activity-CDNYyLBC.js +0 -11
  303. package/dist/web/server/assets/activity-DhzxlXUk.js +0 -12
  304. package/dist/web/server/assets/activity-lf7L7wiL.js +0 -14
  305. package/dist/web/server/assets/agents-BzJDqrC8.js +0 -11
  306. package/dist/web/server/assets/agents-C65TunMF.js +0 -505
  307. package/dist/web/server/assets/agents-uXBu1F5L.js +0 -387
  308. package/dist/web/server/assets/approvals-CcU_pIWW.js +0 -11
  309. package/dist/web/server/assets/approvals-CpDs6ASO.js +0 -14
  310. package/dist/web/server/assets/approvals-FyuTjfdY.js +0 -332
  311. package/dist/web/server/assets/approvals-szknIxB6.js +0 -12
  312. package/dist/web/server/assets/attention-BeA3zGve.js +0 -268
  313. package/dist/web/server/assets/attention-jtJ9PIMp.js +0 -11
  314. package/dist/web/server/assets/browser-BiDvr0fy.js +0 -66
  315. package/dist/web/server/assets/context-DuxjdpaW.js +0 -11
  316. package/dist/web/server/assets/daemon-client-C-RlJHYO.js +0 -301
  317. package/dist/web/server/assets/git-review-BB3M9nYg.js +0 -26
  318. package/dist/web/server/assets/git-review-CqZTrIWS.js +0 -179
  319. package/dist/web/server/assets/git-review-presentation-TJiHJhen.js +0 -81
  320. package/dist/web/server/assets/inbox-Be3CUU4o.js +0 -11
  321. package/dist/web/server/assets/inbox-D1ROE7jB.js +0 -44
  322. package/dist/web/server/assets/inbox-DsH5oRK0.js +0 -168
  323. package/dist/web/server/assets/inbox-qKMkeprB.js +0 -29
  324. package/dist/web/server/assets/learning-BYCwIOzZ.js +0 -18
  325. package/dist/web/server/assets/learning-C3pqLE5b.js +0 -11
  326. package/dist/web/server/assets/learning-D7jWRhqD.js +0 -365
  327. package/dist/web/server/assets/mcp-BQ4KvXp1.js +0 -11
  328. package/dist/web/server/assets/mcp-Dhryb75M.js +0 -328
  329. package/dist/web/server/assets/members-8aWhtn4G.js +0 -100
  330. package/dist/web/server/assets/members-Cjpysp35.js +0 -14
  331. package/dist/web/server/assets/members-DWedYCMh.js +0 -11
  332. package/dist/web/server/assets/memory-BH7L-l65.js +0 -11
  333. package/dist/web/server/assets/memory-Bq0s1fr7.js +0 -18
  334. package/dist/web/server/assets/memory-CS-9Bb6q.js +0 -28
  335. package/dist/web/server/assets/memory-DN5iMDQL.js +0 -389
  336. package/dist/web/server/assets/policy-CK3VuVuv.js +0 -11
  337. package/dist/web/server/assets/policy-DDi8AjcD.js +0 -21
  338. package/dist/web/server/assets/policy-DcYIJaHW.js +0 -490
  339. package/dist/web/server/assets/policy-JF7ZI2-i.js +0 -40
  340. package/dist/web/server/assets/public-origin-xV0lm0Ty.js +0 -25
  341. package/dist/web/server/assets/publications-DV2uRrvJ.js +0 -57
  342. package/dist/web/server/assets/results-CkNoVDrY.js +0 -362
  343. package/dist/web/server/assets/results-DSGwi3vj.js +0 -14
  344. package/dist/web/server/assets/results-DlOsdBE7.js +0 -11
  345. package/dist/web/server/assets/results-vtkmZPro.js +0 -12
  346. package/dist/web/server/assets/review-BG71IaCa.js +0 -1061
  347. package/dist/web/server/assets/review-Bs6AbrSn.js +0 -40
  348. package/dist/web/server/assets/review-CPmUi4PR.js +0 -11
  349. package/dist/web/server/assets/review-packets-CO69K-FK.js +0 -172
  350. package/dist/web/server/assets/router-BFqyjkYu.js +0 -921
  351. package/dist/web/server/assets/routes-B6TnJyQ8.js +0 -57
  352. package/dist/web/server/assets/routes-BfEa101d.js +0 -14
  353. package/dist/web/server/assets/routes-pUMIGzyy.js +0 -53
  354. package/dist/web/server/assets/services-Ba6tFlZz.js +0 -16
  355. package/dist/web/server/assets/skills-CGvPejPD.js +0 -11
  356. package/dist/web/server/assets/skills-cVlLDnvf.js +0 -399
  357. package/dist/web/server/assets/start-D4Wq9iTa.js +0 -70
  358. package/dist/web/server/assets/team-policy-vPG01onj.js +0 -180
  359. package/dist/web/server/assets/teams-6c5B9wnI.js +0 -11
  360. package/dist/web/server/assets/teams-BEIUG9fI.js +0 -112
  361. package/dist/web/server/assets/teams-Bi3CeEM5.js +0 -11
  362. package/dist/web/server/assets/teams-C9tfV3IC.js +0 -12
  363. package/dist/web/server/assets/teams-DKROLgw-.js +0 -36
  364. package/dist/web/server/assets/teams-DLt48Vxw.js +0 -284
  365. package/dist/web/server/assets/teams-DuhXk1M5.js +0 -14
  366. package/dist/web/server/assets/templates-CuqFhsiO.js +0 -11
  367. package/dist/web/server/assets/tokens-DDJYBy6R.js +0 -16
  368. package/dist/web/server/assets/tokens-qVijmBxr.js +0 -11
  369. package/dist/web/server/assets/tokens-zSK57Trr.js +0 -452
  370. package/dist/web/server/assets/triggers-B9CIl4Co.js +0 -27
  371. package/dist/web/server/assets/triggers-Cr9af7Xw.js +0 -367
  372. package/dist/web/server/assets/triggers-DIruOyMb.js +0 -18
  373. package/dist/web/server/assets/triggers-x_OA9u5f.js +0 -11
  374. package/dist/web/server/assets/utils-ySbqTi3g.js +0 -24
  375. package/dist/web/server/assets/verification-DBsJYadO.js +0 -97
  376. package/dist/web/server/assets/verifications-DjZsx65b.js +0 -12
  377. package/dist/web/server/assets/verifications-DvOyI3Mr.js +0 -28
  378. package/dist/web/server/assets/verifications-YrEdiZmk.js +0 -326
  379. package/dist/web/server/assets/web-search-dgw10fLn.js +0 -12
  380. package/dist/web/server/assets/wire-constants-C8nBJcU3.js +0 -16
  381. /package/{LICENSE → dist/LICENSE} +0 -0
  382. /package/dist/web/client/assets/{ProductionTeamPolicyEditor-DLioOiRN.css → TeamPolicyEditor-DLioOiRN.css} +0 -0
@@ -1,2962 +0,0 @@
1
- import { n as Button } from "./utils-ySbqTi3g.js";
2
- import { r as fetchSnapshotApplicability } from "./git-review-BB3M9nYg.js";
3
- import { n as applicabilityWarns, t as applicabilityLabel } from "./git-review-presentation-TJiHJhen.js";
4
- import { t as ResultCard } from "./ResultCard-BtVFqdRU.js";
5
- import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, useSyncExternalStore } from "react";
6
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
- import DOMPurify from "dompurify";
8
- import { marked } from "marked";
9
- //#region src/lib/coding-presentation.ts
10
- /** Presentation only: excerpts are never used for authorization or receipt validity. */
11
- function codingFailureSummary(diagnostic) {
12
- const error = diagnostic.split("\n").map((line) => line.trim()).find((line) => /^(?:[A-Za-z]*Error(?: \[[A-Z_]+\])?:|ERR_[A-Z_]+\b)/.test(line));
13
- if (!error) return null;
14
- return error.length > 240 ? `${error.slice(0, 237)}…` : error;
15
- }
16
- /** Historical admission metadata, never an availability or verification verdict. */
17
- function nativeCodingRuntimeLabel(value) {
18
- if (!value || typeof value !== "object") return "Native runtime (details unavailable)";
19
- const facts = value;
20
- if (!["linux-bwrap", "darwin-seatbelt"].includes(String(facts.backend)) || !["x64", "arm64"].includes(String(facts.architecture)) || typeof facts.nodeVersion !== "string" || !/^v\d+\.\d+\.\d+$/.test(facts.nodeVersion)) return "Native runtime (details unavailable)";
21
- return `Native runtime: ${facts.backend} · ${facts.architecture} · Node ${facts.nodeVersion}`;
22
- }
23
- function inboxUpdateLabel(body) {
24
- const header = body.split("\n").find((line) => line.startsWith("--- from "));
25
- if (!header) return "Teammate update received";
26
- const match = /^--- from (.+?) \(message [0-9a-f-]+(?:, reply to [0-9a-f-]+)?\) ---$/.exec(header);
27
- if (!match) return "Teammate update received";
28
- const name = match[1]?.replace(/ \([0-9a-f-]{36}\)$/, "").trim();
29
- if (!name || /^[0-9a-f-]{36}$/.test(name)) return "Teammate update received";
30
- return `Update from ${name.slice(0, 100)}`;
31
- }
32
- //#endregion
33
- //#region src/lib/coding-log.ts
34
- /** Bounded first page. Larger reads and search are a later iteration. */
35
- var CODING_LOG_PAGE_BYTES = 65536;
36
- /**
37
- * Read a retained coding log through the same-origin `/api` proxy.
38
- *
39
- * The daemon stays the authority: it re-checks Team membership and disclosure
40
- * state on every call, so holding an opaque reference in history grants nothing
41
- * on its own. `fetchImpl` is injectable for tests.
42
- */
43
- async function fetchRetainedCodingLog(reference, fetchImpl = fetch) {
44
- const base = `/api/teams/${encodeURIComponent(reference.teamId)}/coding-commands/${encodeURIComponent(reference.commandId)}/log`;
45
- try {
46
- const response = await fetchImpl(`${base}?limit=${CODING_LOG_PAGE_BYTES}`, { headers: { accept: "application/json" } });
47
- if (response.status === 403) return { status: "not-shared" };
48
- if (response.status === 404) return { status: "missing" };
49
- if (!response.ok) return {
50
- status: "unavailable",
51
- message: `Request failed (${response.status}).`
52
- };
53
- const body = await response.json();
54
- const view = readView(body);
55
- if (!view) return {
56
- status: "unavailable",
57
- message: "Unexpected response from the daemon."
58
- };
59
- if (field(body, "page") === null) return { status: "not-shared" };
60
- const page = readPage(field(body, "page"));
61
- if (!page) return {
62
- status: "unavailable",
63
- message: "Unexpected response from the daemon."
64
- };
65
- return {
66
- status: "available",
67
- page,
68
- view
69
- };
70
- } catch {
71
- return {
72
- status: "unavailable",
73
- message: "The daemon could not be reached."
74
- };
75
- }
76
- }
77
- function readView(body) {
78
- const view = field(body, "view");
79
- if (!isRecord(view)) return null;
80
- if (typeof view.commandId !== "string" || typeof view.availability !== "string") return null;
81
- if (typeof view.byteLength !== "number") return null;
82
- return view;
83
- }
84
- function readPage(page) {
85
- if (!isRecord(page)) return null;
86
- if (typeof page.text !== "string" || typeof page.availability !== "string") return null;
87
- if (typeof page.offset !== "number" || typeof page.hasMore !== "boolean") return null;
88
- if (typeof page.byteLength !== "number") return null;
89
- return page;
90
- }
91
- function field(body, key) {
92
- return isRecord(body) ? body[key] : void 0;
93
- }
94
- function isRecord(value) {
95
- return typeof value === "object" && value !== null && !Array.isArray(value);
96
- }
97
- //#endregion
98
- //#region src/components/CodingToolResult.tsx
99
- /**
100
- * Presents already-authorized chat text. A masked history card may additionally
101
- * offer retained output, but that read is an explicit operator action through
102
- * the daemon's releasing route — nothing is disclosed by rendering the card.
103
- */
104
- function CodingToolResult({ name, body, pending = false, log }) {
105
- if (!pending && body === "Coding context or command evidence retained privately. Captured transport output follows its communication approval; ask the Agent for the relevant result.") return /* @__PURE__ */ jsxs("details", {
106
- className: "py-1 text-xs font-sans",
107
- "aria-label": "Private command details",
108
- children: [
109
- /* @__PURE__ */ jsx("summary", {
110
- className: "cursor-pointer",
111
- children: "Detailed output isn’t included in this history view"
112
- }),
113
- /* @__PURE__ */ jsx("p", {
114
- className: "mt-1",
115
- children: "The Agent’s summary is shown in the conversation. Ask the Agent to summarize its retained command result if you need more detail."
116
- }),
117
- log && /* @__PURE__ */ jsx(RetainedLogControl, { reference: log })
118
- ]
119
- });
120
- let parsed;
121
- try {
122
- parsed = JSON.parse(body);
123
- } catch {
124
- return /* @__PURE__ */ jsx("span", { children: body });
125
- }
126
- if (!parsed || typeof parsed !== "object") return /* @__PURE__ */ jsx("span", { children: body });
127
- if (pending) {
128
- const input = parsed;
129
- return /* @__PURE__ */ jsxs("p", {
130
- className: "py-1 break-words",
131
- children: [
132
- name === "coding_command" ? "Running" : "Inspecting",
133
- ":",
134
- " ",
135
- typeof input.command === "string" ? input.command : typeof input.target === "string" ? input.target : "command evidence"
136
- ]
137
- });
138
- }
139
- if (name === "repository_context") {
140
- const report = parsed;
141
- if (!Array.isArray(report.instructions?.files)) return /* @__PURE__ */ jsx("span", { children: body });
142
- return /* @__PURE__ */ jsxs("details", {
143
- className: "py-1",
144
- children: [
145
- /* @__PURE__ */ jsxs("summary", {
146
- className: "cursor-pointer",
147
- children: [
148
- "Repository: ",
149
- report.target,
150
- " ·",
151
- " ",
152
- report.instructions.state === "complete" ? `${report.instructions.files.length} instruction files` : "instructions unavailable"
153
- ]
154
- }),
155
- report.instructions.files.map((file) => /* @__PURE__ */ jsx("p", { children: file.path }, file.path)),
156
- /* @__PURE__ */ jsxs("p", { children: [
157
- report.commands?.candidates?.length ?? 0,
158
- " suggested commands ·",
159
- " ",
160
- report.git?.state === "available" ? report.git.branch : "Git unavailable"
161
- ] }),
162
- /* @__PURE__ */ jsx("pre", {
163
- className: "max-h-64 overflow-auto whitespace-pre-wrap break-words",
164
- children: body
165
- })
166
- ]
167
- });
168
- }
169
- if (name === "coding_log") {
170
- const page = parsed;
171
- if (typeof page.text !== "string" || typeof page.availability !== "string") return /* @__PURE__ */ jsx("span", { children: body });
172
- return /* @__PURE__ */ jsxs("details", {
173
- className: "py-1",
174
- "aria-label": "Retained command output",
175
- children: [
176
- /* @__PURE__ */ jsxs("summary", {
177
- className: "cursor-pointer",
178
- children: [
179
- "Retained output: ",
180
- page.availability,
181
- page.hasMore ? " · more available" : ""
182
- ]
183
- }),
184
- /* @__PURE__ */ jsx("pre", {
185
- className: "max-h-64 overflow-auto whitespace-pre-wrap break-words",
186
- children: page.text
187
- }),
188
- /* @__PURE__ */ jsxs("p", {
189
- className: "text-xs",
190
- children: [
191
- "bytes ",
192
- typeof page.offset === "number" ? page.offset : 0,
193
- "–",
194
- (typeof page.offset === "number" ? page.offset : 0) + page.text.length,
195
- " of",
196
- " ",
197
- typeof page.byteLength === "number" ? page.byteLength : 0
198
- ]
199
- })
200
- ]
201
- });
202
- }
203
- if (name === "coding_environment") {
204
- const value = parsed;
205
- if (typeof value.posture !== "string") return /* @__PURE__ */ jsx("span", { children: body });
206
- return /* @__PURE__ */ jsxs("details", {
207
- className: "py-1",
208
- children: [
209
- /* @__PURE__ */ jsxs("summary", {
210
- className: "cursor-pointer",
211
- children: [
212
- "Environment: ",
213
- value.posture,
214
- " · ",
215
- value.cwd
216
- ]
217
- }),
218
- /* @__PURE__ */ jsx("p", {
219
- className: "break-all",
220
- children: value.posture === "native" ? nativeCodingRuntimeLabel(value.native) : value.imageId ?? "Host runtime"
221
- }),
222
- Array.isArray(value.restrictions) && value.restrictions.filter((x) => typeof x === "string").map((text) => /* @__PURE__ */ jsx("p", { children: text }, text))
223
- ]
224
- });
225
- }
226
- const view = parsed;
227
- const receipt = name === "coding_receipt" ? view.receipt : parsed;
228
- if (!receipt || typeof receipt.state !== "string" || typeof receipt.input?.command !== "string" || typeof receipt.input?.cwd !== "string") return /* @__PURE__ */ jsx("span", { children: body });
229
- const failure = receipt.state === "failed" && typeof receipt.diagnostic === "string" ? codingFailureSummary(receipt.diagnostic) : null;
230
- return /* @__PURE__ */ jsxs("div", {
231
- className: "py-2",
232
- "aria-label": "Coding command result",
233
- children: [
234
- /* @__PURE__ */ jsxs("p", {
235
- className: "font-sans",
236
- children: [
237
- /* @__PURE__ */ jsx("strong", {
238
- className: receipt.state === "succeeded" ? "text-sapphire-deep" : "text-mocha",
239
- children: receipt.state.replaceAll("_", " ")
240
- }),
241
- " ",
242
- "· ",
243
- receipt.input.purpose,
244
- typeof receipt.exitCode === "number" ? ` · exit ${receipt.exitCode}` : "",
245
- name === "coding_receipt" ? ` · ${view.applicability}` : ""
246
- ]
247
- }),
248
- /* @__PURE__ */ jsx("p", {
249
- className: "whitespace-pre-wrap break-words",
250
- children: receipt.input.command
251
- }),
252
- /* @__PURE__ */ jsxs("p", {
253
- className: "text-xs",
254
- children: [
255
- receipt.input.cwd,
256
- " · ",
257
- receipt.environment?.posture,
258
- " · result at execution time"
259
- ]
260
- }),
261
- failure && /* @__PURE__ */ jsx("p", {
262
- className: "mt-1 font-sans text-rose-baziu",
263
- "aria-label": "Command failure summary",
264
- children: failure
265
- }),
266
- typeof receipt.reason === "string" && /* @__PURE__ */ jsx("p", { children: receipt.reason }),
267
- /* @__PURE__ */ jsxs("details", { children: [
268
- /* @__PURE__ */ jsx("summary", {
269
- className: "cursor-pointer",
270
- children: "Output and evidence"
271
- }),
272
- /* @__PURE__ */ jsx("pre", {
273
- className: "max-h-64 overflow-auto whitespace-pre-wrap break-words",
274
- children: receipt.diagnostic
275
- }),
276
- receipt.truncated && /* @__PURE__ */ jsx("p", { children: "Output truncated." }),
277
- /* @__PURE__ */ jsxs("p", {
278
- className: "break-all",
279
- children: ["coding-receipt:", receipt.id]
280
- }),
281
- /* @__PURE__ */ jsx(SourceApplicability, {
282
- teamId: receipt.teamId,
283
- after: receipt.sourceAfter ?? null,
284
- before: receipt.sourceBefore ?? null
285
- }),
286
- receipt.environment?.imageId && /* @__PURE__ */ jsx("p", {
287
- className: "break-all",
288
- children: receipt.environment.imageId
289
- }),
290
- receipt.environment?.posture === "native" && /* @__PURE__ */ jsx("p", { children: nativeCodingRuntimeLabel(receipt.environment.native) })
291
- ] })
292
- ]
293
- });
294
- }
295
- /**
296
- * Whether this result's tested source still matches the current source (BAZ-042 criterion 4).
297
- *
298
- * Nothing is assumed from the fact that a result exists: a receipt with no captured source reads as
299
- * **Not checked**, and the verdict is loaded only when the operator asks for it.
300
- */
301
- function SourceApplicability({ teamId, after, before }) {
302
- const [state, setState] = useState(null);
303
- const [loading, setLoading] = useState(false);
304
- async function check() {
305
- if (!after) return;
306
- setLoading(true);
307
- try {
308
- setState(await fetchSnapshotApplicability({ data: {
309
- teamId,
310
- snapshotId: after.id
311
- } }));
312
- } finally {
313
- setLoading(false);
314
- }
315
- }
316
- const verdict = state?.status === "ok" ? state : null;
317
- const label = applicabilityLabel(verdict);
318
- return /* @__PURE__ */ jsxs("p", {
319
- className: applicabilityWarns(verdict) ? "text-rose-baziu" : void 0,
320
- children: [
321
- label,
322
- after ? /* @__PURE__ */ jsxs(Fragment, { children: [
323
- " · tested version ",
324
- /* @__PURE__ */ jsx("span", {
325
- className: "break-all font-mono",
326
- children: after.id.slice(0, 12)
327
- }),
328
- after.complete ? "" : " (incomplete)",
329
- verdict === null && /* @__PURE__ */ jsxs(Fragment, { children: [" ", /* @__PURE__ */ jsx(Button, {
330
- variant: "ghost",
331
- disabled: loading,
332
- onClick: () => void check(),
333
- children: loading ? "Checking…" : "Check applicability"
334
- })] }),
335
- state?.status === "unavailable" && /* @__PURE__ */ jsxs("span", { children: [" · ", state.message] })
336
- ] }) : " · no source snapshot was captured for this result",
337
- before && /* @__PURE__ */ jsxs(Fragment, { children: [" · started from ", /* @__PURE__ */ jsx("span", {
338
- className: "break-all font-mono",
339
- children: before.id.slice(0, 12)
340
- })] })
341
- ]
342
- });
343
- }
344
- /**
345
- * Explicit operator read of a retained log. Loads a single bounded first page
346
- * on demand; the daemon re-authorizes every call and reports a held log as
347
- * `not-shared` so it can never be mistaken for an empty result.
348
- */
349
- function RetainedLogControl({ reference }) {
350
- const [result, setResult] = useState(null);
351
- const [loading, setLoading] = useState(false);
352
- async function load() {
353
- setLoading(true);
354
- try {
355
- setResult(await fetchRetainedCodingLog(reference));
356
- } finally {
357
- setLoading(false);
358
- }
359
- }
360
- if (result === null) return /* @__PURE__ */ jsx("p", {
361
- className: "mt-2",
362
- children: /* @__PURE__ */ jsx(Button, {
363
- variant: "ghost",
364
- disabled: loading,
365
- onClick: () => void load(),
366
- children: loading ? "Loading…" : "Show retained output"
367
- })
368
- });
369
- if (result.status === "not-shared") return /* @__PURE__ */ jsx("p", {
370
- className: "mt-2",
371
- children: "This command’s output hasn’t been shared with the conversation yet."
372
- });
373
- if (result.status === "missing") return /* @__PURE__ */ jsx("p", {
374
- className: "mt-2",
375
- children: "This retained output is no longer available."
376
- });
377
- if (result.status === "unavailable") return /* @__PURE__ */ jsx("p", {
378
- className: "mt-2",
379
- role: "alert",
380
- children: result.message
381
- });
382
- return /* @__PURE__ */ jsxs("div", {
383
- className: "mt-2",
384
- children: [/* @__PURE__ */ jsx("pre", {
385
- className: "max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-sm bg-[rgba(42,31,22,0.04)] p-2",
386
- children: result.page.text
387
- }), /* @__PURE__ */ jsxs("p", { children: [
388
- "Retained output: ",
389
- result.page.availability,
390
- result.page.hasMore ? " · earlier output omitted" : "",
391
- " · bytes ",
392
- result.page.offset,
393
- "–",
394
- result.page.offset + result.page.text.length,
395
- " of ",
396
- result.page.byteLength
397
- ] })]
398
- });
399
- }
400
- //#endregion
401
- //#region src/lib/md.ts
402
- var installed = false;
403
- function install() {
404
- if (installed) return;
405
- marked.setOptions({
406
- breaks: true,
407
- gfm: true
408
- });
409
- DOMPurify.addHook("afterSanitizeAttributes", (node) => {
410
- if (node.nodeName === "A") {
411
- node.setAttribute("target", "_blank");
412
- node.setAttribute("rel", "noopener noreferrer");
413
- }
414
- });
415
- installed = true;
416
- }
417
- function renderMd(text, domReady) {
418
- if (!text) return "";
419
- if (!domReady || typeof window === "undefined") return escapeHtml(text);
420
- try {
421
- install();
422
- const html = marked.parse(text, { async: false });
423
- return DOMPurify.sanitize(html);
424
- } catch {
425
- return escapeHtml(text);
426
- }
427
- }
428
- function escapeHtml(s) {
429
- return String(s).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
430
- }
431
- //#endregion
432
- //#region src/components/ConversationLibrary.tsx
433
- function ConversationLibrary({ agentId, turnBusy, onCreated, renderHistory, initialConversationId }) {
434
- const [library, setLibrary] = useState(null);
435
- const [offset, setOffset] = useState(0);
436
- const [refresh, setRefresh] = useState(0);
437
- const [selected, setSelected] = useState(null);
438
- const [history, setHistory] = useState(null);
439
- const [title, setTitle] = useState("");
440
- const [error, setError] = useState("");
441
- const [historyError, setHistoryError] = useState("");
442
- const [busy, setBusy] = useState(false);
443
- const pendingKey = `bazilion:conversation-create:${agentId}`;
444
- const pendingCreate = useRef(null);
445
- useEffect(() => {
446
- try {
447
- pendingCreate.current = JSON.parse(sessionStorage.getItem(pendingKey) ?? "null");
448
- } catch {
449
- pendingCreate.current = null;
450
- }
451
- }, [pendingKey]);
452
- function clearPending() {
453
- pendingCreate.current = null;
454
- sessionStorage.removeItem(pendingKey);
455
- }
456
- const base = `/api/agents/${encodeURIComponent(agentId)}/conversations`;
457
- useEffect(() => {
458
- if (!initialConversationId) return;
459
- const controller = new AbortController();
460
- fetch(`${base}/${encodeURIComponent(initialConversationId)}`, { signal: controller.signal }).then(async (response) => {
461
- if (!response.ok) throw new Error("Retained conversation is unavailable");
462
- const body = await response.json();
463
- if (!controller.signal.aborted) {
464
- setSelected(body.conversation);
465
- setTitle(body.conversation.title);
466
- }
467
- }).catch((error) => {
468
- if (!controller.signal.aborted) setError(error.message);
469
- });
470
- return () => controller.abort();
471
- }, [base, initialConversationId]);
472
- useEffect(() => {
473
- const controller = new AbortController();
474
- setLibrary(null);
475
- fetch(`${base}?limit=20&offset=${offset}`, { signal: controller.signal }).then(async (response) => {
476
- if (!response.ok) throw new Error("Could not load conversations.");
477
- const body = await response.json();
478
- if (!controller.signal.aborted) setLibrary(body);
479
- }).catch((error) => {
480
- if (!controller.signal.aborted) setError(error.message);
481
- });
482
- return () => controller.abort();
483
- }, [
484
- base,
485
- offset,
486
- refresh
487
- ]);
488
- useEffect(() => {
489
- if (!selected) return;
490
- const controller = new AbortController();
491
- setHistory(null);
492
- setHistoryError("");
493
- fetch(`${base}/${encodeURIComponent(selected.id)}`, { signal: controller.signal }).then(async (response) => {
494
- if (!response.ok) throw new Error("This conversation history is unavailable. You can still start a new conversation.");
495
- const body = await response.json();
496
- if (!controller.signal.aborted) setHistory(body.messages);
497
- }).catch((error) => {
498
- if (!controller.signal.aborted) setHistoryError(error.message);
499
- });
500
- return () => controller.abort();
501
- }, [base, selected?.id]);
502
- async function create() {
503
- if (!library || busy || turnBusy) return;
504
- setBusy(true);
505
- setError("");
506
- const request = pendingCreate.current ?? {
507
- requestId: crypto.randomUUID(),
508
- expectedSelection: library.selection
509
- };
510
- pendingCreate.current = request;
511
- try {
512
- sessionStorage.setItem(pendingKey, JSON.stringify(request));
513
- const response = await fetch(base, {
514
- method: "POST",
515
- headers: { "content-type": "application/json" },
516
- body: JSON.stringify(request)
517
- });
518
- const body = await response.json();
519
- if (!response.ok) {
520
- if (response.status === 409 || response.status === 400) clearPending();
521
- throw new Error(body.error ?? "Could not create conversation.");
522
- }
523
- clearPending();
524
- setSelected(null);
525
- setOffset(0);
526
- setRefresh((value) => value + 1);
527
- await onCreated();
528
- } catch (error) {
529
- setError(error instanceof Error ? error.message : "Could not create conversation.");
530
- } finally {
531
- setBusy(false);
532
- }
533
- }
534
- async function rename() {
535
- if (!selected || busy) return;
536
- setBusy(true);
537
- setError("");
538
- try {
539
- const response = await fetch(`${base}/${encodeURIComponent(selected.id)}`, {
540
- method: "PATCH",
541
- headers: { "content-type": "application/json" },
542
- body: JSON.stringify({
543
- title,
544
- expectedTitleRevision: selected.titleRevision
545
- })
546
- });
547
- const body = await response.json();
548
- if (!response.ok) throw new Error(body.error ?? "Could not rename conversation.");
549
- setSelected(body.conversation);
550
- setRefresh((value) => value + 1);
551
- } catch (error) {
552
- setError(error instanceof Error ? error.message : "Could not rename conversation.");
553
- } finally {
554
- setBusy(false);
555
- }
556
- }
557
- return /* @__PURE__ */ jsxs("section", {
558
- "aria-live": "off",
559
- className: "my-3 min-w-0 space-y-4 rounded-lg border border-fawn bg-ivory p-4",
560
- "aria-label": "Conversation library",
561
- children: [
562
- /* @__PURE__ */ jsxs("div", {
563
- className: "flex flex-col items-start gap-3 sm:flex-row sm:items-center sm:justify-between",
564
- children: [/* @__PURE__ */ jsx("h2", {
565
- className: "m-0 text-lg",
566
- children: "Conversations"
567
- }), /* @__PURE__ */ jsx(Button, {
568
- variant: "primary",
569
- disabled: !library || busy || turnBusy,
570
- onClick: () => void create(),
571
- children: "New conversation"
572
- })]
573
- }),
574
- /* @__PURE__ */ jsx("p", {
575
- className: "m-0 text-sm",
576
- children: "Starting a new conversation keeps previous history and saved files. Viewing history does not change the active conversation."
577
- }),
578
- turnBusy && /* @__PURE__ */ jsx("p", {
579
- role: "status",
580
- children: "Wait for the current turn to finish before starting a new conversation."
581
- }),
582
- error && /* @__PURE__ */ jsxs("p", {
583
- role: "alert",
584
- children: [
585
- error,
586
- " ",
587
- /* @__PURE__ */ jsx(Button, {
588
- variant: "ghost",
589
- disabled: busy,
590
- onClick: () => {
591
- setError("");
592
- setRefresh((value) => value + 1);
593
- },
594
- children: "Refresh library"
595
- })
596
- ]
597
- }),
598
- !library ? /* @__PURE__ */ jsx("p", {
599
- role: "status",
600
- children: "Loading conversations…"
601
- }) : /* @__PURE__ */ jsxs(Fragment, { children: [
602
- !library.total && /* @__PURE__ */ jsx("p", { children: "No conversations yet." }),
603
- /* @__PURE__ */ jsx("ul", {
604
- className: "mt-4 grid list-none gap-2 p-0",
605
- children: library.conversations.map((item) => /* @__PURE__ */ jsxs("li", {
606
- className: "flex min-w-0 flex-col items-start gap-3 rounded border border-fawn p-3 sm:flex-row sm:items-center sm:justify-between",
607
- children: [/* @__PURE__ */ jsxs("span", {
608
- className: "flex min-w-0 flex-1 flex-wrap items-center gap-2",
609
- children: [/* @__PURE__ */ jsx("span", {
610
- className: "min-w-0 break-words [overflow-wrap:anywhere]",
611
- children: item.title
612
- }), item.id === library.selection.conversationId && /* @__PURE__ */ jsx("strong", {
613
- className: "shrink-0 rounded-full bg-frost px-2 py-0.5 text-xs",
614
- children: "Active"
615
- })]
616
- }), /* @__PURE__ */ jsxs(Button, {
617
- variant: "ghost",
618
- className: "max-w-full whitespace-normal break-words text-left sm:max-w-[50%]",
619
- disabled: busy,
620
- "aria-pressed": selected?.id === item.id,
621
- onClick: () => {
622
- setSelected(item);
623
- setTitle(item.title);
624
- },
625
- children: ["View ", item.title]
626
- })]
627
- }, item.id))
628
- }),
629
- /* @__PURE__ */ jsxs("div", {
630
- className: "mt-4 flex flex-wrap items-center gap-2",
631
- children: [
632
- /* @__PURE__ */ jsx(Button, {
633
- variant: "ghost",
634
- disabled: busy || offset === 0,
635
- onClick: () => setOffset(Math.max(0, offset - 20)),
636
- children: "Previous"
637
- }),
638
- /* @__PURE__ */ jsx(Button, {
639
- variant: "ghost",
640
- disabled: busy || offset + library.conversations.length >= library.total,
641
- onClick: () => setOffset(offset + 20),
642
- children: "Next"
643
- }),
644
- /* @__PURE__ */ jsxs("span", {
645
- className: "text-sm",
646
- children: [library.total, " conversations"]
647
- })
648
- ]
649
- })
650
- ] }),
651
- selected && /* @__PURE__ */ jsxs("section", {
652
- className: "space-y-4 border-t border-fawn pt-4",
653
- "aria-label": "Retained conversation",
654
- children: [
655
- /* @__PURE__ */ jsxs("div", {
656
- className: "grid min-w-0 grid-cols-2 items-end gap-2 sm:grid-cols-[minmax(0,1fr)_auto_auto]",
657
- children: [
658
- /* @__PURE__ */ jsxs("label", {
659
- className: "col-span-2 m-0 grid min-w-0 gap-2 sm:col-span-1",
660
- children: ["Conversation title", /* @__PURE__ */ jsx("input", {
661
- className: "h-11",
662
- value: title,
663
- maxLength: 200,
664
- onChange: (event) => setTitle(event.target.value)
665
- })]
666
- }),
667
- /* @__PURE__ */ jsx(Button, {
668
- variant: "ghost",
669
- className: "h-11",
670
- disabled: busy || !title.trim(),
671
- onClick: () => void rename(),
672
- children: "Rename"
673
- }),
674
- /* @__PURE__ */ jsx(Button, {
675
- variant: "ghost",
676
- className: "h-11",
677
- disabled: busy,
678
- onClick: () => setSelected(null),
679
- children: "Close history"
680
- })
681
- ]
682
- }),
683
- /* @__PURE__ */ jsx("p", {
684
- className: "m-0 text-sm",
685
- children: "Viewing retained history. New messages still go to the active conversation."
686
- }),
687
- historyError ? /* @__PURE__ */ jsx("p", {
688
- role: "alert",
689
- children: historyError
690
- }) : history === null ? /* @__PURE__ */ jsx("p", {
691
- role: "status",
692
- children: "Loading history…"
693
- }) : history.length ? renderHistory(history) : /* @__PURE__ */ jsx("p", { children: "This conversation is empty." })
694
- ]
695
- })
696
- ]
697
- });
698
- }
699
- //#endregion
700
- //#region src/lib/queue-journal.ts
701
- /** Store bytes before submission so a reload can retry the exact same attempt. */
702
- async function queueJournal(agentId, value, clearRequestId) {
703
- return new Promise((resolve, reject) => {
704
- const opening = indexedDB.open("bazilion-queue-attempts", 1);
705
- opening.onupgradeneeded = () => {
706
- opening.result.createObjectStore("requests", { keyPath: "input.requestId" }).createIndex("agentId", "agentId");
707
- };
708
- opening.onerror = () => reject(/* @__PURE__ */ new Error("Local queue recovery storage is unavailable"));
709
- opening.onblocked = () => reject(/* @__PURE__ */ new Error("Close other Bazilion tabs to open queue recovery storage"));
710
- opening.onsuccess = () => {
711
- const db = opening.result;
712
- const tx = db.transaction("requests", value === void 0 ? "readonly" : "readwrite");
713
- const store = tx.objectStore("requests");
714
- if (value === null && !clearRequestId) {
715
- db.close();
716
- reject(/* @__PURE__ */ new Error("Queue request identity is required to clear recovery state"));
717
- return;
718
- }
719
- const request = value === void 0 ? store.index("agentId").get(agentId) : value === null ? store.delete(clearRequestId) : store.put(value);
720
- tx.oncomplete = () => {
721
- db.close();
722
- resolve(value === void 0 ? request.result ?? null : value);
723
- };
724
- tx.onerror = tx.onabort = () => {
725
- db.close();
726
- reject(/* @__PURE__ */ new Error("Unable to retain queue request locally; it was not acknowledged"));
727
- };
728
- };
729
- });
730
- }
731
- //#endregion
732
- //#region src/components/UserQueuePanel.tsx
733
- var UserQueuePanel = forwardRef(function UserQueuePanel({ agentId, selection, onQueueMode, onViewConversation }, ref) {
734
- const base = `/api/agents/${encodeURIComponent(agentId)}/queue`;
735
- const [state, setState] = useState(null);
736
- const [error, setError] = useState("");
737
- const [notice, setNotice] = useState("");
738
- const [busy, setBusy] = useState(false);
739
- const [ready, setReady] = useState(false);
740
- const readyRef = useRef(false);
741
- const [pending, setPending] = useState(null);
742
- const pendingRef = useRef(null);
743
- const locked = useRef(false);
744
- const mounted = useRef(true);
745
- const refreshGeneration = useRef(0);
746
- useEffect(() => {
747
- mounted.current = true;
748
- return () => {
749
- mounted.current = false;
750
- };
751
- }, []);
752
- const [editing, setEditing] = useState(null);
753
- const [text, setText] = useState("");
754
- const [editFiles, setEditFiles] = useState([]);
755
- const [history, setHistory] = useState(false);
756
- const [offset, setOffset] = useState(0);
757
- const modeRef = useRef(onQueueMode);
758
- modeRef.current = onQueueMode;
759
- async function refresh() {
760
- const generation = ++refreshGeneration.current;
761
- const response = await fetch(`${base}?all=${history ? 1 : 0}&offset=${offset}`);
762
- if (!response.ok) throw new Error("Queue could not be loaded");
763
- const body = await response.json();
764
- const activeResponse = history ? await fetch(base) : null;
765
- const active = activeResponse?.ok ? await activeResponse.json() : body;
766
- if (mounted.current && generation === refreshGeneration.current) {
767
- setState(body);
768
- if (readyRef.current) modeRef.current(active.total > 0 || active.control.paused || !!pendingRef.current);
769
- }
770
- return body;
771
- }
772
- useEffect(() => {
773
- let live = true;
774
- queueJournal(agentId).then((value) => {
775
- if (live) {
776
- pendingRef.current = value;
777
- setPending(value);
778
- readyRef.current = true;
779
- setReady(true);
780
- refresh().catch((e) => setError(e.message));
781
- }
782
- }).catch((e) => {
783
- if (live) setError(e.message);
784
- });
785
- return () => {
786
- live = false;
787
- };
788
- }, [agentId]);
789
- useEffect(() => {
790
- refresh().catch((e) => setError(e.message));
791
- const timer = setInterval(() => {
792
- refresh().catch((e) => setError(e.message));
793
- }, 2e3);
794
- return () => clearInterval(timer);
795
- }, [
796
- agentId,
797
- history,
798
- offset
799
- ]);
800
- async function clearPending(record) {
801
- await queueJournal(agentId, null, record.input.requestId);
802
- const remaining = await queueJournal(agentId);
803
- pendingRef.current = remaining;
804
- setPending(remaining);
805
- }
806
- async function submit(record, retry = false) {
807
- if (locked.current || !ready) return false;
808
- if (pendingRef.current && !retry) {
809
- setError("Resolve the unacknowledged queue request before sending another.");
810
- return false;
811
- }
812
- locked.current = true;
813
- setBusy(true);
814
- setError("");
815
- setNotice("");
816
- try {
817
- await queueJournal(agentId, record);
818
- pendingRef.current = record;
819
- setPending(record);
820
- const response = await fetch(record.replacementId ? `${base}/${encodeURIComponent(record.replacementId)}` : base, {
821
- method: record.replacementId ? "PATCH" : "POST",
822
- headers: { "content-type": "application/json" },
823
- body: JSON.stringify(record.input)
824
- });
825
- if (!response.ok) {
826
- const detail = await response.json().catch(() => ({}));
827
- if (response.status >= 400 && response.status < 500) await clearPending(record);
828
- throw new Error(detail.error ?? "Queue acknowledgement unavailable; retry this same request.");
829
- }
830
- const item = await response.json();
831
- await clearPending(record);
832
- setNotice(`Follow-up ${item.status}.`);
833
- setEditing(null);
834
- await refresh().catch(() => setError("Input acknowledged; queue display could not refresh."));
835
- return true;
836
- } catch (e) {
837
- setError(e instanceof Error ? e.message : "Queue request failed");
838
- return false;
839
- } finally {
840
- locked.current = false;
841
- setBusy(false);
842
- }
843
- }
844
- async function action(path, body, method = "POST") {
845
- if (locked.current) return false;
846
- locked.current = true;
847
- setBusy(true);
848
- setError("");
849
- try {
850
- const response = await fetch(`${base}${path}`, {
851
- method,
852
- headers: { "content-type": "application/json" },
853
- body: JSON.stringify(body)
854
- });
855
- if (!response.ok) {
856
- const detail = await response.json();
857
- throw new Error(detail.error ?? "Queue changed; refresh and try again");
858
- }
859
- await refresh();
860
- return true;
861
- } catch (e) {
862
- setError(e instanceof Error ? e.message : "Queue action failed");
863
- await refresh().catch(() => {});
864
- return false;
865
- } finally {
866
- locked.current = false;
867
- setBusy(false);
868
- }
869
- }
870
- useImperativeHandle(ref, () => ({
871
- async enqueue(message, attachments, expectedSelection) {
872
- if (!expectedSelection) {
873
- setError("Refresh conversation history before queuing input.");
874
- return false;
875
- }
876
- return submit({
877
- agentId,
878
- input: {
879
- requestId: crypto.randomUUID(),
880
- message,
881
- attachments,
882
- expectedSelection
883
- }
884
- });
885
- },
886
- async stop() {
887
- if (!state) {
888
- setError("Load queue controls before stopping.");
889
- return false;
890
- }
891
- return action("/stop", { expectedRevision: state.control.revision });
892
- }
893
- }));
894
- async function edit(item) {
895
- try {
896
- const response = await fetch(`${base}/${encodeURIComponent(item.id)}/input`);
897
- if (!response.ok) throw new Error("Retained input is unavailable");
898
- const input = await response.json();
899
- setEditing(item);
900
- setText(input.message);
901
- setEditFiles(input.attachments);
902
- } catch (e) {
903
- setError(e instanceof Error ? e.message : "Could not edit");
904
- }
905
- }
906
- return /* @__PURE__ */ jsxs("section", {
907
- "aria-label": "Follow-up queue",
908
- className: "max-h-[45%] min-w-0 shrink-0 space-y-3 overflow-y-auto border-t border-frost px-5 py-4 text-sm",
909
- children: [
910
- /* @__PURE__ */ jsxs("div", {
911
- className: "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",
912
- children: [/* @__PURE__ */ jsxs("strong", {
913
- className: "shrink-0",
914
- children: ["Follow-ups ", state?.control.paused ? "· Paused" : ""]
915
- }), /* @__PURE__ */ jsxs("div", {
916
- className: "flex flex-wrap items-center gap-2",
917
- children: [
918
- state && /* @__PURE__ */ jsx(Button, {
919
- variant: "ghost",
920
- disabled: busy,
921
- onClick: () => void action("/control", {
922
- paused: !state.control.paused,
923
- expectedRevision: state.control.revision
924
- }),
925
- children: state.control.paused ? "Resume queue" : "Pause queue"
926
- }),
927
- state && /* @__PURE__ */ jsx(Button, {
928
- variant: "danger",
929
- disabled: busy,
930
- onClick: () => void action("/stop", { expectedRevision: state.control.revision }),
931
- children: "Stop and pause"
932
- }),
933
- /* @__PURE__ */ jsx(Button, {
934
- variant: "ghost",
935
- onClick: () => {
936
- setHistory(!history);
937
- setOffset(0);
938
- },
939
- children: history ? "Pending" : "History"
940
- })
941
- ]
942
- })]
943
- }),
944
- error && /* @__PURE__ */ jsx("p", {
945
- role: "alert",
946
- className: "m-0 break-words text-danger",
947
- children: error
948
- }),
949
- notice && /* @__PURE__ */ jsx("p", {
950
- role: "status",
951
- className: "m-0 text-mocha",
952
- children: notice
953
- }),
954
- pending && /* @__PURE__ */ jsxs("div", {
955
- role: "status",
956
- className: "flex min-w-0 flex-col gap-3 rounded-lg border border-frost bg-ivory p-3",
957
- children: [
958
- /* @__PURE__ */ jsx("p", { children: "A queue request has no confirmed acknowledgement. Retrying uses the same request and files." }),
959
- /* @__PURE__ */ jsx("p", {
960
- className: "truncate",
961
- children: pending.input.message
962
- }),
963
- /* @__PURE__ */ jsx(Button, {
964
- variant: "primary",
965
- disabled: busy,
966
- onClick: () => void submit(pending, true),
967
- children: "Retry saved request"
968
- })
969
- ]
970
- }),
971
- /* @__PURE__ */ jsxs("div", {
972
- className: "min-w-0 space-y-3",
973
- children: [state?.items.map((item) => /* @__PURE__ */ jsxs("article", {
974
- className: "flex min-w-0 flex-col gap-3 rounded-lg border border-frost bg-ivory p-3",
975
- children: [
976
- /* @__PURE__ */ jsxs("div", {
977
- className: "flex flex-wrap items-center justify-between gap-3",
978
- children: [/* @__PURE__ */ jsxs("div", {
979
- className: "flex flex-wrap items-center gap-2",
980
- children: [/* @__PURE__ */ jsx("strong", {
981
- className: "rounded-full bg-frost px-2 py-1 text-xs capitalize",
982
- children: item.status
983
- }), /* @__PURE__ */ jsx("span", {
984
- className: "text-xs text-mocha",
985
- children: item.source === "telegram" ? "Telegram" : "Web / API"
986
- })]
987
- }), /* @__PURE__ */ jsx(Button, {
988
- variant: "ghost",
989
- onClick: () => onViewConversation(item.conversationId),
990
- children: "View conversation"
991
- })]
992
- }),
993
- /* @__PURE__ */ jsx("p", {
994
- className: "m-0 whitespace-pre-wrap break-words [overflow-wrap:anywhere]",
995
- children: item.text ?? "Input retention expired"
996
- }),
997
- item.attachments.map((file) => /* @__PURE__ */ jsxs("p", {
998
- className: "m-0 break-all text-xs text-mocha",
999
- children: [
1000
- file.name ?? "Attachment",
1001
- " · ",
1002
- file.byteLength,
1003
- " bytes"
1004
- ]
1005
- }, file.id)),
1006
- item.diagnostic && /* @__PURE__ */ jsx("p", {
1007
- className: "m-0 break-words",
1008
- children: item.diagnostic
1009
- }),
1010
- item.approvalId && /* @__PURE__ */ jsx("a", {
1011
- href: `/approvals`,
1012
- children: "Review communication approval"
1013
- }),
1014
- item.status === "pending" && /* @__PURE__ */ jsxs("div", {
1015
- className: "flex flex-wrap items-center gap-2",
1016
- children: [/* @__PURE__ */ jsx(Button, {
1017
- variant: "ghost",
1018
- disabled: busy || !!pending,
1019
- onClick: () => void edit(item),
1020
- children: "Edit"
1021
- }), /* @__PURE__ */ jsx(Button, {
1022
- variant: "danger",
1023
- disabled: busy,
1024
- onClick: () => void action(`/${item.id}`, { expectedRevision: item.revision }, "DELETE"),
1025
- children: "Remove"
1026
- })]
1027
- }),
1028
- item.status === "uncertain" && /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("p", { children: "This input may already have acted. Review its conversation before closing it. Closing never retries it." }), /* @__PURE__ */ jsx(Button, {
1029
- variant: "danger",
1030
- disabled: busy,
1031
- onClick: () => void action(`/${item.id}/reconcile`, {
1032
- expectedRevision: item.revision,
1033
- acknowledged: true
1034
- }),
1035
- children: "Acknowledge and close"
1036
- })] })
1037
- ]
1038
- }, item.id)), editing && /* @__PURE__ */ jsxs("form", {
1039
- className: "flex min-w-0 flex-col gap-3 rounded-lg border border-frost bg-ivory p-3",
1040
- onSubmit: (e) => {
1041
- e.preventDefault();
1042
- const expectedSelection = selection();
1043
- if (expectedSelection) submit({
1044
- agentId,
1045
- replacementId: editing.id,
1046
- input: {
1047
- requestId: crypto.randomUUID(),
1048
- expectedRevision: editing.revision,
1049
- expectedSelection,
1050
- message: text,
1051
- attachments: editFiles
1052
- }
1053
- });
1054
- },
1055
- children: [
1056
- /* @__PURE__ */ jsxs("label", {
1057
- className: "m-0 grid gap-2",
1058
- children: ["Edit queued input", /* @__PURE__ */ jsx("textarea", {
1059
- "aria-label": "Edit queued input",
1060
- rows: 3,
1061
- className: "w-full resize-y",
1062
- value: text,
1063
- onChange: (e) => setText(e.target.value)
1064
- })]
1065
- }),
1066
- editFiles.map((file, index) => /* @__PURE__ */ jsxs("div", { children: [
1067
- file.name ?? "Attachment",
1068
- " ",
1069
- /* @__PURE__ */ jsx(Button, {
1070
- variant: "ghost",
1071
- onClick: () => setEditFiles((files) => files.filter((_, i) => i !== index)),
1072
- children: "Remove attachment"
1073
- })
1074
- ] }, index)),
1075
- /* @__PURE__ */ jsxs("div", {
1076
- className: "flex flex-wrap items-center gap-2",
1077
- children: [/* @__PURE__ */ jsx(Button, {
1078
- variant: "primary",
1079
- type: "submit",
1080
- disabled: busy || !!pending,
1081
- children: "Save replacement"
1082
- }), /* @__PURE__ */ jsx(Button, {
1083
- variant: "ghost",
1084
- onClick: () => setEditing(null),
1085
- children: "Cancel edit"
1086
- })]
1087
- })
1088
- ]
1089
- })]
1090
- }),
1091
- state && (offset > 0 || offset + state.items.length < state.total) && /* @__PURE__ */ jsxs("div", {
1092
- className: "flex flex-wrap items-center gap-2",
1093
- children: [/* @__PURE__ */ jsx(Button, {
1094
- variant: "ghost",
1095
- disabled: offset === 0,
1096
- onClick: () => setOffset(Math.max(0, offset - 20)),
1097
- children: "Previous"
1098
- }), /* @__PURE__ */ jsx(Button, {
1099
- variant: "ghost",
1100
- disabled: offset + state.items.length >= state.total,
1101
- onClick: () => setOffset(offset + 20),
1102
- children: "Next"
1103
- })]
1104
- })
1105
- ]
1106
- });
1107
- });
1108
- //#endregion
1109
- //#region src/components/AgentQuestions.tsx
1110
- function AgentQuestions({ agentId }) {
1111
- const [items, setItems] = useState([]);
1112
- const [error, setError] = useState("");
1113
- useEffect(() => {
1114
- let live = true;
1115
- let running = false;
1116
- const refresh = async () => {
1117
- if (running) return;
1118
- running = true;
1119
- try {
1120
- const response = await fetch(`/api/agents/${encodeURIComponent(agentId)}/questions`, { cache: "no-store" });
1121
- if (!response.ok) throw new Error("Questions could not be refreshed");
1122
- const body = await response.json();
1123
- if (live) {
1124
- setItems(body.questions);
1125
- setError("");
1126
- }
1127
- } catch (e) {
1128
- if (live) {
1129
- setItems([]);
1130
- setError(e instanceof Error ? e.message : "Questions unavailable");
1131
- }
1132
- } finally {
1133
- running = false;
1134
- }
1135
- };
1136
- refresh();
1137
- const timer = setInterval(() => {
1138
- refresh();
1139
- }, 2e3);
1140
- return () => {
1141
- live = false;
1142
- clearInterval(timer);
1143
- };
1144
- }, [agentId]);
1145
- if (!items.length && !error) return null;
1146
- return /* @__PURE__ */ jsxs("section", {
1147
- "aria-label": "Agent questions",
1148
- className: "max-h-[40vh] min-w-0 shrink-0 space-y-3 overflow-y-auto border-t border-frost px-5 py-3",
1149
- children: [
1150
- error && /* @__PURE__ */ jsx("p", {
1151
- role: "status",
1152
- children: error
1153
- }),
1154
- items.filter((item) => item.status === "pending" || item.continuation === "unconfirmed").map((item) => /* @__PURE__ */ jsx(QuestionCard, { item }, item.id)),
1155
- items.some((item) => item.status !== "pending" && item.continuation !== "unconfirmed") && /* @__PURE__ */ jsxs("details", { children: [/* @__PURE__ */ jsx("summary", { children: "Recent question outcomes" }), items.filter((item) => item.status !== "pending" && item.continuation !== "unconfirmed").map((item) => /* @__PURE__ */ jsx(QuestionCard, { item }, item.id))] })
1156
- ]
1157
- });
1158
- }
1159
- function QuestionCard({ item }) {
1160
- const storageKey = `bazilion-question-answer:${item.agentId}:${item.id}`;
1161
- const [choice, setChoice] = useState("");
1162
- const [text, setText] = useState("");
1163
- const [pending, setPending] = useState(null);
1164
- const pendingRef = useRef(null);
1165
- const [ready, setReady] = useState(false);
1166
- const [busy, setBusy] = useState(false);
1167
- const locked = useRef(false);
1168
- const [error, setError] = useState("");
1169
- const [notice, setNotice] = useState("");
1170
- useEffect(() => {
1171
- try {
1172
- const saved = sessionStorage.getItem(storageKey);
1173
- if (saved) {
1174
- const value = JSON.parse(saved);
1175
- pendingRef.current = value;
1176
- setPending(value);
1177
- }
1178
- setReady(true);
1179
- } catch {
1180
- setError("Answer recovery storage is unavailable. Enable session storage before answering.");
1181
- }
1182
- }, [storageKey]);
1183
- useEffect(() => {
1184
- if (item.status === "pending") return;
1185
- try {
1186
- sessionStorage.removeItem(storageKey);
1187
- pendingRef.current = null;
1188
- setPending(null);
1189
- } catch {}
1190
- }, [item.status, storageKey]);
1191
- async function submit(answer) {
1192
- if (locked.current || !ready || item.status !== "pending") return;
1193
- locked.current = true;
1194
- setBusy(true);
1195
- setError("");
1196
- try {
1197
- if (!pendingRef.current && !answer) throw new Error("Choose an answer first");
1198
- const input = pendingRef.current ?? {
1199
- requestId: crypto.randomUUID(),
1200
- conversationId: item.conversationId,
1201
- answer
1202
- };
1203
- sessionStorage.setItem(storageKey, JSON.stringify(input));
1204
- pendingRef.current = input;
1205
- setPending(input);
1206
- const response = await fetch(`/api/agents/${encodeURIComponent(item.agentId)}/questions/${encodeURIComponent(item.id)}/answer`, {
1207
- method: "POST",
1208
- headers: { "content-type": "application/json" },
1209
- body: JSON.stringify(input)
1210
- }).catch(() => {
1211
- throw new Error("Answer acknowledgement unavailable. Retry the same answer.");
1212
- });
1213
- if (!response.ok) {
1214
- if (response.status === 409 || response.status === 404) throw new Error("This question is no longer answerable. Its outcome will refresh shortly.");
1215
- throw new Error("Answer acknowledgement unavailable. Retry the same answer.");
1216
- }
1217
- if ((await response.json()).kind === "held") setNotice("Answer awaits communication approval. The Agent has not received it.");
1218
- else {
1219
- sessionStorage.removeItem(storageKey);
1220
- setNotice("Answer accepted. Waiting for saved conversation evidence that the Agent consumed it.");
1221
- }
1222
- } catch (e) {
1223
- setError(e instanceof Error ? e.message : "Answer failed");
1224
- } finally {
1225
- locked.current = false;
1226
- setBusy(false);
1227
- }
1228
- }
1229
- const disabled = !ready || busy || !!pending || item.status !== "pending" || !!item.answerApprovalId;
1230
- return /* @__PURE__ */ jsxs("article", {
1231
- className: "flex min-w-0 flex-col gap-3 rounded-lg border border-frost bg-ivory p-3",
1232
- children: [
1233
- /* @__PURE__ */ jsx("p", {
1234
- className: "m-0 break-words font-medium",
1235
- children: item.question.prompt
1236
- }),
1237
- /* @__PURE__ */ jsxs("details", {
1238
- className: "text-xs text-mocha",
1239
- children: [/* @__PURE__ */ jsxs("summary", {
1240
- className: "cursor-pointer",
1241
- children: ["Question details · ", item.status]
1242
- }), /* @__PURE__ */ jsxs("p", {
1243
- className: "mt-2 break-all",
1244
- children: [
1245
- "Conversation ",
1246
- item.conversationId,
1247
- " · ",
1248
- item.continuation
1249
- ]
1250
- })]
1251
- }),
1252
- item.status === "pending" ? /* @__PURE__ */ jsxs("form", {
1253
- className: "flex min-w-0 flex-col gap-3",
1254
- onSubmit: (event) => {
1255
- event.preventDefault();
1256
- if (choice === "other") submit({
1257
- kind: "text",
1258
- text
1259
- });
1260
- else if (choice !== "") submit({
1261
- kind: "choice",
1262
- index: Number(choice)
1263
- });
1264
- },
1265
- children: [
1266
- /* @__PURE__ */ jsxs("fieldset", {
1267
- disabled,
1268
- className: "m-0 grid min-w-0 gap-2 border-0 p-0 sm:grid-cols-2",
1269
- children: [
1270
- /* @__PURE__ */ jsx("legend", {
1271
- className: "sr-only",
1272
- children: "Answer this question"
1273
- }),
1274
- item.question.choices.map((option, index) => /* @__PURE__ */ jsxs("label", {
1275
- className: "m-0 flex min-w-0 cursor-pointer items-center gap-2 rounded-md border border-frost px-3 py-2.5 has-[:checked]:border-sapphire has-[:checked]:bg-sapphire-glow",
1276
- children: [/* @__PURE__ */ jsx("input", {
1277
- className: "m-0 h-4 w-4 shrink-0 accent-sapphire",
1278
- type: "radio",
1279
- name: `question-${item.id}`,
1280
- value: index,
1281
- checked: choice === String(index),
1282
- onChange: () => setChoice(String(index))
1283
- }), /* @__PURE__ */ jsxs("span", {
1284
- className: "min-w-0 break-words [overflow-wrap:anywhere]",
1285
- children: [
1286
- option.label,
1287
- item.question.recommendedIndex === index ? " (Recommended)" : "",
1288
- option.description && /* @__PURE__ */ jsx("small", {
1289
- className: "block",
1290
- children: option.description
1291
- })
1292
- ]
1293
- })]
1294
- }, index)),
1295
- /* @__PURE__ */ jsxs("label", {
1296
- className: "m-0 flex min-w-0 cursor-pointer items-center gap-2 rounded-md border border-frost px-3 py-2.5 has-[:checked]:border-sapphire has-[:checked]:bg-sapphire-glow",
1297
- children: [/* @__PURE__ */ jsx("input", {
1298
- className: "m-0 h-4 w-4 shrink-0 accent-sapphire",
1299
- type: "radio",
1300
- name: `question-${item.id}`,
1301
- checked: choice === "other",
1302
- onChange: () => setChoice("other")
1303
- }), /* @__PURE__ */ jsx("span", { children: "Other" })]
1304
- }),
1305
- choice === "other" && /* @__PURE__ */ jsxs("label", {
1306
- className: "m-0 grid gap-2 sm:col-span-2",
1307
- children: ["Your answer", /* @__PURE__ */ jsx("textarea", {
1308
- rows: 2,
1309
- className: "w-full resize-y",
1310
- value: text,
1311
- maxLength: 4096,
1312
- onChange: (event) => setText(event.target.value)
1313
- })]
1314
- })
1315
- ]
1316
- }),
1317
- pending && /* @__PURE__ */ jsxs("p", {
1318
- className: "break-words",
1319
- children: ["Saved answer: ", pending.answer.kind === "choice" ? item.question.choices[pending.answer.index]?.label : pending.answer.kind === "text" ? pending.answer.text : "Skip"]
1320
- }),
1321
- /* @__PURE__ */ jsxs("div", {
1322
- className: "flex flex-wrap gap-2",
1323
- children: [
1324
- /* @__PURE__ */ jsx(Button, {
1325
- variant: "primary",
1326
- type: "submit",
1327
- disabled: disabled || !choice || choice === "other" && (!text.trim() || new TextEncoder().encode(text).length > 4096),
1328
- children: "Send answer"
1329
- }),
1330
- /* @__PURE__ */ jsx(Button, {
1331
- variant: "ghost",
1332
- disabled,
1333
- onClick: () => {
1334
- submit({ kind: "skip" });
1335
- },
1336
- children: "Skip"
1337
- }),
1338
- pending && !item.answerApprovalId && /* @__PURE__ */ jsx(Button, {
1339
- variant: "ghost",
1340
- disabled: busy,
1341
- onClick: () => {
1342
- submit();
1343
- },
1344
- children: "Retry same answer"
1345
- })
1346
- ]
1347
- }),
1348
- /* @__PURE__ */ jsxs("p", {
1349
- className: "m-0 text-xs text-mocha",
1350
- children: [
1351
- "Clarification does not grant permission. This question expires at ",
1352
- new Date(item.expiresAt).toLocaleTimeString(),
1353
- "."
1354
- ]
1355
- }),
1356
- item.answerApprovalId && /* @__PURE__ */ jsx("a", {
1357
- href: "/approvals",
1358
- children: "View communication approvals"
1359
- })
1360
- ]
1361
- }) : /* @__PURE__ */ jsxs("p", { children: [
1362
- item.answer?.kind === "choice" ? item.question.choices[item.answer.index]?.label : item.answer?.kind === "text" ? item.answer.text : `No answer: ${item.noAnswerReason ?? item.status}`,
1363
- ". ",
1364
- item.continuation === "consumed" ? "Saved in the originating conversation; task completion is separate." : item.continuation === "interrupted" ? "The waiting turn ended." : "Consumption has not been confirmed."
1365
- ] }),
1366
- notice && /* @__PURE__ */ jsx("p", {
1367
- role: "status",
1368
- children: notice
1369
- }),
1370
- error && /* @__PURE__ */ jsx("p", {
1371
- role: "alert",
1372
- children: error
1373
- })
1374
- ]
1375
- });
1376
- }
1377
- //#endregion
1378
- //#region src/components/ChatPane.tsx
1379
- var INBOX_WAKE_PREFIX = "[[bazilion:inbox-wake]]\n";
1380
- var COMPACTION_REPLAY_PREFIX = "[conversation summary]";
1381
- var AUTOSCROLL_THRESHOLD_PX = 40;
1382
- var SESSION_POLL_MS = 1e4;
1383
- var TOOL_GROUP_MAX_HEIGHT_PX = 320;
1384
- var MAX_INPUT_HEIGHT = 200;
1385
- var subscribeToHydration = () => () => {};
1386
- var browserMarkdownReady = () => true;
1387
- var serverMarkdownReady = () => false;
1388
- /** Keep one inline card per ephemeral shell approval while preserving its first position. */
1389
- function upsertCommandApprovalEntry(entries, approval) {
1390
- const index = entries.findIndex((entry) => entry.type === "command_approval" && entry.approval.id === approval.id);
1391
- if (index === -1) return [...entries, {
1392
- type: "command_approval",
1393
- approval
1394
- }];
1395
- const next = [...entries];
1396
- next[index] = {
1397
- type: "command_approval",
1398
- approval
1399
- };
1400
- return next;
1401
- }
1402
- function interactiveChatRequest(message, attachments) {
1403
- return {
1404
- message,
1405
- attachments,
1406
- bashApprovalMode: "interactive",
1407
- questionMode: "web"
1408
- };
1409
- }
1410
- function shellApprovalsUrl(agentId) {
1411
- return `/api/shell-approvals?agentId=${encodeURIComponent(agentId)}`;
1412
- }
1413
- var SLASH_HELP = "slash commands:\n /context — context breakdown (system prompt, tools, skills, history)\n /compact [N] — summarize the head; keep the last N messages verbatim (default 10)\n /new — open the retained conversation library\n /help — show this list";
1414
- function prettyArgs(raw) {
1415
- if (!raw) return "";
1416
- try {
1417
- return JSON.stringify(JSON.parse(raw), null, 2);
1418
- } catch {
1419
- return raw;
1420
- }
1421
- }
1422
- function formatBytes(n) {
1423
- if (n < 1024) return `${n} B`;
1424
- if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
1425
- return `${(n / (1024 * 1024)).toFixed(2)} MiB`;
1426
- }
1427
- /** Read any File into a base64 Attachment (strips the data: URL prefix). */
1428
- function fileToAttachment(file) {
1429
- return new Promise((resolve, reject) => {
1430
- const reader = new FileReader();
1431
- reader.onload = () => {
1432
- const result = String(reader.result);
1433
- const comma = result.indexOf(",");
1434
- resolve({
1435
- name: file.name,
1436
- data: comma >= 0 ? result.slice(comma + 1) : result,
1437
- mimeType: file.type || "application/octet-stream"
1438
- });
1439
- };
1440
- reader.onerror = () => reject(reader.error);
1441
- reader.readAsDataURL(file);
1442
- });
1443
- }
1444
- var isImageMime = (m) => m.startsWith("image/");
1445
- function projectMessages(msgs) {
1446
- const entries = [];
1447
- let openTool = null;
1448
- for (const m of msgs) if (m.role === "user") {
1449
- openTool = null;
1450
- entries.push({
1451
- type: "user",
1452
- content: m.content,
1453
- ...m.images && m.images.length > 0 ? { images: m.images } : {}
1454
- });
1455
- } else if (m.role === "assistant") {
1456
- if (m.content) {
1457
- openTool = null;
1458
- entries.push({
1459
- type: "assistant",
1460
- content: m.content
1461
- });
1462
- }
1463
- if (m.toolCalls && m.toolCalls.length > 0) {
1464
- if (!openTool) {
1465
- openTool = {
1466
- type: "tool",
1467
- items: []
1468
- };
1469
- entries.push(openTool);
1470
- }
1471
- for (const tc of m.toolCalls) openTool.items.push({
1472
- kind: "call",
1473
- id: tc.id,
1474
- name: tc.name,
1475
- body: tc.arguments
1476
- });
1477
- }
1478
- } else if (m.role === "tool") {
1479
- if (!openTool) {
1480
- openTool = {
1481
- type: "tool",
1482
- items: []
1483
- };
1484
- entries.push(openTool);
1485
- }
1486
- const isError = m.content.startsWith("Error:") || m.content.startsWith("error:");
1487
- openTool.items.push({
1488
- kind: isError ? "error" : "result",
1489
- id: m.toolCallId ?? "",
1490
- name: m.toolName ?? "",
1491
- body: m.content,
1492
- ...m.codingLog ? { codingLog: m.codingLog } : {}
1493
- });
1494
- for (const ref of m.results ?? (m.result ? [m.result] : [])) {
1495
- entries.push({
1496
- type: "result",
1497
- resultId: ref.resultId
1498
- });
1499
- openTool = null;
1500
- }
1501
- if (m.images && m.images.length > 0) {
1502
- entries.push({
1503
- type: "images",
1504
- images: m.images
1505
- });
1506
- openTool = null;
1507
- }
1508
- }
1509
- return entries;
1510
- }
1511
- function ChatPane({ agentId, agentName, initialMessages, initialSessionHead }) {
1512
- const markdownReady = useSyncExternalStore(subscribeToHydration, browserMarkdownReady, serverMarkdownReady);
1513
- const [serverMessages, setServerMessages] = useState(initialMessages);
1514
- const [liveEntries, setLiveEntries] = useState([]);
1515
- const deliveredCoding = useRef(/* @__PURE__ */ new Map());
1516
- const [systemBubbles, setSystemBubbles] = useState([]);
1517
- const [thinking, setThinking] = useState(false);
1518
- const [streaming, setStreaming] = useState(false);
1519
- const [editIdx, setEditIdx] = useState(null);
1520
- const [input, setInput] = useState("");
1521
- const [attachments, setAttachments] = useState([]);
1522
- const [dragging, setDragging] = useState(false);
1523
- const [staleBanner, setStaleBanner] = useState(false);
1524
- const [recoveredTurn, setRecoveredTurn] = useState(false);
1525
- const [approvalBusy, setApprovalBusy] = useState({});
1526
- const [approvalErrors, setApprovalErrors] = useState({});
1527
- const [libraryOpen, setLibraryOpen] = useState(false);
1528
- const [queueConversation, setQueueConversation] = useState();
1529
- const [queueMode, setQueueMode] = useState(false);
1530
- const [queueReady, setQueueReady] = useState(false);
1531
- const queueRef = useRef(null);
1532
- const [historyUnavailable, setHistoryUnavailable] = useState(initialSessionHead?.unavailable ?? false);
1533
- const messagesRef = useRef(null);
1534
- const fileInputRef = useRef(null);
1535
- const inputRef = useRef(null);
1536
- const currentAbortRef = useRef(null);
1537
- const currentAgentIdRef = useRef(agentId);
1538
- const commandApprovalTurnRef = useRef(false);
1539
- currentAgentIdRef.current = agentId;
1540
- const systemIdRef = useRef(0);
1541
- const visibleEntryCountRef = useRef(0);
1542
- const knownHeadRef = useRef(initialSessionHead ?? {
1543
- file: null,
1544
- size: 0
1545
- });
1546
- const streamingRef = useRef(false);
1547
- streamingRef.current = streaming;
1548
- const turnBusy = streaming || recoveredTurn;
1549
- useEffect(() => {
1550
- currentAbortRef.current?.abort();
1551
- currentAbortRef.current = null;
1552
- commandApprovalTurnRef.current = false;
1553
- deliveredCoding.current.clear();
1554
- setServerMessages(initialMessages);
1555
- setLiveEntries([]);
1556
- setSystemBubbles([]);
1557
- setEditIdx(null);
1558
- setInput("");
1559
- setQueueReady(false);
1560
- setAttachments([]);
1561
- setHistoryUnavailable(initialSessionHead?.unavailable ?? false);
1562
- setThinking(false);
1563
- setStreaming(false);
1564
- setStaleBanner(false);
1565
- setRecoveredTurn(false);
1566
- setApprovalBusy({});
1567
- setApprovalErrors({});
1568
- knownHeadRef.current = initialSessionHead ?? {
1569
- file: null,
1570
- size: 0
1571
- };
1572
- }, [agentId]);
1573
- useEffect(() => {
1574
- const controller = new AbortController();
1575
- let stopped = false;
1576
- async function recoverPendingCommandApprovals() {
1577
- try {
1578
- const response = await fetch(shellApprovalsUrl(agentId), { signal: controller.signal });
1579
- if (!response.ok) return;
1580
- const pending = (await response.json()).approvals.filter((approval) => approval.agentId === agentId && approval.status === "pending");
1581
- if (stopped || pending.length === 0) return;
1582
- sessionStorage.removeItem(`bz_pending_${agentId}`);
1583
- commandApprovalTurnRef.current = true;
1584
- setLiveEntries((entries) => pending.reduce(upsertCommandApprovalEntry, entries));
1585
- setRecoveredTurn(true);
1586
- } catch (error) {
1587
- if (error.name === "AbortError") return;
1588
- }
1589
- }
1590
- recoverPendingCommandApprovals();
1591
- return () => {
1592
- stopped = true;
1593
- controller.abort();
1594
- };
1595
- }, [agentId]);
1596
- const wasNearBottomRef = useRef(true);
1597
- useLayoutEffect(() => {
1598
- const el = messagesRef.current;
1599
- if (!el) return;
1600
- if (wasNearBottomRef.current) el.scrollTop = el.scrollHeight;
1601
- });
1602
- function captureScroll() {
1603
- const el = messagesRef.current;
1604
- if (!el) {
1605
- wasNearBottomRef.current = true;
1606
- return;
1607
- }
1608
- wasNearBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < AUTOSCROLL_THRESHOLD_PX;
1609
- }
1610
- useLayoutEffect(() => {
1611
- const el = inputRef.current;
1612
- if (!el) return;
1613
- el.style.height = "auto";
1614
- el.style.height = `${Math.min(el.scrollHeight, MAX_INPUT_HEIGHT)}px`;
1615
- }, [input]);
1616
- useEffect(() => {
1617
- const key = `bz_pending_${agentId}`;
1618
- function onVis() {
1619
- if (document.visibilityState === "visible" && sessionStorage.getItem(key)) {
1620
- sessionStorage.removeItem(key);
1621
- setStaleBanner(true);
1622
- }
1623
- }
1624
- document.addEventListener("visibilitychange", onVis);
1625
- return () => document.removeEventListener("visibilitychange", onVis);
1626
- }, [agentId]);
1627
- useEffect(() => {
1628
- if (!initialSessionHead) return;
1629
- let stopped = false;
1630
- let timer = null;
1631
- async function tick() {
1632
- if (stopped) return;
1633
- if (!document.hidden && !streamingRef.current && !staleBanner) try {
1634
- const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/sessions/head`);
1635
- if (res.ok) {
1636
- const body = await res.json();
1637
- if (typeof body.size === "number") {
1638
- const known = knownHeadRef.current;
1639
- if (body.unavailable !== known.unavailable || body.file !== known.file || body.size !== known.size) setStaleBanner(true);
1640
- }
1641
- }
1642
- } catch {}
1643
- timer = setTimeout(tick, SESSION_POLL_MS);
1644
- }
1645
- timer = setTimeout(tick, SESSION_POLL_MS);
1646
- return () => {
1647
- stopped = true;
1648
- if (timer) clearTimeout(timer);
1649
- };
1650
- }, [
1651
- agentId,
1652
- initialSessionHead,
1653
- staleBanner
1654
- ]);
1655
- async function refreshConversationHistory() {
1656
- if (streamingRef.current) return;
1657
- try {
1658
- const response = await fetch(`/api/agents/${encodeURIComponent(agentId)}/sessions/messages`);
1659
- if (!response.ok) throw new Error("Conversation history is unavailable. Your draft is preserved.");
1660
- const body = await response.json();
1661
- if (currentAgentIdRef.current !== agentId) return;
1662
- setHistoryUnavailable(body.head.unavailable ?? false);
1663
- setServerMessages(body.messages);
1664
- setLiveEntries([]);
1665
- setEditIdx(null);
1666
- knownHeadRef.current = body.head;
1667
- setStaleBanner(false);
1668
- } catch (error) {
1669
- pushSystem(error instanceof Error ? error.message : "Could not refresh conversation");
1670
- }
1671
- }
1672
- async function refreshKnownHead() {
1673
- if (currentAgentIdRef.current !== agentId) return;
1674
- try {
1675
- const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/sessions/head`);
1676
- if (!res.ok) return;
1677
- const body = await res.json();
1678
- if (currentAgentIdRef.current === agentId && typeof body.size === "number") {
1679
- const prior = knownHeadRef.current.selection;
1680
- if (prior?.conversationId && prior.conversationId !== body.selection?.conversationId) {
1681
- setStaleBanner(true);
1682
- return;
1683
- }
1684
- setHistoryUnavailable(body.unavailable ?? false);
1685
- knownHeadRef.current = body;
1686
- }
1687
- } catch {}
1688
- }
1689
- function pushSystem(text) {
1690
- captureScroll();
1691
- setSystemBubbles((prev) => [...prev, {
1692
- id: systemIdRef.current++,
1693
- content: text,
1694
- afterIdx: visibleEntryCountRef.current
1695
- }]);
1696
- }
1697
- async function runContextCommand() {
1698
- try {
1699
- const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/chat/context`);
1700
- if (!res.ok) {
1701
- pushSystem(`/context failed: ${res.statusText}`);
1702
- return;
1703
- }
1704
- const ctx = await res.json();
1705
- const fmt = (chars, tokens) => `${chars.toLocaleString()} chars (~${tokens.toLocaleString()} tok)`;
1706
- const lines = [];
1707
- lines.push(`context for ${ctx.agentId}`);
1708
- lines.push(`model: ${ctx.model}`);
1709
- lines.push("");
1710
- lines.push(`system prompt: ${fmt(ctx.systemPrompt.chars, ctx.systemPrompt.tokens)}`);
1711
- for (const f of ctx.systemPrompt.files) lines.push(` - ${f.name}: ${f.chars.toLocaleString()} chars`);
1712
- lines.push("");
1713
- lines.push(`tools: ${ctx.tools.count} (${ctx.tools.schemaChars.toLocaleString()} chars of schema)`);
1714
- for (const t of ctx.tools.entries.slice(0, 5)) lines.push(` - ${t.name}: ${t.schemaChars.toLocaleString()} chars`);
1715
- if (ctx.skills.count > 0) {
1716
- lines.push("");
1717
- lines.push(`skills: ${ctx.skills.count}`);
1718
- for (const s of ctx.skills.entries.slice(0, 10)) lines.push(` - ${s.name}: ${s.blockChars.toLocaleString()} chars`);
1719
- }
1720
- lines.push("");
1721
- lines.push(`history: ${ctx.history.messageEntries} messages / ${ctx.history.compactionEntries} compactions`);
1722
- lines.push(` ${fmt(ctx.history.chars, ctx.history.tokensEstimate)}`);
1723
- lines.push(` bytes on disk: ${formatBytes(ctx.history.bytes)}`);
1724
- lines.push("");
1725
- lines.push(`TOTAL: ${fmt(ctx.totals.chars, ctx.totals.tokens)}`);
1726
- pushSystem(lines.join("\n"));
1727
- } catch (err) {
1728
- pushSystem(`/context failed: ${err.message}`);
1729
- }
1730
- }
1731
- async function runCompactCommand(rest) {
1732
- if (serverMessages.length < 2) {
1733
- pushSystem("/compact: need ≥2 messages to compact");
1734
- return;
1735
- }
1736
- let keepTail;
1737
- const argText = rest.trim();
1738
- if (argText) {
1739
- const n = Number(argText);
1740
- if (Number.isFinite(n) && n >= 0) keepTail = Math.floor(n);
1741
- }
1742
- exitEditMode();
1743
- setStreaming(true);
1744
- setThinking(true);
1745
- try {
1746
- const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/chat/compact`, {
1747
- method: "POST",
1748
- headers: { "content-type": "application/json" },
1749
- body: JSON.stringify({
1750
- keepTail,
1751
- expectedSelection: knownHeadRef.current.selection
1752
- })
1753
- });
1754
- if (!res.ok) {
1755
- let msg = res.statusText;
1756
- try {
1757
- msg = (await res.json()).error || msg;
1758
- } catch {}
1759
- pushSystem(`/compact failed: ${msg}`);
1760
- return;
1761
- }
1762
- const body = await res.json();
1763
- pushSystem(`/compact: ${body.before} → ${body.after} entries (${body.summarized} summarized, ${body.keptTail} kept verbatim; ~${body.tokensBefore.toLocaleString()} → ~${body.tokensAfter.toLocaleString()} tok). reloading…`);
1764
- setTimeout(() => window.location.reload(), 400);
1765
- } catch (err) {
1766
- pushSystem(`/compact failed: ${err.message}`);
1767
- } finally {
1768
- setThinking(false);
1769
- setStreaming(false);
1770
- }
1771
- }
1772
- async function maybeHandleSlashCommand(text) {
1773
- const trimmed = text.trim();
1774
- if (!trimmed.startsWith("/")) return false;
1775
- const parts = trimmed.split(/\s+/);
1776
- const cmd = (parts[0] ?? "").toLowerCase();
1777
- const rest = parts.slice(1).join(" ");
1778
- switch (cmd) {
1779
- case "/help":
1780
- pushSystem(SLASH_HELP);
1781
- return true;
1782
- case "/context":
1783
- await runContextCommand();
1784
- return true;
1785
- case "/new":
1786
- setLibraryOpen(true);
1787
- return true;
1788
- case "/compact":
1789
- await runCompactCommand(rest);
1790
- return true;
1791
- default: return false;
1792
- }
1793
- }
1794
- function findLastUserIdx() {
1795
- for (let i = serverMessages.length - 1; i >= 0; i--) if (serverMessages[i]?.role === "user") return i;
1796
- return -1;
1797
- }
1798
- function enterEditMode() {
1799
- if (liveEntries.length > 0 || turnBusy) return;
1800
- const idx = findLastUserIdx();
1801
- if (idx === -1) return;
1802
- const userMsg = serverMessages[idx];
1803
- if (!userMsg) return;
1804
- setEditIdx(idx);
1805
- setInput(userMsg.content);
1806
- inputRef.current?.focus();
1807
- }
1808
- function exitEditMode() {
1809
- setEditIdx(null);
1810
- }
1811
- async function addFiles(files) {
1812
- if (!files) return;
1813
- const arr = Array.from(files);
1814
- if (arr.length === 0) return;
1815
- const encoded = await Promise.all(arr.map(fileToAttachment));
1816
- setAttachments((prev) => [...prev, ...encoded].slice(0, 16));
1817
- }
1818
- function onPaste(e) {
1819
- const files = Array.from(e.clipboardData.files);
1820
- if (files.some((f) => f.type.startsWith("image/"))) {
1821
- e.preventDefault();
1822
- addFiles(files);
1823
- }
1824
- }
1825
- function onDragOver(e) {
1826
- if (!Array.from(e.dataTransfer.types).includes("Files")) return;
1827
- e.preventDefault();
1828
- setDragging(true);
1829
- }
1830
- function onDragLeave(e) {
1831
- if (e.currentTarget === e.target) setDragging(false);
1832
- }
1833
- function onDrop(e) {
1834
- if (e.dataTransfer.files.length === 0) return;
1835
- e.preventDefault();
1836
- setDragging(false);
1837
- addFiles(e.dataTransfer.files);
1838
- }
1839
- const send = useCallback(async (text) => {
1840
- const atts = attachments;
1841
- if (!text.trim() && atts.length === 0) return;
1842
- if (!queueReady) {
1843
- pushSystem("Queue status is loading. Your draft is preserved.");
1844
- return;
1845
- }
1846
- if (turnBusy || queueMode) {
1847
- if (await queueRef.current?.enqueue(text, atts, knownHeadRef.current.selection) && currentAgentIdRef.current === agentId) {
1848
- setInput((current) => current === text ? "" : current);
1849
- setAttachments((current) => current === atts ? [] : current);
1850
- }
1851
- return;
1852
- }
1853
- setInput("");
1854
- if (await maybeHandleSlashCommand(text)) return;
1855
- setAttachments([]);
1856
- let truncatedServerMessages = null;
1857
- if (editIdx !== null) {
1858
- const keep = editIdx;
1859
- try {
1860
- const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/chat/truncate`, {
1861
- method: "POST",
1862
- headers: { "content-type": "application/json" },
1863
- body: JSON.stringify({
1864
- keepCount: keep,
1865
- expectedSelection: knownHeadRef.current.selection
1866
- })
1867
- });
1868
- if (!res.ok) {
1869
- let err = res.statusText;
1870
- try {
1871
- err = (await res.json()).error || err;
1872
- } catch {}
1873
- setInput(text);
1874
- pushSystem(`Could not replace the last turn: ${err}`);
1875
- return;
1876
- }
1877
- truncatedServerMessages = serverMessages.slice(0, keep);
1878
- setServerMessages(truncatedServerMessages);
1879
- setEditIdx(null);
1880
- } catch (err) {
1881
- setInput(text);
1882
- pushSystem(`Could not replace the last turn: ${err.message}`);
1883
- return;
1884
- }
1885
- }
1886
- captureScroll();
1887
- const previewImages = atts.filter((a) => isImageMime(a.mimeType));
1888
- const previewFiles = atts.filter((a) => !isImageMime(a.mimeType));
1889
- setLiveEntries([{
1890
- type: "user",
1891
- content: text,
1892
- ...previewImages.length > 0 ? { images: previewImages } : {},
1893
- ...previewFiles.length > 0 ? { files: previewFiles.map((f) => ({ name: f.name ?? "file" })) } : {}
1894
- }]);
1895
- setRecoveredTurn(false);
1896
- setApprovalBusy({});
1897
- setApprovalErrors({});
1898
- commandApprovalTurnRef.current = false;
1899
- sessionStorage.setItem(`bz_pending_${agentId}`, "1");
1900
- const abort = new AbortController();
1901
- currentAbortRef.current = abort;
1902
- setStreaming(true);
1903
- setThinking(true);
1904
- let terminalFrameReceived = false;
1905
- try {
1906
- const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/chat`, {
1907
- method: "POST",
1908
- headers: { "content-type": "application/json" },
1909
- body: JSON.stringify({
1910
- ...interactiveChatRequest(text, atts),
1911
- expectedSelection: knownHeadRef.current.selection
1912
- }),
1913
- signal: abort.signal
1914
- });
1915
- if (res.status === 202) {
1916
- const pending = await res.json();
1917
- setLiveEntries((prev) => [...prev, {
1918
- type: "error",
1919
- content: `[approval pending] ${pending.approvalId} · expires ${new Date(pending.expiresAt).toLocaleString()} · review in /approvals`
1920
- }]);
1921
- sessionStorage.removeItem(`bz_pending_${agentId}`);
1922
- return;
1923
- }
1924
- if (res.status === 409) {
1925
- setInput(text);
1926
- setAttachments(atts);
1927
- setLiveEntries([]);
1928
- setStaleBanner(true);
1929
- sessionStorage.removeItem(`bz_pending_${agentId}`);
1930
- pushSystem("Conversation changed. Refresh history, then review and send your preserved draft.");
1931
- return;
1932
- }
1933
- if (!res.ok || !res.body) {
1934
- let err = res.statusText;
1935
- try {
1936
- err = (await res.json()).error || err;
1937
- } catch {}
1938
- setLiveEntries((prev) => [...prev, {
1939
- type: "error",
1940
- content: `[error] ${err}`
1941
- }]);
1942
- return;
1943
- }
1944
- const admittedSelection = res.headers.get("x-bazilion-conversation-selection");
1945
- if (admittedSelection) try {
1946
- const selection = JSON.parse(admittedSelection);
1947
- if (typeof selection.conversationId === "string" && Number.isSafeInteger(selection.revision) && selection.revision >= 0) knownHeadRef.current = {
1948
- ...knownHeadRef.current,
1949
- selection
1950
- };
1951
- } catch {}
1952
- const reader = res.body.getReader();
1953
- const decoder = new TextDecoder();
1954
- let buffer = "";
1955
- while (true) {
1956
- const { done, value } = await reader.read();
1957
- if (done) break;
1958
- buffer += decoder.decode(value, { stream: true });
1959
- const lines = buffer.split("\n");
1960
- buffer = lines.pop() ?? "";
1961
- for (const line of lines) {
1962
- if (!line.trim()) continue;
1963
- let frame;
1964
- try {
1965
- frame = JSON.parse(line);
1966
- } catch {
1967
- continue;
1968
- }
1969
- if (frame.kind === "done" || frame.kind === "fatal") terminalFrameReceived = true;
1970
- handleFrame(frame);
1971
- }
1972
- }
1973
- if (buffer.trim()) try {
1974
- const frame = JSON.parse(buffer);
1975
- if (frame.kind === "done" || frame.kind === "fatal") terminalFrameReceived = true;
1976
- handleFrame(frame);
1977
- } catch {}
1978
- await refreshKnownHead();
1979
- sessionStorage.removeItem(`bz_pending_${agentId}`);
1980
- } catch (err) {
1981
- if (err.name !== "AbortError") setLiveEntries((prev) => [...prev, {
1982
- type: "error",
1983
- content: `[network error] ${err.message}`
1984
- }]);
1985
- sessionStorage.removeItem(`bz_pending_${agentId}`);
1986
- } finally {
1987
- if (currentAgentIdRef.current === agentId && currentAbortRef.current === abort) {
1988
- if (!terminalFrameReceived && commandApprovalTurnRef.current) setRecoveredTurn(true);
1989
- setThinking(false);
1990
- setStreaming(false);
1991
- currentAbortRef.current = null;
1992
- }
1993
- }
1994
- }, [
1995
- agentId,
1996
- editIdx,
1997
- serverMessages,
1998
- turnBusy,
1999
- queueMode,
2000
- queueReady,
2001
- attachments
2002
- ]);
2003
- function handleFrame(frame) {
2004
- if (currentAgentIdRef.current !== agentId) return;
2005
- if (frame.kind === "fatal") {
2006
- commandApprovalTurnRef.current = false;
2007
- setLiveEntries((prev) => [...prev.map((entry) => entry.type === "command_approval" && entry.approval.status === "pending" ? {
2008
- type: "command_approval",
2009
- approval: {
2010
- ...entry.approval,
2011
- status: "cancelled"
2012
- }
2013
- } : entry), {
2014
- type: "error",
2015
- content: `[fatal] ${frame.error}`
2016
- }]);
2017
- setRecoveredTurn(false);
2018
- return;
2019
- }
2020
- if (frame.kind === "done") {
2021
- commandApprovalTurnRef.current = false;
2022
- setServerMessages(frame.messages);
2023
- setLiveEntries([]);
2024
- setRecoveredTurn(false);
2025
- setApprovalBusy({});
2026
- setApprovalErrors({});
2027
- return;
2028
- }
2029
- if (frame.kind !== "event") return;
2030
- const ev = frame.event;
2031
- captureScroll();
2032
- if (ev.type === "user_message") return;
2033
- if (ev.type === "assistant_delta") {
2034
- setThinking(false);
2035
- setLiveEntries((prev) => {
2036
- const next = [...prev];
2037
- const last = next[next.length - 1];
2038
- if (last?.type === "assistant") next[next.length - 1] = {
2039
- type: "assistant",
2040
- content: last.content + ev.delta
2041
- };
2042
- else next.push({
2043
- type: "assistant",
2044
- content: ev.delta
2045
- });
2046
- return next;
2047
- });
2048
- return;
2049
- }
2050
- if (ev.type === "assistant_message") {
2051
- setThinking(false);
2052
- setLiveEntries((prev) => {
2053
- const next = [...prev];
2054
- if (next[next.length - 1]?.type === "assistant") next[next.length - 1] = {
2055
- type: "assistant",
2056
- content: ev.text
2057
- };
2058
- else next.push({
2059
- type: "assistant",
2060
- content: ev.text
2061
- });
2062
- return next;
2063
- });
2064
- return;
2065
- }
2066
- if (ev.type === "command_approval") {
2067
- if (ev.approval.agentId !== agentId) return;
2068
- commandApprovalTurnRef.current = true;
2069
- setThinking(ev.approval.status !== "pending" && ev.approval.status !== "cancelled");
2070
- setLiveEntries((entries) => upsertCommandApprovalEntry(entries, ev.approval));
2071
- return;
2072
- }
2073
- if (ev.type === "coding_progress") {
2074
- setLiveEntries((prev) => upsertCodingProgress(prev, ev));
2075
- return;
2076
- }
2077
- if (ev.type === "tool_call" || ev.type === "tool_result" || ev.type === "tool_error") {
2078
- setThinking(ev.type !== "tool_call");
2079
- const item = ev.type === "tool_call" ? {
2080
- kind: "call",
2081
- id: ev.id,
2082
- name: ev.name,
2083
- body: ev.arguments
2084
- } : ev.type === "tool_result" ? {
2085
- kind: "result",
2086
- id: ev.id,
2087
- name: ev.name,
2088
- body: ev.result
2089
- } : {
2090
- kind: "error",
2091
- id: ev.id,
2092
- name: ev.name,
2093
- body: ev.error
2094
- };
2095
- if (ev.type === "tool_result" && [
2096
- "repository_context",
2097
- "coding_environment",
2098
- "coding_command",
2099
- "coding_receipt",
2100
- "coding_log",
2101
- "source_snapshot"
2102
- ].includes(ev.name)) {
2103
- deliveredCoding.current.set(`${ev.name}:${ev.id}`, ev.result);
2104
- while (deliveredCoding.current.size > 20) deliveredCoding.current.delete(deliveredCoding.current.keys().next().value);
2105
- }
2106
- const images = ev.type === "tool_result" ? ev.images : void 0;
2107
- setLiveEntries((prev) => {
2108
- const next = [...prev.map((entry) => entry.type === "tool" ? {
2109
- ...entry,
2110
- items: entry.items.filter((i) => !(i.kind === "progress" && i.id === ev.id))
2111
- } : entry)];
2112
- const last = next[next.length - 1];
2113
- if (last?.type === "tool") next[next.length - 1] = {
2114
- type: "tool",
2115
- items: [...last.items, item]
2116
- };
2117
- else next.push({
2118
- type: "tool",
2119
- items: [item]
2120
- });
2121
- if (images && images.length > 0) next.push({
2122
- type: "images",
2123
- images
2124
- });
2125
- return next;
2126
- });
2127
- return;
2128
- }
2129
- if (ev.type === "file") {
2130
- if (ev.result) {
2131
- const resultId = ev.result.resultId;
2132
- setLiveEntries((prev) => [...prev, {
2133
- type: "result",
2134
- resultId
2135
- }]);
2136
- return;
2137
- }
2138
- setLiveEntries((prev) => [...prev, {
2139
- type: "file",
2140
- name: ev.name,
2141
- mimeType: ev.mimeType,
2142
- data: ev.data
2143
- }]);
2144
- return;
2145
- }
2146
- if (ev.type === "error") setLiveEntries((prev) => [...prev, {
2147
- type: "error",
2148
- content: `[error] ${ev.error}`
2149
- }]);
2150
- }
2151
- async function reconcileCommandApproval(approvalId) {
2152
- if (currentAgentIdRef.current !== agentId) return null;
2153
- try {
2154
- const response = await fetch(shellApprovalsUrl(agentId));
2155
- if (!response.ok) return null;
2156
- const body = await response.json();
2157
- if (currentAgentIdRef.current !== agentId) return null;
2158
- const approval = body.approvals.find((item) => item.id === approvalId && item.agentId === agentId);
2159
- if (approval) setLiveEntries((entries) => upsertCommandApprovalEntry(entries, approval));
2160
- return approval ?? null;
2161
- } catch {
2162
- return null;
2163
- }
2164
- }
2165
- async function decideCommandApproval(approval, decision) {
2166
- if (approval.agentId !== agentId || approval.status !== "pending") return;
2167
- setApprovalBusy((current) => ({
2168
- ...current,
2169
- [approval.id]: true
2170
- }));
2171
- setApprovalErrors((current) => {
2172
- const next = { ...current };
2173
- delete next[approval.id];
2174
- return next;
2175
- });
2176
- try {
2177
- const response = await fetch(`/api/shell-approvals/${encodeURIComponent(approval.id)}`, {
2178
- method: "POST",
2179
- headers: { "content-type": "application/json" },
2180
- body: JSON.stringify({ decision })
2181
- });
2182
- const body = await response.json().catch(() => null);
2183
- if (currentAgentIdRef.current !== agentId) return;
2184
- if (body?.approval?.agentId === agentId) setLiveEntries((entries) => upsertCommandApprovalEntry(entries, body.approval));
2185
- if (!response.ok) {
2186
- const message = body?.error ?? `Decision failed (${response.status})`;
2187
- const terminalStatus = commandApprovalStatusFromConflict(message);
2188
- if (terminalStatus) {
2189
- setLiveEntries((entries) => upsertCommandApprovalEntry(entries, {
2190
- ...approval,
2191
- status: terminalStatus
2192
- }));
2193
- return;
2194
- }
2195
- throw new Error(message);
2196
- }
2197
- } catch (error) {
2198
- const reconciled = await reconcileCommandApproval(approval.id);
2199
- if (currentAgentIdRef.current !== agentId) return;
2200
- if (!reconciled || reconciled.status === "pending") setApprovalErrors((current) => ({
2201
- ...current,
2202
- [approval.id]: error instanceof Error ? error.message : String(error)
2203
- }));
2204
- } finally {
2205
- if (currentAgentIdRef.current === agentId) setApprovalBusy((current) => ({
2206
- ...current,
2207
- [approval.id]: false
2208
- }));
2209
- }
2210
- }
2211
- async function cancel() {
2212
- if (!await queueRef.current?.stop() && currentAgentIdRef.current === agentId) pushSystem("Stop was not confirmed. Check queue controls and try again; the active response may still be running.");
2213
- }
2214
- function onKeyDown(e) {
2215
- if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
2216
- e.preventDefault();
2217
- send(input);
2218
- }
2219
- }
2220
- const baseEntries = projectMessages(serverMessages.map((message) => {
2221
- if (message.role !== "tool" || !message.toolCallId || !message.toolName) return message;
2222
- const body = deliveredCoding.current.get(`${message.toolName}:${message.toolCallId}`);
2223
- return body === void 0 ? message : {
2224
- ...message,
2225
- content: body
2226
- };
2227
- }));
2228
- visibleEntryCountRef.current = baseEntries.length + liveEntries.length;
2229
- const lastUserIdx = (() => {
2230
- if (liveEntries.length > 0 || turnBusy) return -1;
2231
- for (let i = baseEntries.length - 1; i >= 0; i--) if (baseEntries[i]?.type === "user") return i;
2232
- return -1;
2233
- })();
2234
- const willDropFromIdx = (() => {
2235
- if (editIdx === null) return -1;
2236
- let userCount = 0;
2237
- for (let i = 0; i < baseEntries.length; i++) if (baseEntries[i]?.type === "user") {
2238
- if (userCount === serverMessages.slice(0, editIdx + 1).filter((m) => m.role === "user").length - 1) return i;
2239
- userCount++;
2240
- }
2241
- return lastUserIdx;
2242
- })();
2243
- return /* @__PURE__ */ jsxs("div", {
2244
- className: "relative flex h-full flex-col overflow-hidden rounded-[16px] border border-frost bg-snow shadow-baziu-sm",
2245
- onDragOver,
2246
- onDragLeave,
2247
- onDrop,
2248
- children: [
2249
- dragging && /* @__PURE__ */ jsx("div", {
2250
- className: "pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-[16px] border-2 border-dashed border-sapphire bg-sapphire-glow/80 text-[0.95em] font-medium text-sapphire-deep",
2251
- children: "drop images or files to attach"
2252
- }),
2253
- /* @__PURE__ */ jsxs("div", {
2254
- className: "flex items-center justify-between gap-3 border-b border-frost px-4 py-2.5",
2255
- children: [/* @__PURE__ */ jsxs("div", {
2256
- className: "flex min-w-0 items-center gap-2",
2257
- children: [/* @__PURE__ */ jsx("a", {
2258
- href: "/",
2259
- className: "inline-flex h-7 items-center rounded-md border border-frost px-2 text-xs font-semibold text-mocha lg:hidden",
2260
- children: "← agents"
2261
- }), /* @__PURE__ */ jsx("h1", {
2262
- className: "truncate font-display text-[1.2rem] text-charcoal",
2263
- children: agentName
2264
- })]
2265
- }), /* @__PURE__ */ jsx("a", {
2266
- href: `/agents/${agentId}?mode=settings`,
2267
- className: "shrink-0 text-xs text-mocha-light hover:text-sapphire",
2268
- children: "Manage agent →"
2269
- })]
2270
- }),
2271
- /* @__PURE__ */ jsx("div", {
2272
- className: "mx-5 mt-2",
2273
- children: /* @__PURE__ */ jsx(Button, {
2274
- variant: "ghost",
2275
- "aria-expanded": libraryOpen,
2276
- onClick: () => setLibraryOpen((value) => !value),
2277
- children: libraryOpen ? "Close conversations" : "Conversations"
2278
- })
2279
- }),
2280
- historyUnavailable && /* @__PURE__ */ jsx("p", {
2281
- role: "alert",
2282
- className: "mx-5 mt-2 text-sm",
2283
- children: "Selected conversation history is unavailable. Open Conversations to start a new one; retained history and files stay listed."
2284
- }),
2285
- staleBanner && /* @__PURE__ */ jsxs("div", {
2286
- role: "status",
2287
- "aria-live": "polite",
2288
- "aria-atomic": "true",
2289
- className: "mx-5 mt-2 flex items-center gap-2 rounded-md border border-sapphire bg-frost px-4 py-2 text-[0.86em] text-mocha",
2290
- children: [
2291
- /* @__PURE__ */ jsx("span", {
2292
- className: "h-2 w-2 flex-none rounded-full bg-sapphire",
2293
- "aria-hidden": "true"
2294
- }),
2295
- /* @__PURE__ */ jsx("span", {
2296
- className: "flex-1",
2297
- children: recoveredTurn ? "the recovered turn has new activity — reload to see it" : "new activity from another source — reload to see it"
2298
- }),
2299
- /* @__PURE__ */ jsx("button", {
2300
- type: "button",
2301
- onClick: () => void refreshConversationHistory(),
2302
- className: "rounded-sm bg-sapphire px-3 py-1 text-[0.92em] text-snow hover:opacity-90",
2303
- children: "reload"
2304
- }),
2305
- /* @__PURE__ */ jsx("button", {
2306
- type: "button",
2307
- onClick: () => setStaleBanner(false),
2308
- className: "px-1 text-mocha-light hover:text-mocha",
2309
- "aria-label": "dismiss",
2310
- children: "×"
2311
- })
2312
- ]
2313
- }),
2314
- /* @__PURE__ */ jsxs("div", {
2315
- ref: messagesRef,
2316
- onScroll: captureScroll,
2317
- role: "log",
2318
- "aria-label": `Conversation with ${agentName}`,
2319
- "aria-live": "polite",
2320
- "aria-relevant": "additions",
2321
- "aria-busy": turnBusy,
2322
- className: `min-h-0 flex-1 overflow-y-auto px-5 py-5 ${editIdx !== null ? "is-editing" : ""}`,
2323
- children: [
2324
- libraryOpen && /* @__PURE__ */ jsx(ConversationLibrary, {
2325
- initialConversationId: queueConversation,
2326
- agentId,
2327
- turnBusy,
2328
- onCreated: refreshConversationHistory,
2329
- renderHistory: (messages) => /* @__PURE__ */ jsx(ResultTranscript, { messages })
2330
- }, agentId),
2331
- !historyUnavailable && baseEntries.length === 0 && liveEntries.length === 0 && systemBubbles.length === 0 && /* @__PURE__ */ jsx("p", {
2332
- className: "py-12 text-center italic text-mocha-light",
2333
- children: "Start a conversation…"
2334
- }),
2335
- (() => {
2336
- const out = [];
2337
- let sysIdx = 0;
2338
- const flushSysUpTo = (idx) => {
2339
- while (sysIdx < systemBubbles.length && systemBubbles[sysIdx].afterIdx <= idx) {
2340
- const sb = systemBubbles[sysIdx];
2341
- out.push(/* @__PURE__ */ jsx(Bubble, {
2342
- entry: {
2343
- type: "system",
2344
- content: sb.content
2345
- },
2346
- markdownReady,
2347
- onCommandApprovalDecision: decideCommandApproval
2348
- }, `y-${sb.id}`));
2349
- sysIdx++;
2350
- }
2351
- };
2352
- flushSysUpTo(0);
2353
- for (let i = 0; i < baseEntries.length; i++) {
2354
- const entry = baseEntries[i];
2355
- out.push(/* @__PURE__ */ jsx(Bubble, {
2356
- entry,
2357
- markdownReady,
2358
- isLastUser: i === lastUserIdx && editIdx === null,
2359
- isWillDrop: willDropFromIdx !== -1 && i >= willDropFromIdx,
2360
- onEdit: enterEditMode,
2361
- onCommandApprovalDecision: decideCommandApproval,
2362
- commandApprovalBusy: entry.type === "command_approval" && Boolean(approvalBusy[entry.approval.id]),
2363
- commandApprovalError: entry.type === "command_approval" ? approvalErrors[entry.approval.id] : void 0
2364
- }, `s-${i}`));
2365
- flushSysUpTo(i + 1);
2366
- }
2367
- for (let i = 0; i < liveEntries.length; i++) {
2368
- const entry = liveEntries[i];
2369
- out.push(/* @__PURE__ */ jsx(Bubble, {
2370
- entry,
2371
- markdownReady,
2372
- onCommandApprovalDecision: decideCommandApproval,
2373
- commandApprovalBusy: entry.type === "command_approval" && Boolean(approvalBusy[entry.approval.id]),
2374
- commandApprovalError: entry.type === "command_approval" ? approvalErrors[entry.approval.id] : void 0
2375
- }, `l-${i}`));
2376
- flushSysUpTo(baseEntries.length + i + 1);
2377
- }
2378
- while (sysIdx < systemBubbles.length) {
2379
- const sb = systemBubbles[sysIdx];
2380
- out.push(/* @__PURE__ */ jsx(Bubble, {
2381
- entry: {
2382
- type: "system",
2383
- content: sb.content
2384
- },
2385
- markdownReady,
2386
- onCommandApprovalDecision: decideCommandApproval
2387
- }, `y-${sb.id}`));
2388
- sysIdx++;
2389
- }
2390
- return out;
2391
- })(),
2392
- thinking && /* @__PURE__ */ jsxs("div", {
2393
- className: "flex items-center gap-2 px-1 py-1 text-[0.85em] text-mocha-light",
2394
- children: [
2395
- /* @__PURE__ */ jsx(Dot, {}),
2396
- /* @__PURE__ */ jsx(Dot, { delay: "0.15s" }),
2397
- /* @__PURE__ */ jsx(Dot, { delay: "0.3s" }),
2398
- /* @__PURE__ */ jsx("span", { children: "agent is thinking…" })
2399
- ]
2400
- })
2401
- ]
2402
- }),
2403
- /* @__PURE__ */ jsx("p", {
2404
- className: "sr-only",
2405
- role: "status",
2406
- "aria-live": "polite",
2407
- "aria-atomic": "true",
2408
- children: turnBusy ? `${agentName} is responding.` : "Conversation ready."
2409
- }),
2410
- editIdx !== null && /* @__PURE__ */ jsxs("div", {
2411
- className: "flex items-center gap-2 border-t border-frost bg-sapphire-glow px-5 py-2 text-[0.85em] text-sapphire-deep",
2412
- children: [/* @__PURE__ */ jsx("span", { children: "editing last message — submit to replace, or" }), /* @__PURE__ */ jsx("button", {
2413
- type: "button",
2414
- onClick: exitEditMode,
2415
- className: "ml-auto rounded-sm border border-sapphire-light bg-transparent px-2 py-0.5 text-[0.92em] text-sapphire-deep hover:bg-snow",
2416
- children: "cancel"
2417
- })]
2418
- }),
2419
- attachments.length > 0 && /* @__PURE__ */ jsx("div", {
2420
- className: "flex max-h-24 shrink-0 flex-wrap gap-2 overflow-y-auto border-t border-frost bg-ivory px-5 pt-3",
2421
- children: attachments.map((a, i) => {
2422
- const remove = () => setAttachments((prev) => prev.filter((_, j) => j !== i));
2423
- return isImageMime(a.mimeType) ? /* @__PURE__ */ jsxs("div", {
2424
- className: "relative",
2425
- children: [/* @__PURE__ */ jsx("img", {
2426
- src: `data:${a.mimeType};base64,${a.data}`,
2427
- alt: "pending attachment",
2428
- className: "h-16 w-16 rounded-md border border-frost object-cover"
2429
- }), /* @__PURE__ */ jsx("button", {
2430
- type: "button",
2431
- onClick: remove,
2432
- className: "absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-frost bg-snow text-[0.7em] text-mocha hover:border-sapphire hover:text-sapphire",
2433
- "aria-label": "remove attachment",
2434
- children: "✕"
2435
- })]
2436
- }, `${a.mimeType}-${i}`) : /* @__PURE__ */ jsxs("div", {
2437
- className: "flex items-center gap-1.5 rounded-md border border-frost bg-snow px-2 py-1 text-[0.82em] text-mocha",
2438
- children: [
2439
- /* @__PURE__ */ jsx("span", { children: "📄" }),
2440
- /* @__PURE__ */ jsx("span", {
2441
- className: "max-w-[160px] truncate",
2442
- children: a.name ?? "file"
2443
- }),
2444
- /* @__PURE__ */ jsx("button", {
2445
- type: "button",
2446
- onClick: remove,
2447
- className: "text-[0.85em] text-mocha hover:text-sapphire",
2448
- "aria-label": "remove attachment",
2449
- children: "✕"
2450
- })
2451
- ]
2452
- }, `${a.name ?? "file"}-${i}`);
2453
- })
2454
- }),
2455
- /* @__PURE__ */ jsx(UserQueuePanel, {
2456
- onViewConversation: (id) => {
2457
- setQueueConversation(id);
2458
- setLibraryOpen(true);
2459
- },
2460
- ref: queueRef,
2461
- agentId,
2462
- selection: () => knownHeadRef.current.selection,
2463
- onQueueMode: (mode) => {
2464
- setQueueMode(mode);
2465
- setQueueReady(true);
2466
- }
2467
- }, agentId),
2468
- /* @__PURE__ */ jsx(AgentQuestions, { agentId }, `questions-${agentId}`),
2469
- /* @__PURE__ */ jsxs("form", {
2470
- "aria-busy": !queueReady,
2471
- className: "grid shrink-0 grid-cols-[auto_minmax(0,1fr)] items-end gap-2 border-t border-frost bg-ivory px-3 py-3 sm:grid-cols-[auto_minmax(0,1fr)_auto] sm:px-5",
2472
- onSubmit: (e) => {
2473
- e.preventDefault();
2474
- send(input);
2475
- },
2476
- children: [
2477
- /* @__PURE__ */ jsx("input", {
2478
- ref: fileInputRef,
2479
- type: "file",
2480
- multiple: true,
2481
- className: "hidden",
2482
- onChange: (e) => {
2483
- addFiles(e.target.files);
2484
- e.target.value = "";
2485
- }
2486
- }),
2487
- /* @__PURE__ */ jsx("button", {
2488
- type: "button",
2489
- onClick: () => fileInputRef.current?.click(),
2490
- title: "attach images or files",
2491
- "aria-label": "attach files",
2492
- className: "flex h-11 items-center justify-center rounded-md border-[1.5px] border-frost bg-snow px-3 py-2 text-[1em] text-mocha transition-colors hover:border-sapphire hover:text-sapphire disabled:cursor-not-allowed disabled:opacity-50",
2493
- children: "📎"
2494
- }),
2495
- /* @__PURE__ */ jsx("textarea", {
2496
- ref: inputRef,
2497
- rows: 1,
2498
- value: input,
2499
- onChange: (e) => setInput(e.target.value),
2500
- onKeyDown,
2501
- onPaste,
2502
- placeholder: "Write a message…",
2503
- title: "Shift+Enter for a new line. Paste or attach files with the paperclip.",
2504
- autoComplete: "off",
2505
- "aria-label": `Message ${agentName}`,
2506
- className: "max-h-[200px] min-h-11 min-w-0 flex-1 resize-none overflow-y-auto rounded-md border-[1.5px] border-frost bg-snow px-3 py-2 text-[0.93em] leading-[1.45] text-chocolate outline-none transition-colors focus:border-sapphire focus:shadow-[0_0_0_3px_var(--color-sapphire-glow)]"
2507
- }),
2508
- /* @__PURE__ */ jsxs("div", {
2509
- className: "col-span-2 flex flex-wrap justify-end gap-2 sm:col-span-1",
2510
- children: [/* @__PURE__ */ jsx(Button, {
2511
- variant: "primary",
2512
- type: "submit",
2513
- className: "min-h-11 whitespace-normal text-center",
2514
- disabled: !input.trim() && attachments.length === 0,
2515
- children: turnBusy || queueMode ? "Queue follow-up" : "Send"
2516
- }), turnBusy && /* @__PURE__ */ jsx(Button, {
2517
- variant: "danger",
2518
- className: "min-h-11",
2519
- onClick: () => void cancel(),
2520
- "aria-label": "Stop response and pause queue",
2521
- children: "Stop"
2522
- })]
2523
- })
2524
- ]
2525
- })
2526
- ]
2527
- });
2528
- }
2529
- function Bubble({ entry, markdownReady, isLastUser, isWillDrop, onEdit, onCommandApprovalDecision, commandApprovalBusy, commandApprovalError }) {
2530
- const dropCls = isWillDrop ? "opacity-40 [&_.bubble-content]:line-through" : "";
2531
- if (entry.type === "user") {
2532
- if (entry.content.startsWith(INBOX_WAKE_PREFIX)) {
2533
- const body = entry.content.slice(24);
2534
- return /* @__PURE__ */ jsxs("details", {
2535
- className: `my-3 rounded-lg border border-fawn bg-ivory px-3 py-2 text-sm text-mocha ${dropCls}`,
2536
- "aria-label": "Teammate update",
2537
- children: [
2538
- /* @__PURE__ */ jsx("summary", {
2539
- className: "cursor-pointer font-medium",
2540
- children: inboxUpdateLabel(body)
2541
- }),
2542
- /* @__PURE__ */ jsx("p", {
2543
- className: "mt-2 text-xs",
2544
- children: "Original message and Agent instructions"
2545
- }),
2546
- /* @__PURE__ */ jsx("pre", {
2547
- className: "mt-1 max-h-64 overflow-auto whitespace-pre-wrap break-words text-xs",
2548
- children: body
2549
- })
2550
- ]
2551
- });
2552
- }
2553
- return /* @__PURE__ */ jsxs("div", {
2554
- className: `team relative my-4 flex flex-col items-end ${dropCls}`,
2555
- children: [
2556
- /* @__PURE__ */ jsx("span", {
2557
- className: "sr-only",
2558
- children: "you"
2559
- }),
2560
- entry.images && entry.images.length > 0 && /* @__PURE__ */ jsx("div", {
2561
- className: "mb-1 flex max-w-[85%] flex-wrap justify-end gap-1",
2562
- children: entry.images.map((img, i) => /* @__PURE__ */ jsx("img", {
2563
- src: `data:${img.mimeType};base64,${img.data}`,
2564
- alt: "attachment",
2565
- className: "max-h-48 rounded-lg border border-sapphire-light"
2566
- }, i))
2567
- }),
2568
- entry.files && entry.files.length > 0 && /* @__PURE__ */ jsx("div", {
2569
- className: "mb-1 flex max-w-[85%] flex-wrap justify-end gap-1",
2570
- children: entry.files.map((f, i) => /* @__PURE__ */ jsxs("span", {
2571
- className: "flex items-center gap-1 rounded-md border border-sapphire-light bg-sapphire-glow px-2 py-1 text-[0.8em] text-chocolate",
2572
- children: ["📄 ", /* @__PURE__ */ jsx("span", {
2573
- className: "max-w-[180px] truncate",
2574
- children: f.name
2575
- })]
2576
- }, i))
2577
- }),
2578
- entry.content && /* @__PURE__ */ jsx("div", {
2579
- className: "bubble-content max-w-[85%] whitespace-pre-wrap break-words rounded-[14px_14px_4px_14px] border border-sapphire-light bg-sapphire-glow px-3 py-2 text-chocolate",
2580
- children: entry.content
2581
- }),
2582
- isLastUser && onEdit && /* @__PURE__ */ jsx("button", {
2583
- type: "button",
2584
- onClick: onEdit,
2585
- title: "edit and resend — replaces the last turn",
2586
- className: "absolute left-1 top-1 rounded-sm border border-fawn bg-ivory px-2 py-0.5 text-[0.78em] font-medium text-mocha opacity-65 transition hover:border-sapphire hover:bg-sapphire-glow hover:text-sapphire hover:opacity-100 team-hover:opacity-100 team-focus-within:opacity-100",
2587
- children: "edit"
2588
- })
2589
- ]
2590
- });
2591
- }
2592
- if (entry.type === "assistant") {
2593
- if (entry.content.startsWith(COMPACTION_REPLAY_PREFIX)) {
2594
- const summary = entry.content.slice(22).trim();
2595
- return /* @__PURE__ */ jsx("div", {
2596
- className: `my-3 border-y border-dashed border-frost py-2 text-[0.85em] italic text-mocha-light ${dropCls}`,
2597
- children: /* @__PURE__ */ jsxs("details", { children: [/* @__PURE__ */ jsx("summary", {
2598
- className: "cursor-pointer select-none text-center [&::-webkit-details-marker]:hidden",
2599
- children: "— conversation summary (click to expand) —"
2600
- }), /* @__PURE__ */ jsx("div", {
2601
- className: "md-content mt-2 rounded-sm bg-frost/40 p-2 not-italic",
2602
- dangerouslySetInnerHTML: { __html: renderMd(summary, markdownReady) }
2603
- })] })
2604
- });
2605
- }
2606
- if (entry.content.startsWith("[error]") || entry.content.startsWith("[fatal]") || entry.content.startsWith("[network error]")) return /* @__PURE__ */ jsxs("div", {
2607
- className: `my-4 flex flex-col items-start ${dropCls}`,
2608
- children: [/* @__PURE__ */ jsx("span", {
2609
- className: "mb-1 text-[0.72em] font-semibold uppercase tracking-wider text-danger",
2610
- children: "error"
2611
- }), /* @__PURE__ */ jsx("div", {
2612
- className: "bubble-content rounded-r-sm border-l-[3px] border-l-danger bg-danger/10 py-1 pl-3 pr-2 leading-[1.55]",
2613
- dangerouslySetInnerHTML: { __html: renderMd(entry.content, markdownReady) }
2614
- })]
2615
- });
2616
- return /* @__PURE__ */ jsxs("div", {
2617
- className: `my-4 flex flex-col items-start ${dropCls}`,
2618
- children: [/* @__PURE__ */ jsx("span", {
2619
- className: "sr-only",
2620
- children: "agent"
2621
- }), /* @__PURE__ */ jsx("div", {
2622
- className: "md-content bubble-content w-full leading-[1.55] text-chocolate",
2623
- dangerouslySetInnerHTML: { __html: renderMd(entry.content, markdownReady) }
2624
- })]
2625
- });
2626
- }
2627
- if (entry.type === "tool") return /* @__PURE__ */ jsx(ToolGroup, {
2628
- items: entry.items,
2629
- dropCls
2630
- });
2631
- if (entry.type === "images") return /* @__PURE__ */ jsx("div", {
2632
- className: `my-2 space-y-2 ${dropCls}`,
2633
- children: entry.images.map((img, i) => /* @__PURE__ */ jsx("img", {
2634
- src: `data:${img.mimeType};base64,${img.data}`,
2635
- alt: "screenshot",
2636
- className: "block max-w-full rounded-lg border border-fawn"
2637
- }, i))
2638
- });
2639
- if (entry.type === "result") return /* @__PURE__ */ jsx(ResultCard, { resultId: entry.resultId });
2640
- if (entry.type === "file") {
2641
- const isImage = entry.mimeType.startsWith("image/");
2642
- const href = `data:${entry.mimeType};base64,${entry.data}`;
2643
- return /* @__PURE__ */ jsxs("div", {
2644
- className: `my-2 ${dropCls}`,
2645
- children: [isImage && /* @__PURE__ */ jsx("img", {
2646
- src: href,
2647
- alt: entry.name,
2648
- className: "mb-1 block max-w-full rounded-lg border border-fawn"
2649
- }), /* @__PURE__ */ jsxs("a", {
2650
- href,
2651
- download: entry.name,
2652
- className: "inline-flex items-center gap-2 rounded-md border border-fawn bg-ivory px-3 py-2 text-[0.88em] text-mocha hover:border-sapphire hover:text-sapphire",
2653
- children: [
2654
- /* @__PURE__ */ jsx("span", { children: "📄" }),
2655
- /* @__PURE__ */ jsx("span", {
2656
- className: "max-w-[260px] truncate",
2657
- children: entry.name
2658
- }),
2659
- /* @__PURE__ */ jsx("span", {
2660
- className: "text-[0.85em] opacity-70",
2661
- children: "download"
2662
- })
2663
- ]
2664
- })]
2665
- });
2666
- }
2667
- if (entry.type === "command_approval") return /* @__PURE__ */ jsx(CommandApprovalCard, {
2668
- approval: entry.approval,
2669
- busy: commandApprovalBusy,
2670
- error: commandApprovalError,
2671
- onDecision: onCommandApprovalDecision
2672
- });
2673
- if (entry.type === "system") return /* @__PURE__ */ jsxs("div", {
2674
- className: `my-3 rounded-r-sm border-l-[3px] border-sapphire bg-sapphire-glow px-3 py-1 font-mono text-[0.88em] text-sapphire-deep ${dropCls}`,
2675
- children: [/* @__PURE__ */ jsx("span", {
2676
- className: "mr-2 font-semibold uppercase tracking-wider opacity-80",
2677
- children: "system"
2678
- }), /* @__PURE__ */ jsx("span", {
2679
- className: "whitespace-pre-wrap",
2680
- children: entry.content
2681
- })]
2682
- });
2683
- if (entry.type === "error") return /* @__PURE__ */ jsx("div", {
2684
- className: `my-3 rounded-r-sm border-l-[3px] border-danger bg-danger/10 px-3 py-1 text-[0.92em] text-danger ${dropCls}`,
2685
- children: entry.content
2686
- });
2687
- return null;
2688
- }
2689
- function CommandApprovalCard({ approval, busy = false, error, onDecision }) {
2690
- const pending = approval.status === "pending";
2691
- return /* @__PURE__ */ jsxs("section", {
2692
- className: "my-3 rounded-lg border border-danger/50 bg-danger/5 p-4 text-chocolate",
2693
- "aria-label": "Shell command approval",
2694
- children: [
2695
- /* @__PURE__ */ jsxs("div", {
2696
- className: "flex flex-wrap items-start justify-between gap-2",
2697
- children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("p", {
2698
- className: "m-0 text-[0.72em] font-semibold uppercase tracking-wider text-danger",
2699
- children: "Shell command approval"
2700
- }), /* @__PURE__ */ jsx("h2", {
2701
- className: "m-0 mt-1 font-body text-[0.95em] font-semibold",
2702
- children: pending ? "A risky command is waiting for you" : "Command decision recorded"
2703
- })] }), /* @__PURE__ */ jsx("span", {
2704
- className: "rounded-full border border-danger/30 px-2 py-0.5 text-[0.75em] font-semibold uppercase tracking-wide text-danger",
2705
- children: approval.status.replaceAll("_", " ")
2706
- })]
2707
- }),
2708
- /* @__PURE__ */ jsx("pre", {
2709
- className: "mt-3 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded-md border border-fawn bg-snow p-3 font-mono text-[0.82em] leading-[1.45] text-charcoal",
2710
- children: approval.command
2711
- }),
2712
- /* @__PURE__ */ jsx("ul", {
2713
- className: "mt-3 space-y-1.5 pl-5 text-[0.84em] leading-[1.4] text-mocha",
2714
- children: approval.risks.map((risk) => /* @__PURE__ */ jsxs("li", { children: [
2715
- /* @__PURE__ */ jsx("span", {
2716
- className: "font-medium text-chocolate",
2717
- children: risk.message
2718
- }),
2719
- " ",
2720
- /* @__PURE__ */ jsx("code", {
2721
- className: "text-[0.9em]",
2722
- children: risk.code
2723
- })
2724
- ] }, `${risk.code}:${risk.span.start}:${risk.span.end}`))
2725
- }),
2726
- pending ? /* @__PURE__ */ jsxs(Fragment, { children: [
2727
- /* @__PURE__ */ jsxs("p", {
2728
- className: "mt-3 text-[0.78em] text-mocha-light",
2729
- children: [
2730
- "This approval expires",
2731
- " ",
2732
- /* @__PURE__ */ jsx("time", {
2733
- dateTime: new Date(approval.expiresAt).toISOString(),
2734
- children: new Date(approval.expiresAt).toLocaleString()
2735
- }),
2736
- ". Deny blocks only this command; cancel stops the whole turn."
2737
- ]
2738
- }),
2739
- error && /* @__PURE__ */ jsx("p", {
2740
- role: "alert",
2741
- className: "mt-2 rounded-md bg-danger/10 px-3 py-2 text-[0.82em] text-danger",
2742
- children: error
2743
- }),
2744
- onDecision && /* @__PURE__ */ jsxs("div", {
2745
- className: "mt-3 flex flex-wrap gap-2",
2746
- children: [/* @__PURE__ */ jsx(Button, {
2747
- variant: "primary",
2748
- disabled: busy,
2749
- onClick: () => onDecision(approval, "deny"),
2750
- children: "Deny"
2751
- }), /* @__PURE__ */ jsx(Button, {
2752
- variant: "danger",
2753
- disabled: busy,
2754
- onClick: () => onDecision(approval, "allow"),
2755
- children: "Allow once"
2756
- })]
2757
- })
2758
- ] }) : /* @__PURE__ */ jsx("p", {
2759
- role: "status",
2760
- className: "mt-3 text-[0.84em] font-medium text-mocha",
2761
- children: commandApprovalStatusCopy(approval.status)
2762
- })
2763
- ]
2764
- });
2765
- }
2766
- function commandApprovalStatusCopy(status) {
2767
- switch (status) {
2768
- case "pending": return "Waiting for a decision.";
2769
- case "allowed": return "Allowed once — the command may run for this tool call only.";
2770
- case "denied": return "Denied — the command was not run.";
2771
- case "auto_denied": return "Automatically denied — no interactive approval path was available.";
2772
- case "expired": return "Expired — the command was not run.";
2773
- case "cancelled": return "Cancelled — the command was not run.";
2774
- }
2775
- }
2776
- function commandApprovalStatusFromConflict(message) {
2777
- if (!message.startsWith("shell approval already decided: ")) return null;
2778
- const status = message.slice(32);
2779
- switch (status) {
2780
- case "allowed":
2781
- case "denied":
2782
- case "auto_denied":
2783
- case "expired":
2784
- case "cancelled": return status;
2785
- default: return null;
2786
- }
2787
- }
2788
- /** Insert or replace the live progress tail for one coding tool call. */
2789
- function upsertCodingProgress(entries, ev) {
2790
- const progress = {
2791
- kind: "progress",
2792
- id: ev.id,
2793
- name: "coding_command",
2794
- body: ev.output,
2795
- elapsedMs: ev.elapsedMs,
2796
- truncated: ev.truncated
2797
- };
2798
- for (let i = entries.length - 1; i >= 0; i--) {
2799
- const entry = entries[i];
2800
- if (entry?.type !== "tool") continue;
2801
- const at = entry.items.findIndex((item) => item.id === ev.id);
2802
- if (at < 0) continue;
2803
- const items = [...entry.items];
2804
- items[at] = progress;
2805
- const next = [...entries];
2806
- next[i] = {
2807
- type: "tool",
2808
- items
2809
- };
2810
- return next;
2811
- }
2812
- const last = entries[entries.length - 1];
2813
- if (last?.type === "tool") return [...entries.slice(0, -1), {
2814
- type: "tool",
2815
- items: [...last.items, progress]
2816
- }];
2817
- return [...entries, {
2818
- type: "tool",
2819
- items: [progress]
2820
- }];
2821
- }
2822
- function ToolGroup({ items, dropCls }) {
2823
- const codingNames = [
2824
- "repository_context",
2825
- "coding_command",
2826
- "coding_environment",
2827
- "coding_receipt",
2828
- "coding_log",
2829
- "source_snapshot",
2830
- "send_message"
2831
- ];
2832
- const hasCoding = items.some((item) => codingNames.includes(item.name));
2833
- const visibleItems = items.filter((item) => !(item.kind === "call" && codingNames.includes(item.name) && items.some((other) => other.id === item.id && other.kind !== "call")));
2834
- const [expanded, setExpanded] = useState(false);
2835
- const contentRef = useRef(null);
2836
- const [overflows, setOverflows] = useState(false);
2837
- useLayoutEffect(() => {
2838
- const el = contentRef.current;
2839
- if (!el) return;
2840
- setOverflows(el.scrollHeight > 324);
2841
- }, [items.length]);
2842
- return /* @__PURE__ */ jsxs("div", {
2843
- className: `my-1.5 rounded-r-sm border-l-[3px] border-fawn bg-ivory px-3 py-2 font-mono text-[0.82em] leading-[1.5] text-mocha-light ${dropCls}`,
2844
- children: [/* @__PURE__ */ jsxs("div", {
2845
- ref: contentRef,
2846
- className: "relative overflow-hidden",
2847
- style: { maxHeight: expanded || hasCoding ? "none" : `${TOOL_GROUP_MAX_HEIGHT_PX}px` },
2848
- children: [visibleItems.map((it, i) => /* @__PURE__ */ jsx(ToolLine, { item: it }, i)), overflows && !expanded && !hasCoding && /* @__PURE__ */ jsx("div", {
2849
- className: "pointer-events-none absolute inset-x-0 bottom-0 h-10",
2850
- style: { background: "linear-gradient(to bottom, rgba(247,240,229,0), var(--color-ivory))" }
2851
- })]
2852
- }), overflows && !hasCoding && /* @__PURE__ */ jsx("button", {
2853
- type: "button",
2854
- onClick: () => setExpanded((v) => !v),
2855
- className: "mt-2 rounded-sm border border-fawn bg-transparent px-2 py-0.5 text-[0.9em] text-mocha hover:border-sapphire hover:text-sapphire-deep",
2856
- children: expanded ? "show less ↑" : "show more ↓"
2857
- })]
2858
- });
2859
- }
2860
- function ToolLine({ item }) {
2861
- if (item.name === "send_message" && item.kind !== "error") return /* @__PURE__ */ jsxs("details", {
2862
- className: "py-1 font-sans text-sm",
2863
- children: [/* @__PURE__ */ jsx("summary", {
2864
- className: "cursor-pointer",
2865
- children: item.kind === "call" ? "Sending teammate message…" : item.body.startsWith("sent message ") ? "Teammate message sent" : "Teammate message status"
2866
- }), /* @__PURE__ */ jsx("pre", {
2867
- className: "mt-1 max-h-64 overflow-auto whitespace-pre-wrap break-words text-xs",
2868
- children: item.body
2869
- })]
2870
- });
2871
- if (item.kind === "progress") return /* @__PURE__ */ jsxs("div", {
2872
- className: "py-1",
2873
- "aria-label": "Live coding progress",
2874
- children: [
2875
- /* @__PURE__ */ jsxs("p", {
2876
- className: "font-sans",
2877
- children: [
2878
- "Running coding command · ",
2879
- Math.max(0, Math.round((item.elapsedMs ?? 0) / 1e3)),
2880
- "s"
2881
- ]
2882
- }),
2883
- /* @__PURE__ */ jsx("pre", {
2884
- className: "max-h-64 overflow-auto whitespace-pre-wrap break-words",
2885
- children: item.body
2886
- }),
2887
- item.truncated && /* @__PURE__ */ jsx("p", { children: "Earlier output omitted; the retained log holds more." })
2888
- ]
2889
- });
2890
- if (item.kind !== "error" && [
2891
- "repository_context",
2892
- "coding_command",
2893
- "coding_environment",
2894
- "coding_receipt",
2895
- "coding_log",
2896
- "source_snapshot"
2897
- ].includes(item.name)) return /* @__PURE__ */ jsx(CodingToolResult, {
2898
- name: item.name,
2899
- body: item.body,
2900
- pending: item.kind === "call",
2901
- log: item.codingLog
2902
- });
2903
- if (item.kind === "call") {
2904
- const args = prettyArgs(item.body);
2905
- const multiLine = args.includes("\n");
2906
- return /* @__PURE__ */ jsxs("div", {
2907
- className: "whitespace-pre-wrap break-words py-0.5",
2908
- children: [
2909
- /* @__PURE__ */ jsx("span", {
2910
- className: "mr-1 opacity-45",
2911
- children: "→"
2912
- }),
2913
- /* @__PURE__ */ jsx("span", {
2914
- className: "font-medium text-mocha",
2915
- children: item.name
2916
- }),
2917
- multiLine ? /* @__PURE__ */ jsx("pre", {
2918
- className: "ml-4 mt-0.5 rounded-sm bg-[rgba(42,31,22,0.04)] px-2 py-1 font-mono text-[0.95em] leading-[1.4] text-mocha",
2919
- children: args
2920
- }) : args ? /* @__PURE__ */ jsxs("span", { children: [
2921
- " (",
2922
- args,
2923
- ")"
2924
- ] }) : null
2925
- ]
2926
- });
2927
- }
2928
- if (item.kind === "error") return /* @__PURE__ */ jsxs("div", {
2929
- className: "whitespace-pre-wrap break-words py-0.5 text-rose-baziu",
2930
- children: [/* @__PURE__ */ jsx("span", {
2931
- className: "mr-1 opacity-45",
2932
- children: "←"
2933
- }), item.body]
2934
- });
2935
- return /* @__PURE__ */ jsxs("div", {
2936
- className: "whitespace-pre-wrap break-words py-0.5",
2937
- children: [/* @__PURE__ */ jsx("span", {
2938
- className: "mr-1 opacity-45",
2939
- children: "←"
2940
- }), item.body]
2941
- });
2942
- }
2943
- function Dot({ delay = "0s" }) {
2944
- return /* @__PURE__ */ jsx("span", {
2945
- className: "inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-mocha-light/60",
2946
- style: { animationDelay: delay },
2947
- "aria-hidden": "true"
2948
- });
2949
- }
2950
- /** Read-only projection used when opening the exact available source of a saved result. */
2951
- function ResultTranscript({ messages }) {
2952
- const markdownReady = useSyncExternalStore(subscribeToHydration, browserMarkdownReady, serverMarkdownReady);
2953
- return /* @__PURE__ */ jsx("div", {
2954
- "aria-label": "Source conversation",
2955
- children: projectMessages(messages).map((entry, index) => /* @__PURE__ */ jsx(Bubble, {
2956
- entry,
2957
- markdownReady
2958
- }, index))
2959
- });
2960
- }
2961
- //#endregion
2962
- export { ResultTranscript as n, ChatPane as t };