bazilion 0.27.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (234) hide show
  1. package/dist/cli.js +651 -309
  2. package/dist/cli.js.map +1 -1
  3. package/dist/daemon.js +2105 -997
  4. package/dist/daemon.js.map +1 -1
  5. package/dist/web/client/assets/AddProviderDialog-Diic36c_.js +1 -0
  6. package/dist/web/client/assets/ConfigPage-pupvtSCX.js +1 -0
  7. package/dist/web/client/assets/ConfirmDialog-GFDcHI1L.js +1 -0
  8. package/dist/web/client/assets/ConnectionsView-y1CeY-6U.js +1 -0
  9. package/dist/web/client/assets/Dialog-bg86_x4v.js +1 -0
  10. package/dist/web/client/assets/FieldRow-B8eIni5r.js +1 -0
  11. package/dist/web/client/assets/ModelSelect-DvCLUmkW.js +1 -0
  12. package/dist/web/client/assets/SectionTabs-D4ezA6U4.js +1 -0
  13. package/dist/web/client/assets/Segmented-Dh77vmpp.js +1 -0
  14. package/dist/web/client/assets/SkillFindings-BzLO1lNA.js +1 -0
  15. package/dist/web/client/assets/SkillsPicker-hI3YXvib.js +1 -0
  16. package/dist/web/client/assets/SpawnDialog-YJX6UMBC.js +1 -0
  17. package/dist/web/client/assets/Tabs-f6bHvCGn.js +1 -0
  18. package/dist/web/client/assets/TeamForm-kda1HYZG.js +1 -0
  19. package/dist/web/client/assets/TeamThread-DFvbakHo.js +1 -0
  20. package/dist/web/client/assets/UnsavedChangesGuard-DBJikVgc.js +1 -0
  21. package/dist/web/client/assets/_id-BjNtLwak.js +1 -0
  22. package/dist/web/client/assets/_id-BklaQf3z.js +1 -0
  23. package/dist/web/client/assets/agents-D9cUF2d9.js +1 -0
  24. package/dist/web/client/assets/agents-wuBlzx4e.js +1 -0
  25. package/dist/web/client/assets/api-HC_YzjBy.js +1 -0
  26. package/dist/web/client/assets/arrow-right-Gm_FDWJ_.js +1 -0
  27. package/dist/web/client/assets/attention-8ZkSLl2e.js +1 -0
  28. package/dist/web/client/assets/check-BjgKoGvU.js +1 -0
  29. package/dist/web/client/assets/config-Con_BbSh.js +1 -0
  30. package/dist/web/client/assets/createLucideIcon-C6gOo8sD.js +1 -0
  31. package/dist/web/client/assets/index-Br9qkGM-.js +54 -0
  32. package/dist/web/client/assets/link-Cbztlp_R.js +1 -0
  33. package/dist/web/client/assets/login-llnOKSJc.js +1 -0
  34. package/dist/web/client/assets/mcp-zIUguMSI.js +1 -0
  35. package/dist/web/client/assets/plus-CWrKMtvA.js +1 -0
  36. package/dist/web/client/assets/routes-BY5uqJ2n.js +76 -0
  37. package/dist/web/client/assets/save-f9O-CQia.js +1 -0
  38. package/dist/web/client/assets/services-esLrcTwe.js +1 -0
  39. package/dist/web/client/assets/skills-DzYXksM0.js +1 -0
  40. package/dist/web/client/assets/style-Cdzqt_TJ.js +7 -0
  41. package/dist/web/client/assets/styles-BRSS6yrm.css +2 -0
  42. package/dist/web/client/assets/system-CsI66nyZ.js +1 -0
  43. package/dist/web/client/assets/teams-CHE_zpxS.js +1 -0
  44. package/dist/web/client/assets/teams-dxG9OESG.js +1 -0
  45. package/dist/web/client/assets/telegram-C3dGndJV.js +1 -0
  46. package/dist/web/client/assets/tokens-CNNH-Wr9.js +1 -0
  47. package/dist/web/client/assets/use-resource-BjnxgGvh.js +1 -0
  48. package/dist/web/client/assets/welcome-C8EOtc8P.js +1 -0
  49. package/dist/web/server/assets/AddProviderDialog-CR6TRYdZ.js +910 -0
  50. package/dist/web/server/assets/{ConfigPage-CGld_wCK.js → ConfigPage-CIh3ohea.js} +4 -4
  51. package/dist/web/server/assets/ConfirmDialog-B79K2KEW.js +52 -0
  52. package/dist/web/server/assets/ConnectionsView-BIMYdp9C.js +710 -0
  53. package/dist/web/server/assets/{ConfirmDialog-LdVlEanK.js → Dialog-CVqpXxuN.js} +3 -50
  54. package/dist/web/server/assets/{FieldRow-Dah2KKqo.js → FieldRow-CHVhX2rS.js} +4 -4
  55. package/dist/web/server/assets/{ModelSelect-Vwro6OkL.js → ModelSelect-DrZrdndo.js} +7 -7
  56. package/dist/web/server/assets/Rail-Cg-efcpA.js +698 -0
  57. package/dist/web/server/assets/{SectionTabs-CqFg9Vwx.js → SectionTabs-DrcgVeZd.js} +4 -18
  58. package/dist/web/server/assets/Segmented-3ZLdqa5U.js +18 -0
  59. package/dist/web/server/assets/{SkillFindings-Bd6e81Wu.js → SkillFindings-DSDiL6hn.js} +1 -1
  60. package/dist/web/server/assets/{SpawnDialog-BGNaMfFb.js → SpawnDialog-BUUlLxE9.js} +25 -7
  61. package/dist/web/server/assets/{TeamForm-C93tpn9r.js → TeamForm-CvQAs2FA.js} +1 -1
  62. package/dist/web/server/assets/TeamThread-5CjVPcDr.js +190 -0
  63. package/dist/web/server/assets/{UnsavedChangesGuard-Dm4a27_5.js → UnsavedChangesGuard-CyF2Z9p1.js} +8 -4
  64. package/dist/web/server/assets/{TeamPolicyEditor-BHS3J0R9.js → _id-0fEWiVZX.js} +114 -263
  65. package/dist/web/server/assets/{_id-B0x1ffz3.js → _id-8bsYEcGg.js} +2 -2
  66. package/dist/web/server/assets/{_id-sW6zXrTP.js → _id-BvAaRSUW.js} +2 -2
  67. package/dist/web/server/assets/{_id-lOVnT5sS.js → _id-Dg6M_qfr.js} +6 -6
  68. package/dist/web/server/assets/{_id-ByiXeIPS.js → _id-Dji7xr9C.js} +2 -2
  69. package/dist/web/server/assets/{_id-Bdf_Rg62.js → _id-TVruGcOd.js} +1 -1
  70. package/dist/web/server/assets/_tanstack-start-manifest_v-sxiIH4M7.js +214 -0
  71. package/dist/web/server/assets/{agents-D4tqK1kH.js → agents-BDA5yYZ2.js} +14 -15
  72. package/dist/web/server/assets/{agents-Cn9GkXFX.js → agents-BTDxmp-F.js} +2 -2
  73. package/dist/web/server/assets/{agents-BNPkidbH.js → agents-BnWgFo6o.js} +1 -1
  74. package/dist/web/server/assets/{agents-lOqc6VGd.js → agents-DM7guWF2.js} +2 -2
  75. package/dist/web/server/assets/{agents-DycxHDt8.js → agents-DktqUffG.js} +10 -10
  76. package/dist/web/server/assets/{agents-BK8OmB8g.js → agents-xgZ9rsac.js} +2 -2
  77. package/dist/web/server/assets/{attention-DULVjdmF.js → attention-CHQEQiZl.js} +2 -2
  78. package/dist/web/server/assets/{attention-YWnLKA2E.js → attention-Cr7puThv.js} +1 -1
  79. package/dist/web/server/assets/{attention-BIm455bC.js → attention-De3-ehuf.js} +6 -6
  80. package/dist/web/server/assets/{auth-DiN92ydD.js → auth-dJnrFW6y.js} +1 -1
  81. package/dist/web/server/assets/config-DOp28gcy.js +1067 -0
  82. package/dist/web/server/assets/config-DzgkbBoD.js +17 -0
  83. package/dist/web/server/assets/config-X7qWbbpH.js +20 -0
  84. package/dist/web/server/assets/{Page-CMSYKXWJ.js → createSsrRpc-CcLbajrF.js} +17 -2
  85. package/dist/web/server/assets/{daemon-client-DL2ik2Em.js → daemon-client-B_ZRIIrT.js} +2 -1
  86. package/dist/web/server/assets/{mcp-BwmpNQPN.js → mcp-C97uAZe1.js} +1 -1
  87. package/dist/web/server/assets/{mcp-B09_O05r.js → mcp-CO_tycXU.js} +9 -9
  88. package/dist/web/server/assets/{mcp-CqdTfXcn.js → mcp-D3OCoHtO.js} +2 -2
  89. package/dist/web/server/assets/router-Cs2Ak4II.js +892 -0
  90. package/dist/web/server/assets/routes-BSNOKE-C.js +7647 -0
  91. package/dist/web/server/assets/routes-BVwqgZGI.js +16 -0
  92. package/dist/web/server/assets/routes-CO4l-GJ0.js +57 -0
  93. package/dist/web/server/assets/{services-Q9HYQXXB.js → services-DZLxUSG8.js} +2 -2
  94. package/dist/web/server/assets/{services-BLvAvb8g.js → services-DsHRLL8q.js} +1 -1
  95. package/dist/web/server/assets/{services-tCfB1B83.js → services-DsvpaF3L.js} +4 -4
  96. package/dist/web/server/assets/{skills-BZg_txbf.js → skills-CggQJk6a.js} +2 -2
  97. package/dist/web/server/assets/{skills-C7fqRPna.js → skills-DKYV7PTk.js} +11 -11
  98. package/dist/web/server/assets/{skills-C_g8IKag.js → skills-h5aHa7Q8.js} +1 -1
  99. package/dist/web/server/assets/style-GYDODk2F.js +178 -0
  100. package/dist/web/server/assets/system-CZ2qzBz3.js +138 -0
  101. package/dist/web/server/assets/system-DsJfpBPl.js +12 -0
  102. package/dist/web/server/assets/system-DtswhLW62.js +18 -0
  103. package/dist/web/server/assets/{teams-BS-oweRl.js → teams-B6PzNcoy.js} +23 -15
  104. package/dist/web/server/assets/{teams-D4CaU76n.js → teams-B6lBhvdL.js} +2 -2
  105. package/dist/web/server/assets/{teams-BHkhnt6b.js → teams-Bp2tERZe.js} +2 -2
  106. package/dist/web/server/assets/{teams-DX2HmKqi.js → teams-BxnvFTyn.js} +1 -1
  107. package/dist/web/server/assets/{teams-BSflKBP8.js → teams-C-8iz-uV.js} +6 -6
  108. package/dist/web/server/assets/{teams-CNyB5nM9.js → teams-YrmyutM4.js} +1 -1
  109. package/dist/web/server/assets/{telegram-CrJiygCX.js → telegram-CXrP3hMp.js} +6 -6
  110. package/dist/web/server/assets/{telegram-BUdnc8oF.js → telegram-D2RZriz_.js} +2 -2
  111. package/dist/web/server/assets/{telegram-C4v1HhyJ.js → telegram-Gy7_9yih.js} +1 -1
  112. package/dist/web/server/assets/{tokens-DqldzPUq.js → tokens-C-oDTqnp.js} +2 -2
  113. package/dist/web/server/assets/{tokens-B1twAJdd.js → tokens-CEdl8puR.js} +1 -1
  114. package/dist/web/server/assets/{tokens-DdjEyALj.js → tokens-DSLwQ1Pw.js} +10 -10
  115. package/dist/web/server/assets/use-resource-ChQozXVI.js +63 -0
  116. package/dist/web/server/assets/welcome-BLw1G6SS.js +318 -0
  117. package/dist/web/server/assets/welcome-ByAkvHSP.js +26 -0
  118. package/dist/web/server/assets/welcome-CxXMI4HI.js +15 -0
  119. package/dist/web/server/assets/workspace-DeEYMPDX.js +658 -0
  120. package/dist/web/server/server.js +30 -74
  121. package/dist/worker.js +78 -36
  122. package/dist/worker.js.map +1 -1
  123. package/package.json +1 -1
  124. package/dist/web/client/assets/AgentAvatar-DWx-bM6n.js +0 -1
  125. package/dist/web/client/assets/ChatPane-DOV_HJg-.js +0 -72
  126. package/dist/web/client/assets/ConfigPage-Dfu9DzFX.js +0 -1
  127. package/dist/web/client/assets/ConfirmDialog-536ziJ5P.js +0 -1
  128. package/dist/web/client/assets/FieldRow-z1JqCdqn.js +0 -1
  129. package/dist/web/client/assets/ModelSelect-CvOHjUyB.js +0 -1
  130. package/dist/web/client/assets/ResultCard-X4nTbjYY.js +0 -1
  131. package/dist/web/client/assets/SectionTabs-DXHzXmmb.js +0 -1
  132. package/dist/web/client/assets/SkillFindings-8LX6bYf_.js +0 -1
  133. package/dist/web/client/assets/SkillsPicker-Cr87y_W-.js +0 -1
  134. package/dist/web/client/assets/SpawnDialog-DoZl-yes.js +0 -1
  135. package/dist/web/client/assets/SpawnTeamModal-C638hEoN.js +0 -1
  136. package/dist/web/client/assets/Tabs-D0LgBNIk.js +0 -1
  137. package/dist/web/client/assets/TeamForm-C-WzvOl4.js +0 -1
  138. package/dist/web/client/assets/TeamPolicyEditor-CSKBx0oK.js +0 -7
  139. package/dist/web/client/assets/UnsavedChangesGuard-GC-vzw7h.js +0 -1
  140. package/dist/web/client/assets/_id-BKLynswT.js +0 -1
  141. package/dist/web/client/assets/_id-BYM_NORr.js +0 -1
  142. package/dist/web/client/assets/_id-Cxa98a9m.js +0 -1
  143. package/dist/web/client/assets/_id-D4hV1U1t.js +0 -1
  144. package/dist/web/client/assets/agent-actions-CXQCoxKO.js +0 -1
  145. package/dist/web/client/assets/agents-BxPS1_Bp.js +0 -1
  146. package/dist/web/client/assets/agents-GozAWW-l.js +0 -1
  147. package/dist/web/client/assets/attention-Cz9rZcrr.js +0 -1
  148. package/dist/web/client/assets/chevron-right-CPAb1zac.js +0 -1
  149. package/dist/web/client/assets/config-9vv9Lipb.js +0 -3
  150. package/dist/web/client/assets/inbox-DHLArXxl.js +0 -1
  151. package/dist/web/client/assets/index-1YXquAq8.js +0 -52
  152. package/dist/web/client/assets/jsx-runtime-bzQ4Vb5N.js +0 -1
  153. package/dist/web/client/assets/learning-PvtXm8Ne.js +0 -1
  154. package/dist/web/client/assets/login-DIJpNQFo.js +0 -1
  155. package/dist/web/client/assets/mcp-pKBL0xIf.js +0 -1
  156. package/dist/web/client/assets/members-DHWsgsEs.js +0 -1
  157. package/dist/web/client/assets/memory-CEVppPyU.js +0 -1
  158. package/dist/web/client/assets/plus-BaIRdB10.js +0 -1
  159. package/dist/web/client/assets/policy-DEh4BLSw.js +0 -1
  160. package/dist/web/client/assets/preload-helper-eUUcpe2S.js +0 -1
  161. package/dist/web/client/assets/results-DgJPjEZF.js +0 -1
  162. package/dist/web/client/assets/review-BbshafTQ.js +0 -1
  163. package/dist/web/client/assets/route-Ccb8v41z.js +0 -1
  164. package/dist/web/client/assets/route-D1d6kCEV.js +0 -1
  165. package/dist/web/client/assets/routes-g7V4ru7T.js +0 -1
  166. package/dist/web/client/assets/services-B2f7e5jV.js +0 -1
  167. package/dist/web/client/assets/settings-B6elpcYm.js +0 -1
  168. package/dist/web/client/assets/skills-CngE7TF8.js +0 -1
  169. package/dist/web/client/assets/styles-xUnZ-ep_.css +0 -2
  170. package/dist/web/client/assets/teams-BdJZXOan.js +0 -1
  171. package/dist/web/client/assets/teams-c496ISsT.js +0 -1
  172. package/dist/web/client/assets/telegram-B_-hK6EC.js +0 -1
  173. package/dist/web/client/assets/tokens-CKz8gx4-.js +0 -1
  174. package/dist/web/client/assets/triggers-DCEPciGW.js +0 -1
  175. package/dist/web/client/assets/welcome-D-zVOLGA.js +0 -1
  176. package/dist/web/server/assets/AgentAvatar-8gTAy_tP.js +0 -37
  177. package/dist/web/server/assets/ChatPane-De_FPEoD.js +0 -1887
  178. package/dist/web/server/assets/ResultCard-CZn1w4KA.js +0 -97
  179. package/dist/web/server/assets/Sidebar-puq47KyR.js +0 -430
  180. package/dist/web/server/assets/SpawnTeamModal-C6GbfScI.js +0 -97
  181. package/dist/web/server/assets/_id-BR6tnR6I.js +0 -23
  182. package/dist/web/server/assets/_id-Bm611NQz.js +0 -13
  183. package/dist/web/server/assets/_id-D5UCoyES.js +0 -359
  184. package/dist/web/server/assets/_id-DHx5UmmL.js +0 -12
  185. package/dist/web/server/assets/_id-DLpGmOVm.js +0 -19
  186. package/dist/web/server/assets/_id-Y5ctILG2.js +0 -13
  187. package/dist/web/server/assets/_id-dDA0pdVo.js +0 -54
  188. package/dist/web/server/assets/_tanstack-start-manifest_v-B8u80HjK.js +0 -292
  189. package/dist/web/server/assets/agent-actions-BBdFVdoa.js +0 -20
  190. package/dist/web/server/assets/api-WWxPqx67.js +0 -85
  191. package/dist/web/server/assets/config-BNEgu7WG.js +0 -798
  192. package/dist/web/server/assets/config-C1VB28se.js +0 -12
  193. package/dist/web/server/assets/config-TdVqnqNL.js +0 -25
  194. package/dist/web/server/assets/createSsrRpc-6LHNEsSK.js +0 -16
  195. package/dist/web/server/assets/inbox-4Vj5jTT8.js +0 -245
  196. package/dist/web/server/assets/inbox-D4IqUv3l.js +0 -38
  197. package/dist/web/server/assets/inbox-Dle24AfV.js +0 -23
  198. package/dist/web/server/assets/learning-BScq7VbO.js +0 -12
  199. package/dist/web/server/assets/learning-CBWFEnhg.js +0 -263
  200. package/dist/web/server/assets/learning-DWAKevhF.js +0 -25
  201. package/dist/web/server/assets/members-B8QBF6TF.js +0 -12
  202. package/dist/web/server/assets/members-DsF02Wp7.js +0 -12
  203. package/dist/web/server/assets/members-tWZA9b15.js +0 -36
  204. package/dist/web/server/assets/memory-BNN0b-0x.js +0 -12
  205. package/dist/web/server/assets/memory-CTl1E1Rm.js +0 -267
  206. package/dist/web/server/assets/memory-CV5uCBb2.js +0 -12
  207. package/dist/web/server/assets/policy-C9M6zV6w.js +0 -79
  208. package/dist/web/server/assets/policy-h-6NpU3m.js +0 -19
  209. package/dist/web/server/assets/policy-xEw9X0DK.js +0 -12
  210. package/dist/web/server/assets/results-D3A3UA4d.js +0 -182
  211. package/dist/web/server/assets/results-D6Ui5S8D.js +0 -12
  212. package/dist/web/server/assets/results-DWmxvfyn.js +0 -15
  213. package/dist/web/server/assets/review-CyQky-WQ.js +0 -40
  214. package/dist/web/server/assets/review-Sq0GGcPV.js +0 -322
  215. package/dist/web/server/assets/review-XWbSF8cF.js +0 -12
  216. package/dist/web/server/assets/route-BErtkz6t.js +0 -19
  217. package/dist/web/server/assets/route-CLoV-An_.js +0 -48
  218. package/dist/web/server/assets/route-WQ19JkBa.js +0 -19
  219. package/dist/web/server/assets/route-dEK_2GLj.js +0 -203
  220. package/dist/web/server/assets/route-iHTkhO81.js +0 -16
  221. package/dist/web/server/assets/route-zs8uUQtB.js +0 -16
  222. package/dist/web/server/assets/router-BI9gmY3S.js +0 -751
  223. package/dist/web/server/assets/routes-081s4n24.js +0 -45
  224. package/dist/web/server/assets/routes-CWo5WPsr.js +0 -15
  225. package/dist/web/server/assets/routes-Cqp1ufHm.js +0 -56
  226. package/dist/web/server/assets/settings-CVaGv-xF.js +0 -12
  227. package/dist/web/server/assets/settings-D9viV-86.js +0 -561
  228. package/dist/web/server/assets/settings-DaZNZ_CC.js +0 -27
  229. package/dist/web/server/assets/triggers-B7LW784F.js +0 -214
  230. package/dist/web/server/assets/triggers-C5sMCZXv2.js +0 -12
  231. package/dist/web/server/assets/triggers-DMfVdImD.js +0 -12
  232. package/dist/web/server/assets/welcome-D0d38Pzx.js +0 -93
  233. package/dist/web/client/assets/{TeamPolicyEditor-DLioOiRN.css → style-DLioOiRN.css} +0 -0
  234. package/dist/web/server/assets/{start-DTX6aKCi.js → start-DhW7sy23.js} +1 -1
package/dist/daemon.js CHANGED
@@ -359,7 +359,7 @@ function onRequest(req, res) {
359
359
  }
360
360
  function getSsrfProxy() {
361
361
  if (proxyUrl) return Promise.resolve(proxyUrl);
362
- starting ??= new Promise((resolve8, reject2) => {
362
+ starting ??= new Promise((resolve9, reject2) => {
363
363
  const s = createServer(onRequest);
364
364
  s.on("connect", onConnect);
365
365
  s.on("connection", track);
@@ -371,7 +371,7 @@ function getSsrfProxy() {
371
371
  s.unref();
372
372
  server = s;
373
373
  proxyUrl = `http://127.0.0.1:${s.address().port}`;
374
- resolve8(proxyUrl);
374
+ resolve9(proxyUrl);
375
375
  });
376
376
  }).finally(() => {
377
377
  starting = null;
@@ -385,7 +385,7 @@ async function closeSsrfProxy() {
385
385
  if (!s) return;
386
386
  for (const socket of sockets) socket.destroy();
387
387
  sockets.clear();
388
- await new Promise((resolve8) => s.close(() => resolve8()));
388
+ await new Promise((resolve9) => s.close(() => resolve9()));
389
389
  }
390
390
  var server, proxyUrl, starting, sockets;
391
391
  var init_proxy = __esm({
@@ -425,8 +425,8 @@ function withTimeout(promise, ms) {
425
425
  () => {
426
426
  }
427
427
  ),
428
- new Promise((resolve8) => {
429
- timer = setTimeout(resolve8, ms);
428
+ new Promise((resolve9) => {
429
+ timer = setTimeout(resolve9, ms);
430
430
  })
431
431
  ]).finally(() => clearTimeout(timer));
432
432
  }
@@ -513,10 +513,10 @@ function connection(server3, connect3, signal) {
513
513
  if (!signal) return getMcpConnection(server3, connect3);
514
514
  if (signal.aborted) return Promise.reject(new McpAbortError());
515
515
  const ready = getMcpConnection(server3, connect3);
516
- return new Promise((resolve8, reject2) => {
516
+ return new Promise((resolve9, reject2) => {
517
517
  const abort = () => reject2(new McpAbortError());
518
518
  signal.addEventListener("abort", abort, { once: true });
519
- ready.then(resolve8, reject2).finally(() => signal.removeEventListener("abort", abort));
519
+ ready.then(resolve9, reject2).finally(() => signal.removeEventListener("abort", abort));
520
520
  });
521
521
  }
522
522
  async function listMcpTools(server3, connect3, signal) {
@@ -611,7 +611,7 @@ var init_pool = __esm({
611
611
  }
612
612
  const deadline = Date.now() + KILL_WAIT_MS;
613
613
  while (Date.now() < deadline) {
614
- await new Promise((resolve8) => setTimeout(resolve8, 20));
614
+ await new Promise((resolve9) => setTimeout(resolve9, 20));
615
615
  try {
616
616
  process.kill(-group, 0);
617
617
  } catch {
@@ -720,24 +720,24 @@ var init_ssrf = __esm({
720
720
  import { readFileSync as readFileSync6 } from "node:fs";
721
721
  import { connect as connect2 } from "node:net";
722
722
  import { homedir as homedir2 } from "node:os";
723
- import { join as join10 } from "node:path";
723
+ import { join as join11 } from "node:path";
724
724
  function runningBrowserDirs(platform = process.platform, home = homedir2()) {
725
725
  if (platform === "darwin") {
726
- const root2 = join10(home, "Library", "Application Support");
726
+ const root2 = join11(home, "Library", "Application Support");
727
727
  return [
728
- { name: "Google Chrome", dir: join10(root2, "Google", "Chrome") },
729
- { name: "Google Chrome Beta", dir: join10(root2, "Google", "Chrome Beta") },
730
- { name: "Google Chrome Canary", dir: join10(root2, "Google", "Chrome Canary") },
731
- { name: "Chromium", dir: join10(root2, "Chromium") }
728
+ { name: "Google Chrome", dir: join11(root2, "Google", "Chrome") },
729
+ { name: "Google Chrome Beta", dir: join11(root2, "Google", "Chrome Beta") },
730
+ { name: "Google Chrome Canary", dir: join11(root2, "Google", "Chrome Canary") },
731
+ { name: "Chromium", dir: join11(root2, "Chromium") }
732
732
  ];
733
733
  }
734
- const root = process.env.XDG_CONFIG_HOME || join10(home, ".config");
734
+ const root = process.env.XDG_CONFIG_HOME || join11(home, ".config");
735
735
  return [
736
- { name: "Google Chrome", dir: join10(root, "google-chrome") },
737
- { name: "Google Chrome Beta", dir: join10(root, "google-chrome-beta") },
738
- { name: "Google Chrome Dev", dir: join10(root, "google-chrome-unstable") },
739
- { name: "Chromium", dir: join10(root, "chromium") },
740
- { name: "Chromium", dir: join10(home, "snap", "chromium", "common", "chromium") }
736
+ { name: "Google Chrome", dir: join11(root, "google-chrome") },
737
+ { name: "Google Chrome Beta", dir: join11(root, "google-chrome-beta") },
738
+ { name: "Google Chrome Dev", dir: join11(root, "google-chrome-unstable") },
739
+ { name: "Chromium", dir: join11(root, "chromium") },
740
+ { name: "Chromium", dir: join11(home, "snap", "chromium", "common", "chromium") }
741
741
  ];
742
742
  }
743
743
  function parseDevToolsActivePort(content) {
@@ -747,11 +747,11 @@ function parseDevToolsActivePort(content) {
747
747
  return `ws://127.0.0.1:${port2}${path}`;
748
748
  }
749
749
  function isListening(endpoint2) {
750
- return new Promise((resolve8) => {
750
+ return new Promise((resolve9) => {
751
751
  const socket = connect2({ host: "127.0.0.1", port: Number(new URL(endpoint2).port) });
752
752
  const done = (listening) => {
753
753
  socket.destroy();
754
- resolve8(listening);
754
+ resolve9(listening);
755
755
  };
756
756
  socket.setTimeout(1e3, () => done(false));
757
757
  socket.once("connect", () => done(true));
@@ -763,7 +763,7 @@ async function findRunningBrowser(dirs = runningBrowserDirs()) {
763
763
  for (const { name, dir } of dirs) {
764
764
  let content;
765
765
  try {
766
- content = readFileSync6(join10(dir, "DevToolsActivePort"), "utf8");
766
+ content = readFileSync6(join11(dir, "DevToolsActivePort"), "utf8");
767
767
  } catch (error) {
768
768
  const code = error.code;
769
769
  if (code === "EPERM" || code === "EACCES") denied = dir;
@@ -891,21 +891,21 @@ var init_attach = __esm({
891
891
  });
892
892
 
893
893
  // ../daemon/src/lib/browser/executable.ts
894
- import { accessSync, constants, readdirSync as readdirSync3, statSync as statSync3 } from "node:fs";
894
+ import { accessSync, constants, readdirSync as readdirSync3, statSync as statSync4 } from "node:fs";
895
895
  import { homedir as homedir3 } from "node:os";
896
- import { basename as basename3, isAbsolute, join as join11 } from "node:path";
896
+ import { basename as basename3, isAbsolute, join as join12 } from "node:path";
897
897
  function installedBrowserPaths(platform = process.platform, home = homedir3()) {
898
898
  if (platform !== "darwin") return LINUX_INSTALLED;
899
- return ["/Applications", join11(home, "Applications")].flatMap(
899
+ return ["/Applications", join12(home, "Applications")].flatMap(
900
900
  (root) => MAC_APPS.map(({ app: app2, name }) => ({
901
- path: join11(root, `${app2}.app`, "Contents", "MacOS", app2),
901
+ path: join12(root, `${app2}.app`, "Contents", "MacOS", app2),
902
902
  name
903
903
  }))
904
904
  );
905
905
  }
906
906
  function isExecutableFile(path) {
907
907
  try {
908
- if (!statSync3(path).isFile()) return false;
908
+ if (!statSync4(path).isFile()) return false;
909
909
  accessSync(path, constants.X_OK);
910
910
  return true;
911
911
  } catch {
@@ -913,7 +913,7 @@ function isExecutableFile(path) {
913
913
  }
914
914
  }
915
915
  function playwrightCacheDir(platform = process.platform, home = homedir3()) {
916
- return process.env.PLAYWRIGHT_BROWSERS_PATH || (platform === "darwin" ? join11(home, "Library", "Caches", "ms-playwright") : join11(home, ".cache", "ms-playwright"));
916
+ return process.env.PLAYWRIGHT_BROWSERS_PATH || (platform === "darwin" ? join12(home, "Library", "Caches", "ms-playwright") : join12(home, ".cache", "ms-playwright"));
917
917
  }
918
918
  function bundledChromium(root = playwrightCacheDir()) {
919
919
  let entries;
@@ -925,7 +925,7 @@ function bundledChromium(root = playwrightCacheDir()) {
925
925
  const revisions = entries.filter((entry) => /^chromium-\d+$/.test(entry)).sort((a, b) => Number(b.slice("chromium-".length)) - Number(a.slice("chromium-".length)));
926
926
  for (const revision of revisions) {
927
927
  for (const layout of BUNDLED_LAYOUTS) {
928
- const path = join11(root, revision, ...layout);
928
+ const path = join12(root, revision, ...layout);
929
929
  if (isExecutableFile(path)) return { path, name: "Chromium (Playwright)" };
930
930
  }
931
931
  }
@@ -987,14 +987,14 @@ var init_executable = __esm({
987
987
  // ../daemon/src/lib/browser/install.ts
988
988
  import { spawn } from "node:child_process";
989
989
  import { createRequire } from "node:module";
990
- import { dirname as dirname3, join as join12 } from "node:path";
990
+ import { dirname as dirname3, join as join13 } from "node:path";
991
991
  function downloadAllowed() {
992
992
  const skip2 = process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD?.trim().toLowerCase();
993
993
  return !skip2 || skip2 === "0" || skip2 === "false";
994
994
  }
995
995
  function runInstaller() {
996
- return new Promise((resolve8, reject2) => {
997
- const cli = join12(
996
+ return new Promise((resolve9, reject2) => {
997
+ const cli = join13(
998
998
  dirname3(createRequire(import.meta.url).resolve("playwright/package.json")),
999
999
  "cli.js"
1000
1000
  );
@@ -1017,7 +1017,7 @@ function runInstaller() {
1017
1017
  child.stderr.on("data", keep);
1018
1018
  child.once("error", reject2);
1019
1019
  child.once("exit", (code, signal) => {
1020
- if (code === 0) resolve8();
1020
+ if (code === 0) resolve9();
1021
1021
  else reject2(new Error(output.trim() || `the installer ended with ${signal ?? code}`));
1022
1022
  });
1023
1023
  });
@@ -1081,13 +1081,13 @@ var init_install = __esm({
1081
1081
  // ../daemon/src/lib/browser/launch.ts
1082
1082
  import { execFileSync, spawn as spawn2 } from "node:child_process";
1083
1083
  import { mkdirSync as mkdirSync5, readFileSync as readFileSync7, readlinkSync, writeFileSync as writeFileSync4 } from "node:fs";
1084
- import { join as join13 } from "node:path";
1084
+ import { join as join14 } from "node:path";
1085
1085
  function launchArgs(opts) {
1086
1086
  const wayland = !opts.headless && !process.env.DISPLAY && !!process.env.WAYLAND_DISPLAY;
1087
1087
  return [
1088
1088
  // Chromium picks the port and prints the endpoint on stderr.
1089
1089
  "--remote-debugging-port=0",
1090
- `--user-data-dir=${join13(opts.dir, "user-data")}`,
1090
+ `--user-data-dir=${join14(opts.dir, "user-data")}`,
1091
1091
  "--no-first-run",
1092
1092
  "--no-default-browser-check",
1093
1093
  "--disable-sync",
@@ -1113,7 +1113,7 @@ function launchArgs(opts) {
1113
1113
  function browserEnv(opts) {
1114
1114
  const env = {
1115
1115
  PATH: process.env.PATH ?? "/usr/bin:/bin",
1116
- HOME: join13(opts.dir, "home"),
1116
+ HOME: join14(opts.dir, "home"),
1117
1117
  LANG: "C.UTF-8"
1118
1118
  };
1119
1119
  if (!opts.headless) {
@@ -1150,10 +1150,10 @@ function runsOnProfile(pid, userDataDir) {
1150
1150
  }
1151
1151
  }
1152
1152
  async function killOrphanBrowser(dir) {
1153
- const userDataDir = join13(dir, "user-data");
1153
+ const userDataDir = join14(dir, "user-data");
1154
1154
  let pid;
1155
1155
  try {
1156
- pid = Number(/-(\d+)$/.exec(readlinkSync(join13(userDataDir, "SingletonLock")))?.[1]);
1156
+ pid = Number(/-(\d+)$/.exec(readlinkSync(join14(userDataDir, "SingletonLock")))?.[1]);
1157
1157
  if (!runsOnProfile(pid, userDataDir)) return;
1158
1158
  } catch {
1159
1159
  return;
@@ -1166,8 +1166,8 @@ async function killOrphanBrowser(dir) {
1166
1166
  for (let i = 0; i < 40 && isAlive(pid); i++) await sleep(50);
1167
1167
  }
1168
1168
  function skipSessionRestore(userDataDir) {
1169
- const dir = join13(userDataDir, "Default");
1170
- const file = join13(dir, "Preferences");
1169
+ const dir = join14(userDataDir, "Default");
1170
+ const file = join14(dir, "Preferences");
1171
1171
  let prefs = {};
1172
1172
  try {
1173
1173
  const parsed = JSON.parse(readFileSync7(file, "utf8"));
@@ -1190,9 +1190,9 @@ function trackGroup(pid) {
1190
1190
  });
1191
1191
  }
1192
1192
  async function launchBrowser(opts) {
1193
- const userDataDir = join13(opts.dir, "user-data");
1193
+ const userDataDir = join14(opts.dir, "user-data");
1194
1194
  mkdirSync5(userDataDir, { recursive: true, mode: 448 });
1195
- mkdirSync5(join13(opts.dir, "home"), { recursive: true, mode: 448 });
1195
+ mkdirSync5(join14(opts.dir, "home"), { recursive: true, mode: 448 });
1196
1196
  await killOrphanBrowser(opts.dir);
1197
1197
  skipSessionRestore(userDataDir);
1198
1198
  const child = spawn2(opts.executablePath, launchArgs(opts), {
@@ -1210,7 +1210,7 @@ async function launchBrowser(opts) {
1210
1210
  liveGroups.delete(pid);
1211
1211
  });
1212
1212
  }
1213
- const exited = new Promise((resolve8) => child.once("exit", () => resolve8(true)));
1213
+ const exited = new Promise((resolve9) => child.once("exit", () => resolve9(true)));
1214
1214
  const waitForExit = (ms) => Promise.race([exited, sleep(ms).then(() => false)]);
1215
1215
  const running = () => child.exitCode === null && child.signalCode === null;
1216
1216
  let browser;
@@ -1233,7 +1233,7 @@ async function launchBrowser(opts) {
1233
1233
  })();
1234
1234
  let stderr = "";
1235
1235
  try {
1236
- const endpoint2 = await new Promise((resolve8, reject2) => {
1236
+ const endpoint2 = await new Promise((resolve9, reject2) => {
1237
1237
  const fail2 = (message) => {
1238
1238
  clearTimeout(timer);
1239
1239
  reject2(new Error(stderr.trim() ? `${message}:
@@ -1263,7 +1263,7 @@ ${stderr.trim()}` : message));
1263
1263
  );
1264
1264
  if (match?.[1]) {
1265
1265
  clearTimeout(timer);
1266
- resolve8(match[1]);
1266
+ resolve9(match[1]);
1267
1267
  }
1268
1268
  }
1269
1269
  });
@@ -1301,7 +1301,7 @@ var init_launch = __esm({
1301
1301
  NO_WEBRTC_SCRIPT = `for (const name of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'mozRTCPeerConnection']) {
1302
1302
  Object.defineProperty(window, name, { configurable: false, get() { return undefined } })
1303
1303
  }`;
1304
- sleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
1304
+ sleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
1305
1305
  liveGroups = /* @__PURE__ */ new Set();
1306
1306
  exitHookInstalled = false;
1307
1307
  }
@@ -1335,15 +1335,15 @@ ${line}` : line;
1335
1335
  function clip(text4, max = FIELD_CHARS) {
1336
1336
  return text4.length <= max ? text4 : `${text4.slice(0, cutAt(text4, max))}\u2026`;
1337
1337
  }
1338
- function formatSnapshot(snapshot2, n = 1) {
1339
- const total = snapshot2.pages.length;
1338
+ function formatSnapshot(snapshot3, n = 1) {
1339
+ const total = snapshot3.pages.length;
1340
1340
  const more = n < total ? ` \u2014 read on with browser_snapshot {"page": ${n + 1}}` : "";
1341
1341
  return [
1342
- `- Page URL: ${clip(snapshot2.url)}`,
1343
- `- Page title: ${clip(snapshot2.title)}`,
1344
- `- Snapshot of ${snapshot2.tabId}, page ${n} of ${total}${more}`,
1342
+ `- Page URL: ${clip(snapshot3.url)}`,
1343
+ `- Page title: ${clip(snapshot3.title)}`,
1344
+ `- Snapshot of ${snapshot3.tabId}, page ${n} of ${total}${more}`,
1345
1345
  "",
1346
- snapshot2.pages[n - 1] ?? ""
1346
+ snapshot3.pages[n - 1] ?? ""
1347
1347
  ].join("\n");
1348
1348
  }
1349
1349
  function capText(text4) {
@@ -1587,7 +1587,7 @@ function browserStatus(agentId, config, paths, enabled) {
1587
1587
  }
1588
1588
  return status2;
1589
1589
  }
1590
- function text(value) {
1590
+ function text2(value) {
1591
1591
  return [{ type: "text", text: capText(value) }];
1592
1592
  }
1593
1593
  function firstLine(error) {
@@ -1647,7 +1647,7 @@ async function act(session, refs, action) {
1647
1647
  const page = await activePage(session);
1648
1648
  for (const ref of refs) {
1649
1649
  if (await page.locator(`aria-ref=${ref}`).count() === 0) {
1650
- return text(
1650
+ return text2(
1651
1651
  `Ref "${ref}" is not on the page any more, so nothing was done. Use a ref from this fresh snapshot:
1652
1652
 
1653
1653
  ${await freshSnapshot(session, page)}`
@@ -1657,14 +1657,14 @@ ${await freshSnapshot(session, page)}`
1657
1657
  try {
1658
1658
  await action(page);
1659
1659
  } catch (error) {
1660
- return text(
1660
+ return text2(
1661
1661
  `Could not act on ref "${refs.join(", ")}": ${firstLine(error)}
1662
1662
  The action may still have taken effect: check the page below before trying again, and never repeat a submission blindly.
1663
1663
 
1664
1664
  ` + await freshSnapshot(session, page)
1665
1665
  );
1666
1666
  }
1667
- return text(await freshSnapshot(session, page));
1667
+ return text2(await freshSnapshot(session, page));
1668
1668
  }
1669
1669
  async function runAction(session, action, args, config) {
1670
1670
  switch (action) {
@@ -1673,14 +1673,14 @@ async function runAction(session, action, args, config) {
1673
1673
  await checkUrl(url, config);
1674
1674
  const page = await activePage(session);
1675
1675
  await page.goto(url, { waitUntil: "domcontentloaded" });
1676
- return text(await freshSnapshot(session, page));
1676
+ return text2(await freshSnapshot(session, page));
1677
1677
  }
1678
1678
  case "snapshot": {
1679
- if (args.page !== void 0) return text(snapshotPage(session, args.page));
1679
+ if (args.page !== void 0) return text2(snapshotPage(session, args.page));
1680
1680
  const page = await activePage(session);
1681
- if (isBlank(page)) return text(NO_PAGE_HINT);
1681
+ if (isBlank(page)) return text2(NO_PAGE_HINT);
1682
1682
  const ref = args.ref === void 0 ? void 0 : elementRef(args.ref);
1683
- return text(await snapshot(session, page, ref));
1683
+ return text2(await snapshot(session, page, ref));
1684
1684
  }
1685
1685
  case "click": {
1686
1686
  const ref = elementRef(args.ref);
@@ -1727,18 +1727,18 @@ async function runAction(session, action, args, config) {
1727
1727
  const key2 = stringArg(args, "key");
1728
1728
  const page = await activePage(session);
1729
1729
  await page.keyboard.press(key2);
1730
- return text(await freshSnapshot(session, page));
1730
+ return text2(await freshSnapshot(session, page));
1731
1731
  }
1732
1732
  case "go_back": {
1733
1733
  const page = await activePage(session);
1734
1734
  await page.goBack({ waitUntil: "domcontentloaded" });
1735
- return text(await freshSnapshot(session, page));
1735
+ return text2(await freshSnapshot(session, page));
1736
1736
  }
1737
1737
  case "tabs":
1738
1738
  return tabs(session, args, config);
1739
1739
  case "take_screenshot": {
1740
1740
  const page = await activePage(session);
1741
- if (isBlank(page)) return text(NO_PAGE_HINT);
1741
+ if (isBlank(page)) return text2(NO_PAGE_HINT);
1742
1742
  const png = await page.screenshot({
1743
1743
  type: "png",
1744
1744
  fullPage: args.full_page === true,
@@ -1755,9 +1755,9 @@ async function runAction(session, action, args, config) {
1755
1755
  ];
1756
1756
  }
1757
1757
  case "console":
1758
- return text(session.console.join("\n") || "no console messages");
1758
+ return text2(session.console.join("\n") || "no console messages");
1759
1759
  case "network":
1760
- return text(
1760
+ return text2(
1761
1761
  session.network.map((r) => `${r.method} ${r.status ?? "..."} ${r.url}`).join("\n") || "no network requests recorded"
1762
1762
  );
1763
1763
  default:
@@ -1772,7 +1772,7 @@ async function tabs(session, args, config) {
1772
1772
  const id2 = tabId(session, page2);
1773
1773
  return `${id2 === session.activeTab ? "*" : " "} ${id2} ${clip(page2.url())}`;
1774
1774
  }).join("\n");
1775
- return text(lines || "No tabs are open.");
1775
+ return text2(lines || "No tabs are open.");
1776
1776
  }
1777
1777
  if (op === "new") {
1778
1778
  if (browser.pages().length >= MAX_TABS) {
@@ -1782,9 +1782,9 @@ async function tabs(session, args, config) {
1782
1782
  if (url) await checkUrl(url, config);
1783
1783
  const page2 = await browser.newPage();
1784
1784
  session.activeTab = tabId(session, page2);
1785
- if (!url) return text(`Opened ${session.activeTab} (about:blank).`);
1785
+ if (!url) return text2(`Opened ${session.activeTab} (about:blank).`);
1786
1786
  await page2.goto(url, { waitUntil: "domcontentloaded" });
1787
- return text(await freshSnapshot(session, page2));
1787
+ return text2(await freshSnapshot(session, page2));
1788
1788
  }
1789
1789
  const id = stringArg(args, "tabId");
1790
1790
  const page = browser.pages().find((p) => tabId(session, p) === id);
@@ -1792,14 +1792,14 @@ async function tabs(session, args, config) {
1792
1792
  if (!page) throw new Error(`No open tab "${id}"; browser_tabs {"op":"list"} lists them.`);
1793
1793
  await page.bringToFront();
1794
1794
  session.activeTab = id;
1795
- return text(
1795
+ return text2(
1796
1796
  isBlank(page) ? `Selected ${id} (about:blank).` : await freshSnapshot(session, page)
1797
1797
  );
1798
1798
  }
1799
1799
  if (op === "close") {
1800
- if (!page) return text(`Tab "${id}" is not open.`);
1800
+ if (!page) return text2(`Tab "${id}" is not open.`);
1801
1801
  await page.close();
1802
- return text(`Closed ${id}.`);
1802
+ return text2(`Closed ${id}.`);
1803
1803
  }
1804
1804
  throw new Error(`unknown tabs op "${op}" (expected list, new, select or close)`);
1805
1805
  }
@@ -3155,6 +3155,11 @@ var ATTENTION_KINDS = [
3155
3155
  "queue_interrupted"
3156
3156
  ];
3157
3157
  var bounded = (value, fallback) => (value?.trim() || fallback).replace(/(authorization:\s*bearer\s+)[^\s,;]+/gi, "$1[redacted]").replace(/\bsk-[a-z0-9_-]{8,}\b/gi, "[redacted]").replace(/(https?:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[redacted]@").slice(0, 500);
3158
+ function agentHref(agentId, section) {
3159
+ const query = new URLSearchParams({ agent: agentId ?? "" });
3160
+ if (section) query.set("section", section);
3161
+ return `/?${query}`;
3162
+ }
3158
3163
  var sources = [
3159
3164
  {
3160
3165
  kind: "lesson_proposal",
@@ -3169,7 +3174,7 @@ var sources = [
3169
3174
  severity: "action_required",
3170
3175
  title: "Lesson proposal ready",
3171
3176
  diagnostic: "A reviewed-learning proposal is waiting for approval or rejection.",
3172
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}/learning`,
3177
+ href: agentHref(r.agentId, "learning"),
3173
3178
  acknowledgeable: false
3174
3179
  })
3175
3180
  )
@@ -3188,7 +3193,7 @@ var sources = [
3188
3193
  severity: "error",
3189
3194
  title: r.status === "cancelled" ? "Agent review cancelled" : "Agent review failed",
3190
3195
  diagnostic: bounded(r.diagnostic, "The review stopped without completing."),
3191
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}/learning`,
3196
+ href: agentHref(r.agentId, "learning"),
3192
3197
  acknowledgeable: true
3193
3198
  })
3194
3199
  )
@@ -3208,7 +3213,7 @@ var sources = [
3208
3213
  severity: "error",
3209
3214
  title: "Scheduled trigger failed",
3210
3215
  diagnostic: bounded(r.diagnostic, "The scheduled Agent turn failed."),
3211
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}/triggers`,
3216
+ href: agentHref(r.agentId, "schedules"),
3212
3217
  acknowledgeable: true
3213
3218
  })
3214
3219
  )
@@ -3226,7 +3231,7 @@ var sources = [
3226
3231
  severity: "warning",
3227
3232
  title: "Agent message loop stopped",
3228
3233
  diagnostic: `Message chain stopped at hop ${r.attempted_hop} (limit ${r.max_hops}).`,
3229
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}/inbox`,
3234
+ href: agentHref(r.agentId, "mailbox"),
3230
3235
  acknowledgeable: true
3231
3236
  })
3232
3237
  )
@@ -3255,7 +3260,7 @@ var sources = [
3255
3260
  severity: "action_required",
3256
3261
  title: "Agent queue paused after a daemon restart",
3257
3262
  diagnostic: `The daemon restarted during a follow-up, which was not run again (${r.interrupted_count} interrupted). ${r.waiting_count} follow-up${r.waiting_count === 1 ? " waits" : "s wait"} in the paused queue: check them, then resume the queue.`,
3258
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}`,
3263
+ href: agentHref(r.agentId),
3259
3264
  acknowledgeable: false
3260
3265
  })
3261
3266
  )
@@ -4190,23 +4195,29 @@ function localServer(provider) {
4190
4195
  endpoint: { env: provider.urlEnv, fallback: provider.url },
4191
4196
  local: provider.local,
4192
4197
  fields: [
4193
- { envVar: provider.urlEnv, kind: "config", label: "Endpoint URL", placeholder: provider.url },
4194
- { envVar: provider.keyEnv, kind: "secret", ...provider.keyField }
4198
+ { envVar: provider.urlEnv, kind: "config", label: "Address", placeholder: provider.url },
4199
+ { envVar: provider.keyEnv, kind: "secret", advanced: true, ...provider.keyField }
4195
4200
  ]
4196
4201
  };
4197
4202
  }
4198
4203
  var PROVIDERS = [
4199
4204
  {
4200
4205
  id: "openai-codex",
4201
- displayName: "OpenAI ChatGPT (OAuth)",
4202
- hint: "Use your ChatGPT Plus/Pro/Team account (same login as Codex CLI)",
4206
+ displayName: "ChatGPT",
4207
+ hint: "Use your ChatGPT Plus, Pro or Team plan. No API key.",
4203
4208
  // Credentials come from the OAuth flow (/api/auth/openai), not from fields.
4204
- fields: []
4209
+ fields: [],
4210
+ popular: true,
4211
+ suggested: ["gpt-6.1-sol", "gpt-6-luna"]
4212
+ },
4213
+ {
4214
+ ...apiKey("openai", "OpenAI", "OPENAI_API_KEY", {
4215
+ hint: "GPT models \xB7 platform.openai.com",
4216
+ placeholder: "sk-..."
4217
+ }),
4218
+ popular: true,
4219
+ suggested: ["gpt-6.1-sol", "gpt-6-luna"]
4205
4220
  },
4206
- apiKey("openai", "OpenAI", "OPENAI_API_KEY", {
4207
- hint: "GPT models \xB7 platform.openai.com",
4208
- placeholder: "sk-..."
4209
- }),
4210
4221
  {
4211
4222
  id: "anthropic",
4212
4223
  displayName: "Anthropic",
@@ -4218,14 +4229,21 @@ var PROVIDERS = [
4218
4229
  envVar: "ANTHROPIC_OAUTH_TOKEN",
4219
4230
  kind: "secret",
4220
4231
  label: "OAuth token (alternative to API key)",
4221
- description: "Takes precedence over ANTHROPIC_API_KEY when set"
4232
+ description: "Takes precedence over ANTHROPIC_API_KEY when set",
4233
+ advanced: true
4222
4234
  }
4223
- ]
4235
+ ],
4236
+ popular: true,
4237
+ suggested: ["claude-fable-5-2", "claude-haiku-5-5"]
4238
+ },
4239
+ {
4240
+ ...apiKey("google", "Google Gemini", "GEMINI_API_KEY", {
4241
+ hint: "Gemini models \xB7 ai.google.dev (free tier available)",
4242
+ placeholder: "AIza..."
4243
+ }),
4244
+ popular: true,
4245
+ suggested: ["gemini-4-argon", "gemini-3.8-flash"]
4224
4246
  },
4225
- apiKey("google", "Google (Gemini)", "GEMINI_API_KEY", {
4226
- hint: "Gemini models \xB7 ai.google.dev (free tier available)",
4227
- placeholder: "AIza..."
4228
- }),
4229
4247
  {
4230
4248
  id: "google-vertex",
4231
4249
  displayName: "Google Vertex AI",
@@ -4253,7 +4271,8 @@ var PROVIDERS = [
4253
4271
  envVar: "GOOGLE_VERTEX_CREDENTIALS_JSON",
4254
4272
  kind: "secret",
4255
4273
  label: "Explicit credentials JSON (learning reviews)",
4256
- description: "Service-account or ADC JSON given only to the learning-review worker, which cannot read ambient ADC files."
4274
+ description: "Service-account or ADC JSON given only to the learning-review worker, which cannot read ambient ADC files.",
4275
+ advanced: true
4257
4276
  }
4258
4277
  ]
4259
4278
  },
@@ -4409,11 +4428,15 @@ var PROVIDERS = [
4409
4428
  { envVar: "CLOUDFLARE_ACCOUNT_ID", kind: "config", label: "Account ID" }
4410
4429
  ]
4411
4430
  },
4412
- apiKey("openrouter", "OpenRouter", "OPENROUTER_API_KEY", {
4413
- hint: "Proxy for 200+ models \xB7 openrouter.ai",
4414
- placeholder: "sk-or-...",
4415
- modelsUrl: "https://openrouter.ai/api/v1"
4416
- }),
4431
+ {
4432
+ ...apiKey("openrouter", "OpenRouter", "OPENROUTER_API_KEY", {
4433
+ hint: "Many providers through one key \xB7 openrouter.ai",
4434
+ placeholder: "sk-or-...",
4435
+ modelsUrl: "https://openrouter.ai/api/v1"
4436
+ }),
4437
+ popular: true,
4438
+ suggested: ["~anthropic/claude-sonnet-latest", "~anthropic/claude-haiku-latest"]
4439
+ },
4417
4440
  {
4418
4441
  id: "vercel-ai-gateway",
4419
4442
  displayName: "Vercel AI Gateway",
@@ -4426,7 +4449,8 @@ var PROVIDERS = [
4426
4449
  envVar: "AI_GATEWAY_BASE_URL",
4427
4450
  kind: "config",
4428
4451
  label: "Base URL (optional)",
4429
- placeholder: "https://ai-gateway.vercel.sh/v1"
4452
+ placeholder: "https://ai-gateway.vercel.sh/v1",
4453
+ advanced: true
4430
4454
  }
4431
4455
  ]
4432
4456
  },
@@ -4512,6 +4536,11 @@ function isProviderConfigured(id, env) {
4512
4536
  if (provider.configured) return provider.configured(env);
4513
4537
  return (provider.keyEnv ?? []).some((name) => Boolean(env[name]));
4514
4538
  }
4539
+ function providersUsingField(envVar) {
4540
+ return PROVIDERS.filter(
4541
+ (provider) => provider.fields.some((field) => field.envVar === envVar)
4542
+ ).map((provider) => provider.id);
4543
+ }
4515
4544
  function providerModelsUrl(id, env) {
4516
4545
  const provider = findProvider(id);
4517
4546
  if (!provider?.local && !provider?.modelsUrl) return void 0;
@@ -4519,26 +4548,59 @@ function providerModelsUrl(id, env) {
4519
4548
  }
4520
4549
 
4521
4550
  // ../daemon/src/core/image-generation-config.ts
4522
- var IMAGE_MODEL_CHOICES = [
4523
- "off",
4524
- "openai-codex:gpt-image-2",
4525
- "openai:gpt-image-2",
4526
- "openrouter:google/gemini-3.1-flash-image",
4527
- "openrouter:openai/gpt-image-2"
4551
+ var IMAGE_ROUTES = [
4552
+ {
4553
+ id: "openai-codex:gpt-image-2",
4554
+ model: "GPT Image 2",
4555
+ provider: "openai-codex",
4556
+ label: "GPT Image 2 \xB7 ChatGPT sign-in",
4557
+ billing: "Uses your ChatGPT subscription"
4558
+ },
4559
+ {
4560
+ id: "openai:gpt-image-2",
4561
+ model: "GPT Image 2",
4562
+ provider: "openai",
4563
+ label: "GPT Image 2 \xB7 OpenAI API key",
4564
+ billing: "Billed per image by OpenAI"
4565
+ },
4566
+ {
4567
+ id: "openrouter:google/gemini-3.1-flash-image",
4568
+ model: "Gemini 3.1 Flash Image",
4569
+ provider: "openrouter",
4570
+ label: "Gemini 3.1 Flash Image \xB7 OpenRouter",
4571
+ billing: "Billed by OpenRouter"
4572
+ },
4573
+ {
4574
+ id: "openrouter:openai/gpt-image-2",
4575
+ model: "GPT Image 2",
4576
+ provider: "openrouter",
4577
+ label: "GPT Image 2 \xB7 OpenRouter",
4578
+ billing: "Billed by OpenRouter"
4579
+ }
4528
4580
  ];
4581
+ var IMAGE_MODEL_CHOICES = ["off", ...IMAGE_ROUTES.map(({ id }) => id)];
4582
+ function isImageModel(provider, model) {
4583
+ return IMAGE_ROUTES.some((route) => route.id === `${provider}:${model}`);
4584
+ }
4585
+ var ROUTE_KEY = { openai: "OPENAI_API_KEY", openrouter: "OPENROUTER_API_KEY" };
4586
+ function imageRouteNeeds(route, env, codexConnected) {
4587
+ if (route.provider === "openai-codex") return codexConnected ? null : "a ChatGPT sign-in";
4588
+ if (env[ROUTE_KEY[route.provider]]?.trim()) return null;
4589
+ return route.provider === "openai" ? "an OpenAI API key" : "an OpenRouter API key";
4590
+ }
4529
4591
  function imageRoute(env, codexConnected) {
4530
4592
  const model = env.BAZILION_IMAGE_MODEL || "off";
4531
4593
  if (model === "off") return { ready: false, reason: "Image generation is off." };
4532
- if (!IMAGE_MODEL_CHOICES.includes(model))
4533
- return { ready: false, reason: `Unknown image model "${model}".` };
4534
- const { providerName, modelId } = parseModelString(model);
4535
- const provider = providerName;
4594
+ const route = IMAGE_ROUTES.find(({ id }) => id === model);
4595
+ if (!route) return { ready: false, reason: `Unknown image model "${model}".` };
4596
+ const { modelId } = parseModelString(model);
4597
+ const provider = route.provider;
4536
4598
  if (provider === "openai-codex")
4537
4599
  return codexConnected ? { ready: true, model, provider, modelId } : {
4538
4600
  ready: false,
4539
- reason: `${model} needs a ChatGPT login: connect ChatGPT on /config or run bazilion auth openai login.`
4601
+ reason: `${model} needs a ChatGPT login: sign in under Setup, Models, or run bazilion auth openai login.`
4540
4602
  };
4541
- const key2 = provider === "openai" ? "OPENAI_API_KEY" : "OPENROUTER_API_KEY";
4603
+ const key2 = ROUTE_KEY[provider];
4542
4604
  const apiKey2 = env[key2]?.trim();
4543
4605
  return apiKey2 ? { ready: true, model, provider, modelId, apiKey: apiKey2 } : { ready: false, reason: `${model} needs ${key2}.` };
4544
4606
  }
@@ -4575,8 +4637,8 @@ var SERVICES = [
4575
4637
  {
4576
4638
  id: "image-generation",
4577
4639
  displayName: "Image generation",
4578
- category: "service",
4579
- team: "Content tools",
4640
+ // Chosen under Images on the Models page; the field stays here for `bazilion config`.
4641
+ category: "function",
4580
4642
  hint: "The image_generate tool: images are saved to Team Results. At most four image_generate calls per turn.",
4581
4643
  fields: [
4582
4644
  {
@@ -4586,12 +4648,9 @@ var SERVICES = [
4586
4648
  options: IMAGE_MODEL_CHOICES,
4587
4649
  optionLabels: {
4588
4650
  off: "Off",
4589
- "openai-codex:gpt-image-2": "GPT Image 2 \xB7 ChatGPT login",
4590
- "openai:gpt-image-2": "GPT Image 2 \xB7 OpenAI API key",
4591
- "openrouter:google/gemini-3.1-flash-image": "Gemini 3.1 Flash Image \xB7 OpenRouter",
4592
- "openrouter:openai/gpt-image-2": "GPT Image 2 \xB7 OpenRouter"
4651
+ ...Object.fromEntries(IMAGE_ROUTES.map((route) => [route.id, route.label]))
4593
4652
  },
4594
- description: "Off by default. API-key routes are billed per image; the ChatGPT login uses your subscription."
4653
+ description: "Off by default. API-key routes are billed per image; the ChatGPT sign-in uses your subscription."
4595
4654
  }
4596
4655
  ]
4597
4656
  },
@@ -4683,7 +4742,7 @@ var SERVICES = [
4683
4742
  displayName: "Browser Automation",
4684
4743
  category: "service",
4685
4744
  team: "Browser",
4686
- hint: 'Each Agent gets its own persistent browser profile (cookies, logins), kept across turns and Team moves and excluded from backups. Reset on the Agent page, or deleting the Agent, removes it. With "Use my running browser" on, Agents work in your own Chrome or Chromium instead.',
4745
+ hint: 'Each Agent gets its own persistent browser profile (cookies, logins), kept across turns and Team moves and excluded from backups. Reset under Browser in the web workspace, or deleting the Agent, removes it. With "Use my running browser" on, Agents work in your own Chrome or Chromium instead.',
4687
4746
  fields: [
4688
4747
  {
4689
4748
  envVar: "BROWSER_ENABLED",
@@ -4791,7 +4850,9 @@ function servicesByCategory(category) {
4791
4850
  }
4792
4851
 
4793
4852
  // ../daemon/src/core/repos/config.ts
4853
+ var PROVIDER_CHECKS_KEY = "PROVIDER_CHECKS";
4794
4854
  var INTERNAL_CONFIG_KEYS = [
4855
+ PROVIDER_CHECKS_KEY,
4795
4856
  // Telegram: polling watermark + derived topic/message ids.
4796
4857
  "TELEGRAM_LAST_UPDATE_ID",
4797
4858
  "TELEGRAM_SERVICE_TOPIC_ID",
@@ -4950,6 +5011,7 @@ var messages_exports = {};
4950
5011
  __export(messages_exports, {
4951
5012
  drainUnreadForAgent: () => drainUnreadForAgent,
4952
5013
  get: () => get10,
5014
+ listForTeam: () => listForTeam,
4953
5015
  listInbox: () => listInbox,
4954
5016
  listRecipientsWithUnread: () => listRecipientsWithUnread,
4955
5017
  markRead: () => markRead,
@@ -5001,6 +5063,14 @@ function listInbox(db, agentId, opts) {
5001
5063
  const sql = opts?.unreadOnly ? "SELECT * FROM messages WHERE to_agent_id = ? AND read_at IS NULL ORDER BY created_at ASC" : "SELECT * FROM messages WHERE to_agent_id = ? ORDER BY created_at ASC";
5002
5064
  return db.raw.query(sql).all(agentId).map(toMessage);
5003
5065
  }
5066
+ function listForTeam(db, teamId, limit) {
5067
+ return db.raw.query(
5068
+ `SELECT m.* FROM messages m
5069
+ WHERE m.from_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5070
+ OR m.to_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5071
+ ORDER BY m.created_at DESC, m.id DESC LIMIT ?`
5072
+ ).all(teamId, teamId, limit).map(toMessage);
5073
+ }
5004
5074
  function markRead(db, id) {
5005
5075
  db.raw.run("UPDATE messages SET read_at = ? WHERE id = ? AND read_at IS NULL", [Date.now(), id]);
5006
5076
  }
@@ -5655,7 +5725,8 @@ function readAuthFile(authFile) {
5655
5725
  };
5656
5726
  }
5657
5727
  function mergeSecretsIntoEnv(db, password, env = process.env) {
5658
- return { ...openConfig(db).getAll(), ...openSecrets(db, password).getAll(), ...env };
5728
+ const { [PROVIDER_CHECKS_KEY]: _checks, ...config } = openConfig(db).getAll();
5729
+ return { ...config, ...openSecrets(db, password).getAll(), ...env };
5659
5730
  }
5660
5731
 
5661
5732
  // ../daemon/src/core/skills/import.ts
@@ -6193,6 +6264,214 @@ async function authMiddleware(c, next) {
6193
6264
  await next();
6194
6265
  }
6195
6266
 
6267
+ // ../daemon/src/lib/activity.ts
6268
+ import { statSync as statSync3 } from "node:fs";
6269
+ import { join as join10 } from "node:path";
6270
+
6271
+ // ../daemon/src/core/repos/conversations.ts
6272
+ var columns = "id, agent_id AS agentId, title, created_at AS createdAt, updated_at AS updatedAt";
6273
+ var ConversationChangedError = class extends DomainError {
6274
+ constructor() {
6275
+ super(409, "The Agent switched to another conversation. Reload before trying again.");
6276
+ }
6277
+ };
6278
+ function selectedId(db, agentId) {
6279
+ return db.raw.query(
6280
+ "SELECT conversation_id AS id FROM agent_conversation_selection WHERE agent_id = ?"
6281
+ ).get(agentId)?.id ?? null;
6282
+ }
6283
+ function get16(db, agentId, id) {
6284
+ return db.raw.query(
6285
+ `SELECT ${columns} FROM agent_conversations WHERE agent_id = ? AND id = ?`
6286
+ ).get(agentId, id);
6287
+ }
6288
+ function list11(db, agentId, limit = 20, offset = 0) {
6289
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
6290
+ throw new DomainError(400, "Invalid conversation pagination");
6291
+ const conversations = db.raw.query(
6292
+ `SELECT ${columns} FROM agent_conversations WHERE agent_id = ? ORDER BY created_at DESC, id LIMIT ? OFFSET ?`
6293
+ ).all(agentId, limit, offset);
6294
+ const total = db.raw.query(
6295
+ "SELECT COUNT(*) AS n FROM agent_conversations WHERE agent_id = ?"
6296
+ ).get(agentId)?.n ?? 0;
6297
+ return { conversations, selectedId: selectedId(db, agentId), total, offset, limit };
6298
+ }
6299
+ function validTitle(value) {
6300
+ if (typeof value !== "string" || !value.trim() || value.length > 200 || Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
6301
+ throw new DomainError(
6302
+ 400,
6303
+ "Conversation title must be 1\u2013200 characters without control characters"
6304
+ );
6305
+ return value.trim();
6306
+ }
6307
+ function create5(db, agentId, id, title) {
6308
+ const displayTitle = title === void 0 ? void 0 : validTitle(title);
6309
+ return db.raw.transaction(() => {
6310
+ const now = Date.now();
6311
+ db.raw.run(
6312
+ `INSERT INTO agent_conversations (id, agent_id, title, created_at, updated_at)
6313
+ VALUES (?, ?, ?, ?, ?)`,
6314
+ [id, agentId, displayTitle ?? `Conversation ${list11(db, agentId, 1).total + 1}`, now, now]
6315
+ );
6316
+ db.raw.run(
6317
+ `INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
6318
+ ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
6319
+ [agentId, id]
6320
+ );
6321
+ const conversation = get16(db, agentId, id);
6322
+ if (!conversation) throw new Error("Conversation not found");
6323
+ return conversation;
6324
+ })();
6325
+ }
6326
+ function select(db, agentId, id) {
6327
+ const conversation = get16(db, agentId, id);
6328
+ if (!conversation) throw new DomainError(404, "Conversation not found");
6329
+ db.raw.run(
6330
+ `INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
6331
+ ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
6332
+ [agentId, id]
6333
+ );
6334
+ return conversation;
6335
+ }
6336
+ function hasDefaultTitle(conversation) {
6337
+ return /^Conversation \d+$/.test(conversation.title);
6338
+ }
6339
+ function rename(db, agentId, id, title) {
6340
+ db.raw.run(
6341
+ "UPDATE agent_conversations SET title = ?, updated_at = ? WHERE agent_id = ? AND id = ?",
6342
+ [validTitle(title), Date.now(), agentId, id]
6343
+ );
6344
+ const conversation = get16(db, agentId, id);
6345
+ if (!conversation) throw new DomainError(404, "Conversation not found");
6346
+ return conversation;
6347
+ }
6348
+
6349
+ // ../daemon/src/core/repos/results.ts
6350
+ import { createHash as createHash3, randomUUID as randomUUID13 } from "node:crypto";
6351
+
6352
+ // ../daemon/src/core/tool-call-id.ts
6353
+ function isToolCallId(value) {
6354
+ return typeof value === "string" && value.length <= 256 && // A true end assertion also rejects a trailing newline (unlike JavaScript '$').
6355
+ /^[A-Za-z0-9._:-]+(?:\|[A-Za-z0-9._:-]+)?$(?![\s\S])/.test(value);
6356
+ }
6357
+
6358
+ // ../daemon/src/core/repos/results.ts
6359
+ var MAX_RESULT_BYTES = 25 * 1024 * 1024;
6360
+ var MAX_RETAINED_RESULT_BYTES = 1024 * 1024 * 1024;
6361
+ var columns2 = `id, team_id AS teamId, agent_id AS agentId, session_id AS sessionId,
6362
+ tool_call_id AS toolCallId, source_index AS sourceIndex, name, mime_type AS mimeType,
6363
+ byte_length AS byteLength, sha256, image_model AS imageModel, created_at AS createdAt`;
6364
+ function get17(db, id) {
6365
+ return db.raw.query(`SELECT ${columns2} FROM agent_results WHERE id = ?`).get(id);
6366
+ }
6367
+ function publish(db, input) {
6368
+ if (!isToolCallId(input.toolCallId)) throw new Error("Invalid result tool call");
6369
+ if (typeof input.name !== "string" || !input.name || input.name.length > 255 || /[/\\]/.test(input.name) || [...input.name].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) || input.name === "." || input.name === "..")
6370
+ throw new Error("Invalid result filename");
6371
+ if (typeof input.mimeType !== "string" || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(input.mimeType))
6372
+ throw new Error("Invalid result media type");
6373
+ if (input.bytes.byteLength > MAX_RESULT_BYTES)
6374
+ throw new Error("Result exceeds the 25 MiB per-file limit");
6375
+ const bytes = Buffer.from(input.bytes);
6376
+ const sourceIndex = input.sourceIndex ?? 0;
6377
+ return db.raw.transaction(() => {
6378
+ const existing = db.raw.query(
6379
+ `SELECT id FROM agent_results
6380
+ WHERE agent_id = ? AND session_id = ? AND tool_call_id = ? AND source_index = ?`
6381
+ ).get(input.agentId, input.sessionId, input.toolCallId, sourceIndex);
6382
+ if (existing) return get17(db, existing.id);
6383
+ const retained = db.raw.query(
6384
+ "SELECT coalesce(sum(byte_length), 0) AS bytes FROM agent_results"
6385
+ ).get()?.bytes ?? 0;
6386
+ if (retained + bytes.byteLength > MAX_RETAINED_RESULT_BYTES)
6387
+ throw new Error(
6388
+ "Result storage is full (1 GiB). Delete saved results before delivering more files."
6389
+ );
6390
+ const id = randomUUID13();
6391
+ db.raw.run(
6392
+ `INSERT INTO agent_results
6393
+ (id, team_id, agent_id, session_id, tool_call_id, source_index, name, mime_type,
6394
+ byte_length, sha256, image_model, created_at, bytes)
6395
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
6396
+ [
6397
+ id,
6398
+ input.teamId,
6399
+ input.agentId,
6400
+ input.sessionId,
6401
+ input.toolCallId,
6402
+ sourceIndex,
6403
+ input.name,
6404
+ input.mimeType,
6405
+ bytes.byteLength,
6406
+ createHash3("sha256").update(bytes).digest("hex"),
6407
+ input.imageModel ?? null,
6408
+ Date.now(),
6409
+ bytes
6410
+ ]
6411
+ );
6412
+ return get17(db, id);
6413
+ })();
6414
+ }
6415
+ function whereClause(filter) {
6416
+ const where = [];
6417
+ const params = [];
6418
+ for (const [column, value] of [
6419
+ ["team_id", filter.teamId],
6420
+ ["agent_id", filter.agentId],
6421
+ ["session_id", filter.sessionId]
6422
+ ]) {
6423
+ if (value === void 0) continue;
6424
+ where.push(`${column} = ?`);
6425
+ params.push(value);
6426
+ }
6427
+ return { sql: where.length ? `WHERE ${where.join(" AND ")}` : "", params };
6428
+ }
6429
+ function list12(db, opts = {}) {
6430
+ const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 50)));
6431
+ const offset = Math.max(0, Math.floor(opts.offset ?? 0));
6432
+ const { sql: filter, params } = whereClause(opts);
6433
+ const total = db.raw.query(`SELECT count(*) AS total FROM agent_results ${filter}`).get(...params)?.total ?? 0;
6434
+ const results = db.raw.query(
6435
+ `SELECT ${columns2} FROM agent_results ${filter} ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`
6436
+ ).all(...params, limit, offset);
6437
+ return { results, total, limit, offset };
6438
+ }
6439
+ function read(db, id) {
6440
+ const row = db.raw.query(
6441
+ "SELECT bytes, sha256 FROM agent_results WHERE id = ?"
6442
+ ).get(id);
6443
+ if (!row) throw new Error("Result not found");
6444
+ const bytes = Buffer.from(row.bytes);
6445
+ if (createHash3("sha256").update(bytes).digest("hex") !== row.sha256)
6446
+ throw new Error("Saved file failed its integrity check");
6447
+ return bytes;
6448
+ }
6449
+ function summaryByAgent(db) {
6450
+ const rows = db.raw.query(
6451
+ `SELECT agent_id AS agentId, count(*) AS count, max(created_at) AS lastAt
6452
+ FROM agent_results GROUP BY agent_id`
6453
+ ).all();
6454
+ return new Map(rows.map((row) => [row.agentId, { count: row.count, lastAt: row.lastAt }]));
6455
+ }
6456
+ function listForArchive(db, filter, maxBytes) {
6457
+ const { sql, params } = whereClause(filter);
6458
+ const all = db.raw.query(
6459
+ // Oldest first; files saved in the same millisecond keep the order they were saved in.
6460
+ `SELECT ${columns2} FROM agent_results ${sql} ORDER BY created_at, rowid`
6461
+ ).all(...params);
6462
+ const results = [];
6463
+ let bytes = 0;
6464
+ for (const result of all) {
6465
+ if (bytes + result.byteLength > maxBytes) return { results, truncated: true };
6466
+ bytes += result.byteLength;
6467
+ results.push(result);
6468
+ }
6469
+ return { results, truncated: false };
6470
+ }
6471
+ function remove10(db, id) {
6472
+ return db.raw.run("DELETE FROM agent_results WHERE id = ?", [id]).changes === 1;
6473
+ }
6474
+
6196
6475
  // ../daemon/src/lib/agent-cancel.ts
6197
6476
  var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("bazilion.agent-cancel.registry");
6198
6477
  var AgentTurnActiveError = class extends DomainError {
@@ -6224,7 +6503,7 @@ function unregisterAgent(agentId) {
6224
6503
  if (!state2.active.delete(agentId)) return;
6225
6504
  const waiters = state2.idleWaiters.get(agentId);
6226
6505
  state2.idleWaiters.delete(agentId);
6227
- for (const resolve8 of waiters ?? []) resolve8();
6506
+ for (const resolve9 of waiters ?? []) resolve9();
6228
6507
  }
6229
6508
  function cancelAgent(agentId) {
6230
6509
  const { active } = registry();
@@ -6252,9 +6531,9 @@ function stopAgentTurns() {
6252
6531
  function waitForAgentIdle(agentId) {
6253
6532
  const state2 = registry();
6254
6533
  if (!state2.active.has(agentId)) return Promise.resolve();
6255
- return new Promise((resolve8) => {
6534
+ return new Promise((resolve9) => {
6256
6535
  const waiters = state2.idleWaiters.get(agentId) ?? /* @__PURE__ */ new Set();
6257
- waiters.add(resolve8);
6536
+ waiters.add(resolve9);
6258
6537
  state2.idleWaiters.set(agentId, waiters);
6259
6538
  });
6260
6539
  }
@@ -6273,56 +6552,273 @@ function isShuttingDownError(error) {
6273
6552
  return error instanceof Error && error.message === SHUTTING_DOWN;
6274
6553
  }
6275
6554
 
6276
- // ../daemon/src/lib/browser/config.ts
6277
- var FALSEY = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
6278
- function envBool(value, fallback) {
6279
- if (value === void 0 || value.trim() === "") return fallback;
6280
- return !FALSEY.has(value.trim().toLowerCase());
6281
- }
6282
- function envInt(value, fallback) {
6283
- const n = Number.parseInt(value ?? "", 10);
6284
- return Number.isFinite(n) && n > 0 ? n : fallback;
6285
- }
6286
- function isBrowserEnabled(env) {
6287
- return envBool(env.BROWSER_ENABLED, true);
6288
- }
6289
- function resolveBrowserConfig(env) {
6290
- const executablePath = env.BROWSER_EXECUTABLE_PATH?.trim();
6291
- const attachUrl = env.BROWSER_ATTACH_URL?.trim();
6292
- return {
6293
- headless: envBool(env.BROWSER_HEADLESS, true),
6294
- ...executablePath ? { executablePath } : {},
6295
- allowPrivate: envBool(env.BROWSER_ALLOW_PRIVATE_NETWORK, false),
6296
- attach: envBool(env.BROWSER_ATTACH, false),
6297
- ...attachUrl ? { attachUrl } : {},
6298
- idleMs: envInt(env.BROWSER_IDLE_MS, 9e5),
6299
- maxSessions: envInt(env.BROWSER_MAX_SESSIONS, 4)
6300
- };
6301
- }
6302
-
6303
- // ../daemon/src/routes/agent-browser.ts
6304
- init_pool2();
6305
-
6306
- // ../daemon/src/routes/http.ts
6307
- import { Hono } from "hono";
6308
- import { HTTPException } from "hono/http-exception";
6309
- function newRouter() {
6310
- return new Hono().onError(onRouteError);
6311
- }
6312
- function onRouteError(error, c) {
6313
- if (error instanceof HTTPException) return error.getResponse();
6314
- if (error instanceof DomainError) {
6315
- return c.json(
6316
- { error: error.message, ...error.code ? { code: error.code } : {} },
6317
- error.status
6318
- );
6555
+ // ../daemon/src/lib/bash-approval.ts
6556
+ var DEFAULT_TIMEOUT_MS = 12e4;
6557
+ var CommandApprovalRegistry = class {
6558
+ #pending = /* @__PURE__ */ new Map();
6559
+ #timeoutMs;
6560
+ constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
6561
+ this.#timeoutMs = timeoutMs;
6319
6562
  }
6320
- console.error(error);
6321
- return c.json({ error: error.message || "Internal error" }, 500);
6322
- }
6323
- function routeAgent(c, param = "id") {
6324
- const ref = c.req.param(param) ?? "";
6325
- const { db } = getCtx();
6563
+ begin(input, signal) {
6564
+ const approval = {
6565
+ id: input.id,
6566
+ turnId: input.turnId,
6567
+ toolCallId: input.toolCallId,
6568
+ agentId: input.agentId,
6569
+ teamId: input.teamId,
6570
+ command: input.command,
6571
+ risks: input.risks,
6572
+ status: "pending",
6573
+ expiresAt: Date.now() + this.#timeoutMs
6574
+ };
6575
+ const immediate = input.mode === "auto_deny" ? "auto_denied" : signal?.aborted ? "cancelled" : void 0;
6576
+ if (immediate) {
6577
+ const settled2 = logged({ ...approval, status: immediate });
6578
+ return { approval: settled2, settled: Promise.resolve(settled2) };
6579
+ }
6580
+ if (this.#pending.has(approval.id))
6581
+ throw new Error(`duplicate shell approval id: ${approval.id}`);
6582
+ const settled = new Promise((resolve9) => {
6583
+ const settle = (status2) => {
6584
+ this.#pending.delete(approval.id);
6585
+ clearTimeout(timer);
6586
+ signal?.removeEventListener("abort", onAbort);
6587
+ const result = logged({ ...approval, status: status2 });
6588
+ resolve9(result);
6589
+ return result;
6590
+ };
6591
+ const onAbort = () => settle("cancelled");
6592
+ const timer = setTimeout(() => settle("expired"), this.#timeoutMs);
6593
+ timer.unref();
6594
+ signal?.addEventListener("abort", onAbort, { once: true });
6595
+ this.#pending.set(approval.id, { approval, settle });
6596
+ });
6597
+ return { approval, settled };
6598
+ }
6599
+ list(agentId) {
6600
+ return Array.from(this.#pending.values(), (entry) => entry.approval).filter((approval) => agentId === void 0 || approval.agentId === agentId).sort((a, b) => a.expiresAt - b.expiresAt || a.id.localeCompare(b.id));
6601
+ }
6602
+ /** Answer a pending approval; undefined when there is none (unknown, or already settled). */
6603
+ respond(id, decision) {
6604
+ return this.#pending.get(id)?.settle(decision === "allow" ? "allowed" : "denied");
6605
+ }
6606
+ };
6607
+ function logged(approval) {
6608
+ console.info("bash approval decision", {
6609
+ approvalId: approval.id,
6610
+ agentId: approval.agentId,
6611
+ teamId: approval.teamId,
6612
+ riskCodes: [...new Set(approval.risks.map((risk) => risk.code))],
6613
+ status: approval.status
6614
+ });
6615
+ return approval;
6616
+ }
6617
+ var commandApprovalRegistry = new CommandApprovalRegistry();
6618
+
6619
+ // ../daemon/src/lib/questions.ts
6620
+ import { randomUUID as randomUUID14 } from "node:crypto";
6621
+ var QUESTION_WAIT_MS = 5 * 6e4;
6622
+ var QUESTION_LIMITS = Object.freeze({
6623
+ promptChars: 2e3,
6624
+ labelChars: 120,
6625
+ descriptionChars: 500,
6626
+ answerChars: 4096
6627
+ });
6628
+ function text(value, limit, what) {
6629
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${what} must be non-empty text`);
6630
+ if (value.length > limit) throw new Error(`${what} is longer than ${limit} characters`);
6631
+ return value;
6632
+ }
6633
+ function parseQuestionInput(value) {
6634
+ const input = value ?? {};
6635
+ const prompt = text(input.prompt, QUESTION_LIMITS.promptChars, "The prompt");
6636
+ if (!Array.isArray(input.choices) || input.choices.length < 2 || input.choices.length > 4)
6637
+ throw new Error("ask_user needs 2 to 4 choices");
6638
+ const labels = /* @__PURE__ */ new Set();
6639
+ const choices = input.choices.map((raw, index) => {
6640
+ const choice = raw ?? {};
6641
+ const label = text(choice.label, QUESTION_LIMITS.labelChars, `Choice ${index + 1} label`);
6642
+ const key2 = label.normalize("NFKC").trim().toLowerCase();
6643
+ if (labels.has(key2)) throw new Error("Choice labels must be distinct");
6644
+ labels.add(key2);
6645
+ if (choice.description === void 0) return { label };
6646
+ const description = text(
6647
+ choice.description,
6648
+ QUESTION_LIMITS.descriptionChars,
6649
+ `Choice ${index + 1} description`
6650
+ );
6651
+ return { label, description };
6652
+ });
6653
+ const recommended = input.recommendedIndex;
6654
+ if (recommended === void 0) return { prompt, choices };
6655
+ if (typeof recommended !== "number" || !Number.isInteger(recommended))
6656
+ throw new Error("recommendedIndex must be a choice index");
6657
+ if (recommended < 0 || recommended >= choices.length)
6658
+ throw new Error("recommendedIndex must be a choice index");
6659
+ return { prompt, choices, recommendedIndex: recommended };
6660
+ }
6661
+ function parseQuestionAnswer(value, question) {
6662
+ const answer = value ?? {};
6663
+ if (answer.kind === "skip") return { kind: "skip" };
6664
+ if (answer.kind === "text")
6665
+ return { kind: "text", text: text(answer.text, QUESTION_LIMITS.answerChars, "The answer") };
6666
+ const index = answer.index;
6667
+ if (answer.kind === "choice" && typeof index === "number" && Number.isInteger(index)) {
6668
+ if (index >= 0 && index < question.choices.length) return { kind: "choice", index };
6669
+ throw new Error(
6670
+ `Choice ${index + 1} does not exist; this question has ${question.choices.length} choices`
6671
+ );
6672
+ }
6673
+ throw new Error("An answer is a choice index, text or skip");
6674
+ }
6675
+ var QuestionRegistry = class {
6676
+ #pending = /* @__PURE__ */ new Map();
6677
+ #waitMs;
6678
+ constructor(waitMs = QUESTION_WAIT_MS) {
6679
+ this.#waitMs = waitMs;
6680
+ }
6681
+ /** Register a question. `result` settles on the first answer, the timeout or `signal`. */
6682
+ ask(context, input, signal) {
6683
+ const prompt = parseQuestionInput(input);
6684
+ if (this.list(context.agentId).length > 0)
6685
+ throw new Error("Another question from this Agent is still waiting for an answer");
6686
+ if (signal?.aborted) throw new Error("The turn has ended");
6687
+ const now = Date.now();
6688
+ const question = {
6689
+ id: randomUUID14(),
6690
+ agentId: context.agentId,
6691
+ conversationId: context.conversationId,
6692
+ question: prompt,
6693
+ createdAt: now,
6694
+ expiresAt: now + this.#waitMs
6695
+ };
6696
+ const { promise, resolve: resolve9 } = Promise.withResolvers();
6697
+ const cancel3 = () => finish3({ kind: "no_answer", reason: "cancelled" });
6698
+ const timer = setTimeout(() => finish3({ kind: "no_answer", reason: "expired" }), this.#waitMs);
6699
+ timer.unref();
6700
+ const finish3 = (outcome) => {
6701
+ if (!this.#pending.delete(question.id)) return false;
6702
+ clearTimeout(timer);
6703
+ signal?.removeEventListener("abort", cancel3);
6704
+ resolve9({ questionId: question.id, question: prompt, ...outcome });
6705
+ return true;
6706
+ };
6707
+ this.#pending.set(question.id, { question, result: promise, finish: finish3 });
6708
+ signal?.addEventListener("abort", cancel3, { once: true });
6709
+ return { question, result: promise };
6710
+ }
6711
+ list(agentId) {
6712
+ return [...this.#pending.values()].map((entry) => entry.question).filter((question) => agentId === void 0 || question.agentId === agentId);
6713
+ }
6714
+ get(id) {
6715
+ return this.#pending.get(id)?.question;
6716
+ }
6717
+ /** The outcome of a waiting question; undefined once it has settled. */
6718
+ settled(id) {
6719
+ return this.#pending.get(id)?.result;
6720
+ }
6721
+ /** Answer a waiting question. False when it is no longer waiting; throws on an invalid answer. */
6722
+ answer(agentId, id, value) {
6723
+ const entry = this.#pending.get(id);
6724
+ if (!entry || entry.question.agentId !== agentId) return false;
6725
+ const answer = parseQuestionAnswer(value, entry.question.question);
6726
+ return entry.finish(
6727
+ answer.kind === "skip" ? { kind: "no_answer", reason: "skipped" } : { kind: "answer", answer }
6728
+ );
6729
+ }
6730
+ };
6731
+ var questionRegistry = new QuestionRegistry();
6732
+
6733
+ // ../daemon/src/lib/activity.ts
6734
+ var TARGET_CHARS = 160;
6735
+ var TARGET_KEYS = ["path", "command", "url", "query", "to", "key", "file"];
6736
+ var STEPS_KEY = /* @__PURE__ */ Symbol.for("bazilion.activity.steps");
6737
+ function steps() {
6738
+ const holder = globalThis;
6739
+ let map = holder[STEPS_KEY];
6740
+ if (!map) {
6741
+ map = /* @__PURE__ */ new Map();
6742
+ holder[STEPS_KEY] = map;
6743
+ }
6744
+ return map;
6745
+ }
6746
+ function stepTarget(rawArguments) {
6747
+ let args;
6748
+ try {
6749
+ args = JSON.parse(rawArguments);
6750
+ } catch {
6751
+ return null;
6752
+ }
6753
+ if (!args || typeof args !== "object") return null;
6754
+ for (const key2 of TARGET_KEYS) {
6755
+ const value = args[key2];
6756
+ if (typeof value === "string" && value.trim()) {
6757
+ const line = value.trim().split("\n")[0] ?? "";
6758
+ return line.length > TARGET_CHARS ? `${line.slice(0, TARGET_CHARS - 1)}\u2026` : line;
6759
+ }
6760
+ }
6761
+ return null;
6762
+ }
6763
+ function noteTurnFrame(agentId, frame) {
6764
+ if (frame.kind !== "event" || frame.event.type !== "tool_call") return;
6765
+ steps().set(agentId, { tool: frame.event.name, target: stepTarget(frame.event.arguments) });
6766
+ }
6767
+ function noteTurnEnd(agentId) {
6768
+ steps().delete(agentId);
6769
+ }
6770
+ function lastActivityAt(db, paths, agentId) {
6771
+ const conversationId = selectedId(db, agentId);
6772
+ if (!conversationId) return null;
6773
+ try {
6774
+ const file = join10(paths.agentDir(agentId), "sessions", `${conversationId}.jsonl`);
6775
+ return Math.floor(statSync3(file).mtimeMs);
6776
+ } catch {
6777
+ return null;
6778
+ }
6779
+ }
6780
+ function readActivity(db, paths) {
6781
+ const saved = summaryByAgent(db);
6782
+ const questions = questionRegistry.list();
6783
+ const approvals = commandApprovalRegistry.list();
6784
+ return list(db).map((agent) => {
6785
+ const working = isActiveAgent(agent.id);
6786
+ const produced = saved.get(agent.id);
6787
+ return {
6788
+ agentId: agent.id,
6789
+ teamId: agent.teamId,
6790
+ working,
6791
+ step: working ? steps().get(agent.id) ?? null : null,
6792
+ questions: questions.filter((question) => question.agentId === agent.id).length,
6793
+ approvals: approvals.filter((approval) => approval.agentId === agent.id).length,
6794
+ queuePaused: isPaused(db, agent.id) && pendingCount(db, agent.id) > 0,
6795
+ lastActivityAt: lastActivityAt(db, paths, agent.id),
6796
+ results: produced?.count ?? 0,
6797
+ lastResultAt: produced?.lastAt ?? null
6798
+ };
6799
+ });
6800
+ }
6801
+
6802
+ // ../daemon/src/routes/http.ts
6803
+ import { Hono } from "hono";
6804
+ import { HTTPException } from "hono/http-exception";
6805
+ function newRouter() {
6806
+ return new Hono().onError(onRouteError);
6807
+ }
6808
+ function onRouteError(error, c) {
6809
+ if (error instanceof HTTPException) return error.getResponse();
6810
+ if (error instanceof DomainError) {
6811
+ return c.json(
6812
+ { error: error.message, ...error.code ? { code: error.code } : {} },
6813
+ error.status
6814
+ );
6815
+ }
6816
+ console.error(error);
6817
+ return c.json({ error: error.message || "Internal error" }, 500);
6818
+ }
6819
+ function routeAgent(c, param = "id") {
6820
+ const ref = c.req.param(param) ?? "";
6821
+ const { db } = getCtx();
6326
6822
  const agent = get(db, ref);
6327
6823
  if (agent) return agent;
6328
6824
  const named = db.raw.query("SELECT id FROM agents WHERE name = ? ORDER BY created_at").all(ref);
@@ -6344,7 +6840,42 @@ async function jsonBody(c) {
6344
6840
  return body !== null && typeof body === "object" && !Array.isArray(body) ? body : null;
6345
6841
  }
6346
6842
 
6843
+ // ../daemon/src/routes/activity.ts
6844
+ var activityRouter = newRouter();
6845
+ activityRouter.get("/", (c) => {
6846
+ const { db, paths } = getCtx();
6847
+ return c.json({ agents: readActivity(db, paths) });
6848
+ });
6849
+
6850
+ // ../daemon/src/lib/browser/config.ts
6851
+ var FALSEY = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
6852
+ function envBool(value, fallback) {
6853
+ if (value === void 0 || value.trim() === "") return fallback;
6854
+ return !FALSEY.has(value.trim().toLowerCase());
6855
+ }
6856
+ function envInt(value, fallback) {
6857
+ const n = Number.parseInt(value ?? "", 10);
6858
+ return Number.isFinite(n) && n > 0 ? n : fallback;
6859
+ }
6860
+ function isBrowserEnabled(env) {
6861
+ return envBool(env.BROWSER_ENABLED, true);
6862
+ }
6863
+ function resolveBrowserConfig(env) {
6864
+ const executablePath = env.BROWSER_EXECUTABLE_PATH?.trim();
6865
+ const attachUrl = env.BROWSER_ATTACH_URL?.trim();
6866
+ return {
6867
+ headless: envBool(env.BROWSER_HEADLESS, true),
6868
+ ...executablePath ? { executablePath } : {},
6869
+ allowPrivate: envBool(env.BROWSER_ALLOW_PRIVATE_NETWORK, false),
6870
+ attach: envBool(env.BROWSER_ATTACH, false),
6871
+ ...attachUrl ? { attachUrl } : {},
6872
+ idleMs: envInt(env.BROWSER_IDLE_MS, 9e5),
6873
+ maxSessions: envInt(env.BROWSER_MAX_SESSIONS, 4)
6874
+ };
6875
+ }
6876
+
6347
6877
  // ../daemon/src/routes/agent-browser.ts
6878
+ init_pool2();
6348
6879
  var agentBrowserRouter = newRouter();
6349
6880
  agentBrowserRouter.get("/:id/browser", (c) => {
6350
6881
  const { db, paths, authToken } = getCtx();
@@ -6366,72 +6897,7 @@ agentBrowserRouter.delete("/:id/browser/profile", async (c) => {
6366
6897
  // ../daemon/src/routes/agent-chat.ts
6367
6898
  import { randomUUID as randomUUID19 } from "node:crypto";
6368
6899
  import { existsSync as existsSync16, readFileSync as readFileSync10 } from "node:fs";
6369
- import { join as join26 } from "node:path";
6370
-
6371
- // ../daemon/src/core/repos/conversations.ts
6372
- var columns = "id, agent_id AS agentId, title, created_at AS createdAt, updated_at AS updatedAt";
6373
- var ConversationChangedError = class extends DomainError {
6374
- constructor() {
6375
- super(409, "The Agent switched to another conversation. Reload before trying again.");
6376
- }
6377
- };
6378
- function selectedId(db, agentId) {
6379
- return db.raw.query(
6380
- "SELECT conversation_id AS id FROM agent_conversation_selection WHERE agent_id = ?"
6381
- ).get(agentId)?.id ?? null;
6382
- }
6383
- function get16(db, agentId, id) {
6384
- return db.raw.query(
6385
- `SELECT ${columns} FROM agent_conversations WHERE agent_id = ? AND id = ?`
6386
- ).get(agentId, id);
6387
- }
6388
- function list11(db, agentId, limit = 20, offset = 0) {
6389
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
6390
- throw new DomainError(400, "Invalid conversation pagination");
6391
- const conversations = db.raw.query(
6392
- `SELECT ${columns} FROM agent_conversations WHERE agent_id = ? ORDER BY created_at DESC, id LIMIT ? OFFSET ?`
6393
- ).all(agentId, limit, offset);
6394
- const total = db.raw.query(
6395
- "SELECT COUNT(*) AS n FROM agent_conversations WHERE agent_id = ?"
6396
- ).get(agentId)?.n ?? 0;
6397
- return { conversations, selectedId: selectedId(db, agentId), total, offset, limit };
6398
- }
6399
- function validTitle(value) {
6400
- if (typeof value !== "string" || !value.trim() || value.length > 200 || Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
6401
- throw new DomainError(
6402
- 400,
6403
- "Conversation title must be 1\u2013200 characters without control characters"
6404
- );
6405
- return value.trim();
6406
- }
6407
- function create5(db, agentId, id, title) {
6408
- const displayTitle = title === void 0 ? void 0 : validTitle(title);
6409
- return db.raw.transaction(() => {
6410
- const now = Date.now();
6411
- db.raw.run(
6412
- `INSERT INTO agent_conversations (id, agent_id, title, created_at, updated_at)
6413
- VALUES (?, ?, ?, ?, ?)`,
6414
- [id, agentId, displayTitle ?? `Conversation ${list11(db, agentId, 1).total + 1}`, now, now]
6415
- );
6416
- db.raw.run(
6417
- `INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
6418
- ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
6419
- [agentId, id]
6420
- );
6421
- const conversation = get16(db, agentId, id);
6422
- if (!conversation) throw new Error("Conversation not found");
6423
- return conversation;
6424
- })();
6425
- }
6426
- function rename(db, agentId, id, title) {
6427
- db.raw.run(
6428
- "UPDATE agent_conversations SET title = ?, updated_at = ? WHERE agent_id = ? AND id = ?",
6429
- [validTitle(title), Date.now(), agentId, id]
6430
- );
6431
- const conversation = get16(db, agentId, id);
6432
- if (!conversation) throw new DomainError(404, "Conversation not found");
6433
- return conversation;
6434
- }
6900
+ import { join as join27 } from "node:path";
6435
6901
 
6436
6902
  // ../daemon/src/runtime/auth/openai-codex.ts
6437
6903
  import { openaiCodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
@@ -6563,7 +7029,7 @@ import {
6563
7029
  rmSync as rmSync9,
6564
7030
  writeFileSync as writeFileSync5
6565
7031
  } from "node:fs";
6566
- import { dirname as dirname4, isAbsolute as isAbsolute2, join as join14, relative, resolve as resolve4, sep as sep2 } from "node:path";
7032
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join15, relative, resolve as resolve4, sep as sep2 } from "node:path";
6567
7033
  import { createStore, extractSnippet } from "@tobilu/qmd";
6568
7034
 
6569
7035
  // ../daemon/src/lib/native-module-error.ts
@@ -6609,7 +7075,7 @@ function getStore(dir, storeFactory) {
6609
7075
  if (!p) {
6610
7076
  p = withNativeModuleErrorBoundary(
6611
7077
  () => storeFactory({
6612
- dbPath: join14(dir, INDEX_FILENAME),
7078
+ dbPath: join15(dir, INDEX_FILENAME),
6613
7079
  config: {
6614
7080
  collections: {
6615
7081
  [COLLECTION_NAME]: { path: dir, pattern: PATTERN }
@@ -6687,7 +7153,7 @@ function inspectSafePath(root, path) {
6687
7153
  let current2 = root;
6688
7154
  const components = rel.split(sep2).filter(Boolean);
6689
7155
  for (let index = 0; index < components.length; index += 1) {
6690
- current2 = join14(current2, components[index]);
7156
+ current2 = join15(current2, components[index]);
6691
7157
  const info = lstatIfPresent(current2);
6692
7158
  if (!info) return void 0;
6693
7159
  if (info.isSymbolicLink()) {
@@ -6706,7 +7172,7 @@ function ensureSafeParentDirectories(root, path) {
6706
7172
  const rel = relative(root, parent);
6707
7173
  let current2 = root;
6708
7174
  for (const component2 of rel.split(sep2).filter(Boolean)) {
6709
- current2 = join14(current2, component2);
7175
+ current2 = join15(current2, component2);
6710
7176
  let info = lstatIfPresent(current2);
6711
7177
  if (!info) {
6712
7178
  mkdirSync6(current2);
@@ -6772,7 +7238,7 @@ function writeSafeFile(root, path, content) {
6772
7238
  function assertSafeTree(root, dir = root) {
6773
7239
  assertContained(root, realpathSync2(dir));
6774
7240
  for (const entry of readdirSync4(dir, { withFileTypes: true })) {
6775
- const full = join14(dir, entry.name);
7241
+ const full = join15(dir, entry.name);
6776
7242
  const info = lstatSync(full);
6777
7243
  if (info.isSymbolicLink()) {
6778
7244
  throw unsafeMemoryPath(full, "symbolic links are not allowed in memory storage");
@@ -6786,7 +7252,7 @@ function assertSafeTree(root, dir = root) {
6786
7252
  }
6787
7253
  function walkMd(root, dir, prefix, out) {
6788
7254
  for (const entry of readdirSync4(dir, { withFileTypes: true })) {
6789
- const full = join14(dir, entry.name);
7255
+ const full = join15(dir, entry.name);
6790
7256
  const info = lstatSync(full);
6791
7257
  if (info.isSymbolicLink()) {
6792
7258
  throw unsafeMemoryPath(full, "symbolic links are not allowed in memory storage");
@@ -6893,17 +7359,17 @@ function qmdBackend(root, options = {}) {
6893
7359
  // ../daemon/src/runtime/worker/runtime.ts
6894
7360
  import { mkdirSync as mkdirSync7, mkdtempSync as mkdtempSync2, rmSync as rmSync10 } from "node:fs";
6895
7361
  import { tmpdir as tmpdir2 } from "node:os";
6896
- import { join as join15 } from "node:path";
7362
+ import { join as join16 } from "node:path";
6897
7363
  var REDACTED_VALUE = "[REDACTED]";
6898
7364
  function createMinimalWorkerScratch(parentDir = tmpdir2()) {
6899
- const root = mkdtempSync2(join15(parentDir, "bazilion-worker-"));
7365
+ const root = mkdtempSync2(join16(parentDir, "bazilion-worker-"));
6900
7366
  const scratch = {
6901
7367
  root,
6902
- homeDir: join15(root, "home"),
6903
- tempDir: join15(root, "tmp"),
6904
- piAgentDir: join15(root, "pi"),
6905
- reviewCwd: join15(root, "review-work"),
6906
- reviewSessionDir: join15(root, "review-session")
7368
+ homeDir: join16(root, "home"),
7369
+ tempDir: join16(root, "tmp"),
7370
+ piAgentDir: join16(root, "pi"),
7371
+ reviewCwd: join16(root, "review-work"),
7372
+ reviewSessionDir: join16(root, "review-session")
6907
7373
  };
6908
7374
  try {
6909
7375
  for (const path of Object.values(scratch).slice(1)) {
@@ -7121,8 +7587,8 @@ function extractResultReferences(value) {
7121
7587
  }
7122
7588
 
7123
7589
  // ../daemon/src/runtime/pi/session.ts
7124
- import { existsSync as existsSync14, mkdirSync as mkdirSync10, statSync as statSync6, writeFileSync as writeFileSync7 } from "node:fs";
7125
- import { basename as basename5, join as join21 } from "node:path";
7590
+ import { existsSync as existsSync14, mkdirSync as mkdirSync10, statSync as statSync7, writeFileSync as writeFileSync7 } from "node:fs";
7591
+ import { basename as basename5, join as join22 } from "node:path";
7126
7592
  import {
7127
7593
  buildSessionContext,
7128
7594
  createAgentSession,
@@ -7226,7 +7692,7 @@ async function testProviderModel(spec) {
7226
7692
 
7227
7693
  // ../daemon/src/runtime/session/prompt.ts
7228
7694
  import { existsSync as existsSync11, readdirSync as readdirSync5 } from "node:fs";
7229
- import { join as join16 } from "node:path";
7695
+ import { join as join17 } from "node:path";
7230
7696
 
7231
7697
  // ../daemon/src/runtime/safe-files.ts
7232
7698
  import {
@@ -7240,7 +7706,7 @@ import {
7240
7706
  readlinkSync as readlinkSync2,
7241
7707
  readSync,
7242
7708
  realpathSync as realpathSync3,
7243
- statSync as statSync4
7709
+ statSync as statSync5
7244
7710
  } from "node:fs";
7245
7711
  import { dirname as dirname5, isAbsolute as isAbsolute3, relative as relative2, resolve as resolve5, sep as sep3 } from "node:path";
7246
7712
  var ContainedFileError = class extends Error {
@@ -7254,7 +7720,7 @@ var ContainedFileError = class extends Error {
7254
7720
  function readContainedFile(path, realRoot, maxBytes) {
7255
7721
  const real = realpathSync3(path);
7256
7722
  if (!isContained2(realRoot, real)) throw new ContainedFileError("outside");
7257
- const checked = statSync4(real);
7723
+ const checked = statSync5(real);
7258
7724
  if (!checked.isFile()) throw new ContainedFileError("not_file");
7259
7725
  if (checked.size > maxBytes) throw new ContainedFileError("too_large");
7260
7726
  const fd = openSync2(real, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
@@ -7372,9 +7838,9 @@ function loadPromptSkills(skillsDir, attachedNames) {
7372
7838
  const discovered = readdirSync5(skillsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && attached.has(entry.name)).sort((a, b) => a.name.localeCompare(b.name));
7373
7839
  const loaded = [];
7374
7840
  for (const entry of discovered) {
7375
- const hostDir = join16(skillsDir, entry.name);
7841
+ const hostDir = join17(skillsDir, entry.name);
7376
7842
  try {
7377
- const parsed = parseSkillContent(readRegularFileNoFollow(join16(hostDir, "SKILL.md")));
7843
+ const parsed = parseSkillContent(readRegularFileNoFollow(join17(hostDir, "SKILL.md")));
7378
7844
  const safeLabel = entry.name.replace(/[^A-Za-z0-9._-]/g, "_") || "skill";
7379
7845
  loaded.push({
7380
7846
  name: entry.name,
@@ -7393,7 +7859,7 @@ function loadHomeDocuments(agentDir2) {
7393
7859
  const root = resolveRealDirectory(agentDir2);
7394
7860
  const read2 = (file) => {
7395
7861
  try {
7396
- return readRegularFileNoFollow(join16(root, file));
7862
+ return readRegularFileNoFollow(join17(root, file));
7397
7863
  } catch (error) {
7398
7864
  if (error.code === "ENOENT") return null;
7399
7865
  throw new Error(`private Agent home is unsafe at ${file}`);
@@ -7563,7 +8029,7 @@ function boundReviewedLessons(lessons, maxCharacters = 8e3) {
7563
8029
 
7564
8030
  // ../daemon/src/runtime/shell/docker.ts
7565
8031
  import { spawn as spawn3 } from "node:child_process";
7566
- import { createHash as createHash3, randomUUID as randomUUID13 } from "node:crypto";
8032
+ import { createHash as createHash4, randomUUID as randomUUID15 } from "node:crypto";
7567
8033
  var CONTAINER_WORKSPACE = "/workspace";
7568
8034
  var DOCKER_CALL_TIMEOUT_MS = 5e3;
7569
8035
  var MAX_TIMER_MS = 2147483647;
@@ -7626,9 +8092,9 @@ function createDockerBashOperations(sandbox) {
7626
8092
  throw new Error("Invalid timeout: must be a positive number of seconds");
7627
8093
  if (signal?.aborted) throw new Error("aborted");
7628
8094
  const current2 = sandbox();
7629
- const name = `${current2.containerPrefix}${randomUUID13().replaceAll("-", "").slice(0, 12)}`;
8095
+ const name = `${current2.containerPrefix}${randomUUID15().replaceAll("-", "").slice(0, 12)}`;
7630
8096
  const args = dockerRunArgs(current2, name, command);
7631
- return new Promise((resolve8, reject2) => {
8097
+ return new Promise((resolve9, reject2) => {
7632
8098
  const child = spawn3("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
7633
8099
  let stopped;
7634
8100
  let settled = false;
@@ -7651,7 +8117,7 @@ function createDockerBashOperations(sandbox) {
7651
8117
  await removeContainers([name]);
7652
8118
  reject2(stopped);
7653
8119
  } else if (error) reject2(dockerError(error));
7654
- else resolve8({ exitCode });
8120
+ else resolve9({ exitCode });
7655
8121
  };
7656
8122
  child.stdout.on("data", onData);
7657
8123
  child.stderr.on("data", onData);
@@ -7670,10 +8136,10 @@ async function checkDockerImage(image) {
7670
8136
  }
7671
8137
  }
7672
8138
  function homeContainerPrefix(home) {
7673
- return `bazilion-${createHash3("sha256").update(home).digest("hex").slice(0, 12)}-`;
8139
+ return `bazilion-${createHash4("sha256").update(home).digest("hex").slice(0, 12)}-`;
7674
8140
  }
7675
8141
  function turnContainerPrefix(home) {
7676
- return `${homeContainerPrefix(home)}${randomUUID13().replaceAll("-", "").slice(0, 12)}-`;
8142
+ return `${homeContainerPrefix(home)}${randomUUID15().replaceAll("-", "").slice(0, 12)}-`;
7677
8143
  }
7678
8144
  async function removeDockerContainers(prefix) {
7679
8145
  try {
@@ -7697,7 +8163,7 @@ async function removeContainers(names) {
7697
8163
  });
7698
8164
  }
7699
8165
  function docker(args) {
7700
- return new Promise((resolve8, reject2) => {
8166
+ return new Promise((resolve9, reject2) => {
7701
8167
  const child = spawn3("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
7702
8168
  let stdout = "";
7703
8169
  let stderr = "";
@@ -7717,7 +8183,7 @@ function docker(args) {
7717
8183
  });
7718
8184
  child.once("close", (code) => {
7719
8185
  clearTimeout(timer);
7720
- if (code === 0) resolve8(stdout.trim());
8186
+ if (code === 0) resolve9(stdout.trim());
7721
8187
  else reject2(new Error(stderr.trim() || `docker ${args[0]} exited with status ${code}`));
7722
8188
  });
7723
8189
  });
@@ -7727,8 +8193,8 @@ function dockerError(error) {
7727
8193
  }
7728
8194
 
7729
8195
  // ../daemon/src/runtime/shell/tooling.ts
7730
- import { existsSync as existsSync12, lstatSync as lstatSync3, mkdirSync as mkdirSync9, realpathSync as realpathSync4, statSync as statSync5 } from "node:fs";
7731
- import { dirname as dirname6, isAbsolute as isAbsolute4, join as join17, relative as relative3, sep as sep4 } from "node:path";
8196
+ import { existsSync as existsSync12, lstatSync as lstatSync3, mkdirSync as mkdirSync9, realpathSync as realpathSync4, statSync as statSync6 } from "node:fs";
8197
+ import { dirname as dirname6, isAbsolute as isAbsolute4, join as join18, relative as relative3, sep as sep4 } from "node:path";
7732
8198
  import {
7733
8199
  createBashToolDefinition,
7734
8200
  createLocalBashOperations,
@@ -8050,15 +8516,15 @@ function createSessionShellTools(cwd, env, options = {}) {
8050
8516
  };
8051
8517
  const sandbox = () => {
8052
8518
  const workspace = realpathSync4(cwd);
8053
- if (turn.cwd !== "." && !statSync5(join17(workspace, turn.cwd), { throwIfNoEntry: false })?.isDirectory())
8519
+ if (turn.cwd !== "." && !statSync6(join18(workspace, turn.cwd), { throwIfNoEntry: false })?.isDirectory())
8054
8520
  throw new Error(`Working directory does not exist: ${containerWorkdir(turn.cwd)}`);
8055
- mkdirSync9(join17(workspace, "memory"), { recursive: true });
8521
+ mkdirSync9(join18(workspace, "memory"), { recursive: true });
8056
8522
  return {
8057
8523
  image: turn.image,
8058
8524
  workspace,
8059
8525
  workdir: containerWorkdir(turn.cwd),
8060
8526
  readOnlyMounts: [
8061
- readOnlyMount(join17(workspace, "memory"), SANDBOX_MEMORY_DIR, workspace),
8527
+ readOnlyMount(join18(workspace, "memory"), SANDBOX_MEMORY_DIR, workspace),
8062
8528
  ...options.inputsDir && existsSync12(options.inputsDir) ? [readOnlyMount(options.inputsDir, SANDBOX_INPUTS_DIR, dirname6(options.inputsDir))] : [],
8063
8529
  ...(options.skillMounts ?? []).map(
8064
8530
  (mount) => readOnlyMount(mount.source, mount.target, dirname6(mount.source))
@@ -8094,13 +8560,13 @@ function readOnlyMount(source, target, root) {
8094
8560
 
8095
8561
  // ../daemon/src/runtime/pi/session-file.ts
8096
8562
  import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSync3, openSync as openSync3, readSync as readSync2 } from "node:fs";
8097
- import { join as join18 } from "node:path";
8563
+ import { join as join19 } from "node:path";
8098
8564
  var MAX_SESSION_BYTES = 64 * 1024 * 1024;
8099
8565
  var MAX_HEADER_BYTES = 64 * 1024;
8100
8566
  function readStart(directory, id, limit) {
8101
8567
  if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error("Invalid conversation id");
8102
8568
  const fd = openSync3(
8103
- join18(directory, `${id}.jsonl`),
8569
+ join19(directory, `${id}.jsonl`),
8104
8570
  constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK
8105
8571
  );
8106
8572
  try {
@@ -8130,6 +8596,13 @@ function readSessionFile(directory, id) {
8130
8596
  checkHeader(entries[0], id);
8131
8597
  return entries;
8132
8598
  }
8599
+ function sessionHasEntries(directory, id) {
8600
+ const { bytes, size } = readStart(directory, id, MAX_HEADER_BYTES);
8601
+ if (size > bytes.length) return true;
8602
+ const text4 = bytes.toString("utf8");
8603
+ const end = text4.indexOf("\n");
8604
+ return end >= 0 && text4.slice(end + 1).trim().length > 0;
8605
+ }
8133
8606
  function readSessionHeader(directory, id) {
8134
8607
  const text4 = readStart(directory, id, MAX_HEADER_BYTES).bytes.toString("utf8");
8135
8608
  const end = text4.indexOf("\n");
@@ -8178,7 +8651,7 @@ function askUserTool(ask) {
8178
8651
 
8179
8652
  // ../daemon/src/runtime/tools/bootstrap.ts
8180
8653
  import { existsSync as existsSync13, rmSync as rmSync11 } from "node:fs";
8181
- import { join as join19 } from "node:path";
8654
+ import { join as join20 } from "node:path";
8182
8655
  function bootstrapTool(agentDir2) {
8183
8656
  return {
8184
8657
  def: {
@@ -8187,7 +8660,7 @@ function bootstrapTool(agentDir2) {
8187
8660
  parameters: { type: "object", properties: {} }
8188
8661
  },
8189
8662
  async invoke() {
8190
- const path = join19(agentDir2, "BOOTSTRAP.md");
8663
+ const path = join20(agentDir2, "BOOTSTRAP.md");
8191
8664
  if (existsSync13(path)) {
8192
8665
  rmSync11(path);
8193
8666
  return "BOOTSTRAP.md removed. Bootstrap is complete.";
@@ -8320,10 +8793,10 @@ function isWithin(root, candidate) {
8320
8793
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute5(rel);
8321
8794
  }
8322
8795
  function deliverFileTool(cwd, sink) {
8323
- const workspacePath = resolve6(cwd);
8796
+ const workspacePath2 = resolve6(cwd);
8324
8797
  let workspaceRealPath = null;
8325
8798
  try {
8326
- workspaceRealPath = realpathSync5(workspacePath);
8799
+ workspaceRealPath = realpathSync5(workspacePath2);
8327
8800
  } catch {
8328
8801
  }
8329
8802
  return {
@@ -8348,8 +8821,8 @@ function deliverFileTool(cwd, sink) {
8348
8821
  if (isAbsolute5(p)) {
8349
8822
  throw new Error(`deliver_file: path must stay within the workspace: ${p}`);
8350
8823
  }
8351
- const abs = resolve6(workspacePath, p);
8352
- if (!isWithin(workspacePath, abs)) {
8824
+ const abs = resolve6(workspacePath2, p);
8825
+ if (!isWithin(workspacePath2, abs)) {
8353
8826
  throw new Error(`deliver_file: path must stay within the workspace: ${p}`);
8354
8827
  }
8355
8828
  if (!workspaceRealPath) {
@@ -8387,7 +8860,7 @@ import {
8387
8860
  readdirSync as readdirSync6,
8388
8861
  writeFileSync as writeFileSync6
8389
8862
  } from "node:fs";
8390
- import { join as join20 } from "node:path";
8863
+ import { join as join21 } from "node:path";
8391
8864
  var HOME_FILES_READABLE = [
8392
8865
  "IDENTITY.md",
8393
8866
  "SOUL.md",
@@ -8508,7 +8981,7 @@ function resolvePrivateHomeRoot(agentDir2) {
8508
8981
  }
8509
8982
  }
8510
8983
  function privateHomeFile(homeRoot, file) {
8511
- return join20(homeRoot, file);
8984
+ return join21(homeRoot, file);
8512
8985
  }
8513
8986
  function rejectSymlinkOrNonFile(path) {
8514
8987
  const entry = lstatSync4(path);
@@ -8916,7 +9389,7 @@ var DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWe
8916
9389
  var DEFAULT_CACHE_TTL_MS = 15 * 6e4;
8917
9390
  var DEFAULT_CACHE_MAX = 100;
8918
9391
  var DEFAULT_MAX_LENGTH = 2e4;
8919
- var DEFAULT_TIMEOUT_MS = 3e4;
9392
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
8920
9393
  var DEFAULT_MAX_BODY_BYTES = 3 * 1024 * 1024;
8921
9394
  var FIRECRAWL_FALLBACK_THRESHOLD = 200;
8922
9395
  var FIRECRAWL_DEFAULT_URL = "https://api.firecrawl.dev";
@@ -9073,7 +9546,7 @@ function webFetchTool(opts) {
9073
9546
  const allowPrivate = opts?.allowPrivate ?? false;
9074
9547
  const cacheTtlMs = opts?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
9075
9548
  const cacheMax = opts?.cacheMax ?? DEFAULT_CACHE_MAX;
9076
- const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
9549
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
9077
9550
  const maxBodyBytes = opts?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
9078
9551
  const cache = /* @__PURE__ */ new Map();
9079
9552
  return {
@@ -9291,7 +9764,7 @@ function turnSurface(opts) {
9291
9764
  const shellTools = createSessionShellTools(cwd, env, {
9292
9765
  docker: opts.docker,
9293
9766
  containerPrefix: homeContainerPrefix(paths.home),
9294
- inputsDir: join21(agent.agent.dir, "uploads"),
9767
+ inputsDir: join22(agent.agent.dir, "uploads"),
9295
9768
  skillMounts: promptSkills.map((skill) => ({ source: skill.hostDir, target: skill.sandboxDir })),
9296
9769
  approvalHost: opts.bashApprovalHost
9297
9770
  });
@@ -9332,7 +9805,7 @@ async function createBazilionSession(opts) {
9332
9805
  const { agent, paths } = opts;
9333
9806
  const { providerName, modelId } = parseModelString(agent.model);
9334
9807
  if (!existsSync14(agent.team.path)) mkdirSync10(agent.team.path, { recursive: true });
9335
- mkdirSync10(join21(paths.agentDir(agent.agent.id), "sessions"), { recursive: true });
9808
+ mkdirSync10(join22(paths.agentDir(agent.agent.id), "sessions"), { recursive: true });
9336
9809
  const sessionManager = openConversation(agent, paths, opts.conversation);
9337
9810
  const turn = turnSurface(opts);
9338
9811
  return openPiSession({
@@ -9344,7 +9817,7 @@ async function createBazilionSession(opts) {
9344
9817
  },
9345
9818
  reasoningLevel: agent.reasoningLevel,
9346
9819
  cwd: turn.modelCwd,
9347
- piAgentDir: join21(paths.home, "pi"),
9820
+ piAgentDir: join22(paths.home, "pi"),
9348
9821
  sessionManager,
9349
9822
  appendSystemPrompt: buildSystemPrompt(agent, turn.promptOptions),
9350
9823
  agentsFiles: (opts.repositoryInstructions ?? []).map((file) => ({
@@ -9402,7 +9875,7 @@ function toPiThinkingLevel(level) {
9402
9875
  }
9403
9876
  }
9404
9877
  function openConversation(agent, paths, target) {
9405
- const sessionDir = join21(paths.agentDir(agent.agent.id), "sessions");
9878
+ const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
9406
9879
  return SessionManager.open(
9407
9880
  explicitConversationFile(sessionDir, target),
9408
9881
  sessionDir,
@@ -9411,13 +9884,13 @@ function openConversation(agent, paths, target) {
9411
9884
  }
9412
9885
  function loadInitialMessages(agent, paths, target) {
9413
9886
  if (!target) return [];
9414
- const entries = readSessionFile(join21(paths.agentDir(agent.agent.id), "sessions"), target.id);
9887
+ const entries = readSessionFile(join22(paths.agentDir(agent.agent.id), "sessions"), target.id);
9415
9888
  return buildSessionContext(entries.filter((entry) => entry.type !== "session")).messages;
9416
9889
  }
9417
9890
  function loadSessionMessages(agent, paths, sessionId) {
9418
9891
  if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) return [];
9419
- const sessionDir = join21(paths.agentDir(agent.agent.id), "sessions");
9420
- const file = join21(sessionDir, `${sessionId}.jsonl`);
9892
+ const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
9893
+ const file = join22(sessionDir, `${sessionId}.jsonl`);
9421
9894
  if (!existsSync14(file) || !existsSync14(agent.team.path)) return [];
9422
9895
  try {
9423
9896
  return SessionManager.open(file, sessionDir).buildSessionContext().messages;
@@ -9426,12 +9899,12 @@ function loadSessionMessages(agent, paths, sessionId) {
9426
9899
  }
9427
9900
  }
9428
9901
  function loadSessionHead(agent, paths, target) {
9429
- const sessionDir = join21(paths.agentDir(agent.agent.id), "sessions");
9902
+ const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
9430
9903
  if (!existsSync14(sessionDir)) return { file: null, size: 0 };
9431
9904
  const recent = target ? explicitConversationFile(sessionDir, target) : null;
9432
9905
  if (!recent) return { file: null, size: 0 };
9433
9906
  try {
9434
- const s = statSync6(recent);
9907
+ const s = statSync7(recent);
9435
9908
  return { file: basename5(recent), size: s.size };
9436
9909
  } catch {
9437
9910
  return { file: null, size: 0 };
@@ -9440,15 +9913,40 @@ function loadSessionHead(agent, paths, target) {
9440
9913
  function explicitConversationFile(directory, target) {
9441
9914
  if (!target) throw new Error("Explicit conversation target is required");
9442
9915
  readSessionHeader(directory, target.id);
9443
- return join21(directory, `${target.id}.jsonl`);
9916
+ return join22(directory, `${target.id}.jsonl`);
9444
9917
  }
9445
9918
 
9446
9919
  // ../daemon/src/runtime/providers/catalog.ts
9447
9920
  import { getBuiltinModels } from "@earendil-works/pi-ai/providers/all";
9448
9921
  import { fetch as undiciFetch3 } from "undici";
9449
- function listCatalogModelsSync(providerName) {
9450
- const models = getBuiltinModels(piProviderName(providerName));
9451
- return (models ?? []).map((model) => model.id);
9922
+ function listCatalogEntries(providerName) {
9923
+ const models = getBuiltinModels(
9924
+ piProviderName(providerName)
9925
+ );
9926
+ return (models ?? []).map((model) => {
9927
+ const input = model.cost?.input ?? 0;
9928
+ const output = model.cost?.output ?? 0;
9929
+ return {
9930
+ id: model.id,
9931
+ // Pi marks the undated alias "(latest)"; the dated copy is told apart by its id.
9932
+ name: (model.name ?? model.id).replace(/ \(latest\)$/, ""),
9933
+ contextWindow: model.contextWindow ?? 0,
9934
+ images: model.input?.includes("image") ?? false,
9935
+ reasoning: model.reasoning ?? false,
9936
+ // Subscription and free endpoints are priced at zero, which says nothing about cost.
9937
+ ...input > 0 || output > 0 ? { price: { input, output } } : {}
9938
+ };
9939
+ });
9940
+ }
9941
+ var DATED = /^(.+)-(\d{8}|\d{4}-\d{2}-\d{2})$/;
9942
+ function datedCopies(ids) {
9943
+ const all = new Set(ids);
9944
+ return new Set(
9945
+ ids.filter((id) => {
9946
+ const base = DATED.exec(id)?.[1];
9947
+ return base !== void 0 && all.has(base);
9948
+ })
9949
+ );
9452
9950
  }
9453
9951
  async function fetchLiveModels(baseUrl, apiKey2, signal) {
9454
9952
  try {
@@ -9459,14 +9957,14 @@ async function fetchLiveModels(baseUrl, apiKey2, signal) {
9459
9957
  const body = await res.json();
9460
9958
  return { models: (body?.data ?? []).flatMap((model) => model.id ? [model.id] : []) };
9461
9959
  } catch (err) {
9462
- return { models: [], error: err.message };
9960
+ const cause = err.cause;
9961
+ return { models: [], error: cause?.code ?? cause?.message ?? err.message };
9463
9962
  }
9464
9963
  }
9465
- async function listCatalogModels(providerName, env = process.env, signal) {
9466
- const catalog = listCatalogModelsSync(providerName);
9964
+ async function listLiveModels(providerName, env = process.env, signal) {
9467
9965
  const url = providerModelsUrl(providerName, env);
9468
- if (!url) return { catalog };
9469
- return { catalog, live: await fetchLiveModels(url, providerApiKey(providerName, env), signal) };
9966
+ if (!url) return void 0;
9967
+ return fetchLiveModels(url, providerApiKey(providerName, env), signal);
9470
9968
  }
9471
9969
 
9472
9970
  // ../daemon/src/runtime/worker/spawn.ts
@@ -9496,10 +9994,10 @@ async function refreshApiKeyForTurn(requestedProvider, turnProvider, host3, sign
9496
9994
  }
9497
9995
  function waitForRefresh(pending, signal) {
9498
9996
  if (!signal) return pending;
9499
- return new Promise((resolve8, reject2) => {
9997
+ return new Promise((resolve9, reject2) => {
9500
9998
  const onAbort = () => reject2(refreshCancelledError());
9501
9999
  signal.addEventListener("abort", onAbort, { once: true });
9502
- pending.then(resolve8, reject2).finally(() => signal.removeEventListener("abort", onAbort));
10000
+ pending.then(resolve9, reject2).finally(() => signal.removeEventListener("abort", onAbort));
9503
10001
  });
9504
10002
  }
9505
10003
  var ApiKeyRefreshCancelledError = class extends Error {
@@ -9617,10 +10115,10 @@ async function* runWorker(run) {
9617
10115
  child.stderr?.destroy();
9618
10116
  }, EXIT_DRAIN_MS).unref();
9619
10117
  });
9620
- const exit = new Promise((resolve8) => {
10118
+ const exit = new Promise((resolve9) => {
9621
10119
  if (child.exitCode !== null || child.signalCode !== null) {
9622
- resolve8({ code: child.exitCode, signal: child.signalCode });
9623
- } else child.once("close", (code, signal) => resolve8({ code, signal }));
10120
+ resolve9({ code: child.exitCode, signal: child.signalCode });
10121
+ } else child.once("close", (code, signal) => resolve9({ code, signal }));
9624
10122
  });
9625
10123
  try {
9626
10124
  if (!child.stdout) throw new Error("worker spawn: stdout pipe missing");
@@ -9764,7 +10262,7 @@ var AsyncFrameQueue = class {
9764
10262
  const frame = this.#frames.shift();
9765
10263
  if (frame) return Promise.resolve({ done: false, value: frame });
9766
10264
  if (this.#ended) return Promise.resolve({ done: true, value: void 0 });
9767
- return new Promise((resolve8) => this.#waiters.push(resolve8));
10265
+ return new Promise((resolve9) => this.#waiters.push(resolve9));
9768
10266
  }
9769
10267
  };
9770
10268
  }
@@ -9835,231 +10333,67 @@ function errorMessage2(error) {
9835
10333
  }
9836
10334
  function formatWorkerExitFailure(message, diagnostic) {
9837
10335
  const formatted = formatWorkerDiagnostic(diagnostic);
9838
- if (formatted !== diagnostic) return formatted;
9839
- return diagnostic ? `${message}: ${diagnostic}` : message;
9840
- }
9841
- function formatWorkerDiagnostic(diagnostic) {
9842
- return formatNativeModuleAbiMismatch(diagnostic, { subject: "worker" }) ?? diagnostic;
9843
- }
9844
-
9845
- // ../daemon/src/lib/execution-unavailable.ts
9846
- var ExecutionUnavailableError = class extends DomainError {
9847
- constructor(message) {
9848
- super(409, message);
9849
- }
9850
- };
9851
-
9852
- // ../daemon/src/lib/api-key.ts
9853
- function assertProviderReady(db, authToken, model) {
9854
- let providerName;
9855
- try {
9856
- providerName = parseModelString(model).providerName;
9857
- } catch (error) {
9858
- throw new ExecutionUnavailableError(error.message);
9859
- }
9860
- if (!findProvider(providerName)) {
9861
- throw new ExecutionUnavailableError(`unknown provider: ${providerName}`);
9862
- }
9863
- if (!providerState_exports.listEnabled(db).has(providerName)) {
9864
- throw new ExecutionUnavailableError(
9865
- `${providerName} provider is disabled \u2014 enable it on the /config page`
9866
- );
9867
- }
9868
- if (providerName === "openai-codex" && !hasCredentials(db, authToken)) {
9869
- throw new ExecutionUnavailableError(
9870
- "openai-codex is not connected \u2014 run `bazilion auth openai login` or click Connect on /config"
9871
- );
9872
- }
9873
- }
9874
- async function resolveAgentApiKey(db, authToken, agent) {
9875
- if (parseModelString(agent.model).providerName !== "openai-codex") return {};
9876
- return {
9877
- apiKey: await loadAccessToken(db, authToken),
9878
- refreshApiKey: async (requestedProvider) => {
9879
- if (requestedProvider !== "openai-codex") {
9880
- throw new Error(`unexpected refresh request for ${requestedProvider}`);
9881
- }
9882
- return loadAccessToken(db, authToken);
9883
- }
9884
- };
9885
- }
9886
-
9887
- // ../daemon/src/lib/bash-approval.ts
9888
- var DEFAULT_TIMEOUT_MS2 = 12e4;
9889
- var CommandApprovalRegistry = class {
9890
- #pending = /* @__PURE__ */ new Map();
9891
- #timeoutMs;
9892
- constructor(timeoutMs = DEFAULT_TIMEOUT_MS2) {
9893
- this.#timeoutMs = timeoutMs;
9894
- }
9895
- begin(input, signal) {
9896
- const approval = {
9897
- id: input.id,
9898
- turnId: input.turnId,
9899
- toolCallId: input.toolCallId,
9900
- agentId: input.agentId,
9901
- teamId: input.teamId,
9902
- command: input.command,
9903
- risks: input.risks,
9904
- status: "pending",
9905
- expiresAt: Date.now() + this.#timeoutMs
9906
- };
9907
- const immediate = input.mode === "auto_deny" ? "auto_denied" : signal?.aborted ? "cancelled" : void 0;
9908
- if (immediate) {
9909
- const settled2 = logged({ ...approval, status: immediate });
9910
- return { approval: settled2, settled: Promise.resolve(settled2) };
9911
- }
9912
- if (this.#pending.has(approval.id))
9913
- throw new Error(`duplicate shell approval id: ${approval.id}`);
9914
- const settled = new Promise((resolve8) => {
9915
- const settle = (status2) => {
9916
- this.#pending.delete(approval.id);
9917
- clearTimeout(timer);
9918
- signal?.removeEventListener("abort", onAbort);
9919
- const result = logged({ ...approval, status: status2 });
9920
- resolve8(result);
9921
- return result;
9922
- };
9923
- const onAbort = () => settle("cancelled");
9924
- const timer = setTimeout(() => settle("expired"), this.#timeoutMs);
9925
- timer.unref();
9926
- signal?.addEventListener("abort", onAbort, { once: true });
9927
- this.#pending.set(approval.id, { approval, settle });
9928
- });
9929
- return { approval, settled };
9930
- }
9931
- list(agentId) {
9932
- return Array.from(this.#pending.values(), (entry) => entry.approval).filter((approval) => agentId === void 0 || approval.agentId === agentId).sort((a, b) => a.expiresAt - b.expiresAt || a.id.localeCompare(b.id));
9933
- }
9934
- /** Answer a pending approval; undefined when there is none (unknown, or already settled). */
9935
- respond(id, decision) {
9936
- return this.#pending.get(id)?.settle(decision === "allow" ? "allowed" : "denied");
9937
- }
9938
- };
9939
- function logged(approval) {
9940
- console.info("bash approval decision", {
9941
- approvalId: approval.id,
9942
- agentId: approval.agentId,
9943
- teamId: approval.teamId,
9944
- riskCodes: [...new Set(approval.risks.map((risk) => risk.code))],
9945
- status: approval.status
9946
- });
9947
- return approval;
9948
- }
9949
- var commandApprovalRegistry = new CommandApprovalRegistry();
9950
-
9951
- // ../daemon/src/lib/browser/host.ts
9952
- init_pool2();
9953
- function createBrowserHost(config, turn) {
9954
- return {
9955
- invoke: (_workerAgentId, action, args) => invokeBrowserAction(turn.agentId, action, args, config, turn.paths, turn.signal)
9956
- };
9957
- }
9958
-
9959
- // ../daemon/src/lib/image-generation.ts
9960
- import { createModels } from "@earendil-works/pi-ai";
9961
- import { openrouterProvider } from "@earendil-works/pi-ai/providers/openrouter";
9962
-
9963
- // ../daemon/src/core/repos/results.ts
9964
- import { createHash as createHash4, randomUUID as randomUUID14 } from "node:crypto";
9965
-
9966
- // ../daemon/src/core/tool-call-id.ts
9967
- function isToolCallId(value) {
9968
- return typeof value === "string" && value.length <= 256 && // A true end assertion also rejects a trailing newline (unlike JavaScript '$').
9969
- /^[A-Za-z0-9._:-]+(?:\|[A-Za-z0-9._:-]+)?$(?![\s\S])/.test(value);
9970
- }
9971
-
9972
- // ../daemon/src/core/repos/results.ts
9973
- var MAX_RESULT_BYTES = 25 * 1024 * 1024;
9974
- var MAX_RETAINED_RESULT_BYTES = 1024 * 1024 * 1024;
9975
- var columns2 = `id, team_id AS teamId, agent_id AS agentId, session_id AS sessionId,
9976
- tool_call_id AS toolCallId, source_index AS sourceIndex, name, mime_type AS mimeType,
9977
- byte_length AS byteLength, sha256, image_model AS imageModel, created_at AS createdAt`;
9978
- function get17(db, id) {
9979
- return db.raw.query(`SELECT ${columns2} FROM agent_results WHERE id = ?`).get(id);
9980
- }
9981
- function publish(db, input) {
9982
- if (!isToolCallId(input.toolCallId)) throw new Error("Invalid result tool call");
9983
- if (typeof input.name !== "string" || !input.name || input.name.length > 255 || /[/\\]/.test(input.name) || [...input.name].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) || input.name === "." || input.name === "..")
9984
- throw new Error("Invalid result filename");
9985
- if (typeof input.mimeType !== "string" || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(input.mimeType))
9986
- throw new Error("Invalid result media type");
9987
- if (input.bytes.byteLength > MAX_RESULT_BYTES)
9988
- throw new Error("Result exceeds the 25 MiB per-file limit");
9989
- const bytes = Buffer.from(input.bytes);
9990
- const sourceIndex = input.sourceIndex ?? 0;
9991
- return db.raw.transaction(() => {
9992
- const existing = db.raw.query(
9993
- `SELECT id FROM agent_results
9994
- WHERE agent_id = ? AND session_id = ? AND tool_call_id = ? AND source_index = ?`
9995
- ).get(input.agentId, input.sessionId, input.toolCallId, sourceIndex);
9996
- if (existing) return get17(db, existing.id);
9997
- const retained = db.raw.query(
9998
- "SELECT coalesce(sum(byte_length), 0) AS bytes FROM agent_results"
9999
- ).get()?.bytes ?? 0;
10000
- if (retained + bytes.byteLength > MAX_RETAINED_RESULT_BYTES)
10001
- throw new Error(
10002
- "Result storage is full (1 GiB). Delete saved results before delivering more files."
10003
- );
10004
- const id = randomUUID14();
10005
- db.raw.run(
10006
- `INSERT INTO agent_results
10007
- (id, team_id, agent_id, session_id, tool_call_id, source_index, name, mime_type,
10008
- byte_length, sha256, image_model, created_at, bytes)
10009
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
10010
- [
10011
- id,
10012
- input.teamId,
10013
- input.agentId,
10014
- input.sessionId,
10015
- input.toolCallId,
10016
- sourceIndex,
10017
- input.name,
10018
- input.mimeType,
10019
- bytes.byteLength,
10020
- createHash4("sha256").update(bytes).digest("hex"),
10021
- input.imageModel ?? null,
10022
- Date.now(),
10023
- bytes
10024
- ]
10025
- );
10026
- return get17(db, id);
10027
- })();
10336
+ if (formatted !== diagnostic) return formatted;
10337
+ return diagnostic ? `${message}: ${diagnostic}` : message;
10028
10338
  }
10029
- function list12(db, opts = {}) {
10030
- const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 50)));
10031
- const offset = Math.max(0, Math.floor(opts.offset ?? 0));
10032
- const where = [];
10033
- const params = [];
10034
- if (opts.teamId !== void 0) {
10035
- where.push("team_id = ?");
10036
- params.push(opts.teamId);
10339
+ function formatWorkerDiagnostic(diagnostic) {
10340
+ return formatNativeModuleAbiMismatch(diagnostic, { subject: "worker" }) ?? diagnostic;
10341
+ }
10342
+
10343
+ // ../daemon/src/lib/execution-unavailable.ts
10344
+ var ExecutionUnavailableError = class extends DomainError {
10345
+ constructor(message) {
10346
+ super(409, message);
10347
+ }
10348
+ };
10349
+
10350
+ // ../daemon/src/lib/api-key.ts
10351
+ function assertProviderReady(db, authToken, model) {
10352
+ let providerName;
10353
+ try {
10354
+ providerName = parseModelString(model).providerName;
10355
+ } catch (error) {
10356
+ throw new ExecutionUnavailableError(error.message);
10037
10357
  }
10038
- if (opts.agentId !== void 0) {
10039
- where.push("agent_id = ?");
10040
- params.push(opts.agentId);
10358
+ if (!findProvider(providerName)) {
10359
+ throw new ExecutionUnavailableError(`unknown provider: ${providerName}`);
10360
+ }
10361
+ if (!providerState_exports.listEnabled(db).has(providerName)) {
10362
+ throw new ExecutionUnavailableError(
10363
+ `${providerName} is switched off: connect it under Setup, Models, or run bazilion provider connect ${providerName}`
10364
+ );
10365
+ }
10366
+ if (providerName === "openai-codex" && !hasCredentials(db, authToken)) {
10367
+ throw new ExecutionUnavailableError(
10368
+ "ChatGPT is not signed in: sign in under Setup, Models, or run bazilion auth openai login"
10369
+ );
10041
10370
  }
10042
- const filter = where.length ? `WHERE ${where.join(" AND ")}` : "";
10043
- const total = db.raw.query(`SELECT count(*) AS total FROM agent_results ${filter}`).get(...params)?.total ?? 0;
10044
- const results = db.raw.query(
10045
- `SELECT ${columns2} FROM agent_results ${filter} ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`
10046
- ).all(...params, limit, offset);
10047
- return { results, total, limit, offset };
10048
10371
  }
10049
- function read(db, id) {
10050
- const row = db.raw.query(
10051
- "SELECT bytes, sha256 FROM agent_results WHERE id = ?"
10052
- ).get(id);
10053
- if (!row) throw new Error("Result not found");
10054
- const bytes = Buffer.from(row.bytes);
10055
- if (createHash4("sha256").update(bytes).digest("hex") !== row.sha256)
10056
- throw new Error("Saved file failed its integrity check");
10057
- return bytes;
10372
+ async function resolveAgentApiKey(db, authToken, agent) {
10373
+ if (parseModelString(agent.model).providerName !== "openai-codex") return {};
10374
+ return {
10375
+ apiKey: await loadAccessToken(db, authToken),
10376
+ refreshApiKey: async (requestedProvider) => {
10377
+ if (requestedProvider !== "openai-codex") {
10378
+ throw new Error(`unexpected refresh request for ${requestedProvider}`);
10379
+ }
10380
+ return loadAccessToken(db, authToken);
10381
+ }
10382
+ };
10058
10383
  }
10059
- function remove10(db, id) {
10060
- return db.raw.run("DELETE FROM agent_results WHERE id = ?", [id]).changes === 1;
10384
+
10385
+ // ../daemon/src/lib/browser/host.ts
10386
+ init_pool2();
10387
+ function createBrowserHost(config, turn) {
10388
+ return {
10389
+ invoke: (_workerAgentId, action, args) => invokeBrowserAction(turn.agentId, action, args, config, turn.paths, turn.signal)
10390
+ };
10061
10391
  }
10062
10392
 
10393
+ // ../daemon/src/lib/image-generation.ts
10394
+ import { createModels } from "@earendil-works/pi-ai";
10395
+ import { openrouterProvider } from "@earendil-works/pi-ai/providers/openrouter";
10396
+
10063
10397
  // ../daemon/src/lib/openai-responses.ts
10064
10398
  var OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses";
10065
10399
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
@@ -10340,7 +10674,7 @@ async function resolveMcpForTurn(db, authToken, signal) {
10340
10674
  }
10341
10675
 
10342
10676
  // ../daemon/src/lib/agent-loop-guard.ts
10343
- import { randomUUID as randomUUID15 } from "node:crypto";
10677
+ import { randomUUID as randomUUID16 } from "node:crypto";
10344
10678
  var DEFAULT_MAX_HOPS = 8;
10345
10679
  function toEvent(row) {
10346
10680
  return {
@@ -10390,8 +10724,8 @@ function enforceMessageCausality(db, input) {
10390
10724
  const target = agents_exports.get(db, input.to);
10391
10725
  if (!source || !target) return null;
10392
10726
  const event = {
10393
- id: randomUUID15(),
10394
- causalChainId: input.causality.causalChainId ?? input.causality.parentMessageId ?? randomUUID15(),
10727
+ id: randomUUID16(),
10728
+ causalChainId: input.causality.causalChainId ?? input.causality.parentMessageId ?? randomUUID16(),
10395
10729
  parentMessageId: input.causality.parentMessageId,
10396
10730
  fromAgentId: input.from,
10397
10731
  toAgentId: input.to,
@@ -10419,213 +10753,99 @@ function enforceMessageCausality(db, input) {
10419
10753
  event.attemptedHop,
10420
10754
  event.maxHops,
10421
10755
  event.reason,
10422
- event.origin,
10423
- event.createdAt
10424
- ]
10425
- );
10426
- return event;
10427
- }
10428
- function listAgentLoopBreaks(db, agentId, limit = 50) {
10429
- return db.raw.query(
10430
- `SELECT * FROM agent_loop_break_events
10431
- WHERE from_agent_id = ? OR to_agent_id = ?
10432
- ORDER BY created_at DESC, id DESC LIMIT ?`
10433
- ).all(agentId, agentId, Math.max(1, Math.min(limit, 100))).map(toEvent);
10434
- }
10435
- function selectCausalParent(messages) {
10436
- let selected;
10437
- for (const message of messages) {
10438
- if (!selected || message.causalHop > selected.causalHop) selected = message;
10439
- }
10440
- return selected?.id ?? null;
10441
- }
10442
-
10443
- // ../daemon/src/lib/communication.ts
10444
- var CommunicationDeniedError = class extends DomainError {
10445
- constructor(reason) {
10446
- super(403, `Team Policy denied this message: ${reason}`, "communication_denied");
10447
- }
10448
- };
10449
- function sendAgentMessage(db, input) {
10450
- const outcome = db.raw.transaction(
10451
- () => {
10452
- const causality = resolveMessageCausality(db, input);
10453
- const loopBreak = enforceMessageCausality(db, {
10454
- from: input.from,
10455
- to: input.to,
10456
- origin: input.origin,
10457
- causality
10458
- });
10459
- if (loopBreak) return { loopBreak };
10460
- const decision = mayMessage(db, input.from, input.to);
10461
- if (!decision.allowed) return { denied: decision.reason };
10462
- return {
10463
- message: messages_exports.send(db, {
10464
- ...input,
10465
- causalChainId: causality.causalChainId,
10466
- causalHop: causality.causalHop
10467
- })
10468
- };
10469
- }
10470
- )();
10471
- if (outcome.loopBreak) throw new AgentLoopLimitError(outcome.loopBreak);
10472
- if (outcome.denied !== void 0) {
10473
- console.warn(
10474
- JSON.stringify({
10475
- event: "team_policy_denied",
10476
- from: input.from,
10477
- to: input.to,
10478
- origin: input.origin,
10479
- reason: outcome.denied
10480
- })
10481
- );
10482
- throw new CommunicationDeniedError(outcome.denied);
10483
- }
10484
- if (!outcome.message) throw new Error("communication transaction produced no result");
10485
- return outcome.message;
10486
- }
10487
-
10488
- // ../daemon/src/lib/messaging-host.ts
10489
- function createDbMessagingHost(db, opts = {}) {
10490
- return {
10491
- agentExists(agentId) {
10492
- return agents_exports.get(db, agentId) !== null;
10493
- },
10494
- sendMessage(input) {
10495
- const to = agents_exports.get(db, input.to)?.id ?? input.to;
10496
- const m = sendAgentMessage(db, {
10497
- ...input,
10498
- to,
10499
- causalParentMessageId: opts.causalParentMessageId,
10500
- origin: "agent_tool"
10501
- });
10502
- return { messageId: m.id };
10503
- },
10504
- listInbox(agentId, opts2) {
10505
- return messages_exports.listInbox(db, agentId, { unreadOnly: opts2?.unreadOnly === true });
10506
- },
10507
- markRead(messageId) {
10508
- messages_exports.markRead(db, messageId);
10509
- },
10510
- findReplies(agentId, replyTo) {
10511
- return messages_exports.listInbox(db, agentId).filter((message) => message.replyTo === replyTo);
10512
- }
10513
- };
10514
- }
10515
-
10516
- // ../daemon/src/lib/questions.ts
10517
- import { randomUUID as randomUUID16 } from "node:crypto";
10518
- var QUESTION_WAIT_MS = 5 * 6e4;
10519
- var QUESTION_LIMITS = Object.freeze({
10520
- promptChars: 2e3,
10521
- labelChars: 120,
10522
- descriptionChars: 500,
10523
- answerChars: 4096
10524
- });
10525
- function text2(value, limit, what) {
10526
- if (typeof value !== "string" || !value.trim()) throw new Error(`${what} must be non-empty text`);
10527
- if (value.length > limit) throw new Error(`${what} is longer than ${limit} characters`);
10528
- return value;
10529
- }
10530
- function parseQuestionInput(value) {
10531
- const input = value ?? {};
10532
- const prompt = text2(input.prompt, QUESTION_LIMITS.promptChars, "The prompt");
10533
- if (!Array.isArray(input.choices) || input.choices.length < 2 || input.choices.length > 4)
10534
- throw new Error("ask_user needs 2 to 4 choices");
10535
- const labels = /* @__PURE__ */ new Set();
10536
- const choices = input.choices.map((raw, index) => {
10537
- const choice = raw ?? {};
10538
- const label = text2(choice.label, QUESTION_LIMITS.labelChars, `Choice ${index + 1} label`);
10539
- const key2 = label.normalize("NFKC").trim().toLowerCase();
10540
- if (labels.has(key2)) throw new Error("Choice labels must be distinct");
10541
- labels.add(key2);
10542
- if (choice.description === void 0) return { label };
10543
- const description = text2(
10544
- choice.description,
10545
- QUESTION_LIMITS.descriptionChars,
10546
- `Choice ${index + 1} description`
10547
- );
10548
- return { label, description };
10549
- });
10550
- const recommended = input.recommendedIndex;
10551
- if (recommended === void 0) return { prompt, choices };
10552
- if (typeof recommended !== "number" || !Number.isInteger(recommended))
10553
- throw new Error("recommendedIndex must be a choice index");
10554
- if (recommended < 0 || recommended >= choices.length)
10555
- throw new Error("recommendedIndex must be a choice index");
10556
- return { prompt, choices, recommendedIndex: recommended };
10557
- }
10558
- function parseQuestionAnswer(value, question) {
10559
- const answer = value ?? {};
10560
- if (answer.kind === "skip") return { kind: "skip" };
10561
- if (answer.kind === "text")
10562
- return { kind: "text", text: text2(answer.text, QUESTION_LIMITS.answerChars, "The answer") };
10563
- const index = answer.index;
10564
- if (answer.kind === "choice" && typeof index === "number" && Number.isInteger(index)) {
10565
- if (index >= 0 && index < question.choices.length) return { kind: "choice", index };
10566
- throw new Error(
10567
- `Choice ${index + 1} does not exist; this question has ${question.choices.length} choices`
10568
- );
10569
- }
10570
- throw new Error("An answer is a choice index, text or skip");
10571
- }
10572
- var QuestionRegistry = class {
10573
- #pending = /* @__PURE__ */ new Map();
10574
- #waitMs;
10575
- constructor(waitMs = QUESTION_WAIT_MS) {
10576
- this.#waitMs = waitMs;
10577
- }
10578
- /** Register a question. `result` settles on the first answer, the timeout or `signal`. */
10579
- ask(context, input, signal) {
10580
- const prompt = parseQuestionInput(input);
10581
- if (this.list(context.agentId).length > 0)
10582
- throw new Error("Another question from this Agent is still waiting for an answer");
10583
- if (signal?.aborted) throw new Error("The turn has ended");
10584
- const now = Date.now();
10585
- const question = {
10586
- id: randomUUID16(),
10587
- agentId: context.agentId,
10588
- conversationId: context.conversationId,
10589
- question: prompt,
10590
- createdAt: now,
10591
- expiresAt: now + this.#waitMs
10592
- };
10593
- const { promise, resolve: resolve8 } = Promise.withResolvers();
10594
- const cancel3 = () => finish3({ kind: "no_answer", reason: "cancelled" });
10595
- const timer = setTimeout(() => finish3({ kind: "no_answer", reason: "expired" }), this.#waitMs);
10596
- timer.unref();
10597
- const finish3 = (outcome) => {
10598
- if (!this.#pending.delete(question.id)) return false;
10599
- clearTimeout(timer);
10600
- signal?.removeEventListener("abort", cancel3);
10601
- resolve8({ questionId: question.id, question: prompt, ...outcome });
10602
- return true;
10603
- };
10604
- this.#pending.set(question.id, { question, result: promise, finish: finish3 });
10605
- signal?.addEventListener("abort", cancel3, { once: true });
10606
- return { question, result: promise };
10607
- }
10608
- list(agentId) {
10609
- return [...this.#pending.values()].map((entry) => entry.question).filter((question) => agentId === void 0 || question.agentId === agentId);
10610
- }
10611
- get(id) {
10612
- return this.#pending.get(id)?.question;
10756
+ event.origin,
10757
+ event.createdAt
10758
+ ]
10759
+ );
10760
+ return event;
10761
+ }
10762
+ function listAgentLoopBreaks(db, agentId, limit = 50) {
10763
+ return db.raw.query(
10764
+ `SELECT * FROM agent_loop_break_events
10765
+ WHERE from_agent_id = ? OR to_agent_id = ?
10766
+ ORDER BY created_at DESC, id DESC LIMIT ?`
10767
+ ).all(agentId, agentId, Math.max(1, Math.min(limit, 100))).map(toEvent);
10768
+ }
10769
+ function selectCausalParent(messages) {
10770
+ let selected;
10771
+ for (const message of messages) {
10772
+ if (!selected || message.causalHop > selected.causalHop) selected = message;
10613
10773
  }
10614
- /** The outcome of a waiting question; undefined once it has settled. */
10615
- settled(id) {
10616
- return this.#pending.get(id)?.result;
10774
+ return selected?.id ?? null;
10775
+ }
10776
+
10777
+ // ../daemon/src/lib/communication.ts
10778
+ var CommunicationDeniedError = class extends DomainError {
10779
+ constructor(reason) {
10780
+ super(403, `Team Policy denied this message: ${reason}`, "communication_denied");
10617
10781
  }
10618
- /** Answer a waiting question. False when it is no longer waiting; throws on an invalid answer. */
10619
- answer(agentId, id, value) {
10620
- const entry = this.#pending.get(id);
10621
- if (!entry || entry.question.agentId !== agentId) return false;
10622
- const answer = parseQuestionAnswer(value, entry.question.question);
10623
- return entry.finish(
10624
- answer.kind === "skip" ? { kind: "no_answer", reason: "skipped" } : { kind: "answer", answer }
10782
+ };
10783
+ function sendAgentMessage(db, input) {
10784
+ const outcome = db.raw.transaction(
10785
+ () => {
10786
+ const causality = resolveMessageCausality(db, input);
10787
+ const loopBreak = enforceMessageCausality(db, {
10788
+ from: input.from,
10789
+ to: input.to,
10790
+ origin: input.origin,
10791
+ causality
10792
+ });
10793
+ if (loopBreak) return { loopBreak };
10794
+ const decision = mayMessage(db, input.from, input.to);
10795
+ if (!decision.allowed) return { denied: decision.reason };
10796
+ return {
10797
+ message: messages_exports.send(db, {
10798
+ ...input,
10799
+ causalChainId: causality.causalChainId,
10800
+ causalHop: causality.causalHop
10801
+ })
10802
+ };
10803
+ }
10804
+ )();
10805
+ if (outcome.loopBreak) throw new AgentLoopLimitError(outcome.loopBreak);
10806
+ if (outcome.denied !== void 0) {
10807
+ console.warn(
10808
+ JSON.stringify({
10809
+ event: "team_policy_denied",
10810
+ from: input.from,
10811
+ to: input.to,
10812
+ origin: input.origin,
10813
+ reason: outcome.denied
10814
+ })
10625
10815
  );
10816
+ throw new CommunicationDeniedError(outcome.denied);
10626
10817
  }
10627
- };
10628
- var questionRegistry = new QuestionRegistry();
10818
+ if (!outcome.message) throw new Error("communication transaction produced no result");
10819
+ return outcome.message;
10820
+ }
10821
+
10822
+ // ../daemon/src/lib/messaging-host.ts
10823
+ function createDbMessagingHost(db, opts = {}) {
10824
+ return {
10825
+ agentExists(agentId) {
10826
+ return agents_exports.get(db, agentId) !== null;
10827
+ },
10828
+ sendMessage(input) {
10829
+ const to = agents_exports.get(db, input.to)?.id ?? input.to;
10830
+ const m = sendAgentMessage(db, {
10831
+ ...input,
10832
+ to,
10833
+ causalParentMessageId: opts.causalParentMessageId,
10834
+ origin: "agent_tool"
10835
+ });
10836
+ return { messageId: m.id };
10837
+ },
10838
+ listInbox(agentId, opts2) {
10839
+ return messages_exports.listInbox(db, agentId, { unreadOnly: opts2?.unreadOnly === true });
10840
+ },
10841
+ markRead(messageId) {
10842
+ messages_exports.markRead(db, messageId);
10843
+ },
10844
+ findReplies(agentId, replyTo) {
10845
+ return messages_exports.listInbox(db, agentId).filter((message) => message.replyTo === replyTo);
10846
+ }
10847
+ };
10848
+ }
10629
10849
 
10630
10850
  // ../daemon/src/lib/result-host.ts
10631
10851
  function createResultHost(db, agent, conversationId, signal) {
@@ -11266,7 +11486,7 @@ function mirrorTypingStop(agentId) {
11266
11486
  // ../daemon/src/lib/attachments.ts
11267
11487
  import { randomUUID as randomUUID17 } from "node:crypto";
11268
11488
  import { closeSync as closeSync5, constants as constants6, fstatSync as fstatSync5, openSync as openSync5, writeFileSync as writeFileSync8 } from "node:fs";
11269
- import { join as join22, posix as posix2 } from "node:path";
11489
+ import { join as join23, posix as posix2 } from "node:path";
11270
11490
  var MAX_FILE_BYTES = 25 * 1024 * 1024;
11271
11491
  function safeName(name) {
11272
11492
  const base = name.split(/[\\/]/).pop() ?? "file";
@@ -11278,7 +11498,7 @@ function fmtBytes(n) {
11278
11498
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
11279
11499
  }
11280
11500
  function prepareInputFilesDirectory(agentDir2) {
11281
- return ensureContainedRealDirectory(join22(agentDir2, "uploads"), agentDir2, { create: true });
11501
+ return ensureContainedRealDirectory(join23(agentDir2, "uploads"), agentDir2, { create: true });
11282
11502
  }
11283
11503
  function saveInputFiles(agentDir2, files, options = {}) {
11284
11504
  if (!files || files.length === 0) return "";
@@ -11292,7 +11512,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
11292
11512
  continue;
11293
11513
  }
11294
11514
  const filename = `${randomUUID17().slice(0, 8)}-${safeName(label)}`;
11295
- const path = join22(dir, filename);
11515
+ const path = join23(dir, filename);
11296
11516
  let fd;
11297
11517
  try {
11298
11518
  fd = openSync5(
@@ -11315,7 +11535,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
11315
11535
 
11316
11536
  // ../daemon/src/lib/coding-environment.ts
11317
11537
  import { lstatSync as lstatSync5 } from "node:fs";
11318
- import { join as join23 } from "node:path";
11538
+ import { join as join24 } from "node:path";
11319
11539
 
11320
11540
  // ../daemon/src/core/coding-environment/config.ts
11321
11541
  var CodingEnvironmentValidationError = class extends DomainError {
@@ -11372,7 +11592,7 @@ function setTeamCodingEnvironment(db, team, input, env = process.env) {
11372
11592
  const environment = validateCodingEnvironment(input);
11373
11593
  let path = team.path;
11374
11594
  for (const part of environment.cwd === "." ? [] : environment.cwd.split("/")) {
11375
- path = join23(path, part);
11595
+ path = join24(path, part);
11376
11596
  if (!lstatSync5(path, { throwIfNoEntry: false })?.isDirectory())
11377
11597
  throw new CodingEnvironmentValidationError(
11378
11598
  "The directory must be an existing directory inside the Team"
@@ -11393,17 +11613,17 @@ function dockerTurn(db, paths, agent, env) {
11393
11613
  // ../daemon/src/lib/conversation-target.ts
11394
11614
  import { randomUUID as randomUUID18 } from "node:crypto";
11395
11615
  import { writeFileSync as writeFileSync9 } from "node:fs";
11396
- import { join as join24 } from "node:path";
11616
+ import { join as join25 } from "node:path";
11397
11617
  import { SessionManager as SessionManager2 } from "@earendil-works/pi-coding-agent";
11398
11618
  function sessionsDir(paths, agentId) {
11399
- return join24(paths.agentDir(agentId), "sessions");
11619
+ return join25(paths.agentDir(agentId), "sessions");
11400
11620
  }
11401
11621
  function startConversation(db, paths, agentId, title) {
11402
11622
  const agent = resolveAgent(db, paths, agentId);
11403
11623
  if (title !== void 0) validTitle(title);
11404
11624
  const id = randomUUID18();
11405
11625
  const header = SessionManager2.inMemory(agent.team.path, { id }).getHeader();
11406
- writeFileSync9(join24(sessionsDir(paths, agentId), `${id}.jsonl`), `${JSON.stringify(header)}
11626
+ writeFileSync9(join25(sessionsDir(paths, agentId), `${id}.jsonl`), `${JSON.stringify(header)}
11407
11627
  `, {
11408
11628
  flag: "wx",
11409
11629
  mode: 384
@@ -11416,6 +11636,34 @@ function resolveConversationTarget(db, paths, agentId, pinnedId) {
11416
11636
  readSessionHeader(sessionsDir(paths, agentId), id);
11417
11637
  return { id };
11418
11638
  }
11639
+ function selectConversation(db, paths, agentId, id) {
11640
+ if (!get16(db, agentId, id)) throw new DomainError(404, "Conversation not found");
11641
+ try {
11642
+ readSessionHeader(sessionsDir(paths, agentId), id);
11643
+ } catch {
11644
+ throw new DomainError(409, "That conversation has no readable history, so it cannot continue.");
11645
+ }
11646
+ return select(db, agentId, id);
11647
+ }
11648
+ var TITLE_CHARS = 60;
11649
+ function titleFromMessage(message) {
11650
+ const line = message.split("\n").map((part) => part.replace(/\s+/g, " ").trim()).find((part) => part.length > 0);
11651
+ if (!line) return null;
11652
+ const clean = Array.from(line).filter((char) => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127).join("").trim();
11653
+ if (!clean) return null;
11654
+ if (clean.length <= TITLE_CHARS) return clean;
11655
+ const cut = clean.slice(0, TITLE_CHARS);
11656
+ const space = cut.lastIndexOf(" ");
11657
+ return `${(space > TITLE_CHARS / 2 ? cut.slice(0, space) : cut).trimEnd()}\u2026`;
11658
+ }
11659
+ function titleConversationFromMessage(db, paths, agentId, conversationId, message) {
11660
+ const conversation = get16(db, agentId, conversationId);
11661
+ if (!conversation || !hasDefaultTitle(conversation)) return;
11662
+ if (conversation.updatedAt !== conversation.createdAt) return;
11663
+ if (sessionHasEntries(sessionsDir(paths, agentId), conversationId)) return;
11664
+ const title = titleFromMessage(message);
11665
+ if (title) rename(db, agentId, conversationId, title);
11666
+ }
11419
11667
  function selectedConversationTarget(db, agentId) {
11420
11668
  const id = selectedId(db, agentId);
11421
11669
  return id ? { id } : null;
@@ -11423,7 +11671,7 @@ function selectedConversationTarget(db, agentId) {
11423
11671
 
11424
11672
  // ../daemon/src/lib/repository-instructions.ts
11425
11673
  import { realpathSync as realpathSync6 } from "node:fs";
11426
- import { join as join25 } from "node:path";
11674
+ import { join as join26 } from "node:path";
11427
11675
  var MAX_FILE_BYTES2 = 128 * 1024;
11428
11676
  var SKIPPED = {
11429
11677
  outside: "it resolves outside the Team workspace",
@@ -11443,7 +11691,7 @@ function loadRepositoryInstructions(root, cwd = ".") {
11443
11691
  for (let depth = 0; depth <= parts.length; depth++) {
11444
11692
  const path = [...parts.slice(0, depth), "AGENTS.md"].join("/");
11445
11693
  try {
11446
- const content = readContainedFile(join25(realRoot, path), realRoot, MAX_FILE_BYTES2);
11694
+ const content = readContainedFile(join26(realRoot, path), realRoot, MAX_FILE_BYTES2);
11447
11695
  instructions.push({ path, content: content.toString("utf8") });
11448
11696
  } catch (error) {
11449
11697
  if (error instanceof ContainedFileError) {
@@ -11476,6 +11724,9 @@ async function prepareAgentTurn(request) {
11476
11724
  registerAgent(agentId, controller);
11477
11725
  registered = true;
11478
11726
  }
11727
+ if (request.origin === "http" || request.origin === "telegram") {
11728
+ titleConversationFromMessage(db, paths, agentId, conversation.id, request.message);
11729
+ }
11479
11730
  const env = mergeSecretsIntoEnv(db, authToken);
11480
11731
  const docker2 = resolveShellSecurityConfig(env).sandboxMode === "docker" ? dockerTurn(db, paths, agent, env) : void 0;
11481
11732
  const repositoryInstructions = loadRepositoryInstructions(agent.team.path, docker2?.cwd ?? ".");
@@ -11727,12 +11978,14 @@ async function* runAgentTurn(turn) {
11727
11978
  );
11728
11979
  });
11729
11980
  if (frame.kind === "done") completed = true;
11981
+ noteTurnFrame(agentId, frame);
11730
11982
  yield frame;
11731
11983
  }
11732
11984
  if (completed && (turn.request.origin === "http" || turn.request.origin === "telegram")) {
11733
11985
  agentReviews_exports.recordSuccessfulUserTurn(db, agentId);
11734
11986
  }
11735
11987
  } finally {
11988
+ noteTurnEnd(agentId);
11736
11989
  mirrorTypingStop(agentId);
11737
11990
  if (turn.docker) await removeDockerContainers(turn.docker.containerPrefix);
11738
11991
  releasePreparedAgentTurn(turn);
@@ -12081,7 +12334,7 @@ agentChatRouter.post("/:id/chat/compact", async (c) => {
12081
12334
  const { db, paths, authToken } = getCtx();
12082
12335
  const resolved = resolveAgent(db, paths, id);
12083
12336
  assertProviderReady(db, authToken, resolved.model);
12084
- const memory = qmdBackend(join26(resolved.team.path, "memory"));
12337
+ const memory = qmdBackend(join27(resolved.team.path, "memory"));
12085
12338
  await memory.init();
12086
12339
  const handle12 = await createBazilionSession({
12087
12340
  agent: resolved,
@@ -12139,7 +12392,7 @@ agentChatRouter.get(
12139
12392
  const env = mergeSecretsIntoEnv(db, authToken);
12140
12393
  const files = [];
12141
12394
  for (const file of CONTEXT_FILE_ORDER2) {
12142
- const path = join26(resolved.agent.dir, file);
12395
+ const path = join27(resolved.agent.dir, file);
12143
12396
  if (!existsSync16(path)) continue;
12144
12397
  const content = readFileSync10(path, "utf8").trimEnd();
12145
12398
  if (!content) continue;
@@ -12154,7 +12407,7 @@ agentChatRouter.get(
12154
12407
  agent: resolved,
12155
12408
  paths,
12156
12409
  env,
12157
- memory: qmdBackend(join26(resolved.team.path, "memory")),
12410
+ memory: qmdBackend(join27(resolved.team.path, "memory")),
12158
12411
  messagingHost: createDbMessagingHost(db),
12159
12412
  userMdHost: createDbUserMdHost(db, paths),
12160
12413
  fileSink: reportOnly,
@@ -12258,7 +12511,7 @@ agentChatRouter.post("/:id/chat/truncate", async (c) => {
12258
12511
  });
12259
12512
 
12260
12513
  // ../daemon/src/routes/agent-learning.ts
12261
- import { join as join27 } from "node:path";
12514
+ import { join as join28 } from "node:path";
12262
12515
 
12263
12516
  // ../daemon/src/lib/lesson-decisions.ts
12264
12517
  var LessonProposalConflictError = class extends DomainError {
@@ -12457,7 +12710,7 @@ for (const decision of ["approve", "reject", "revoke"]) {
12457
12710
  const team = teams_exports.get(db, agent.teamId, paths);
12458
12711
  if (!team) return c.json({ error: `team not found: ${agent.teamId}` }, 404);
12459
12712
  const proposal = await runAgentLifecycleMutation(agent.id, async () => {
12460
- const memory = qmdBackend(join27(team.path, "memory"));
12713
+ const memory = qmdBackend(join28(team.path, "memory"));
12461
12714
  if (decision === "approve") return approveLessonProposal(db, memory, current2.id, version);
12462
12715
  if (decision === "reject") return rejectLessonProposal(db, current2.id, version);
12463
12716
  return revokeLessonProposal(db, memory, current2.id, version);
@@ -12485,7 +12738,7 @@ function withEvidenceExcerpts(proposals, agent, paths) {
12485
12738
  }
12486
12739
 
12487
12740
  // ../daemon/src/routes/agents.ts
12488
- import { join as join28 } from "node:path";
12741
+ import { join as join29 } from "node:path";
12489
12742
  init_pool2();
12490
12743
 
12491
12744
  // ../daemon/src/lib/telegram/config.ts
@@ -12760,7 +13013,7 @@ agentsRouter.get("/", (c) => {
12760
13013
  const includeArchived = c.req.query("includeArchived") === "true";
12761
13014
  const agents = agents_exports.list(getCtx().db, { includeArchived }).map((agent) => ({
12762
13015
  ...agent,
12763
- identity: loadIdentityFromFile(join28(agent.dir, "IDENTITY.md"))
13016
+ identity: loadIdentityFromFile(join29(agent.dir, "IDENTITY.md"))
12764
13017
  }));
12765
13018
  return c.json(agents);
12766
13019
  });
@@ -12902,9 +13155,9 @@ var DEVICE_CODE_FALLBACK = "`bazilion auth openai login --device-code` in a term
12902
13155
  async function preflightOpenAICodexCallback(host3 = process.env.PI_OAUTH_CALLBACK_HOST?.trim() || "127.0.0.1", port2 = OPENAI_CODEX_CALLBACK_PORT) {
12903
13156
  const server3 = createServer2();
12904
13157
  try {
12905
- await new Promise((resolve8, reject2) => {
13158
+ await new Promise((resolve9, reject2) => {
12906
13159
  server3.once("error", reject2);
12907
- server3.listen({ host: host3, port: port2, exclusive: true }, resolve8);
13160
+ server3.listen({ host: host3, port: port2, exclusive: true }, resolve9);
12908
13161
  });
12909
13162
  } catch (error) {
12910
13163
  const code = error.code;
@@ -12913,48 +13166,677 @@ async function preflightOpenAICodexCallback(host3 = process.env.PI_OAUTH_CALLBAC
12913
13166
  code === "EADDRINUSE" ? `OpenAI browser login cannot start because callback address ${address} is already in use. Stop the process using that port and try again, or run ${DEVICE_CODE_FALLBACK}.` : `OpenAI browser login cannot bind callback address ${address}${code ? ` (${code})` : ""}. Check PI_OAUTH_CALLBACK_HOST and try again, or run ${DEVICE_CODE_FALLBACK}.`
12914
13167
  );
12915
13168
  } finally {
12916
- await new Promise((resolve8) => server3.close(() => resolve8()));
13169
+ await new Promise((resolve9) => server3.close(() => resolve9()));
13170
+ }
13171
+ }
13172
+ function openAICodexBrowserCommand(platform = process.platform) {
13173
+ return platform === "darwin" ? "/usr/bin/open" : "xdg-open";
13174
+ }
13175
+ function launchOpenAICodexBrowser(url, onFailure) {
13176
+ const command = openAICodexBrowserCommand();
13177
+ const fail2 = (detail) => onFailure(
13178
+ new Error(
13179
+ `Could not open the OpenAI sign-in page with ${command}: ${detail}. Run ${DEVICE_CODE_FALLBACK}.`
13180
+ )
13181
+ );
13182
+ const child = spawn5(command, [url], { stdio: "ignore", detached: true });
13183
+ child.once("error", (error) => fail2(error.message));
13184
+ child.once("exit", (code, signal) => {
13185
+ if (code !== 0) fail2(code === null ? `terminated by ${signal}` : `exited ${code}`);
13186
+ });
13187
+ child.unref();
13188
+ }
13189
+ function answerWebOpenAIPrompt(prompt, login) {
13190
+ if (prompt.type === "select") {
13191
+ return prompt.options.some((option) => option.id === "browser") ? Promise.resolve("browser") : Promise.reject(new Error("Pi openai-codex provider does not support browser login"));
13192
+ }
13193
+ if (prompt.type !== "manual_code") {
13194
+ return Promise.reject(
13195
+ new Error(`Interactive input is not supported in the web flow. Run ${DEVICE_CODE_FALLBACK}.`)
13196
+ );
13197
+ }
13198
+ const ended = prompt.signal ? AbortSignal.any([prompt.signal, login]) : login;
13199
+ return new Promise((_resolve, reject2) => {
13200
+ const stop = () => reject2(new Error("OpenAI browser login ended"));
13201
+ if (ended.aborted) stop();
13202
+ else ended.addEventListener("abort", stop, { once: true });
13203
+ });
13204
+ }
13205
+ function webOpenAILoginError(error, signal) {
13206
+ const reason = signal.aborted ? signal.reason : error;
13207
+ if (reason instanceof Error && reason.name === "TimeoutError") {
13208
+ return `OpenAI browser login timed out after 10 minutes. Try again, or run ${DEVICE_CODE_FALLBACK}.`;
13209
+ }
13210
+ return reason instanceof Error ? reason.message : String(reason);
13211
+ }
13212
+
13213
+ // ../daemon/src/core/model-usage.ts
13214
+ function modelUsage(db) {
13215
+ const usage = /* @__PURE__ */ new Map();
13216
+ const entry = (model) => {
13217
+ let found = usage.get(model);
13218
+ if (!found) {
13219
+ found = { agents: 0, templates: [] };
13220
+ usage.set(model, found);
13221
+ }
13222
+ return found;
13223
+ };
13224
+ const defaults = /* @__PURE__ */ new Map();
13225
+ for (const profile of list3(db)) {
13226
+ defaults.set(profile.id, profile.defaultModel);
13227
+ entry(profile.defaultModel).templates.push(profile.name);
13228
+ }
13229
+ for (const agent of list(db)) {
13230
+ const model = agent.modelOverride ?? defaults.get(agent.profileId);
13231
+ if (model) entry(model).agents += 1;
13232
+ }
13233
+ return usage;
13234
+ }
13235
+
13236
+ // ../daemon/src/core/provider-checks.ts
13237
+ function readProviderChecks(db) {
13238
+ const raw = openConfig(db).get(PROVIDER_CHECKS_KEY);
13239
+ if (!raw) return {};
13240
+ try {
13241
+ const parsed = JSON.parse(raw);
13242
+ return parsed && typeof parsed === "object" ? parsed : {};
13243
+ } catch {
13244
+ return {};
13245
+ }
13246
+ }
13247
+ function writeProviderCheck(db, providerId, check) {
13248
+ const checks = readProviderChecks(db);
13249
+ if (check) checks[providerId] = check;
13250
+ else if (providerId in checks) delete checks[providerId];
13251
+ else return;
13252
+ const store = openConfig(db);
13253
+ if (Object.keys(checks).length === 0) store.remove(PROVIDER_CHECKS_KEY);
13254
+ else store.set(PROVIDER_CHECKS_KEY, JSON.stringify(checks));
13255
+ }
13256
+
13257
+ // ../daemon/src/lib/provider-failure.ts
13258
+ var UNREACHABLE = /connection error|econnrefused|enotfound|ehostunreach|enetunreach|etimedout|econnreset|fetch failed|bad port|socket hang up|getaddrinfo|und_err|request aborted|request timed out/;
13259
+ var CREDENTIALS = /invalid.{0,12}api.?key|incorrect api key|invalid x-api-key|invalid_api_key|authentication_error|unauthorized|invalid.{0,12}(access )?token/;
13260
+ var MODEL = /model_not_found|no models loaded|not found, try pulling|not_found_error.{0,40}\bmodel\b|\bmodel\b.{0,80}(not found|does not exist|do not have access|not available|is not supported)|(must be verified|not have access|no access).{0,60}\bmodel\b/;
13261
+ var LIMIT = /insufficient|quota|rate.?limit|billing|\bcredits?\b|overloaded/;
13262
+ function classifyProviderFailure(message, timedOut = false) {
13263
+ const text4 = message.toLowerCase();
13264
+ const status2 = /^(\d{3})\b/.exec(text4)?.[1];
13265
+ if (timedOut || UNREACHABLE.test(text4)) return "unreachable";
13266
+ if (status2 === "401" || CREDENTIALS.test(text4)) return "credentials";
13267
+ if (MODEL.test(text4)) return "model";
13268
+ if (status2 === "402" || status2 === "429" || LIMIT.test(text4)) return "limit";
13269
+ if (status2 === "403") return "credentials";
13270
+ return "other";
13271
+ }
13272
+ function redactDetail(message, secrets) {
13273
+ let detail = message;
13274
+ for (const secret of secrets) {
13275
+ if (secret.length >= 6) detail = detail.split(secret).join("\u2026");
13276
+ }
13277
+ detail = detail.replace(/\s+/g, " ").trim();
13278
+ return detail.length > 400 ? `${detail.slice(0, 400)}\u2026` : detail;
13279
+ }
13280
+ function describeProviderFailure(message, context) {
13281
+ const { provider, modelName, address, timedOut = false } = context;
13282
+ const name = provider.displayName;
13283
+ const local = Boolean(provider.local);
13284
+ const kind = classifyProviderFailure(message, timedOut);
13285
+ const detail = redactDetail(message, context.secrets ?? []);
13286
+ const status2 = /^(\d{3})\b/.exec(message)?.[1];
13287
+ switch (kind) {
13288
+ case "unreachable":
13289
+ if (timedOut)
13290
+ return {
13291
+ kind,
13292
+ title: `${name} did not answer in time`,
13293
+ hint: local ? "A local model can take a while to load. Try again once it is loaded." : "Try again in a moment.",
13294
+ detail
13295
+ };
13296
+ return local ? {
13297
+ kind,
13298
+ title: `Nothing answers at ${address ?? "that address"}`,
13299
+ hint: `Start ${name} and switch its server on, then try again.`,
13300
+ detail
13301
+ } : {
13302
+ kind,
13303
+ title: `${name} could not be reached`,
13304
+ hint: "Check the network of the machine Bazilion runs on, then try again.",
13305
+ detail
13306
+ };
13307
+ case "credentials":
13308
+ if (provider.id === "openai-codex")
13309
+ return { kind, title: "ChatGPT did not accept the sign-in", hint: "Sign in again.", detail };
13310
+ if (local)
13311
+ return {
13312
+ kind,
13313
+ title: `${name} asked for a key it did not get`,
13314
+ hint: "Set the API key the server was started with, under More settings.",
13315
+ detail
13316
+ };
13317
+ return provider.fields.some((field) => field.kind === "secret") ? {
13318
+ kind,
13319
+ title: `${name} did not accept this key`,
13320
+ hint: "Check that the whole key was pasted and that it was not revoked.",
13321
+ detail
13322
+ } : {
13323
+ kind,
13324
+ title: `${name} did not accept the credentials`,
13325
+ hint: provider.hint ?? "Check the credentials in the daemon\u2019s environment.",
13326
+ detail
13327
+ };
13328
+ case "model":
13329
+ return local ? {
13330
+ kind,
13331
+ title: `${name} does not have ${modelName} ready`,
13332
+ hint: `Load it in ${name}, or choose another model.`,
13333
+ detail
13334
+ } : {
13335
+ kind,
13336
+ title: `${name} does not offer ${modelName} to this account`,
13337
+ hint: "Choose another model.",
13338
+ detail
13339
+ };
13340
+ case "limit":
13341
+ return {
13342
+ kind,
13343
+ title: `${name} accepted the key but refused the request`,
13344
+ hint: "A limit was reached or there is no credit left. Check the plan and billing at the provider.",
13345
+ detail
13346
+ };
13347
+ default:
13348
+ return local && status2 === "404" ? {
13349
+ kind,
13350
+ title: `${address ?? "That address"} answered, but not like a model server`,
13351
+ hint: "Check the address. It usually ends in /v1.",
13352
+ detail
13353
+ } : {
13354
+ kind,
13355
+ title: `${name} answered with an error`,
13356
+ hint: "Its own words are in the details.",
13357
+ detail
13358
+ };
13359
+ }
13360
+ }
13361
+
13362
+ // ../daemon/src/lib/setting-fields.ts
13363
+ function readAll(read2) {
13364
+ try {
13365
+ return read2();
13366
+ } catch {
13367
+ return {};
13368
+ }
13369
+ }
13370
+ function readStoredSettings(db, authToken) {
13371
+ return {
13372
+ config: readAll(() => openConfig(db).getAll()),
13373
+ secrets: readAll(() => openSecrets(db, authToken).getAll())
13374
+ };
13375
+ }
13376
+ function mask(value) {
13377
+ if (value.length === 0) return "";
13378
+ return value.length > 8 ? `${value.slice(0, 6)}\u2026` : "***";
13379
+ }
13380
+ function fieldStates(fields2, stored) {
13381
+ return fields2.map((field) => {
13382
+ const value = (field.kind === "config" ? stored.config : stored.secrets)[field.envVar] ?? "";
13383
+ const state2 = {
13384
+ envVar: field.envVar,
13385
+ kind: field.kind,
13386
+ label: field.label,
13387
+ set: value.length > 0,
13388
+ ...field.placeholder ? { placeholder: field.placeholder } : {},
13389
+ ...field.description ? { description: field.description } : {},
13390
+ ...field.options ? { options: field.options } : {},
13391
+ ...field.optionLabels ? { optionLabels: field.optionLabels } : {},
13392
+ ...field.advanced ? { advanced: true } : {}
13393
+ };
13394
+ if (field.kind === "config") state2.value = value;
13395
+ else if (value.length > 0) state2.preview = mask(value);
13396
+ return state2;
13397
+ });
13398
+ }
13399
+ function writeSetting(db, authToken, field, value) {
13400
+ const store = field.kind === "config" ? openConfig(db) : openSecrets(db, authToken);
13401
+ if (value === "") store.remove(field.envVar);
13402
+ else store.set(field.envVar, value);
13403
+ }
13404
+
13405
+ // ../daemon/src/lib/provider-setup.ts
13406
+ var TEST_MESSAGE = "Reply with one word: ready.";
13407
+ var TEST_TIMEOUT_MS = 6e4;
13408
+ var MAX_TEST_ATTEMPTS = 3;
13409
+ var LIST_TIMEOUT_MS = 4e3;
13410
+ var DISCOVERY_TIMEOUT_MS = 1500;
13411
+ var IMAGE_MODEL_AS_CHAT = "This is an image model: choose it under Images, not as a chat model.";
13412
+ function requireProvider(id) {
13413
+ const provider = findProvider(id);
13414
+ if (!provider) throw new DomainError(404, `unknown provider: ${id}`);
13415
+ return provider;
13416
+ }
13417
+ function connectKind(provider) {
13418
+ if (provider.id === "openai-codex") return "signin";
13419
+ return provider.local ? "local" : "fields";
13420
+ }
13421
+ function chatCatalog(providerId) {
13422
+ return listCatalogEntries(providerId).filter((model) => !isImageModel(providerId, model.id));
13423
+ }
13424
+ function effectiveEnv({ db, authToken }, overrides = {}) {
13425
+ const env = { ...mergeSecretsIntoEnv(db, authToken, {}), ...overrides };
13426
+ for (const [name, value] of Object.entries(overrides)) if (value === "") delete env[name];
13427
+ return { ...env, ...process.env };
13428
+ }
13429
+ function snapshot2(ctx) {
13430
+ return {
13431
+ env: effectiveEnv(ctx),
13432
+ stored: readStoredSettings(ctx.db, ctx.authToken),
13433
+ enabled: providerState_exports.listEnabled(ctx.db),
13434
+ checks: readProviderChecks(ctx.db),
13435
+ codex: getStatus(ctx.db, ctx.authToken)
13436
+ };
13437
+ }
13438
+ function hasCredentials2(provider, env, codexConnected) {
13439
+ return provider.id === "openai-codex" ? codexConnected : isProviderConfigured(provider.id, env);
13440
+ }
13441
+ function localAddress(provider, env) {
13442
+ if (!provider.local) return void 0;
13443
+ return providerEndpoint(provider.id, env) ?? provider.endpoint?.fallback;
13444
+ }
13445
+ function entryOf(provider, snap, db) {
13446
+ const connect3 = connectKind(provider);
13447
+ const configured = hasCredentials2(provider, snap.env, snap.codex.connected);
13448
+ const enabled = snap.enabled.has(provider.id);
13449
+ const models = providerModels_exports.list(db, provider.id);
13450
+ const fields2 = fieldStates(provider.fields, snap.stored);
13451
+ const check = snap.checks[provider.id];
13452
+ let state2 = "untested";
13453
+ if (!enabled) state2 = "off";
13454
+ else if (!configured) state2 = "incomplete";
13455
+ else if (check) state2 = check.ok ? "working" : "failing";
13456
+ const address = localAddress(provider, snap.env);
13457
+ return {
13458
+ id: provider.id,
13459
+ displayName: provider.displayName,
13460
+ ...provider.hint ? { hint: provider.hint } : {},
13461
+ connect: connect3,
13462
+ group: provider.popular ? "popular" : provider.local ? "local" : "more",
13463
+ fields: fields2,
13464
+ configured,
13465
+ enabled,
13466
+ listed: enabled || models.length > 0 || fields2.some((field) => field.set) || connect3 === "signin" && configured,
13467
+ state: state2,
13468
+ ...check ? { check } : {},
13469
+ models,
13470
+ suggested: [...provider.suggested ?? []],
13471
+ catalogSize: chatCatalog(provider.id).length,
13472
+ listsModels: Boolean(provider.local || provider.modelsUrl),
13473
+ ...address ? { address } : {},
13474
+ ...connect3 === "signin" && snap.codex.accountId ? { account: snap.codex.accountId } : {}
13475
+ };
13476
+ }
13477
+ function providerEntries(ctx) {
13478
+ const snap = snapshot2(ctx);
13479
+ return PROVIDERS.map((provider) => entryOf(provider, snap, ctx.db));
13480
+ }
13481
+ function providerEntry(ctx, id) {
13482
+ return entryOf(requireProvider(id), snapshot2(ctx), ctx.db);
13483
+ }
13484
+ function modelsOverview(ctx) {
13485
+ const snap = snapshot2(ctx);
13486
+ const usage = modelUsage(ctx.db);
13487
+ const chat = [];
13488
+ for (const provider of PROVIDERS) {
13489
+ if (!snap.enabled.has(provider.id)) continue;
13490
+ const entry = entryOf(provider, snap, ctx.db);
13491
+ const facts = new Map(chatCatalog(provider.id).map((model) => [model.id, model]));
13492
+ for (const id of entry.models) {
13493
+ const value = `${provider.id}:${id}`;
13494
+ chat.push({
13495
+ ...catalogModel(id, facts.get(id)),
13496
+ selected: true,
13497
+ suggested: entry.suggested.includes(id),
13498
+ value,
13499
+ provider: provider.id,
13500
+ providerName: provider.displayName,
13501
+ providerConnect: entry.connect,
13502
+ providerState: entry.state,
13503
+ usedBy: usage.get(value) ?? { agents: 0, templates: [] }
13504
+ });
13505
+ }
13506
+ }
13507
+ return {
13508
+ chat,
13509
+ images: {
13510
+ selected: snap.env.BAZILION_IMAGE_MODEL || "off",
13511
+ routes: IMAGE_ROUTES.map((route) => {
13512
+ const needs = imageRouteNeeds(route, snap.env, snap.codex.connected);
13513
+ return {
13514
+ id: route.id,
13515
+ model: route.model,
13516
+ provider: route.provider,
13517
+ providerName: findProvider(route.provider)?.displayName ?? route.provider,
13518
+ billing: route.billing,
13519
+ ready: needs === null,
13520
+ ...needs ? { needs } : {}
13521
+ };
13522
+ })
13523
+ }
13524
+ };
13525
+ }
13526
+ function catalogModel(id, facts) {
13527
+ if (!facts) return { id };
13528
+ return {
13529
+ id,
13530
+ name: facts.name,
13531
+ ...facts.contextWindow > 0 ? { contextWindow: facts.contextWindow } : {},
13532
+ images: facts.images,
13533
+ reasoning: facts.reasoning,
13534
+ ...facts.price ? { price: facts.price } : {}
13535
+ };
13536
+ }
13537
+ function providerOverrides(provider, fields2) {
13538
+ if (fields2 === void 0) return {};
13539
+ if (fields2 === null || typeof fields2 !== "object" || Array.isArray(fields2)) {
13540
+ throw new DomainError(400, "fields must be an object of setting names and values");
13541
+ }
13542
+ const overrides = {};
13543
+ for (const [name, value] of Object.entries(fields2)) {
13544
+ if (!provider.fields.some((field) => field.envVar === name)) {
13545
+ throw new DomainError(400, `${name} is not a setting of ${provider.id}`);
13546
+ }
13547
+ if (typeof value !== "string") throw new DomainError(400, `${name} must be a string`);
13548
+ overrides[name] = value.trim();
13549
+ }
13550
+ return overrides;
13551
+ }
13552
+ async function providerCatalog(ctx, id, fields2, signal) {
13553
+ const provider = requireProvider(id);
13554
+ const env = effectiveEnv(ctx, providerOverrides(provider, fields2));
13555
+ const limit = AbortSignal.timeout(LIST_TIMEOUT_MS);
13556
+ const ask = Boolean(provider.local) || providerState_exports.listEnabled(ctx.db).has(id);
13557
+ const live = ask ? await listLiveModels(id, env, signal ? AbortSignal.any([signal, limit]) : limit) : void 0;
13558
+ const listed = (live?.models ?? []).filter((model) => !isImageModel(id, model));
13559
+ const selected = providerModels_exports.list(ctx.db, id);
13560
+ const catalog = provider.local ? [] : chatCatalog(id);
13561
+ const facts = new Map(catalog.map((model) => [model.id, model]));
13562
+ const ids = [.../* @__PURE__ */ new Set([...facts.keys(), ...listed, ...selected])];
13563
+ const dated = datedCopies(ids);
13564
+ const suggested = new Set(provider.suggested ?? []);
13565
+ if (provider.local && selected.length === 0 && listed[0]) suggested.add(listed[0]);
13566
+ return {
13567
+ models: ids.map((model) => ({
13568
+ ...catalogModel(model, facts.get(model)),
13569
+ ...dated.has(model) ? { dated: true } : {},
13570
+ selected: selected.includes(model),
13571
+ suggested: suggested.has(model)
13572
+ })),
13573
+ ...live?.error ? { listError: live.error } : {}
13574
+ };
13575
+ }
13576
+ function setProviderModels(ctx, id, models) {
13577
+ requireProvider(id);
13578
+ if (models.some((model) => isImageModel(id, model.trim()))) {
13579
+ throw new DomainError(400, IMAGE_MODEL_AS_CHAT);
13580
+ }
13581
+ const saved = replaceCuratedModels(ctx.db, id, [...models]);
13582
+ const check = readProviderChecks(ctx.db)[id];
13583
+ if (check && !saved.models.includes(check.model)) writeProviderCheck(ctx.db, id, null);
13584
+ ensureSetupSeeded(ctx.db, ctx.paths);
13585
+ return saved;
13586
+ }
13587
+ async function discoverLocalProviders(ctx) {
13588
+ const env = effectiveEnv(ctx);
13589
+ const servers = await Promise.all(
13590
+ PROVIDERS.filter((provider) => provider.local).map(async (provider) => {
13591
+ const live = await listLiveModels(provider.id, env, AbortSignal.timeout(DISCOVERY_TIMEOUT_MS));
13592
+ return {
13593
+ id: provider.id,
13594
+ displayName: provider.displayName,
13595
+ address: localAddress(provider, env) ?? "",
13596
+ found: Boolean(live) && !live?.error,
13597
+ models: live?.models ?? []
13598
+ };
13599
+ })
13600
+ );
13601
+ return { servers };
13602
+ }
13603
+ function cheapestFirst(providerId, models) {
13604
+ const price = new Map(
13605
+ listCatalogEntries(providerId).map((model) => [
13606
+ model.id,
13607
+ model.price ? model.price.input + model.price.output : Number.POSITIVE_INFINITY
13608
+ ])
13609
+ );
13610
+ const cost = (model) => price.get(model) ?? Number.POSITIVE_INFINITY;
13611
+ return models.map((model, index) => ({ model, index })).sort((a, b) => cost(a.model) - cost(b.model) || a.index - b.index).map(({ model }) => model);
13612
+ }
13613
+ function nameOf(providerId, model) {
13614
+ const name = chatCatalog(providerId).find((entry) => entry.id === model)?.name;
13615
+ return name ? { modelName: name } : {};
13616
+ }
13617
+ function hostOf(address) {
13618
+ if (!address) return void 0;
13619
+ try {
13620
+ return new URL(address).host;
13621
+ } catch {
13622
+ return address;
13623
+ }
13624
+ }
13625
+ async function askModel(ctx, provider, model, env, signal) {
13626
+ const limit = AbortSignal.timeout(TEST_TIMEOUT_MS);
13627
+ const started = Date.now();
13628
+ const secrets = provider.fields.filter((field) => field.kind === "secret").flatMap((field) => env[field.envVar] ?? []);
13629
+ try {
13630
+ const apiKey2 = provider.id === "openai-codex" ? await loadAccessToken(ctx.db, ctx.authToken) : void 0;
13631
+ if (apiKey2) secrets.push(apiKey2);
13632
+ await testProviderModel({
13633
+ providerName: provider.id,
13634
+ modelId: model,
13635
+ env,
13636
+ ...apiKey2 ? { apiKey: apiKey2 } : {},
13637
+ message: TEST_MESSAGE,
13638
+ signal: signal ? AbortSignal.any([signal, limit]) : limit
13639
+ });
13640
+ return { ok: true, ms: Date.now() - started };
13641
+ } catch (error) {
13642
+ const name = chatCatalog(provider.id).find((entry) => entry.id === model)?.name ?? model;
13643
+ return {
13644
+ ok: false,
13645
+ failure: describeProviderFailure(error.message, {
13646
+ provider,
13647
+ modelName: name,
13648
+ address: hostOf(localAddress(provider, env)),
13649
+ timedOut: limit.aborted,
13650
+ secrets
13651
+ })
13652
+ };
12917
13653
  }
12918
13654
  }
12919
- function openAICodexBrowserCommand(platform = process.platform) {
12920
- return platform === "darwin" ? "/usr/bin/open" : "xdg-open";
12921
- }
12922
- function launchOpenAICodexBrowser(url, onFailure) {
12923
- const command = openAICodexBrowserCommand();
12924
- const fail2 = (detail) => onFailure(
12925
- new Error(
12926
- `Could not open the OpenAI sign-in page with ${command}: ${detail}. Run ${DEVICE_CODE_FALLBACK}.`
12927
- )
13655
+ async function nothingToAsk(provider, env, signal) {
13656
+ const name = provider.displayName;
13657
+ if (!provider.local) {
13658
+ return {
13659
+ kind: "model",
13660
+ title: `No chat model was chosen for ${name}`,
13661
+ hint: "Choose at least one: connecting asks it for a short reply.",
13662
+ detail: ""
13663
+ };
13664
+ }
13665
+ const limit = AbortSignal.timeout(LIST_TIMEOUT_MS);
13666
+ const live = await listLiveModels(
13667
+ provider.id,
13668
+ env,
13669
+ signal ? AbortSignal.any([signal, limit]) : limit
12928
13670
  );
12929
- const child = spawn5(command, [url], { stdio: "ignore", detached: true });
12930
- child.once("error", (error) => fail2(error.message));
12931
- child.once("exit", (code, signal) => {
12932
- if (code !== 0) fail2(code === null ? `terminated by ${signal}` : `exited ${code}`);
12933
- });
12934
- child.unref();
13671
+ if (live?.error) {
13672
+ const message = /^\d{3}\b/.test(live.error) ? live.error : `Connection error.: ${live.error}`;
13673
+ return describeProviderFailure(message, {
13674
+ provider,
13675
+ modelName: "",
13676
+ address: hostOf(localAddress(provider, env)),
13677
+ secrets: provider.fields.filter((field) => field.kind === "secret").flatMap((field) => env[field.envVar] ?? [])
13678
+ });
13679
+ }
13680
+ return {
13681
+ kind: "model",
13682
+ title: `${name} lists no models`,
13683
+ hint: `Load or download a model in ${name}, then connect again.`,
13684
+ detail: ""
13685
+ };
12935
13686
  }
12936
- function answerWebOpenAIPrompt(prompt, login) {
12937
- if (prompt.type === "select") {
12938
- return prompt.options.some((option) => option.id === "browser") ? Promise.resolve("browser") : Promise.reject(new Error("Pi openai-codex provider does not support browser login"));
13687
+ function missingCredentials(provider) {
13688
+ const name = provider.displayName;
13689
+ if (provider.id === "openai-codex") {
13690
+ return {
13691
+ kind: "credentials",
13692
+ title: "ChatGPT is not signed in",
13693
+ hint: "Sign in with ChatGPT first, here or with bazilion auth openai login.",
13694
+ detail: ""
13695
+ };
12939
13696
  }
12940
- if (prompt.type !== "manual_code") {
12941
- return Promise.reject(
12942
- new Error(`Interactive input is not supported in the web flow. Run ${DEVICE_CODE_FALLBACK}.`)
12943
- );
13697
+ const field = provider.fields.find((candidate) => !candidate.advanced);
13698
+ return field ? {
13699
+ kind: "credentials",
13700
+ title: `${name} needs its ${field.label}`,
13701
+ hint: "Fill it in, then connect again.",
13702
+ detail: ""
13703
+ } : {
13704
+ kind: "credentials",
13705
+ title: `${name} has no credentials`,
13706
+ hint: provider.hint ?? "Its credentials come from the daemon\u2019s environment.",
13707
+ detail: ""
13708
+ };
13709
+ }
13710
+ function cleanModels(models) {
13711
+ if (!Array.isArray(models) || models.some((model) => typeof model !== "string")) {
13712
+ throw new DomainError(400, "models must be an array of strings");
13713
+ }
13714
+ return [...new Set(models.map((model) => model.trim()).filter(Boolean))];
13715
+ }
13716
+ async function connectProvider(ctx, id, request, signal) {
13717
+ const { db, authToken, paths } = ctx;
13718
+ const provider = requireProvider(id);
13719
+ const overrides = providerOverrides(provider, request.fields);
13720
+ const env = effectiveEnv(ctx, overrides);
13721
+ const codex = getStatus(db, authToken);
13722
+ if (!hasCredentials2(provider, env, codex.connected)) {
13723
+ return { connected: false, failure: missingCredentials(provider) };
13724
+ }
13725
+ const saved = providerModels_exports.list(db, id);
13726
+ const models = request.models === void 0 ? saved.length > 0 ? saved : [...provider.suggested ?? []] : cleanModels(request.models);
13727
+ if (models.some((model) => isImageModel(id, model))) {
13728
+ throw new DomainError(400, IMAGE_MODEL_AS_CHAT);
13729
+ }
13730
+ let check = null;
13731
+ const dropped = [];
13732
+ if (request.test !== false && models.length === 0) {
13733
+ return { connected: false, failure: await nothingToAsk(provider, env, signal) };
13734
+ }
13735
+ if (request.test !== false) {
13736
+ let refused;
13737
+ for (const model of cheapestFirst(id, models).slice(0, MAX_TEST_ATTEMPTS)) {
13738
+ const asked = await askModel(ctx, provider, model, env, signal);
13739
+ if (asked.ok) {
13740
+ check = { ok: true, at: Date.now(), model, ...nameOf(id, model), ms: asked.ms };
13741
+ break;
13742
+ }
13743
+ if (asked.failure.kind !== "model") return { connected: false, failure: asked.failure };
13744
+ dropped.push({ model, detail: asked.failure.detail });
13745
+ refused = asked.failure;
13746
+ }
13747
+ if (!check) return { connected: false, failure: refused };
12944
13748
  }
12945
- const ended = prompt.signal ? AbortSignal.any([prompt.signal, login]) : login;
12946
- return new Promise((_resolve, reject2) => {
12947
- const stop = () => reject2(new Error("OpenAI browser login ended"));
12948
- if (ended.aborted) stop();
12949
- else ended.addEventListener("abort", stop, { once: true });
13749
+ const kept = models.filter((model) => !dropped.some((entry) => entry.model === model));
13750
+ let movedTemplates = [];
13751
+ db.raw.transaction(() => {
13752
+ for (const [name, value] of Object.entries(overrides)) {
13753
+ const field = provider.fields.find((candidate) => candidate.envVar === name);
13754
+ if (field) writeSetting(db, authToken, field, value);
13755
+ }
13756
+ movedTemplates = replaceCuratedModels(db, id, kept).movedTemplates;
13757
+ providerState_exports.setEnabled(db, id, true);
13758
+ writeProviderCheck(db, id, check);
13759
+ })();
13760
+ ensureSetupSeeded(db, paths);
13761
+ return { connected: true, provider: providerEntry(ctx, id), check, dropped, movedTemplates };
13762
+ }
13763
+ async function testProvider(ctx, id, signal) {
13764
+ const provider = requireProvider(id);
13765
+ const env = effectiveEnv(ctx);
13766
+ const model = cheapestFirst(id, providerModels_exports.list(ctx.db, id))[0];
13767
+ if (!model) throw new DomainError(409, `${provider.displayName} has no chat model to ask`);
13768
+ let check;
13769
+ if (!hasCredentials2(provider, env, getStatus(ctx.db, ctx.authToken).connected)) {
13770
+ check = { ok: false, at: Date.now(), model, failure: missingCredentials(provider) };
13771
+ } else {
13772
+ const asked = await askModel(ctx, provider, model, env, signal);
13773
+ check = asked.ok ? { ok: true, at: Date.now(), model, ...nameOf(id, model), ms: asked.ms } : { ok: false, at: Date.now(), model, ...nameOf(id, model), failure: asked.failure };
13774
+ }
13775
+ writeProviderCheck(ctx.db, id, check);
13776
+ return { check, provider: providerEntry(ctx, id) };
13777
+ }
13778
+ function recordProviderTest(ctx, providerId, model, outcome) {
13779
+ const provider = findProvider(providerId);
13780
+ if (!provider) return;
13781
+ if ("ms" in outcome) {
13782
+ writeProviderCheck(ctx.db, providerId, {
13783
+ ok: true,
13784
+ at: Date.now(),
13785
+ model,
13786
+ ...nameOf(providerId, model),
13787
+ ms: outcome.ms
13788
+ });
13789
+ return;
13790
+ }
13791
+ const env = effectiveEnv(ctx);
13792
+ writeProviderCheck(ctx.db, providerId, {
13793
+ ok: false,
13794
+ at: Date.now(),
13795
+ model,
13796
+ ...nameOf(providerId, model),
13797
+ failure: describeProviderFailure(outcome.error, {
13798
+ provider,
13799
+ modelName: chatCatalog(providerId).find((entry) => entry.id === model)?.name ?? model,
13800
+ address: hostOf(localAddress(provider, env)),
13801
+ secrets: provider.fields.filter((field) => field.kind === "secret").flatMap((field) => env[field.envVar] ?? [])
13802
+ })
12950
13803
  });
12951
13804
  }
12952
- function webOpenAILoginError(error, signal) {
12953
- const reason = signal.aborted ? signal.reason : error;
12954
- if (reason instanceof Error && reason.name === "TimeoutError") {
12955
- return `OpenAI browser login timed out after 10 minutes. Try again, or run ${DEVICE_CODE_FALLBACK}.`;
13805
+ function setProviderEnabled(ctx, id, enabled) {
13806
+ const provider = requireProvider(id);
13807
+ if (enabled) {
13808
+ const snap = snapshot2(ctx);
13809
+ if (!hasCredentials2(provider, snap.env, snap.codex.connected)) {
13810
+ throw new DomainError(
13811
+ 409,
13812
+ `${provider.displayName} has no credentials yet: connect it first (bazilion provider connect ${id})`
13813
+ );
13814
+ }
12956
13815
  }
12957
- return reason instanceof Error ? reason.message : String(reason);
13816
+ providerState_exports.setEnabled(ctx.db, id, enabled);
13817
+ ensureSetupSeeded(ctx.db, ctx.paths);
13818
+ }
13819
+ function disconnectProvider(ctx, id) {
13820
+ const { db, authToken } = ctx;
13821
+ const provider = requireProvider(id);
13822
+ const enabled = providerState_exports.listEnabled(db);
13823
+ let result = { models: [], movedTemplates: [] };
13824
+ db.raw.transaction(() => {
13825
+ providerState_exports.setEnabled(db, id, false);
13826
+ for (const field of provider.fields) {
13827
+ const shared = providersUsingField(field.envVar).some(
13828
+ (other) => other !== id && enabled.has(other)
13829
+ );
13830
+ if (!shared) writeSetting(db, authToken, field, "");
13831
+ }
13832
+ if (provider.id === "openai-codex") clearCredentials(db, authToken);
13833
+ result = replaceCuratedModels(db, id, []);
13834
+ writeProviderCheck(db, id, null);
13835
+ })();
13836
+ return result;
13837
+ }
13838
+ function forgetChecksFor(db, envVar) {
13839
+ for (const id of providersUsingField(envVar)) writeProviderCheck(db, id, null);
12958
13840
  }
12959
13841
 
12960
13842
  // ../daemon/src/routes/auth-login.ts
@@ -13034,22 +13916,29 @@ authRouter.post("/providers/test", async (c) => {
13034
13916
  return c.json({ error: "model is required" }, 400);
13035
13917
  }
13036
13918
  const message = typeof body.message === "string" && body.message ? body.message : "say hi briefly";
13037
- const { db, authToken, paths } = getCtx();
13919
+ const ctx = getCtx();
13920
+ const { db, authToken, paths } = ctx;
13921
+ let tested;
13922
+ const started = Date.now();
13038
13923
  try {
13039
13924
  assertProviderReady(db, authToken, body.model);
13040
- const { providerName, modelId } = parseModelString(body.model);
13925
+ tested = parseModelString(body.model);
13041
13926
  const res = await testProviderModel({
13042
- providerName,
13043
- modelId,
13927
+ ...tested,
13044
13928
  env: mergeSecretsIntoEnv(db, authToken),
13045
- ...providerName === "openai-codex" ? { apiKey: await loadAccessToken(db, authToken) } : {},
13929
+ ...tested.providerName === "openai-codex" ? { apiKey: await loadAccessToken(db, authToken) } : {},
13046
13930
  message,
13047
13931
  signal: c.req.raw.signal
13048
13932
  });
13933
+ recordProviderTest(ctx, tested.providerName, tested.modelId, { ms: Date.now() - started });
13049
13934
  ensureSetupSeeded(db, paths);
13050
13935
  return c.json(res);
13051
13936
  } catch (err) {
13052
- return c.json({ error: err.message }, 400);
13937
+ const error = err.message;
13938
+ if (tested && !c.req.raw.signal.aborted) {
13939
+ recordProviderTest(ctx, tested.providerName, tested.modelId, { error });
13940
+ }
13941
+ return c.json({ error }, 400);
13053
13942
  }
13054
13943
  });
13055
13944
  var COOKIE_MAX_AGE_SECONDS = 400 * 24 * 60 * 60;
@@ -13113,90 +14002,74 @@ authRouter.delete("/sessions/:id", (c) => {
13113
14002
 
13114
14003
  // ../daemon/src/routes/config.ts
13115
14004
  var configRouter = newRouter();
13116
- configRouter.get("/providers", async (c) => {
13117
- const { db, authToken } = getCtx();
13118
- const env = mergeSecretsIntoEnv(db, authToken);
13119
- const configValues = readAll(() => openConfig(db).getAll());
13120
- const secretValues = readAll(() => openSecrets(db, authToken).getAll());
13121
- const enabledSet = providerState_exports.listEnabled(db);
13122
- const entries = await Promise.all(
13123
- PROVIDERS.map(async (provider) => {
13124
- const enabled = enabledSet.has(provider.id);
13125
- const { catalog, live } = enabled ? await listCatalogModels(provider.id, env, AbortSignal.timeout(5e3)) : { catalog: listCatalogModelsSync(provider.id), live: void 0 };
13126
- return {
13127
- id: provider.id,
13128
- displayName: provider.displayName,
13129
- ...provider.hint ? { hint: provider.hint } : {},
13130
- enabled,
13131
- fields: resolveFieldStates(provider, configValues, secretValues),
13132
- catalog: catalog.filter((model) => !isImageChoice(provider.id, model)),
13133
- ...live ? {
13134
- live: {
13135
- ...live,
13136
- models: live.models.filter((model) => !isImageChoice(provider.id, model))
13137
- }
13138
- } : {},
13139
- curated: providerModels_exports.list(db, provider.id)
13140
- };
13141
- })
14005
+ configRouter.get(
14006
+ "/providers",
14007
+ (c) => c.json({ providers: providerEntries(getCtx()) })
14008
+ );
14009
+ configRouter.get("/providers/local", async (c) => c.json(await discoverLocalProviders(getCtx())));
14010
+ configRouter.get(
14011
+ "/providers/:name/catalog",
14012
+ async (c) => c.json(await providerCatalog(getCtx(), c.req.param("name"), void 0, c.req.raw.signal))
14013
+ );
14014
+ configRouter.post("/providers/:name/catalog", async (c) => {
14015
+ const body = await jsonBody(c);
14016
+ return c.json(
14017
+ await providerCatalog(getCtx(), c.req.param("name"), body?.fields, c.req.raw.signal)
13142
14018
  );
13143
- const body = { providers: entries };
13144
- return c.json(body);
13145
14019
  });
13146
- configRouter.get("/services", (c) => {
13147
- const { db, authToken } = getCtx();
13148
- const configValues = readAll(() => openConfig(db).getAll());
13149
- const secretValues = readAll(() => openSecrets(db, authToken).getAll());
13150
- const env = mergeSecretsIntoEnv(db, authToken);
13151
- const image = imageRoute(env, hasCredentials(db, authToken));
13152
- const services = servicesByCategory("service").map((svc) => ({
13153
- ...svc.id === "image-generation" ? { status: image.ready ? `Ready: ${image.model}.` : image.reason } : {},
13154
- ...svc.id === "web-search" ? { status: searchStatus(env) } : {},
13155
- id: svc.id,
13156
- displayName: svc.displayName,
13157
- ...svc.hint ? { hint: svc.hint } : {},
13158
- ...svc.team ? { team: svc.team } : {},
13159
- fields: resolveFieldStates(svc, configValues, secretValues)
13160
- }));
13161
- const body = { services };
13162
- return c.json(body);
14020
+ configRouter.post("/providers/:name/connect", async (c) => {
14021
+ const body = await jsonBody(c) ?? {};
14022
+ return c.json(await connectProvider(getCtx(), c.req.param("name"), body, c.req.raw.signal));
13163
14023
  });
14024
+ configRouter.post(
14025
+ "/providers/:name/test",
14026
+ async (c) => c.json(await testProvider(getCtx(), c.req.param("name"), c.req.raw.signal))
14027
+ );
14028
+ configRouter.delete(
14029
+ "/providers/:name",
14030
+ (c) => c.json(disconnectProvider(getCtx(), c.req.param("name")))
14031
+ );
13164
14032
  configRouter.put("/providers/:name/enabled", async (c) => {
13165
14033
  const name = c.req.param("name");
13166
- if (!findProvider(name)) return c.json({ error: `unknown provider: ${name}` }, 404);
14034
+ requireProvider(name);
13167
14035
  const enabled = (await jsonBody(c))?.enabled;
13168
14036
  if (typeof enabled !== "boolean") {
13169
14037
  return c.json({ error: 'body must be {"enabled": boolean}' }, 400);
13170
14038
  }
13171
- const { db, paths } = getCtx();
13172
- providerState_exports.setEnabled(db, name, enabled);
13173
- ensureSetupSeeded(db, paths);
14039
+ setProviderEnabled(getCtx(), name, enabled);
13174
14040
  return c.json({ name, enabled });
13175
14041
  });
13176
- configRouter.get("/providers/:name/models", (c) => {
13177
- const name = c.req.param("name");
13178
- if (!findProvider(name)) return c.json({ error: `unknown provider: ${name}` }, 404);
13179
- const { db } = getCtx();
13180
- return c.json({ models: providerModels_exports.list(db, name) });
13181
- });
13182
14042
  configRouter.put("/providers/:name/models", async (c) => {
13183
- const name = c.req.param("name");
13184
- if (!findProvider(name)) return c.json({ error: `unknown provider: ${name}` }, 404);
13185
14043
  const body = await jsonBody(c);
13186
14044
  if (!Array.isArray(body?.models)) {
13187
14045
  return c.json({ error: "models must be an array of strings" }, 400);
13188
14046
  }
13189
14047
  const models = body.models.filter((m) => typeof m === "string");
13190
- if (models.some((model) => isImageChoice(name, model.trim()))) {
13191
- return c.json(
13192
- { error: "Configure image models in Services \u2192 Image generation, not as chat models." },
13193
- 400
13194
- );
13195
- }
13196
- const { db, paths } = getCtx();
13197
- const saved = replaceCuratedModels(db, name, models);
13198
- ensureSetupSeeded(db, paths);
13199
- return c.json(saved);
14048
+ return c.json(setProviderModels(getCtx(), c.req.param("name"), models));
14049
+ });
14050
+ configRouter.get("/models", (c) => c.json(modelsOverview(getCtx())));
14051
+ configRouter.get(
14052
+ "/available-models",
14053
+ (c) => c.json({ teams: groupAvailableModels(getCtx().db) })
14054
+ );
14055
+ configRouter.get("/services", (c) => {
14056
+ const { db, authToken } = getCtx();
14057
+ const stored = readStoredSettings(db, authToken);
14058
+ const env = mergeSecretsIntoEnv(db, authToken);
14059
+ const image = imageRoute(env, hasCredentials(db, authToken));
14060
+ const card = (svc) => ({
14061
+ ...svc.id === "image-generation" ? { status: image.ready ? `Ready: ${image.model}.` : image.reason } : {},
14062
+ ...svc.id === "web-search" ? { status: searchStatus(env) } : {},
14063
+ id: svc.id,
14064
+ displayName: svc.displayName,
14065
+ ...svc.hint ? { hint: svc.hint } : {},
14066
+ ...svc.team ? { team: svc.team } : {},
14067
+ fields: fieldStates(svc.fields, stored)
14068
+ });
14069
+ return c.json({
14070
+ services: servicesByCategory("service").map(card),
14071
+ functions: servicesByCategory("function").map(card)
14072
+ });
13200
14073
  });
13201
14074
  configRouter.put("/fields/:envVar", async (c) => {
13202
14075
  const envVar = c.req.param("envVar");
@@ -13210,75 +14083,27 @@ configRouter.put("/fields/:envVar", async (c) => {
13210
14083
  return c.json({ error: `Choose one of: ${field.options.join(", ")}` }, 400);
13211
14084
  }
13212
14085
  const { db, authToken } = getCtx();
13213
- if (field.kind === "config") {
13214
- const store = openConfig(db);
13215
- if (body.value === "") store.remove(envVar);
13216
- else store.set(envVar, body.value);
13217
- } else {
13218
- const store = openSecrets(db, authToken);
13219
- if (body.value === "") store.remove(envVar);
13220
- else store.set(envVar, body.value);
13221
- }
14086
+ writeSetting(db, authToken, field, body.value);
14087
+ forgetChecksFor(db, envVar);
13222
14088
  return c.json(readFieldState(db, authToken, envVar, field.kind));
13223
14089
  });
13224
- configRouter.get(
13225
- "/available-models",
13226
- (c) => c.json({ teams: groupAvailableModels(getCtx().db) })
13227
- );
13228
14090
  configRouter.delete("/fields/:envVar", (c) => {
13229
14091
  const envVar = c.req.param("envVar");
13230
14092
  const field = findFieldByEnvVar(envVar);
13231
14093
  if (!field) return c.json({ error: `unknown envVar: ${envVar}` }, 404);
13232
14094
  const { db, authToken } = getCtx();
13233
- if (field.kind === "config") {
13234
- openConfig(db).remove(envVar);
13235
- } else {
13236
- openSecrets(db, authToken).remove(envVar);
13237
- }
14095
+ writeSetting(db, authToken, field, "");
14096
+ forgetChecksFor(db, envVar);
13238
14097
  return c.body(null, 204);
13239
14098
  });
13240
- function isImageChoice(provider, model) {
13241
- return IMAGE_MODEL_CHOICES.includes(`${provider}:${model}`);
13242
- }
13243
- function mask(value) {
13244
- if (value.length === 0) return "";
13245
- return value.length > 8 ? `${value.slice(0, 6)}\u2026` : "***";
13246
- }
13247
- function resolveFieldStates(service, configValues, secretValues) {
13248
- return service.fields.map((f) => {
13249
- const val = (f.kind === "config" ? configValues[f.envVar] : secretValues[f.envVar]) ?? "";
13250
- const state2 = {
13251
- envVar: f.envVar,
13252
- kind: f.kind,
13253
- label: f.label,
13254
- set: val.length > 0,
13255
- ...f.placeholder ? { placeholder: f.placeholder } : {},
13256
- ...f.description ? { description: f.description } : {},
13257
- ...f.options ? { options: f.options } : {},
13258
- ...f.optionLabels ? { optionLabels: f.optionLabels } : {}
13259
- };
13260
- if (f.kind === "config") {
13261
- state2.value = val;
13262
- } else if (val.length > 0) {
13263
- state2.preview = mask(val);
13264
- }
13265
- return state2;
13266
- });
13267
- }
13268
- function readAll(read2) {
13269
- try {
13270
- return read2();
13271
- } catch {
13272
- return {};
13273
- }
13274
- }
13275
14099
  function readFieldState(db, authToken, envVar, kind) {
13276
14100
  if (kind === "config") {
13277
14101
  const v2 = openConfig(db).get(envVar) ?? "";
13278
14102
  return { envVar, kind, set: v2.length > 0, value: v2 };
13279
14103
  }
13280
14104
  const v = openSecrets(db, authToken).get(envVar) ?? "";
13281
- return { envVar, kind, set: v.length > 0, ...v.length > 0 ? { preview: mask(v) } : {} };
14105
+ const preview = v.length > 8 ? `${v.slice(0, 6)}\u2026` : "***";
14106
+ return { envVar, kind, set: v.length > 0, ...v.length > 0 ? { preview } : {} };
13282
14107
  }
13283
14108
 
13284
14109
  // ../daemon/src/routes/conversations.ts
@@ -13331,6 +14156,17 @@ conversationsRouter.get("/:agentId/conversations/:id", (c) => {
13331
14156
  );
13332
14157
  }
13333
14158
  });
14159
+ conversationsRouter.post("/:agentId/conversations/:id/select", async (c) => {
14160
+ const agentId = c.get("agentId");
14161
+ const id = c.req.param("id");
14162
+ const { db, paths } = getCtx();
14163
+ return c.json({
14164
+ conversation: await runAgentLifecycleMutation(
14165
+ agentId,
14166
+ () => selectConversation(db, paths, agentId, id)
14167
+ )
14168
+ });
14169
+ });
13334
14170
  conversationsRouter.patch("/:agentId/conversations/:id", async (c) => {
13335
14171
  const input = await jsonBody(c);
13336
14172
  return c.json({
@@ -13466,6 +14302,13 @@ mcpRouter.post("/:id/test", async (c) => {
13466
14302
 
13467
14303
  // ../daemon/src/routes/messages.ts
13468
14304
  var messagesRouter = newRouter();
14305
+ var teamMessagesRouter = newRouter();
14306
+ teamMessagesRouter.get("/:id/messages", (c) => {
14307
+ const limit = Math.min(Math.max(Number(c.req.query("limit")) || 100, 1), 500);
14308
+ return c.json({
14309
+ messages: messages_exports.listForTeam(getCtx().db, routeTeam(c).id, limit)
14310
+ });
14311
+ });
13469
14312
  messagesRouter.get("/:id", (c) => {
13470
14313
  const msg = messages_exports.get(getCtx().db, c.req.param("id"));
13471
14314
  if (!msg) return c.json({ error: `message not found: ${c.req.param("id")}` }, 404);
@@ -13521,23 +14364,23 @@ agentMessagesRouter.post("/:id/messages", async (c) => {
13521
14364
  // ../daemon/src/routes/misc.ts
13522
14365
  import { existsSync as existsSync17 } from "node:fs";
13523
14366
  import { homedir as homedir4 } from "node:os";
13524
- import { join as join31 } from "node:path";
14367
+ import { join as join32 } from "node:path";
13525
14368
 
13526
14369
  // ../daemon/src/lib/backup.ts
13527
14370
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync13 } from "node:fs";
13528
14371
  import { tmpdir as tmpdir3 } from "node:os";
13529
- import { join as join30, resolve as resolve7 } from "node:path";
14372
+ import { join as join31, resolve as resolve7 } from "node:path";
13530
14373
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
13531
14374
  import { create as create6 } from "tar";
13532
14375
 
13533
14376
  // ../daemon/src/lib/daemon-liveness.ts
13534
14377
  import { mkdirSync as mkdirSync11, readFileSync as readFileSync11, rmSync as rmSync12, writeFileSync as writeFileSync10 } from "node:fs";
13535
- import { join as join29 } from "node:path";
14378
+ import { join as join30 } from "node:path";
13536
14379
  var DAEMON_PID_FILE = "daemon.pid";
13537
14380
  function runningDaemonPid(home) {
13538
14381
  let pid;
13539
14382
  try {
13540
- pid = Number.parseInt(readFileSync11(join29(home, DAEMON_PID_FILE), "utf8"), 10);
14383
+ pid = Number.parseInt(readFileSync11(join30(home, DAEMON_PID_FILE), "utf8"), 10);
13541
14384
  } catch (error) {
13542
14385
  if (error.code === "ENOENT") return null;
13543
14386
  throw error;
@@ -13554,12 +14397,12 @@ function assertDaemonStopped(home) {
13554
14397
  const pid = runningDaemonPid(home);
13555
14398
  if (pid !== null) {
13556
14399
  throw new Error(
13557
- `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${join29(home, DAEMON_PID_FILE)})`
14400
+ `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${join30(home, DAEMON_PID_FILE)})`
13558
14401
  );
13559
14402
  }
13560
14403
  }
13561
14404
  function claimDaemonPidFile(home) {
13562
- const path = join29(home, DAEMON_PID_FILE);
14405
+ const path = join30(home, DAEMON_PID_FILE);
13563
14406
  const content = `${process.pid}
13564
14407
  `;
13565
14408
  mkdirSync11(home, { recursive: true });
@@ -13582,25 +14425,25 @@ function claimDaemonPidFile(home) {
13582
14425
  // ../daemon/src/lib/backup.ts
13583
14426
  var snapshotTail = Promise.resolve();
13584
14427
  function createBackupSnapshot(db) {
13585
- const snapshot2 = snapshotTail.then(() => takeSnapshot(db));
13586
- snapshotTail = snapshot2.catch(() => {
14428
+ const snapshot3 = snapshotTail.then(() => takeSnapshot(db));
14429
+ snapshotTail = snapshot3.catch(() => {
13587
14430
  });
13588
- return snapshot2;
14431
+ return snapshot3;
13589
14432
  }
13590
14433
  async function takeSnapshot(db) {
13591
- const directory = mkdtempSync3(join30(tmpdir3(), "bazilion-backup-"));
14434
+ const directory = mkdtempSync3(join31(tmpdir3(), "bazilion-backup-"));
13592
14435
  const cleanup = () => rmSync13(directory, { recursive: true, force: true });
13593
14436
  try {
13594
- const database = join30(directory, "bazilion.snapshot");
14437
+ const database = join31(directory, "bazilion.snapshot");
13595
14438
  await db.backupTo(database);
13596
- const snapshot2 = new DatabaseSync2(database, { readOnly: true });
14439
+ const snapshot3 = new DatabaseSync2(database, { readOnly: true });
13597
14440
  try {
13598
- const check = snapshot2.prepare("PRAGMA integrity_check").get();
14441
+ const check = snapshot3.prepare("PRAGMA integrity_check").get();
13599
14442
  if (check?.integrity_check !== "ok") {
13600
14443
  throw new Error(`SQLite snapshot failed integrity_check: ${check?.integrity_check}`);
13601
14444
  }
13602
14445
  } finally {
13603
- snapshot2.close();
14446
+ snapshot3.close();
13604
14447
  }
13605
14448
  return { directory, database, cleanup };
13606
14449
  } catch (error) {
@@ -13608,8 +14451,8 @@ async function takeSnapshot(db) {
13608
14451
  throw error;
13609
14452
  }
13610
14453
  }
13611
- function createBackupArchive(paths, snapshot2) {
13612
- const snapshotPath = resolve7(snapshot2.database);
14454
+ function createBackupArchive(paths, snapshot3) {
14455
+ const snapshotPath = resolve7(snapshot3.database);
13613
14456
  return create6(
13614
14457
  {
13615
14458
  cwd: paths.home,
@@ -13680,31 +14523,31 @@ miscRouter.get("/health/details", async (c) => {
13680
14523
  parseErrors++;
13681
14524
  }
13682
14525
  }
13683
- let effectiveEnv = process.env;
14526
+ let effectiveEnv2 = process.env;
13684
14527
  let codexConnected = false;
13685
14528
  if (pathChecks.auth && pathChecks.db) {
13686
14529
  try {
13687
14530
  const { db, authToken } = getCtx();
13688
- effectiveEnv = mergeSecretsIntoEnv(db, authToken);
14531
+ effectiveEnv2 = mergeSecretsIntoEnv(db, authToken);
13689
14532
  codexConnected = hasCredentials(db, authToken);
13690
14533
  } catch {
13691
14534
  }
13692
14535
  }
13693
- const openclawSkillsDir = join31(homedir4(), ".openclaw", "skills");
14536
+ const openclawSkillsDir = join32(homedir4(), ".openclaw", "skills");
13694
14537
  const providerSection = {
13695
14538
  // Hosted providers with credentials; local servers are reported below.
13696
14539
  configured: PROVIDERS.filter(
13697
- (provider) => provider.id === "openai-codex" ? codexConnected : !provider.local && isProviderConfigured(provider.id, effectiveEnv)
14540
+ (provider) => provider.id === "openai-codex" ? codexConnected : !provider.local && isProviderConfigured(provider.id, effectiveEnv2)
13698
14541
  ).map((provider) => provider.id),
13699
14542
  lmstudio: {
13700
- customEndpointConfigured: Boolean(effectiveEnv.LMSTUDIO_URL?.trim()),
13701
- keyConfigured: Boolean(effectiveEnv.LMSTUDIO_API_KEY)
14543
+ customEndpointConfigured: Boolean(effectiveEnv2.LMSTUDIO_URL?.trim()),
14544
+ keyConfigured: Boolean(effectiveEnv2.LMSTUDIO_API_KEY)
13702
14545
  },
13703
- ollama: { customEndpointConfigured: Boolean(effectiveEnv.OLLAMA_URL?.trim()) }
14546
+ ollama: { customEndpointConfigured: Boolean(effectiveEnv2.OLLAMA_URL?.trim()) }
13704
14547
  };
13705
14548
  let shellSecurity;
13706
14549
  try {
13707
- const shellConfig = resolveShellSecurityConfig(effectiveEnv);
14550
+ const shellConfig = resolveShellSecurityConfig(effectiveEnv2);
13708
14551
  const docker2 = shellConfig.sandboxMode === "docker" ? await checkDockerImage(shellConfig.sandboxImage) : null;
13709
14552
  shellSecurity = {
13710
14553
  ok: true,
@@ -13735,8 +14578,8 @@ miscRouter.get("/health/details", async (c) => {
13735
14578
  skills: { installed: skills.length, parseErrors },
13736
14579
  providers: providerSection,
13737
14580
  webSearch: {
13738
- braveConfigured: Boolean(effectiveEnv.BRAVE_API_KEY?.trim()),
13739
- searxngConfigured: Boolean(effectiveEnv.SEARXNG_URL?.trim())
14581
+ braveConfigured: Boolean(effectiveEnv2.BRAVE_API_KEY?.trim()),
14582
+ searxngConfigured: Boolean(effectiveEnv2.SEARXNG_URL?.trim())
13740
14583
  },
13741
14584
  openclaw: {
13742
14585
  path: openclawSkillsDir,
@@ -13770,18 +14613,18 @@ miscRouter.get("/backup", async (c) => {
13770
14613
  if (!existsSync17(paths.home)) {
13771
14614
  return c.json({ error: `bazilion home not found at ${paths.home}` }, 404);
13772
14615
  }
13773
- let snapshot2;
14616
+ let snapshot3;
13774
14617
  try {
13775
- snapshot2 = await createBackupSnapshot(db);
14618
+ snapshot3 = await createBackupSnapshot(db);
13776
14619
  } catch (error) {
13777
14620
  const message = error instanceof Error ? error.message : String(error);
13778
14621
  return c.json({ error: `could not create database snapshot: ${message}` }, 500);
13779
14622
  }
13780
14623
  let archive2;
13781
14624
  try {
13782
- archive2 = createBackupArchive(paths, snapshot2);
14625
+ archive2 = createBackupArchive(paths, snapshot3);
13783
14626
  } catch (error) {
13784
- snapshot2.cleanup();
14627
+ snapshot3.cleanup();
13785
14628
  const message = error instanceof Error ? error.message : String(error);
13786
14629
  return c.json({ error: `could not start backup archive: ${message}` }, 500);
13787
14630
  }
@@ -13794,17 +14637,17 @@ miscRouter.get("/backup", async (c) => {
13794
14637
  controller.enqueue(Buffer.isBuffer(next.value) ? next.value : Buffer.from(next.value));
13795
14638
  return;
13796
14639
  }
13797
- snapshot2.cleanup();
14640
+ snapshot3.cleanup();
13798
14641
  controller.close();
13799
14642
  } catch (error) {
13800
- snapshot2.cleanup();
14643
+ snapshot3.cleanup();
13801
14644
  controller.error(error);
13802
14645
  }
13803
14646
  },
13804
14647
  async cancel() {
13805
14648
  await iterator.return?.();
13806
14649
  archive2.destroy();
13807
- snapshot2.cleanup();
14650
+ snapshot3.cleanup();
13808
14651
  }
13809
14652
  });
13810
14653
  const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
@@ -14099,7 +14942,7 @@ notificationsRouter.put("/", async (c) => {
14099
14942
 
14100
14943
  // ../daemon/src/routes/profiles.ts
14101
14944
  import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "node:fs";
14102
- import { join as join32 } from "node:path";
14945
+ import { join as join33 } from "node:path";
14103
14946
  var profilesRouter = newRouter();
14104
14947
  profilesRouter.get("/", (c) => {
14105
14948
  const { db } = getCtx();
@@ -14182,7 +15025,7 @@ function profileFile(c) {
14182
15025
  if (!PROFILE_FILES.includes(file)) {
14183
15026
  return c.json({ error: `unsupported file: ${file}` }, 400);
14184
15027
  }
14185
- return join32(paths.profilesDir, id, file);
15028
+ return join33(paths.profilesDir, id, file);
14186
15029
  }
14187
15030
  profilesRouter.get("/:id/files/:file", (c) => {
14188
15031
  const path = profileFile(c);
@@ -14222,8 +15065,97 @@ questionsRouter.post("/:agentId/questions/:id/answer", async (c) => {
14222
15065
  return c.json({ ok: true });
14223
15066
  });
14224
15067
 
15068
+ // ../daemon/src/lib/zip.ts
15069
+ import { crc32 } from "node:zlib";
15070
+ var UTF8_NAMES = 2048;
15071
+ function dosDateTime(epochMs) {
15072
+ const d = new Date(epochMs);
15073
+ const year = Math.max(1980, d.getFullYear());
15074
+ return {
15075
+ time: d.getHours() << 11 | d.getMinutes() << 5 | d.getSeconds() >> 1,
15076
+ date: year - 1980 << 9 | d.getMonth() + 1 << 5 | d.getDate()
15077
+ };
15078
+ }
15079
+ function uniqueNames(names) {
15080
+ const seen = /* @__PURE__ */ new Map();
15081
+ return names.map((name) => {
15082
+ const count = (seen.get(name) ?? 0) + 1;
15083
+ seen.set(name, count);
15084
+ if (count === 1) return name;
15085
+ const dot = name.lastIndexOf(".");
15086
+ return dot > 0 ? `${name.slice(0, dot)} (${count})${name.slice(dot)}` : `${name} (${count})`;
15087
+ });
15088
+ }
15089
+ function localHeader(name, bytes, crc, epochMs) {
15090
+ const { time, date } = dosDateTime(epochMs);
15091
+ const header = Buffer.alloc(30);
15092
+ header.writeUInt32LE(67324752, 0);
15093
+ header.writeUInt16LE(20, 4);
15094
+ header.writeUInt16LE(UTF8_NAMES, 6);
15095
+ header.writeUInt16LE(0, 8);
15096
+ header.writeUInt16LE(time, 10);
15097
+ header.writeUInt16LE(date, 12);
15098
+ header.writeUInt32LE(crc, 14);
15099
+ header.writeUInt32LE(bytes.byteLength, 18);
15100
+ header.writeUInt32LE(bytes.byteLength, 22);
15101
+ header.writeUInt16LE(name.byteLength, 26);
15102
+ header.writeUInt16LE(0, 28);
15103
+ return Buffer.concat([header, name]);
15104
+ }
15105
+ function centralHeader(name, size, crc, epochMs, offset) {
15106
+ const { time, date } = dosDateTime(epochMs);
15107
+ const header = Buffer.alloc(46);
15108
+ header.writeUInt32LE(33639248, 0);
15109
+ header.writeUInt16LE(20, 4);
15110
+ header.writeUInt16LE(20, 6);
15111
+ header.writeUInt16LE(UTF8_NAMES, 8);
15112
+ header.writeUInt16LE(0, 10);
15113
+ header.writeUInt16LE(time, 12);
15114
+ header.writeUInt16LE(date, 14);
15115
+ header.writeUInt32LE(crc, 16);
15116
+ header.writeUInt32LE(size, 20);
15117
+ header.writeUInt32LE(size, 24);
15118
+ header.writeUInt16LE(name.byteLength, 28);
15119
+ header.writeUInt32LE(offset, 42);
15120
+ return Buffer.concat([header, name]);
15121
+ }
15122
+ function zipStream(entries) {
15123
+ const names = uniqueNames(entries.map((entry) => entry.name));
15124
+ const directory = [];
15125
+ let offset = 0;
15126
+ let index = 0;
15127
+ return new ReadableStream({
15128
+ pull(controller) {
15129
+ const entry = entries[index];
15130
+ if (entry) {
15131
+ const name = Buffer.from(names[index] ?? entry.name, "utf8");
15132
+ const bytes = entry.read();
15133
+ const crc = crc32(bytes);
15134
+ const header = localHeader(name, bytes, crc, entry.modifiedAt);
15135
+ directory.push(centralHeader(name, bytes.byteLength, crc, entry.modifiedAt, offset));
15136
+ offset += header.byteLength + bytes.byteLength;
15137
+ index++;
15138
+ controller.enqueue(header);
15139
+ controller.enqueue(bytes);
15140
+ return;
15141
+ }
15142
+ const central = Buffer.concat(directory);
15143
+ const end = Buffer.alloc(22);
15144
+ end.writeUInt32LE(101010256, 0);
15145
+ end.writeUInt16LE(entries.length, 8);
15146
+ end.writeUInt16LE(entries.length, 10);
15147
+ end.writeUInt32LE(central.byteLength, 12);
15148
+ end.writeUInt32LE(offset, 16);
15149
+ controller.enqueue(central);
15150
+ controller.enqueue(end);
15151
+ controller.close();
15152
+ }
15153
+ });
15154
+ }
15155
+
14225
15156
  // ../daemon/src/routes/results.ts
14226
15157
  var resultsRouter = newRouter();
15158
+ var MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
14227
15159
  resultsRouter.use("*", async (c, next) => {
14228
15160
  c.header("X-Content-Type-Options", "nosniff");
14229
15161
  await next();
@@ -14238,11 +15170,45 @@ resultsRouter.get("/", (c) => {
14238
15170
  list12(getCtx().db, {
14239
15171
  teamId: c.req.query("teamId"),
14240
15172
  agentId: c.req.query("agentId"),
15173
+ sessionId: c.req.query("sessionId"),
14241
15174
  limit,
14242
15175
  offset
14243
15176
  })
14244
15177
  );
14245
15178
  });
15179
+ resultsRouter.get("/archive", (c) => {
15180
+ const db = getCtx().db;
15181
+ const filter = {
15182
+ teamId: c.req.query("teamId"),
15183
+ agentId: c.req.query("agentId"),
15184
+ sessionId: c.req.query("sessionId")
15185
+ };
15186
+ if (!filter.teamId && !filter.agentId && !filter.sessionId) {
15187
+ return c.json({ error: "teamId, agentId or sessionId is required" }, 400);
15188
+ }
15189
+ const selected = listForArchive(db, filter, MAX_ARCHIVE_BYTES);
15190
+ if (selected.truncated) {
15191
+ return c.json(
15192
+ { error: "These files are larger than 512 MiB together. Narrow the selection." },
15193
+ 413
15194
+ );
15195
+ }
15196
+ if (selected.results.length === 0) return c.json({ error: "No saved files match" }, 404);
15197
+ const name = `bazilion-${filter.teamId ?? "files"}.zip`.replace(/[^\w.-]/g, "-");
15198
+ c.header("Content-Type", "application/zip");
15199
+ c.header("Content-Disposition", `attachment; filename="${name}"`);
15200
+ c.header("Content-Security-Policy", "default-src 'none'; sandbox");
15201
+ return c.body(
15202
+ zipStream(
15203
+ selected.results.map((result) => ({
15204
+ name: result.name,
15205
+ modifiedAt: result.createdAt,
15206
+ // Read when the stream reaches the file; a failed integrity check ends the download.
15207
+ read: () => new Uint8Array(read(db, result.id))
15208
+ }))
15209
+ )
15210
+ );
15211
+ });
14246
15212
  resultsRouter.get("/:id", (c) => {
14247
15213
  const result = get17(getCtx().db, c.req.param("id"));
14248
15214
  if (!result) return c.json({ error: "Result not found" }, 404);
@@ -14292,6 +15258,7 @@ resultsRouter.get("/:id/preview", (c) => {
14292
15258
  return c.json({ error: "File content does not match its image type. Use Download." }, 415);
14293
15259
  c.header("Content-Type", text4 ? "text/plain; charset=utf-8" : result.mimeType);
14294
15260
  c.header("Content-Security-Policy", "default-src 'none'; sandbox");
15261
+ c.header("Cache-Control", "private, max-age=3600");
14295
15262
  return c.body(new Uint8Array(bytes));
14296
15263
  } catch {
14297
15264
  return c.json({ error: "Saved file failed integrity verification" }, 409);
@@ -14323,7 +15290,7 @@ shellApprovalsRouter.post("/:id", async (c) => {
14323
15290
  // ../daemon/src/routes/skills.ts
14324
15291
  import { mkdtempSync as mkdtempSync4, rmSync as rmSync14, writeFileSync as writeFileSync12 } from "node:fs";
14325
15292
  import { homedir as homedir5, tmpdir as tmpdir4 } from "node:os";
14326
- import { join as join33 } from "node:path";
15293
+ import { join as join34 } from "node:path";
14327
15294
  var MAX_ZIP_BYTES = 50 * 1024 * 1024;
14328
15295
  var skillsRouter = newRouter();
14329
15296
  skillsRouter.get("/", (c) => {
@@ -14416,8 +15383,8 @@ async function parseImportInput(request) {
14416
15383
  if (!filename.toLowerCase().endsWith(".zip")) {
14417
15384
  throw new Error("uploaded file must be a .zip archive");
14418
15385
  }
14419
- const tmpDir = mkdtempSync4(join33(tmpdir4(), "bazilion-skill-upload-"));
14420
- const zipPath = join33(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
15386
+ const tmpDir = mkdtempSync4(join34(tmpdir4(), "bazilion-skill-upload-"));
15387
+ const zipPath = join34(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
14421
15388
  const buf = Buffer.from(await file.arrayBuffer());
14422
15389
  writeFileSync12(zipPath, buf);
14423
15390
  const forceField = form.get("force");
@@ -14433,7 +15400,7 @@ async function parseImportInput(request) {
14433
15400
  const { source } = body;
14434
15401
  if (typeof source !== "string" || !source) throw new Error("source is required");
14435
15402
  return {
14436
- source: source === "openclaw" ? join33(homedir5(), ".openclaw", "skills") : source,
15403
+ source: source === "openclaw" ? join34(homedir5(), ".openclaw", "skills") : source,
14437
15404
  force: Boolean(body.force),
14438
15405
  tempZipPath: null,
14439
15406
  sourceLabel: source
@@ -14503,7 +15470,7 @@ teamCodingEnvironmentRouter.put("/:id/coding-environment", async (c) => {
14503
15470
  });
14504
15471
 
14505
15472
  // ../daemon/src/routes/team-memory.ts
14506
- import { join as join34 } from "node:path";
15473
+ import { join as join35 } from "node:path";
14507
15474
  var teamMemoryRouter = newRouter();
14508
15475
  teamMemoryRouter.onError((error, c) => {
14509
15476
  const safe = sanitizeNativeModuleError(error, { subject: "Bazilion memory" });
@@ -14511,7 +15478,7 @@ teamMemoryRouter.onError((error, c) => {
14511
15478
  return onRouteError(safe, c);
14512
15479
  });
14513
15480
  async function openMemory(c) {
14514
- const mem = qmdBackend(join34(routeTeam(c).path, "memory"));
15481
+ const mem = qmdBackend(join35(routeTeam(c).path, "memory"));
14515
15482
  await mem.init();
14516
15483
  return mem;
14517
15484
  }
@@ -14577,7 +15544,7 @@ import {
14577
15544
  readSync as readSync3,
14578
15545
  realpathSync as realpathSync7
14579
15546
  } from "node:fs";
14580
- import { join as join35 } from "node:path";
15547
+ import { join as join36 } from "node:path";
14581
15548
  var hash = (value) => createHash6("sha256").update(value).digest("hex");
14582
15549
  var ContextReadError = class extends Error {
14583
15550
  code;
@@ -14615,12 +15582,12 @@ var ContextDirectory = class _ContextDirectory {
14615
15582
  this.parent = parent;
14616
15583
  if (parent) component(registeredPath);
14617
15584
  parent?.assertOpen();
14618
- const canonicalPath = parent ? join35(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
15585
+ const canonicalPath = parent ? join36(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
14619
15586
  this.canonicalPath = canonicalPath;
14620
15587
  let fd;
14621
15588
  try {
14622
15589
  fd = openSync6(
14623
- parent ? join35(parent.path, registeredPath) : canonicalPath,
15590
+ parent ? join36(parent.path, registeredPath) : canonicalPath,
14624
15591
  constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW
14625
15592
  );
14626
15593
  const stat = fstatSync6(fd, { bigint: true });
@@ -14658,7 +15625,7 @@ var ContextDirectory = class _ContextDirectory {
14658
15625
  component(name);
14659
15626
  this.assertOpen();
14660
15627
  try {
14661
- return lstatSync6(join35(this.path, name));
15628
+ return lstatSync6(join36(this.path, name));
14662
15629
  } catch (error) {
14663
15630
  if (error.code === "ENOENT") return null;
14664
15631
  throw new ContextReadError("unreadable");
@@ -14666,7 +15633,7 @@ var ContextDirectory = class _ContextDirectory {
14666
15633
  }
14667
15634
  observe(name) {
14668
15635
  try {
14669
- return lstatSync6(join35(this.path, name), { bigint: true });
15636
+ return lstatSync6(join36(this.path, name), { bigint: true });
14670
15637
  } catch (error) {
14671
15638
  if (error.code === "ENOENT") return null;
14672
15639
  throw new ContextReadError("unreadable");
@@ -14707,7 +15674,7 @@ var ContextDirectory = class _ContextDirectory {
14707
15674
  let fd;
14708
15675
  try {
14709
15676
  fd = openSync6(
14710
- join35(this.path, name),
15677
+ join36(this.path, name),
14711
15678
  constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK
14712
15679
  );
14713
15680
  const before = fstatSync6(fd, { bigint: true });
@@ -14733,7 +15700,7 @@ var ContextDirectory = class _ContextDirectory {
14733
15700
  }
14734
15701
  validate(skipGit = false, names) {
14735
15702
  this.assertOpen();
14736
- const currentPath = this.parent ? join35(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
15703
+ const currentPath = this.parent ? join36(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
14737
15704
  const stat = lstatSync6(currentPath, { bigint: true });
14738
15705
  if (!stat.isDirectory() || identity(stat) !== identity(this.originalIdentity))
14739
15706
  throw new ContextReadError("root_changed");
@@ -15161,7 +16128,7 @@ async function readOrNull(captured, args) {
15161
16128
  import { execFile } from "node:child_process";
15162
16129
  import { mkdirSync as mkdirSync12, mkdtempSync as mkdtempSync5, rmSync as rmSync15, writeFileSync as writeFileSync13 } from "node:fs";
15163
16130
  import { tmpdir as tmpdir5 } from "node:os";
15164
- import { join as join36 } from "node:path";
16131
+ import { join as join37 } from "node:path";
15165
16132
  var INSPECTION_BUDGET_MS = 5e3;
15166
16133
  var METADATA_BUDGET_MS = 2500;
15167
16134
  var METADATA_BYTES = 64 * 1024 * 1024;
@@ -15190,7 +16157,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
15190
16157
  const dir = git.directory("info");
15191
16158
  if (dir.entry("sparse-checkout")) throw new ContextReadError("unsupported_git_metadata");
15192
16159
  }
15193
- const scratch = mkdtempSync5(join36(tmpdir5(), "bazilion-context-git-"));
16160
+ const scratch = mkdtempSync5(join37(tmpdir5(), "bazilion-context-git-"));
15194
16161
  let cleaned = false;
15195
16162
  const cleanup = () => {
15196
16163
  if (cleaned) return;
@@ -15201,7 +16168,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
15201
16168
  if (Date.now() - start2 >= budgetMs) throw new ContextReadError("git_timeout");
15202
16169
  };
15203
16170
  try {
15204
- const rawGit = (args) => new Promise((resolve8, reject2) => {
16171
+ const rawGit = (args) => new Promise((resolve9, reject2) => {
15205
16172
  if (cleaned) throw new ContextReadError("unreadable");
15206
16173
  checkBudget();
15207
16174
  execFile(
@@ -15224,7 +16191,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
15224
16191
  maxBuffer: RUN_MAX_BUFFER,
15225
16192
  encoding: "utf8"
15226
16193
  },
15227
- (error, stdout) => error ? reject2(error) : resolve8(stdout)
16194
+ (error, stdout) => error ? reject2(error) : resolve9(stdout)
15228
16195
  );
15229
16196
  });
15230
16197
  const inspectionArgs = (args) => [
@@ -15251,7 +16218,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
15251
16218
  if (capturedConfig) {
15252
16219
  bytes += capturedConfig.length;
15253
16220
  count++;
15254
- const configPath = join36(scratch, "captured-config");
16221
+ const configPath = join37(scratch, "captured-config");
15255
16222
  writeFileSync13(configPath, capturedConfig, { mode: 384 });
15256
16223
  const config = await rawGit([
15257
16224
  "config",
@@ -15304,8 +16271,8 @@ objectformat = ${value}`
15304
16271
  const exclude = git.directory("info").read("exclude", METADATA_READ);
15305
16272
  if (exclude) {
15306
16273
  bytes += exclude.length;
15307
- mkdirSync12(join36(scratch, "info"), { mode: 448 });
15308
- writeFileSync13(join36(scratch, "info", "exclude"), exclude, { mode: 384 });
16274
+ mkdirSync12(join37(scratch, "info"), { mode: 448 });
16275
+ writeFileSync13(join37(scratch, "info", "exclude"), exclude, { mode: 384 });
15309
16276
  }
15310
16277
  }
15311
16278
  const copy = (source, destination, depth) => {
@@ -15318,13 +16285,13 @@ objectformat = ${value}`
15318
16285
  if (name === "alternates" || name === "http-alternates")
15319
16286
  throw new ContextReadError("unsupported_git_metadata");
15320
16287
  if (entry.isDirectory()) {
15321
- mkdirSync12(join36(destination, name), { mode: 448 });
15322
- copy(source.directory(name), join36(destination, name), depth + 1);
16288
+ mkdirSync12(join37(destination, name), { mode: 448 });
16289
+ copy(source.directory(name), join37(destination, name), depth + 1);
15323
16290
  } else {
15324
16291
  const content = source.read(name, METADATA_BYTES - bytes);
15325
16292
  if (!content) throw new ContextReadError("source_changed");
15326
16293
  bytes += content.length;
15327
- writeFileSync13(join36(destination, name), content, { mode: 384 });
16294
+ writeFileSync13(join37(destination, name), content, { mode: 384 });
15328
16295
  }
15329
16296
  }
15330
16297
  };
@@ -15333,16 +16300,16 @@ objectformat = ${value}`
15333
16300
  if (content) {
15334
16301
  count++;
15335
16302
  bytes += content.length;
15336
- writeFileSync13(join36(scratch, name), content, { mode: 384 });
16303
+ writeFileSync13(join37(scratch, name), content, { mode: 384 });
15337
16304
  }
15338
16305
  }
15339
16306
  for (const name of ["refs", "objects"]) {
15340
- mkdirSync12(join36(scratch, name), { mode: 448 });
15341
- if (git.entry(name)) copy(git.directory(name), join36(scratch, name), 0);
16307
+ mkdirSync12(join37(scratch, name), { mode: 448 });
16308
+ if (git.entry(name)) copy(git.directory(name), join37(scratch, name), 0);
15342
16309
  }
15343
16310
  if (git.list().some((name) => name.startsWith("sharedindex.")))
15344
16311
  throw new ContextReadError("unsupported_git_metadata");
15345
- writeFileSync13(join36(scratch, "config"), `${configLines.join("\n")}
16312
+ writeFileSync13(join37(scratch, "config"), `${configLines.join("\n")}
15346
16313
  `, { mode: 384 });
15347
16314
  const validate2 = () => git.validate();
15348
16315
  validate2();
@@ -15353,6 +16320,77 @@ objectformat = ${value}`
15353
16320
  }
15354
16321
  }
15355
16322
 
16323
+ // ../daemon/src/lib/git-review/authors.ts
16324
+ import { realpathSync as realpathSync8 } from "node:fs";
16325
+ import { isAbsolute as isAbsolute7, join as join38, relative as relative5, resolve as resolve8, sep as sep6 } from "node:path";
16326
+ var FILE_TOOLS = /* @__PURE__ */ new Set(["write", "edit"]);
16327
+ var CONVERSATIONS_PER_AGENT = 5;
16328
+ var SANDBOX_ROOT = "/workspace";
16329
+ function workspacePath(path, cwd, roots) {
16330
+ const absolute = isAbsolute7(path) ? path : resolve8(cwd, path);
16331
+ for (const root of roots) {
16332
+ const inside = relative5(root, absolute);
16333
+ if (inside && !inside.startsWith("..") && !isAbsolute7(inside)) {
16334
+ return inside.split(sep6).join("/");
16335
+ }
16336
+ }
16337
+ return null;
16338
+ }
16339
+ function readChangeAuthors(db, paths, team, changedPaths) {
16340
+ const wanted = new Set(changedPaths);
16341
+ const authors = {};
16342
+ if (wanted.size === 0) return authors;
16343
+ const roots = [team.path, SANDBOX_ROOT];
16344
+ try {
16345
+ roots.push(realpathSync8(team.path));
16346
+ } catch {
16347
+ }
16348
+ const members = list(db, { includeArchived: true }).filter((agent) => agent.teamId === team.id);
16349
+ for (const agent of members) {
16350
+ const directory = join38(paths.agentDir(agent.id), "sessions");
16351
+ const recent = list11(db, agent.id, CONVERSATIONS_PER_AGENT, 0).conversations;
16352
+ for (const conversation of recent) {
16353
+ let lines;
16354
+ try {
16355
+ lines = readSessionFile(directory, conversation.id);
16356
+ } catch {
16357
+ continue;
16358
+ }
16359
+ const cwd = lines[0]?.cwd ?? team.path;
16360
+ const failed = /* @__PURE__ */ new Set();
16361
+ for (const line of lines) {
16362
+ const message = line.message;
16363
+ if (message?.role === "toolResult" && message.isError && message.toolCallId) {
16364
+ failed.add(message.toolCallId);
16365
+ }
16366
+ }
16367
+ for (const line of lines) {
16368
+ if (line.type !== "message" || line.message?.role !== "assistant") continue;
16369
+ if (!Array.isArray(line.message.content)) continue;
16370
+ const at = Date.parse(line.timestamp ?? "");
16371
+ if (!Number.isFinite(at)) continue;
16372
+ for (const part of line.message.content) {
16373
+ if (part?.type !== "toolCall" || !part.name || !FILE_TOOLS.has(part.name)) continue;
16374
+ if (part.id && failed.has(part.id)) continue;
16375
+ const target = part.arguments?.path;
16376
+ if (typeof target !== "string") continue;
16377
+ const path = workspacePath(target, cwd, roots);
16378
+ if (!path || !wanted.has(path)) continue;
16379
+ const known = authors[path];
16380
+ if (known && known.at >= at) continue;
16381
+ authors[path] = {
16382
+ agentId: agent.id,
16383
+ agentName: agent.name,
16384
+ conversationId: conversation.id,
16385
+ at
16386
+ };
16387
+ }
16388
+ }
16389
+ }
16390
+ }
16391
+ return authors;
16392
+ }
16393
+
15356
16394
  // ../daemon/src/lib/git-review/service.ts
15357
16395
  var ReviewUnavailableError = class extends DomainError {
15358
16396
  constructor(code, message) {
@@ -15405,12 +16443,20 @@ async function readTeamReview(db, paths, teamId, input = {}) {
15405
16443
  const listed = await listChanges(captured, base, identity2, input.limits);
15406
16444
  return input.patches ? attachPatches(captured, listed, input.limits, input.patchPath) : listed;
15407
16445
  });
15408
- return { teamId: team.id, changes };
16446
+ if (!input.authors) return { teamId: team.id, changes };
16447
+ const changedPaths = changes.changes.map((change) => change.path);
16448
+ return {
16449
+ teamId: team.id,
16450
+ changes,
16451
+ authors: readChangeAuthors(db, paths, team, changedPaths)
16452
+ };
15409
16453
  }
15410
16454
 
15411
16455
  // ../daemon/src/lib/git-review/feedback.ts
15412
16456
  var FEEDBACK_NOTE_CHARS = 2e3;
16457
+ var FEEDBACK_COMMENTS = 20;
15413
16458
  var EXCERPT_CHARS = 4e3;
16459
+ var EXCERPT_CHARS_EACH = 1600;
15414
16460
  async function queueReviewFeedback(db, paths, teamId, request) {
15415
16461
  const team = requireTeam(db, paths, teamId);
15416
16462
  const agent = get(db, request.agentId);
@@ -15419,31 +16465,77 @@ async function queueReviewFeedback(db, paths, teamId, request) {
15419
16465
  const message = await withRepository(team.path, async (captured) => {
15420
16466
  const base = await resolveComparisonBase(captured, request.base ?? "HEAD");
15421
16467
  const listed = await listChanges(captured, base, await readRepositoryIdentity(captured));
15422
- const withPatch = await attachPatches(captured, listed, void 0, request.path);
15423
- const change = withPatch.changes.find((entry) => entry.path === request.path);
15424
- if (!change) throw new DomainError(400, "That path is not changed since this baseline.");
15425
- return composeFeedbackMessage(change, base, request.note);
16468
+ const changes = /* @__PURE__ */ new Map();
16469
+ for (const { path } of request.comments) {
16470
+ if (changes.has(path)) continue;
16471
+ const withPatch = await attachPatches(captured, listed, void 0, path);
16472
+ const change = withPatch.changes.find((entry) => entry.path === path);
16473
+ if (!change) throw new DomainError(400, "That path is not changed since this baseline.");
16474
+ changes.set(path, change);
16475
+ }
16476
+ return composeFeedbackMessage(request, changes, base);
15426
16477
  });
15427
16478
  const item = await enqueueUserInput(agent.id, { message, attachments: [] }, { db, paths });
15428
16479
  return { message, item };
15429
16480
  }
15430
- function composeFeedbackMessage(change, base, note) {
16481
+ function hunkForLine(patch, line) {
16482
+ const lines = patch.split("\n");
16483
+ const starts = [];
16484
+ lines.forEach((text4, index) => {
16485
+ if (text4.startsWith("@@")) starts.push(index);
16486
+ });
16487
+ for (const [position, start2] of starts.entries()) {
16488
+ const header = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(lines[start2] ?? "");
16489
+ if (!header) continue;
16490
+ const first = Number(header[1]);
16491
+ const count = header[2] === void 0 ? 1 : Number(header[2]);
16492
+ if (line < first || line >= first + Math.max(count, 1)) continue;
16493
+ return lines.slice(start2, starts[position + 1] ?? lines.length).join("\n");
16494
+ }
16495
+ return null;
16496
+ }
16497
+ function place(comment, change) {
15431
16498
  const file = change.previousPath ? `${change.previousPath} -> ${change.path}` : change.path;
15432
- const lines = [
15433
- `Review feedback on ${file} (${change.status} since ${base.requestedRef}, ${base.resolvedOid.slice(0, 12)}).`
15434
- ];
15435
- const trimmed = note?.trim();
15436
- if (trimmed) lines.push("", trimmed.slice(0, FEEDBACK_NOTE_CHARS));
16499
+ return comment.line === void 0 ? file : `${file}, line ${comment.line}`;
16500
+ }
16501
+ function commentBody(comment, change, room) {
16502
+ const lines = [];
16503
+ const note = comment.note?.trim();
16504
+ if (note) lines.push("", note.slice(0, FEEDBACK_NOTE_CHARS));
15437
16505
  if (change.patch === null) {
15438
16506
  lines.push("", `No diff text (${change.contentOmitted ?? "unavailable"}).`);
15439
- } else {
15440
- const excerpt = change.patch.slice(0, EXCERPT_CHARS);
15441
- const fence = "`".repeat(
15442
- Math.max(3, ...(excerpt.match(/`+/g) ?? []).map((run) => run.length + 1))
15443
- );
15444
- lines.push("", `${fence}diff`, excerpt.trimEnd(), fence);
15445
- if (change.patch.length > EXCERPT_CHARS) lines.push("(diff excerpt truncated)");
16507
+ return lines;
16508
+ }
16509
+ const source = comment.line === void 0 ? change.patch : hunkForLine(change.patch, comment.line) ?? change.patch;
16510
+ const excerpt = source.slice(0, room);
16511
+ const fence = "`".repeat(
16512
+ Math.max(3, ...(excerpt.match(/`+/g) ?? []).map((run) => run.length + 1))
16513
+ );
16514
+ lines.push("", `${fence}diff`, excerpt.trimEnd(), fence);
16515
+ if (source.length > room) lines.push("(diff excerpt truncated)");
16516
+ return lines;
16517
+ }
16518
+ function composeFeedbackMessage(request, changes, base) {
16519
+ const since = `since ${base.requestedRef}, ${base.resolvedOid.slice(0, 12)}`;
16520
+ const overall = request.note?.trim();
16521
+ const [only] = request.comments;
16522
+ if (request.comments.length === 1 && only && !overall) {
16523
+ const change = changes.get(only.path);
16524
+ return [
16525
+ `Review feedback on ${place(only, change)} (${change.status} ${since}).`,
16526
+ ...commentBody(only, change, EXCERPT_CHARS)
16527
+ ].join("\n");
15446
16528
  }
16529
+ const lines = [`Review feedback: ${request.comments.length} comments (${since}).`];
16530
+ if (overall) lines.push("", overall.slice(0, FEEDBACK_NOTE_CHARS));
16531
+ request.comments.forEach((comment, index) => {
16532
+ const change = changes.get(comment.path);
16533
+ lines.push(
16534
+ "",
16535
+ `${index + 1}. ${place(comment, change)} (${change.status})`,
16536
+ ...commentBody(comment, change, EXCERPT_CHARS_EACH)
16537
+ );
16538
+ });
15447
16539
  return lines.join("\n");
15448
16540
  }
15449
16541
 
@@ -15459,25 +16551,39 @@ teamReviewRouter.get("/:id/review", async (c) => {
15459
16551
  const review = await readTeamReview(db, paths, c.req.param("id"), {
15460
16552
  ...base === void 0 ? {} : { base },
15461
16553
  patches: c.req.query("patches") === "1",
15462
- ...patchPath === void 0 ? {} : { patchPath }
16554
+ ...patchPath === void 0 ? {} : { patchPath },
16555
+ authors: c.req.query("authors") === "1"
15463
16556
  });
15464
16557
  return c.json(review);
15465
16558
  });
16559
+ var validNote = (note) => note === void 0 || typeof note === "string" && note.length <= FEEDBACK_NOTE_CHARS;
16560
+ function validComment(value) {
16561
+ const comment = value ?? {};
16562
+ return typeof comment.path === "string" && comment.path.length > 0 && comment.path.length <= 4096 && (comment.line === void 0 || Number.isSafeInteger(comment.line) && comment.line > 0) && validNote(comment.note);
16563
+ }
15466
16564
  teamReviewRouter.post("/:id/review/feedback", async (c) => {
15467
16565
  const body = await jsonBody(c);
15468
- if (!body || typeof body.path !== "string" || body.path.length === 0 || body.path.length > 4096 || typeof body.agentId !== "string" || body.agentId.length === 0) {
15469
- return c.json({ error: "path and agentId are required" }, 400);
16566
+ if (!body || typeof body.agentId !== "string" || body.agentId.length === 0) {
16567
+ return c.json({ error: "agentId is required" }, 400);
15470
16568
  }
15471
- if (body.note !== void 0 && (typeof body.note !== "string" || body.note.length > FEEDBACK_NOTE_CHARS)) {
15472
- return c.json({ error: "Invalid feedback note" }, 400);
16569
+ if (!Array.isArray(body.comments) || body.comments.length === 0 || body.comments.length > FEEDBACK_COMMENTS || !body.comments.every(validComment)) {
16570
+ return c.json(
16571
+ { error: `comments must be 1 to ${FEEDBACK_COMMENTS} entries of { path, line?, note? }` },
16572
+ 400
16573
+ );
15473
16574
  }
16575
+ if (!validNote(body.note)) return c.json({ error: "Invalid feedback note" }, 400);
15474
16576
  if (body.base !== void 0 && typeof body.base !== "string") {
15475
16577
  return c.json({ error: "Invalid comparison base" }, 400);
15476
16578
  }
15477
16579
  const { db, paths } = getCtx();
15478
16580
  const queued = await queueReviewFeedback(db, paths, c.req.param("id"), {
15479
- path: body.path,
15480
16581
  agentId: body.agentId,
16582
+ comments: body.comments.map((comment) => ({
16583
+ path: comment.path,
16584
+ ...comment.line === void 0 ? {} : { line: comment.line },
16585
+ ...comment.note === void 0 ? {} : { note: comment.note }
16586
+ })),
15481
16587
  ...body.note === void 0 ? {} : { note: body.note },
15482
16588
  ...body.base === void 0 ? {} : { base: body.base }
15483
16589
  });
@@ -17525,11 +18631,13 @@ function createApp() {
17525
18631
  app2.route("/api/teams", teamMemoryRouter);
17526
18632
  app2.route("/api/teams", teamPolicyRouter);
17527
18633
  app2.route("/api/teams", teamReviewRouter);
18634
+ app2.route("/api/teams", teamMessagesRouter);
17528
18635
  app2.route("/api/teams", teamCodingEnvironmentRouter);
17529
18636
  app2.route("/api/teams", teamTelegramRouter);
17530
18637
  app2.route("/api/team-templates", teamTemplatesRouter);
17531
18638
  app2.route("/api/results", resultsRouter);
17532
18639
  app2.route("/api/attention", attentionRouter);
18640
+ app2.route("/api/activity", activityRouter);
17533
18641
  app2.route("/api/notifications", notificationsRouter);
17534
18642
  app2.route("/api/shell-approvals", shellApprovalsRouter);
17535
18643
  app2.route("/api/profiles", profilesRouter);