bazilion 0.26.1 → 0.50.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 (203) hide show
  1. package/dist/cli.js +405 -244
  2. package/dist/cli.js.map +1 -1
  3. package/dist/daemon.js +1572 -749
  4. package/dist/daemon.js.map +1 -1
  5. package/dist/web/client/assets/ConfigPage-_FY--9PB.js +1 -0
  6. package/dist/web/client/assets/ConfirmDialog-BblXqMVb.js +1 -0
  7. package/dist/web/client/assets/ConnectionsView-BZHJysCa.js +1 -0
  8. package/dist/web/client/assets/FieldRow-k05wfDy9.js +1 -0
  9. package/dist/web/client/assets/SectionTabs-DlfXtepS.js +1 -0
  10. package/dist/web/client/assets/{SkillFindings-8LX6bYf_.js → SkillFindings-CHf5ZGY0.js} +1 -1
  11. package/dist/web/client/assets/SpawnDialog-C-Ujb4bC.js +1 -0
  12. package/dist/web/client/assets/TeamForm-D6EAAF7m.js +1 -0
  13. package/dist/web/client/assets/TeamThread-DpUOwMoi.js +1 -0
  14. package/dist/web/client/assets/UnsavedChangesGuard-DTUP7hwu.js +1 -0
  15. package/dist/web/client/assets/_id-C94dgBDe.js +1 -0
  16. package/dist/web/client/assets/_id-CxmEfoEp.js +1 -0
  17. package/dist/web/client/assets/agents-C-bJ5R_0.js +1 -0
  18. package/dist/web/client/assets/agents-odqBNx-A.js +1 -0
  19. package/dist/web/client/assets/api-CPzQ_z9m.js +1 -0
  20. package/dist/web/client/assets/arrow-right-Dyta3p06.js +1 -0
  21. package/dist/web/client/assets/attention-D0e7o7fh.js +1 -0
  22. package/dist/web/client/assets/chevron-right-B2YEg9rw.js +1 -0
  23. package/dist/web/client/assets/config-B7Y5MtpM.js +3 -0
  24. package/dist/web/client/assets/createLucideIcon-Cgab8gqu.js +1 -0
  25. package/dist/web/client/assets/index-CNVw44IE.js +54 -0
  26. package/dist/web/client/assets/link-ClwtaO_E.js +1 -0
  27. package/dist/web/client/assets/login-Br1F4rQx.js +1 -0
  28. package/dist/web/client/assets/mcp-B8bIAY6k.js +1 -0
  29. package/dist/web/client/assets/routes-BZdlkRdC.js +76 -0
  30. package/dist/web/client/assets/save-ZqeB_I-c.js +1 -0
  31. package/dist/web/client/assets/{services-B2f7e5jV.js → services-CPJxDrVG.js} +1 -1
  32. package/dist/web/client/assets/skills-DE_kQQGj.js +1 -0
  33. package/dist/web/client/assets/style-BWShXY3e.js +7 -0
  34. package/dist/web/client/assets/styles-Tney8jZq.css +2 -0
  35. package/dist/web/client/assets/teams-AcuSLc3I.js +1 -0
  36. package/dist/web/client/assets/teams-tRamPg7O.js +1 -0
  37. package/dist/web/client/assets/telegram-Ku69-GAv.js +1 -0
  38. package/dist/web/client/assets/tokens-DuLNZMgi.js +1 -0
  39. package/dist/web/client/assets/welcome-CrQk6n6I.js +1 -0
  40. package/dist/web/server/assets/{ConfigPage-CGld_wCK.js → ConfigPage-DSLM5CLw.js} +2 -2
  41. package/dist/web/server/assets/{ConfirmDialog-LdVlEanK.js → ConfirmDialog-CvLZgbfY.js} +1 -1
  42. package/dist/web/server/assets/ConnectionsView-DVLNH81Y.js +708 -0
  43. package/dist/web/server/assets/{FieldRow-Dah2KKqo.js → FieldRow-DQBzMtcR.js} +4 -4
  44. package/dist/web/server/assets/{Page-CMSYKXWJ.js → Page-KIL1CsME.js} +1 -1
  45. package/dist/web/server/assets/Rail-D8LhjS38.js +756 -0
  46. package/dist/web/server/assets/{SectionTabs-CqFg9Vwx.js → SectionTabs-CNcvxbR8.js} +1 -16
  47. package/dist/web/server/assets/{SkillFindings-Bd6e81Wu.js → SkillFindings-DX8lCMG7.js} +1 -1
  48. package/dist/web/server/assets/{SpawnDialog-BGNaMfFb.js → SpawnDialog-Brmkl_ll.js} +24 -6
  49. package/dist/web/server/assets/{TeamForm-C93tpn9r.js → TeamForm-CvQAs2FA.js} +1 -1
  50. package/dist/web/server/assets/TeamThread-BNJi6gPM.js +205 -0
  51. package/dist/web/server/assets/{UnsavedChangesGuard-Dm4a27_5.js → UnsavedChangesGuard-B3Lpl08z.js} +8 -4
  52. package/dist/web/server/assets/{TeamPolicyEditor-BHS3J0R9.js → _id-BH1631a8.js} +114 -263
  53. package/dist/web/server/assets/{_id-sW6zXrTP.js → _id-CA3QO7J5.js} +1 -1
  54. package/dist/web/server/assets/{_id-lOVnT5sS.js → _id-CO1PgvyG.js} +5 -5
  55. package/dist/web/server/assets/{_id-B0x1ffz3.js → _id-DIXUiIaB.js} +1 -1
  56. package/dist/web/server/assets/{_id-ByiXeIPS.js → _id-E2N4gZ4O.js} +2 -2
  57. package/dist/web/server/assets/{_id-Bdf_Rg62.js → _id-TVruGcOd.js} +1 -1
  58. package/dist/web/server/assets/_tanstack-start-manifest_v-BVfrV7LQ.js +191 -0
  59. package/dist/web/server/assets/{agents-BNPkidbH.js → agents-BnWgFo6o.js} +1 -1
  60. package/dist/web/server/assets/{agents-BK8OmB8g.js → agents-C63VycUw.js} +2 -2
  61. package/dist/web/server/assets/{agents-D4tqK1kH.js → agents-CalSKogx.js} +14 -15
  62. package/dist/web/server/assets/{agents-Cn9GkXFX.js → agents-CdZvooeQ.js} +1 -1
  63. package/dist/web/server/assets/{agents-lOqc6VGd.js → agents-DPZVni4Q.js} +1 -1
  64. package/dist/web/server/assets/{agents-DycxHDt8.js → agents-DrkEwIpR.js} +8 -8
  65. package/dist/web/server/assets/{attention-DULVjdmF.js → attention-BbE4yc-V.js} +1 -1
  66. package/dist/web/server/assets/{attention-YWnLKA2E.js → attention-Cr7puThv.js} +1 -1
  67. package/dist/web/server/assets/{attention-BIm455bC.js → attention-DIyX3VMB.js} +6 -6
  68. package/dist/web/server/assets/{auth-DiN92ydD.js → auth-dJnrFW6y.js} +1 -1
  69. package/dist/web/server/assets/{config-C1VB28se.js → config-3tPtOmPE.js} +1 -1
  70. package/dist/web/server/assets/{config-BNEgu7WG.js → config-DJGZiPBJ.js} +13 -13
  71. package/dist/web/server/assets/{config-TdVqnqNL.js → config-rUqhMjIs.js} +1 -1
  72. package/dist/web/server/assets/{daemon-client-DL2ik2Em.js → daemon-client-B_ZRIIrT.js} +2 -1
  73. package/dist/web/server/assets/{mcp-BwmpNQPN.js → mcp-C97uAZe1.js} +1 -1
  74. package/dist/web/server/assets/{mcp-B09_O05r.js → mcp-Cf7KzOJ9.js} +9 -9
  75. package/dist/web/server/assets/{mcp-CqdTfXcn.js → mcp-DE14q5c0.js} +1 -1
  76. package/dist/web/server/assets/{router-BI9gmY3S.js → router-w2yPgmC1.js} +412 -259
  77. package/dist/web/server/assets/routes-1FEodTRm.js +16 -0
  78. package/dist/web/server/assets/routes-B6AO0LjK.js +57 -0
  79. package/dist/web/server/assets/routes-D1NHwz6f.js +7644 -0
  80. package/dist/web/server/assets/{services-tCfB1B83.js → services-BjroGXgC.js} +4 -4
  81. package/dist/web/server/assets/{services-Q9HYQXXB.js → services-Cdk40QHq.js} +1 -1
  82. package/dist/web/server/assets/{services-BLvAvb8g.js → services-DsHRLL8q.js} +1 -1
  83. package/dist/web/server/assets/{skills-BZg_txbf.js → skills-CA17GjuZ.js} +1 -1
  84. package/dist/web/server/assets/{skills-C7fqRPna.js → skills-DC1OTc8n.js} +11 -11
  85. package/dist/web/server/assets/{skills-C_g8IKag.js → skills-h5aHa7Q8.js} +1 -1
  86. package/dist/web/server/assets/style-GYDODk2F.js +178 -0
  87. package/dist/web/server/assets/{teams-D4CaU76n.js → teams-Bm63mbTt.js} +1 -1
  88. package/dist/web/server/assets/{teams-DX2HmKqi.js → teams-BxnvFTyn.js} +1 -1
  89. package/dist/web/server/assets/{teams-BS-oweRl.js → teams-Cg-QQWpH.js} +23 -15
  90. package/dist/web/server/assets/{teams-BHkhnt6b.js → teams-D6Tx-Jyn.js} +1 -1
  91. package/dist/web/server/assets/{teams-BSflKBP8.js → teams-OzHTyVi9.js} +6 -6
  92. package/dist/web/server/assets/{teams-CNyB5nM9.js → teams-YrmyutM4.js} +1 -1
  93. package/dist/web/server/assets/{telegram-CrJiygCX.js → telegram-BJ4l_TA_.js} +6 -6
  94. package/dist/web/server/assets/{telegram-C4v1HhyJ.js → telegram-Gy7_9yih.js} +1 -1
  95. package/dist/web/server/assets/{telegram-BUdnc8oF.js → telegram-xU-vXgef.js} +1 -1
  96. package/dist/web/server/assets/{tokens-DqldzPUq.js → tokens-ByPTGFBQ.js} +1 -1
  97. package/dist/web/server/assets/{tokens-B1twAJdd.js → tokens-CEdl8puR.js} +1 -1
  98. package/dist/web/server/assets/{tokens-DdjEyALj.js → tokens-CsqoRt5T.js} +10 -10
  99. package/dist/web/server/assets/{welcome-D0d38Pzx.js → welcome-O6Rjd7yO.js} +1 -1
  100. package/dist/web/server/assets/workspace-DeEYMPDX.js +658 -0
  101. package/dist/web/server/server.js +20 -72
  102. package/dist/worker.js +51 -7
  103. package/dist/worker.js.map +1 -1
  104. package/package.json +1 -2
  105. package/dist/web/client/assets/AgentAvatar-DWx-bM6n.js +0 -1
  106. package/dist/web/client/assets/ChatPane-DOV_HJg-.js +0 -72
  107. package/dist/web/client/assets/ConfigPage-Dfu9DzFX.js +0 -1
  108. package/dist/web/client/assets/ConfirmDialog-536ziJ5P.js +0 -1
  109. package/dist/web/client/assets/FieldRow-z1JqCdqn.js +0 -1
  110. package/dist/web/client/assets/ResultCard-X4nTbjYY.js +0 -1
  111. package/dist/web/client/assets/SectionTabs-DXHzXmmb.js +0 -1
  112. package/dist/web/client/assets/SpawnDialog-DoZl-yes.js +0 -1
  113. package/dist/web/client/assets/SpawnTeamModal-C638hEoN.js +0 -1
  114. package/dist/web/client/assets/TeamForm-C-WzvOl4.js +0 -1
  115. package/dist/web/client/assets/TeamPolicyEditor-CSKBx0oK.js +0 -7
  116. package/dist/web/client/assets/UnsavedChangesGuard-GC-vzw7h.js +0 -1
  117. package/dist/web/client/assets/_id-BKLynswT.js +0 -1
  118. package/dist/web/client/assets/_id-BYM_NORr.js +0 -1
  119. package/dist/web/client/assets/_id-Cxa98a9m.js +0 -1
  120. package/dist/web/client/assets/_id-D4hV1U1t.js +0 -1
  121. package/dist/web/client/assets/agent-actions-CXQCoxKO.js +0 -1
  122. package/dist/web/client/assets/agents-BxPS1_Bp.js +0 -1
  123. package/dist/web/client/assets/agents-GozAWW-l.js +0 -1
  124. package/dist/web/client/assets/attention-Cz9rZcrr.js +0 -1
  125. package/dist/web/client/assets/chevron-right-CPAb1zac.js +0 -1
  126. package/dist/web/client/assets/config-9vv9Lipb.js +0 -3
  127. package/dist/web/client/assets/inbox-DHLArXxl.js +0 -1
  128. package/dist/web/client/assets/index-1YXquAq8.js +0 -52
  129. package/dist/web/client/assets/learning-PvtXm8Ne.js +0 -1
  130. package/dist/web/client/assets/login-DIJpNQFo.js +0 -1
  131. package/dist/web/client/assets/mcp-pKBL0xIf.js +0 -1
  132. package/dist/web/client/assets/members-DHWsgsEs.js +0 -1
  133. package/dist/web/client/assets/memory-CEVppPyU.js +0 -1
  134. package/dist/web/client/assets/plus-BaIRdB10.js +0 -1
  135. package/dist/web/client/assets/policy-DEh4BLSw.js +0 -1
  136. package/dist/web/client/assets/preload-helper-eUUcpe2S.js +0 -1
  137. package/dist/web/client/assets/results-DgJPjEZF.js +0 -1
  138. package/dist/web/client/assets/review-BbshafTQ.js +0 -1
  139. package/dist/web/client/assets/route-Ccb8v41z.js +0 -1
  140. package/dist/web/client/assets/route-D1d6kCEV.js +0 -1
  141. package/dist/web/client/assets/routes-g7V4ru7T.js +0 -1
  142. package/dist/web/client/assets/settings-B6elpcYm.js +0 -1
  143. package/dist/web/client/assets/skills-CngE7TF8.js +0 -1
  144. package/dist/web/client/assets/styles-xUnZ-ep_.css +0 -2
  145. package/dist/web/client/assets/teams-BdJZXOan.js +0 -1
  146. package/dist/web/client/assets/teams-c496ISsT.js +0 -1
  147. package/dist/web/client/assets/telegram-B_-hK6EC.js +0 -1
  148. package/dist/web/client/assets/tokens-CKz8gx4-.js +0 -1
  149. package/dist/web/client/assets/triggers-DCEPciGW.js +0 -1
  150. package/dist/web/client/assets/welcome-D-zVOLGA.js +0 -1
  151. package/dist/web/server/assets/AgentAvatar-8gTAy_tP.js +0 -37
  152. package/dist/web/server/assets/ChatPane-De_FPEoD.js +0 -1887
  153. package/dist/web/server/assets/ResultCard-CZn1w4KA.js +0 -97
  154. package/dist/web/server/assets/Sidebar-puq47KyR.js +0 -430
  155. package/dist/web/server/assets/SpawnTeamModal-C6GbfScI.js +0 -97
  156. package/dist/web/server/assets/_id-BR6tnR6I.js +0 -23
  157. package/dist/web/server/assets/_id-Bm611NQz.js +0 -13
  158. package/dist/web/server/assets/_id-D5UCoyES.js +0 -359
  159. package/dist/web/server/assets/_id-DHx5UmmL.js +0 -12
  160. package/dist/web/server/assets/_id-DLpGmOVm.js +0 -19
  161. package/dist/web/server/assets/_id-Y5ctILG2.js +0 -13
  162. package/dist/web/server/assets/_id-dDA0pdVo.js +0 -54
  163. package/dist/web/server/assets/_tanstack-start-manifest_v-B8u80HjK.js +0 -292
  164. package/dist/web/server/assets/agent-actions-BBdFVdoa.js +0 -20
  165. package/dist/web/server/assets/api-WWxPqx67.js +0 -85
  166. package/dist/web/server/assets/inbox-4Vj5jTT8.js +0 -245
  167. package/dist/web/server/assets/inbox-D4IqUv3l.js +0 -38
  168. package/dist/web/server/assets/inbox-Dle24AfV.js +0 -23
  169. package/dist/web/server/assets/learning-BScq7VbO.js +0 -12
  170. package/dist/web/server/assets/learning-CBWFEnhg.js +0 -263
  171. package/dist/web/server/assets/learning-DWAKevhF.js +0 -25
  172. package/dist/web/server/assets/members-B8QBF6TF.js +0 -12
  173. package/dist/web/server/assets/members-DsF02Wp7.js +0 -12
  174. package/dist/web/server/assets/members-tWZA9b15.js +0 -36
  175. package/dist/web/server/assets/memory-BNN0b-0x.js +0 -12
  176. package/dist/web/server/assets/memory-CTl1E1Rm.js +0 -267
  177. package/dist/web/server/assets/memory-CV5uCBb2.js +0 -12
  178. package/dist/web/server/assets/policy-C9M6zV6w.js +0 -79
  179. package/dist/web/server/assets/policy-h-6NpU3m.js +0 -19
  180. package/dist/web/server/assets/policy-xEw9X0DK.js +0 -12
  181. package/dist/web/server/assets/results-D3A3UA4d.js +0 -182
  182. package/dist/web/server/assets/results-D6Ui5S8D.js +0 -12
  183. package/dist/web/server/assets/results-DWmxvfyn.js +0 -15
  184. package/dist/web/server/assets/review-CyQky-WQ.js +0 -40
  185. package/dist/web/server/assets/review-Sq0GGcPV.js +0 -322
  186. package/dist/web/server/assets/review-XWbSF8cF.js +0 -12
  187. package/dist/web/server/assets/route-BErtkz6t.js +0 -19
  188. package/dist/web/server/assets/route-CLoV-An_.js +0 -48
  189. package/dist/web/server/assets/route-WQ19JkBa.js +0 -19
  190. package/dist/web/server/assets/route-dEK_2GLj.js +0 -203
  191. package/dist/web/server/assets/route-iHTkhO81.js +0 -16
  192. package/dist/web/server/assets/route-zs8uUQtB.js +0 -16
  193. package/dist/web/server/assets/routes-081s4n24.js +0 -45
  194. package/dist/web/server/assets/routes-CWo5WPsr.js +0 -15
  195. package/dist/web/server/assets/routes-Cqp1ufHm.js +0 -56
  196. package/dist/web/server/assets/settings-CVaGv-xF.js +0 -12
  197. package/dist/web/server/assets/settings-D9viV-86.js +0 -561
  198. package/dist/web/server/assets/settings-DaZNZ_CC.js +0 -27
  199. package/dist/web/server/assets/triggers-B7LW784F.js +0 -214
  200. package/dist/web/server/assets/triggers-C5sMCZXv2.js +0 -12
  201. package/dist/web/server/assets/triggers-DMfVdImD.js +0 -12
  202. package/dist/web/client/assets/{TeamPolicyEditor-DLioOiRN.css → style-DLioOiRN.css} +0 -0
  203. package/dist/web/server/assets/{start-DTX6aKCi.js → start-DhW7sy23.js} +1 -1
package/dist/daemon.js CHANGED
@@ -177,7 +177,7 @@ async function guardedFetch(opts) {
177
177
  let redirects = 0;
178
178
  let dispatcher = null;
179
179
  let activeResponse = null;
180
- const release = async () => {
180
+ const release2 = async () => {
181
181
  if (!activeResponse?.body?.locked) await activeResponse?.body?.cancel().catch(() => {
182
182
  });
183
183
  if (timeoutId) clearTimeout(timeoutId);
@@ -189,11 +189,11 @@ async function guardedFetch(opts) {
189
189
  try {
190
190
  parsed = new URL(current2);
191
191
  } catch {
192
- await release();
192
+ await release2();
193
193
  throw new Error("Invalid URL");
194
194
  }
195
195
  if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
196
- await release();
196
+ await release2();
197
197
  throw new Error("Invalid URL: must be http or https");
198
198
  }
199
199
  const canPin = !opts.fetchImpl;
@@ -202,7 +202,7 @@ async function guardedFetch(opts) {
202
202
  try {
203
203
  addrs = await resolveAndCheck(parsed.hostname);
204
204
  } catch (error) {
205
- await release();
205
+ await release2();
206
206
  throw error;
207
207
  }
208
208
  await closeDispatcher(dispatcher);
@@ -219,7 +219,7 @@ async function guardedFetch(opts) {
219
219
  res = await fetcher(parsed.toString(), init);
220
220
  activeResponse = res;
221
221
  } catch (err) {
222
- await release();
222
+ await release2();
223
223
  throw err;
224
224
  }
225
225
  if (isRedirectStatus(res.status)) {
@@ -227,23 +227,23 @@ async function guardedFetch(opts) {
227
227
  });
228
228
  const loc = res.headers.get("location");
229
229
  if (!loc) {
230
- await release();
230
+ await release2();
231
231
  throw new Error(`Redirect ${res.status} missing Location header`);
232
232
  }
233
233
  redirects += 1;
234
234
  if (redirects > maxRedirects) {
235
- await release();
235
+ await release2();
236
236
  throw new Error(`Too many redirects (> ${maxRedirects})`);
237
237
  }
238
238
  let next;
239
239
  try {
240
240
  next = new URL(loc, parsed).toString();
241
241
  } catch {
242
- await release();
242
+ await release2();
243
243
  throw new Error("Invalid redirect Location");
244
244
  }
245
245
  if (visited.has(next)) {
246
- await release();
246
+ await release2();
247
247
  throw new Error("Redirect loop");
248
248
  }
249
249
  visited.add(next);
@@ -256,7 +256,7 @@ async function guardedFetch(opts) {
256
256
  current2 = next;
257
257
  continue;
258
258
  }
259
- return { response: res, finalUrl: parsed.toString(), release };
259
+ return { response: res, finalUrl: parsed.toString(), release: release2 };
260
260
  }
261
261
  }
262
262
  var SsrFBlockedError, BLOCKED_HOSTNAMES;
@@ -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
  }
@@ -499,28 +499,28 @@ ${stderr.slice(-2e3)}` : ""}`
499
499
  });
500
500
  return conn;
501
501
  }
502
- function getMcpConnection(server3, connect2) {
502
+ function getMcpConnection(server3, connect3) {
503
503
  let conn = resources().mcp.get(server3.id);
504
504
  if (!conn) {
505
- conn = open(server3, connect2());
505
+ conn = open(server3, connect3());
506
506
  resources().mcp.set(server3.id, conn);
507
507
  ensureResourceReaper();
508
508
  }
509
509
  conn.lastUsedAt = Date.now();
510
510
  return conn.ready;
511
511
  }
512
- function connection(server3, connect2, signal) {
513
- if (!signal) return getMcpConnection(server3, connect2);
512
+ function connection(server3, connect3, signal) {
513
+ if (!signal) return getMcpConnection(server3, connect3);
514
514
  if (signal.aborted) return Promise.reject(new McpAbortError());
515
- const ready = getMcpConnection(server3, connect2);
516
- return new Promise((resolve8, reject2) => {
515
+ const ready = getMcpConnection(server3, connect3);
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
- async function listMcpTools(server3, connect2, signal) {
523
- const conn = await connection(server3, connect2, signal);
522
+ async function listMcpTools(server3, connect3, signal) {
523
+ const conn = await connection(server3, connect3, signal);
524
524
  if (conn.tools && !conn.toolsStale) return conn.tools;
525
525
  conn.toolsStale = false;
526
526
  conn.busy++;
@@ -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 {
@@ -679,20 +679,243 @@ var init_resources = __esm({
679
679
  }
680
680
  });
681
681
 
682
- // ../daemon/src/lib/browser/executable.ts
683
- import { accessSync, constants, readdirSync as readdirSync3, statSync as statSync3 } from "node:fs";
682
+ // ../daemon/src/lib/browser/ssrf.ts
683
+ import { lookup as dnsLookup2 } from "node:dns/promises";
684
+ async function browserBlockReason(rawUrl, allowPrivate) {
685
+ if (allowPrivate) return null;
686
+ let url;
687
+ try {
688
+ url = new URL(rawUrl);
689
+ } catch {
690
+ return null;
691
+ }
692
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
693
+ return SAFE_NON_HTTP_SCHEMES.has(url.protocol) ? null : `blocked URL scheme: ${url.protocol}`;
694
+ }
695
+ const host3 = url.hostname;
696
+ if (isBlockedHostname(host3)) return `blocked hostname: ${host3}`;
697
+ if (isPrivateIpAddress(host3)) return `blocked private IP literal: ${host3}`;
698
+ try {
699
+ const results = await dnsLookup2(host3, { all: true });
700
+ for (const r of results) {
701
+ if (isPrivateIpAddress(r.address)) {
702
+ return `${host3} resolves to private IP ${r.address}`;
703
+ }
704
+ }
705
+ } catch {
706
+ return null;
707
+ }
708
+ return null;
709
+ }
710
+ var SAFE_NON_HTTP_SCHEMES;
711
+ var init_ssrf = __esm({
712
+ "../daemon/src/lib/browser/ssrf.ts"() {
713
+ "use strict";
714
+ init_web_ssrf();
715
+ SAFE_NON_HTTP_SCHEMES = /* @__PURE__ */ new Set(["about:", "data:", "blob:"]);
716
+ }
717
+ });
718
+
719
+ // ../daemon/src/lib/browser/attach.ts
720
+ import { readFileSync as readFileSync6 } from "node:fs";
721
+ import { connect as connect2 } from "node:net";
684
722
  import { homedir as homedir2 } from "node:os";
685
- import { basename as basename3, isAbsolute, join as join10 } from "node:path";
723
+ import { join as join11 } from "node:path";
724
+ function runningBrowserDirs(platform = process.platform, home = homedir2()) {
725
+ if (platform === "darwin") {
726
+ const root2 = join11(home, "Library", "Application Support");
727
+ return [
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
+ ];
733
+ }
734
+ const root = process.env.XDG_CONFIG_HOME || join11(home, ".config");
735
+ return [
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
+ ];
742
+ }
743
+ function parseDevToolsActivePort(content) {
744
+ const [port2, path] = content.split("\n").map((line) => line.trim()).filter(Boolean);
745
+ if (!port2 || !/^\d{1,5}$/.test(port2) || Number(port2) < 1 || Number(port2) > 65535) return null;
746
+ if (!path?.startsWith("/")) return null;
747
+ return `ws://127.0.0.1:${port2}${path}`;
748
+ }
749
+ function isListening(endpoint2) {
750
+ return new Promise((resolve9) => {
751
+ const socket = connect2({ host: "127.0.0.1", port: Number(new URL(endpoint2).port) });
752
+ const done = (listening) => {
753
+ socket.destroy();
754
+ resolve9(listening);
755
+ };
756
+ socket.setTimeout(1e3, () => done(false));
757
+ socket.once("connect", () => done(true));
758
+ socket.once("error", () => done(false));
759
+ });
760
+ }
761
+ async function findRunningBrowser(dirs = runningBrowserDirs()) {
762
+ let denied;
763
+ for (const { name, dir } of dirs) {
764
+ let content;
765
+ try {
766
+ content = readFileSync6(join11(dir, "DevToolsActivePort"), "utf8");
767
+ } catch (error) {
768
+ const code = error.code;
769
+ if (code === "EPERM" || code === "EACCES") denied = dir;
770
+ continue;
771
+ }
772
+ const endpoint2 = parseDevToolsActivePort(content);
773
+ if (endpoint2 && await isListening(endpoint2)) return { name, endpoint: endpoint2 };
774
+ }
775
+ throw new Error(
776
+ denied ? `Cannot read ${denied}: the system denies the daemon access to the browser's folder. On macOS, allow the terminal that runs Bazilion under System Settings > Privacy & Security > Files & Folders, or set BROWSER_ATTACH_URL.` : `No running Chrome or Chromium accepts remote debugging. ${HOW_TO_ENABLE}`
777
+ );
778
+ }
779
+ async function openConnection(url) {
780
+ const target = url ? { name: url, endpoint: url } : await findRunningBrowser();
781
+ const { chromium } = await import("playwright");
782
+ let browser;
783
+ try {
784
+ browser = await chromium.connectOverCDP(target.endpoint, {
785
+ timeout: CONNECT_MS,
786
+ ...url ? {} : { isLocal: true }
787
+ });
788
+ } catch (error) {
789
+ const detail = (error instanceof Error ? error.message : String(error)).split("\n")[0];
790
+ throw new Error(
791
+ `Could not attach to ${target.name}: ${detail}. If the browser asks whether to allow remote debugging, allow it and try again.`
792
+ );
793
+ }
794
+ const context = browser.contexts()[0];
795
+ if (!context) {
796
+ await browser.close().catch(() => {
797
+ });
798
+ throw new Error(`${target.name} has no browser window to work in`);
799
+ }
800
+ return { browser, context };
801
+ }
802
+ function acquire(url) {
803
+ const key2 = url ?? "";
804
+ let shared = connections.get(key2);
805
+ if (!shared) {
806
+ const created = { opened: openConnection(url), users: 0 };
807
+ const drop = () => {
808
+ if (connections.get(key2) === created) connections.delete(key2);
809
+ };
810
+ created.opened.then(({ browser }) => browser.once("disconnected", drop), drop);
811
+ connections.set(key2, created);
812
+ shared = created;
813
+ }
814
+ shared.users++;
815
+ return shared;
816
+ }
817
+ async function release(url, shared) {
818
+ if (--shared.users > 0) return;
819
+ if (connections.get(url ?? "") === shared) connections.delete(url ?? "");
820
+ await shared.opened.then(({ browser }) => browser.close()).catch(() => {
821
+ });
822
+ }
823
+ async function refusePrivateRequests(page) {
824
+ await page.route("**/*", async (route) => {
825
+ try {
826
+ const reason = await browserBlockReason(route.request().url(), false);
827
+ await (reason ? route.abort("blockedbyclient") : route.continue());
828
+ } catch {
829
+ }
830
+ });
831
+ }
832
+ async function refuseDownloads(context, page) {
833
+ const cdp = await context.newCDPSession(page);
834
+ await cdp.send("Page.setDownloadBehavior", { behavior: "deny" });
835
+ }
836
+ async function attachBrowser(opts) {
837
+ const shared = acquire(opts.url);
838
+ let connection2;
839
+ try {
840
+ connection2 = await shared.opened;
841
+ } catch (error) {
842
+ await release(opts.url, shared);
843
+ throw error;
844
+ }
845
+ const { browser, context } = connection2;
846
+ const owned = /* @__PURE__ */ new Set();
847
+ const own = (page) => {
848
+ owned.add(page);
849
+ page.once("close", () => owned.delete(page));
850
+ page.on("popup", (popup) => void own(popup));
851
+ page.setDefaultNavigationTimeout(3e4);
852
+ page.setDefaultTimeout(1e4);
853
+ return Promise.all([
854
+ opts.allowPrivate ? void 0 : refusePrivateRequests(page),
855
+ refuseDownloads(context, page)
856
+ ]).catch(() => {
857
+ });
858
+ };
859
+ let closed;
860
+ return {
861
+ context,
862
+ get running() {
863
+ return browser.isConnected();
864
+ },
865
+ pages: () => context.pages().filter((page) => owned.has(page)),
866
+ owns: (page) => page !== null && owned.has(page),
867
+ async newPage() {
868
+ const page = await context.newPage();
869
+ await own(page);
870
+ return page;
871
+ },
872
+ close() {
873
+ closed ??= (async () => {
874
+ await Promise.all([...owned].map((page) => page.close().catch(() => {
875
+ })));
876
+ await release(opts.url, shared);
877
+ })();
878
+ return closed;
879
+ }
880
+ };
881
+ }
882
+ var CONNECT_MS, HOW_TO_ENABLE, connections;
883
+ var init_attach = __esm({
884
+ "../daemon/src/lib/browser/attach.ts"() {
885
+ "use strict";
886
+ init_ssrf();
887
+ CONNECT_MS = 6e4;
888
+ HOW_TO_ENABLE = "In Chrome 144 or later, open chrome://inspect/#remote-debugging and allow remote debugging; or start the browser with --remote-debugging-port and set BROWSER_ATTACH_URL.";
889
+ connections = /* @__PURE__ */ new Map();
890
+ }
891
+ });
892
+
893
+ // ../daemon/src/lib/browser/executable.ts
894
+ import { accessSync, constants, readdirSync as readdirSync3, statSync as statSync4 } from "node:fs";
895
+ import { homedir as homedir3 } from "node:os";
896
+ import { basename as basename3, isAbsolute, join as join12 } from "node:path";
897
+ function installedBrowserPaths(platform = process.platform, home = homedir3()) {
898
+ if (platform !== "darwin") return LINUX_INSTALLED;
899
+ return ["/Applications", join12(home, "Applications")].flatMap(
900
+ (root) => MAC_APPS.map(({ app: app2, name }) => ({
901
+ path: join12(root, `${app2}.app`, "Contents", "MacOS", app2),
902
+ name
903
+ }))
904
+ );
905
+ }
686
906
  function isExecutableFile(path) {
687
907
  try {
688
- if (!statSync3(path).isFile()) return false;
908
+ if (!statSync4(path).isFile()) return false;
689
909
  accessSync(path, constants.X_OK);
690
910
  return true;
691
911
  } catch {
692
912
  return false;
693
913
  }
694
914
  }
695
- function bundledChromium(root = process.env.PLAYWRIGHT_BROWSERS_PATH || join10(homedir2(), ".cache", "ms-playwright")) {
915
+ function playwrightCacheDir(platform = process.platform, home = homedir3()) {
916
+ return process.env.PLAYWRIGHT_BROWSERS_PATH || (platform === "darwin" ? join12(home, "Library", "Caches", "ms-playwright") : join12(home, ".cache", "ms-playwright"));
917
+ }
918
+ function bundledChromium(root = playwrightCacheDir()) {
696
919
  let entries;
697
920
  try {
698
921
  entries = readdirSync3(root);
@@ -701,8 +924,8 @@ function bundledChromium(root = process.env.PLAYWRIGHT_BROWSERS_PATH || join10(h
701
924
  }
702
925
  const revisions = entries.filter((entry) => /^chromium-\d+$/.test(entry)).sort((a, b) => Number(b.slice("chromium-".length)) - Number(a.slice("chromium-".length)));
703
926
  for (const revision of revisions) {
704
- for (const dir of ["chrome-linux64", "chrome-linux"]) {
705
- const path = join10(root, revision, dir, "chrome");
927
+ for (const layout of BUNDLED_LAYOUTS) {
928
+ const path = join12(root, revision, ...layout);
706
929
  if (isExecutableFile(path)) return { path, name: "Chromium (Playwright)" };
707
930
  }
708
931
  }
@@ -715,19 +938,16 @@ function findBrowserExecutable(configuredPath) {
715
938
  }
716
939
  return { path: configuredPath, name: basename3(configuredPath) };
717
940
  }
718
- const found = INSTALLED.find((candidate) => isExecutableFile(candidate.path)) ?? bundledChromium();
719
- if (!found) {
720
- throw new Error(
721
- "No browser found: install Chrome, Brave, Edge or Chromium, or set BROWSER_EXECUTABLE_PATH."
722
- );
723
- }
941
+ const found = installedBrowserPaths().find((candidate) => isExecutableFile(candidate.path)) ?? bundledChromium();
942
+ if (!found) throw new Error(NO_BROWSER_FOUND);
724
943
  return found;
725
944
  }
726
- var INSTALLED;
945
+ var NO_BROWSER_FOUND, LINUX_INSTALLED, MAC_APPS, BUNDLED_LAYOUTS;
727
946
  var init_executable = __esm({
728
947
  "../daemon/src/lib/browser/executable.ts"() {
729
948
  "use strict";
730
- INSTALLED = [
949
+ NO_BROWSER_FOUND = "No browser found: install Chrome, Brave, Edge or Chromium, or set BROWSER_EXECUTABLE_PATH.";
950
+ LINUX_INSTALLED = [
731
951
  { path: "/usr/bin/google-chrome", name: "Google Chrome" },
732
952
  { path: "/usr/bin/google-chrome-stable", name: "Google Chrome" },
733
953
  { path: "/opt/google/chrome/chrome", name: "Google Chrome" },
@@ -742,19 +962,132 @@ var init_executable = __esm({
742
962
  { path: "/usr/bin/chromium-browser", name: "Chromium" },
743
963
  { path: "/snap/bin/chromium", name: "Chromium" }
744
964
  ];
965
+ MAC_APPS = [
966
+ { app: "Google Chrome", name: "Google Chrome" },
967
+ { app: "Brave Browser", name: "Brave" },
968
+ { app: "Microsoft Edge", name: "Microsoft Edge" },
969
+ { app: "Chromium", name: "Chromium" }
970
+ ];
971
+ BUNDLED_LAYOUTS = [
972
+ ["chrome-linux64", "chrome"],
973
+ ["chrome-linux", "chrome"],
974
+ ...["chrome-mac-arm64", "chrome-mac-x64", "chrome-mac"].flatMap(
975
+ (dir) => ["Google Chrome for Testing", "Chromium"].map((app2) => [
976
+ dir,
977
+ `${app2}.app`,
978
+ "Contents",
979
+ "MacOS",
980
+ app2
981
+ ])
982
+ )
983
+ ];
745
984
  }
746
985
  });
747
986
 
748
- // ../daemon/src/lib/browser/launch.ts
987
+ // ../daemon/src/lib/browser/install.ts
749
988
  import { spawn } from "node:child_process";
750
- import { mkdirSync as mkdirSync5, readFileSync as readFileSync6, readlinkSync, writeFileSync as writeFileSync4 } from "node:fs";
751
- import { join as join11 } from "node:path";
989
+ import { createRequire } from "node:module";
990
+ import { dirname as dirname3, join as join13 } from "node:path";
991
+ function downloadAllowed() {
992
+ const skip2 = process.env.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD?.trim().toLowerCase();
993
+ return !skip2 || skip2 === "0" || skip2 === "false";
994
+ }
995
+ function runInstaller() {
996
+ return new Promise((resolve9, reject2) => {
997
+ const cli = join13(
998
+ dirname3(createRequire(import.meta.url).resolve("playwright/package.json")),
999
+ "cli.js"
1000
+ );
1001
+ const child = spawn(
1002
+ process.execPath,
1003
+ [cli, "install", "--no-shell", "--no-progress", "chromium"],
1004
+ {
1005
+ env: Object.fromEntries(
1006
+ Object.entries(process.env).filter(([name]) => INSTALLER_ENV.test(name))
1007
+ ),
1008
+ stdio: ["ignore", "pipe", "pipe"],
1009
+ timeout: DOWNLOAD_TIMEOUT_MS
1010
+ }
1011
+ );
1012
+ let output = "";
1013
+ const keep = (chunk) => {
1014
+ output = (output + chunk.toString("utf8")).slice(-2e3);
1015
+ };
1016
+ child.stdout.on("data", keep);
1017
+ child.stderr.on("data", keep);
1018
+ child.once("error", reject2);
1019
+ child.once("exit", (code, signal) => {
1020
+ if (code === 0) resolve9();
1021
+ else reject2(new Error(output.trim() || `the installer ended with ${signal ?? code}`));
1022
+ });
1023
+ });
1024
+ }
1025
+ function downloadChromium() {
1026
+ if (!download) {
1027
+ console.log("browser: no browser is installed, downloading Chromium (once)\u2026");
1028
+ const run = runInstaller().then(
1029
+ () => {
1030
+ lastError = null;
1031
+ console.log("browser: Chromium downloaded");
1032
+ },
1033
+ (error) => {
1034
+ lastError = error instanceof Error ? error.message : String(error);
1035
+ console.error(`browser: downloading Chromium failed: ${lastError}`);
1036
+ throw error;
1037
+ }
1038
+ );
1039
+ download = run;
1040
+ const clear = () => {
1041
+ if (download === run) download = null;
1042
+ };
1043
+ run.then(clear, clear);
1044
+ }
1045
+ return download;
1046
+ }
1047
+ async function ensureBrowserExecutable(configuredPath) {
1048
+ try {
1049
+ return findBrowserExecutable(configuredPath);
1050
+ } catch (error) {
1051
+ if (configuredPath || !downloadAllowed()) throw error;
1052
+ }
1053
+ try {
1054
+ await downloadChromium();
1055
+ } catch (error) {
1056
+ const detail = error instanceof Error ? error.message : String(error);
1057
+ throw new Error(`${NO_BROWSER_FOUND} Downloading Chromium failed: ${detail}`);
1058
+ }
1059
+ return findBrowserExecutable();
1060
+ }
1061
+ function prepareBrowser(configuredPath) {
1062
+ ensureBrowserExecutable(configuredPath).catch(() => {
1063
+ });
1064
+ }
1065
+ function browserDownloadNote() {
1066
+ if (download) return "No browser is installed yet: Chromium is being downloaded.";
1067
+ return lastError ? `${NO_BROWSER_FOUND} Downloading Chromium failed: ${lastError}` : null;
1068
+ }
1069
+ var DOWNLOAD_TIMEOUT_MS, INSTALLER_ENV, download, lastError;
1070
+ var init_install = __esm({
1071
+ "../daemon/src/lib/browser/install.ts"() {
1072
+ "use strict";
1073
+ init_executable();
1074
+ DOWNLOAD_TIMEOUT_MS = 15 * 6e4;
1075
+ INSTALLER_ENV = /^(PATH|HOME|TMPDIR|XDG_CACHE_HOME|NODE_EXTRA_CA_CERTS|PLAYWRIGHT_.*|(HTTPS?|NO|ALL)_PROXY)$/i;
1076
+ download = null;
1077
+ lastError = null;
1078
+ }
1079
+ });
1080
+
1081
+ // ../daemon/src/lib/browser/launch.ts
1082
+ import { execFileSync, spawn as spawn2 } from "node:child_process";
1083
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync7, readlinkSync, writeFileSync as writeFileSync4 } from "node:fs";
1084
+ import { join as join14 } from "node:path";
752
1085
  function launchArgs(opts) {
753
1086
  const wayland = !opts.headless && !process.env.DISPLAY && !!process.env.WAYLAND_DISPLAY;
754
1087
  return [
755
1088
  // Chromium picks the port and prints the endpoint on stderr.
756
1089
  "--remote-debugging-port=0",
757
- `--user-data-dir=${join11(opts.dir, "user-data")}`,
1090
+ `--user-data-dir=${join14(opts.dir, "user-data")}`,
758
1091
  "--no-first-run",
759
1092
  "--no-default-browser-check",
760
1093
  "--disable-sync",
@@ -780,7 +1113,7 @@ function launchArgs(opts) {
780
1113
  function browserEnv(opts) {
781
1114
  const env = {
782
1115
  PATH: process.env.PATH ?? "/usr/bin:/bin",
783
- HOME: join11(opts.dir, "home"),
1116
+ HOME: join14(opts.dir, "home"),
784
1117
  LANG: "C.UTF-8"
785
1118
  };
786
1119
  if (!opts.headless) {
@@ -805,13 +1138,23 @@ function isAlive(pid) {
805
1138
  return false;
806
1139
  }
807
1140
  }
1141
+ function runsOnProfile(pid, userDataDir) {
1142
+ const flag = `--user-data-dir=${userDataDir}`;
1143
+ try {
1144
+ return readFileSync7(`/proc/${pid}/cmdline`, "utf8").split("\0").includes(flag);
1145
+ } catch {
1146
+ const command = execFileSync("ps", ["-ww", "-o", "command=", "-p", String(pid)], {
1147
+ encoding: "utf8"
1148
+ }).trim();
1149
+ return command.includes(`${flag} `) || command.endsWith(flag);
1150
+ }
1151
+ }
808
1152
  async function killOrphanBrowser(dir) {
809
- const userDataDir = join11(dir, "user-data");
1153
+ const userDataDir = join14(dir, "user-data");
810
1154
  let pid;
811
1155
  try {
812
- pid = Number(/-(\d+)$/.exec(readlinkSync(join11(userDataDir, "SingletonLock")))?.[1]);
813
- const argv = readFileSync6(`/proc/${pid}/cmdline`, "utf8").split("\0");
814
- if (!argv.includes(`--user-data-dir=${userDataDir}`)) return;
1156
+ pid = Number(/-(\d+)$/.exec(readlinkSync(join14(userDataDir, "SingletonLock")))?.[1]);
1157
+ if (!runsOnProfile(pid, userDataDir)) return;
815
1158
  } catch {
816
1159
  return;
817
1160
  }
@@ -823,11 +1166,11 @@ async function killOrphanBrowser(dir) {
823
1166
  for (let i = 0; i < 40 && isAlive(pid); i++) await sleep(50);
824
1167
  }
825
1168
  function skipSessionRestore(userDataDir) {
826
- const dir = join11(userDataDir, "Default");
827
- const file = join11(dir, "Preferences");
1169
+ const dir = join14(userDataDir, "Default");
1170
+ const file = join14(dir, "Preferences");
828
1171
  let prefs = {};
829
1172
  try {
830
- const parsed = JSON.parse(readFileSync6(file, "utf8"));
1173
+ const parsed = JSON.parse(readFileSync7(file, "utf8"));
831
1174
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
832
1175
  prefs = parsed;
833
1176
  }
@@ -847,12 +1190,12 @@ function trackGroup(pid) {
847
1190
  });
848
1191
  }
849
1192
  async function launchBrowser(opts) {
850
- const userDataDir = join11(opts.dir, "user-data");
1193
+ const userDataDir = join14(opts.dir, "user-data");
851
1194
  mkdirSync5(userDataDir, { recursive: true, mode: 448 });
852
- mkdirSync5(join11(opts.dir, "home"), { recursive: true, mode: 448 });
1195
+ mkdirSync5(join14(opts.dir, "home"), { recursive: true, mode: 448 });
853
1196
  await killOrphanBrowser(opts.dir);
854
1197
  skipSessionRestore(userDataDir);
855
- const child = spawn(opts.executablePath, launchArgs(opts), {
1198
+ const child = spawn2(opts.executablePath, launchArgs(opts), {
856
1199
  env: browserEnv(opts),
857
1200
  detached: true,
858
1201
  stdio: ["ignore", "ignore", "pipe"]
@@ -867,7 +1210,7 @@ async function launchBrowser(opts) {
867
1210
  liveGroups.delete(pid);
868
1211
  });
869
1212
  }
870
- const exited = new Promise((resolve8) => child.once("exit", () => resolve8(true)));
1213
+ const exited = new Promise((resolve9) => child.once("exit", () => resolve9(true)));
871
1214
  const waitForExit = (ms) => Promise.race([exited, sleep(ms).then(() => false)]);
872
1215
  const running = () => child.exitCode === null && child.signalCode === null;
873
1216
  let browser;
@@ -890,7 +1233,7 @@ async function launchBrowser(opts) {
890
1233
  })();
891
1234
  let stderr = "";
892
1235
  try {
893
- const endpoint2 = await new Promise((resolve8, reject2) => {
1236
+ const endpoint2 = await new Promise((resolve9, reject2) => {
894
1237
  const fail2 = (message) => {
895
1238
  clearTimeout(timer);
896
1239
  reject2(new Error(stderr.trim() ? `${message}:
@@ -920,7 +1263,7 @@ ${stderr.trim()}` : message));
920
1263
  );
921
1264
  if (match?.[1]) {
922
1265
  clearTimeout(timer);
923
- resolve8(match[1]);
1266
+ resolve9(match[1]);
924
1267
  }
925
1268
  }
926
1269
  });
@@ -938,6 +1281,9 @@ ${stderr.trim()}` : message));
938
1281
  return {
939
1282
  context,
940
1283
  close,
1284
+ pages: () => context.pages(),
1285
+ newPage: () => context.newPage(),
1286
+ owns: () => true,
941
1287
  get running() {
942
1288
  return running();
943
1289
  }
@@ -955,7 +1301,7 @@ var init_launch = __esm({
955
1301
  NO_WEBRTC_SCRIPT = `for (const name of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'mozRTCPeerConnection']) {
956
1302
  Object.defineProperty(window, name, { configurable: false, get() { return undefined } })
957
1303
  }`;
958
- sleep = (ms) => new Promise((resolve8) => setTimeout(resolve8, ms));
1304
+ sleep = (ms) => new Promise((resolve9) => setTimeout(resolve9, ms));
959
1305
  liveGroups = /* @__PURE__ */ new Set();
960
1306
  exitHookInstalled = false;
961
1307
  }
@@ -1014,43 +1360,6 @@ var init_snapshot = __esm({
1014
1360
  }
1015
1361
  });
1016
1362
 
1017
- // ../daemon/src/lib/browser/ssrf.ts
1018
- import { lookup as dnsLookup2 } from "node:dns/promises";
1019
- async function browserBlockReason(rawUrl, allowPrivate) {
1020
- if (allowPrivate) return null;
1021
- let url;
1022
- try {
1023
- url = new URL(rawUrl);
1024
- } catch {
1025
- return null;
1026
- }
1027
- if (url.protocol !== "http:" && url.protocol !== "https:") {
1028
- return SAFE_NON_HTTP_SCHEMES.has(url.protocol) ? null : `blocked URL scheme: ${url.protocol}`;
1029
- }
1030
- const host3 = url.hostname;
1031
- if (isBlockedHostname(host3)) return `blocked hostname: ${host3}`;
1032
- if (isPrivateIpAddress(host3)) return `blocked private IP literal: ${host3}`;
1033
- try {
1034
- const results = await dnsLookup2(host3, { all: true });
1035
- for (const r of results) {
1036
- if (isPrivateIpAddress(r.address)) {
1037
- return `${host3} resolves to private IP ${r.address}`;
1038
- }
1039
- }
1040
- } catch {
1041
- return null;
1042
- }
1043
- return null;
1044
- }
1045
- var SAFE_NON_HTTP_SCHEMES;
1046
- var init_ssrf = __esm({
1047
- "../daemon/src/lib/browser/ssrf.ts"() {
1048
- "use strict";
1049
- init_web_ssrf();
1050
- SAFE_NON_HTTP_SCHEMES = /* @__PURE__ */ new Set(["about:", "data:", "blob:"]);
1051
- }
1052
- });
1053
-
1054
1363
  // ../daemon/src/lib/browser/pool.ts
1055
1364
  import { existsSync as existsSync10, rmSync as rmSync8 } from "node:fs";
1056
1365
  function serialize(agentId, work) {
@@ -1071,7 +1380,14 @@ function errorMessage(error) {
1071
1380
  return error instanceof Error ? error.message : String(error);
1072
1381
  }
1073
1382
  function configKey(config) {
1074
- return `${config.headless}|${config.executablePath ?? ""}|${config.allowPrivate}`;
1383
+ return config.attach ? `attach|${config.attachUrl ?? ""}|${config.allowPrivate}` : `${config.headless}|${config.executablePath ?? ""}|${config.allowPrivate}`;
1384
+ }
1385
+ function requestPage(request) {
1386
+ try {
1387
+ return request.frame().page();
1388
+ } catch {
1389
+ return null;
1390
+ }
1075
1391
  }
1076
1392
  function tabId(session, page) {
1077
1393
  let id = session.tabIds.get(page);
@@ -1087,6 +1403,8 @@ function remember(log, entry) {
1087
1403
  }
1088
1404
  function startSession(agentId, key2, browser, idleMs) {
1089
1405
  const sessions = resources().browsers;
1406
+ const { context } = browser;
1407
+ const unlisten = [];
1090
1408
  let closed;
1091
1409
  const session = {
1092
1410
  agentId,
@@ -1104,6 +1422,7 @@ function startSession(agentId, key2, browser, idleMs) {
1104
1422
  close() {
1105
1423
  if (sessions.get(agentId) === session) sessions.delete(agentId);
1106
1424
  if (!closed) {
1425
+ for (const off of unlisten) off();
1107
1426
  const done = browser.close();
1108
1427
  closed = done;
1109
1428
  closing.set(agentId, done);
@@ -1114,24 +1433,35 @@ function startSession(agentId, key2, browser, idleMs) {
1114
1433
  return closed;
1115
1434
  }
1116
1435
  };
1117
- const { context } = browser;
1118
- for (const page of context.pages()) tabId(session, page);
1119
- context.on("page", (page) => {
1120
- tabId(session, page);
1121
- });
1122
- context.on("console", (message) => {
1436
+ for (const page of browser.pages()) tabId(session, page);
1437
+ const onPage = (page) => {
1438
+ if (browser.owns(page)) tabId(session, page);
1439
+ };
1440
+ const onConsole = (message) => {
1441
+ if (!browser.owns(message.page())) return;
1123
1442
  remember(session.console, clip(`[${message.type()}] ${message.text()}`, CONSOLE_CHARS));
1124
- });
1443
+ };
1125
1444
  const entries = /* @__PURE__ */ new WeakMap();
1126
- context.on("request", (request) => {
1445
+ const onRequest2 = (request) => {
1446
+ if (!browser.owns(requestPage(request))) return;
1127
1447
  const entry = { method: request.method(), url: clip(request.url()) };
1128
1448
  entries.set(request, entry);
1129
1449
  remember(session.network, entry);
1130
- });
1131
- context.on("response", (response) => {
1450
+ };
1451
+ const onResponse = (response) => {
1132
1452
  const entry = entries.get(response.request());
1133
1453
  if (entry) entry.status = response.status();
1134
- });
1454
+ };
1455
+ context.on("page", onPage);
1456
+ context.on("console", onConsole);
1457
+ context.on("request", onRequest2);
1458
+ context.on("response", onResponse);
1459
+ unlisten.push(
1460
+ () => context.off("page", onPage),
1461
+ () => context.off("console", onConsole),
1462
+ () => context.off("request", onRequest2),
1463
+ () => context.off("response", onResponse)
1464
+ );
1135
1465
  sessions.set(agentId, session);
1136
1466
  ensureResourceReaper();
1137
1467
  return session;
@@ -1158,9 +1488,11 @@ async function claimSession(agentId, config, paths) {
1158
1488
  }
1159
1489
  launching++;
1160
1490
  try {
1161
- const executable = findBrowserExecutable(config.executablePath);
1162
- const browser = await launchBrowser({
1163
- executablePath: executable.path,
1491
+ const browser = config.attach ? await attachBrowser({
1492
+ allowPrivate: config.allowPrivate,
1493
+ ...config.attachUrl ? { url: config.attachUrl } : {}
1494
+ }) : await launchBrowser({
1495
+ executablePath: (await ensureBrowserExecutable(config.executablePath)).path,
1164
1496
  dir: paths.browserDir(agentId),
1165
1497
  headless: config.headless,
1166
1498
  ...config.allowPrivate ? {} : { proxyUrl: await getSsrfProxy() }
@@ -1237,17 +1569,25 @@ function browserStatus(agentId, config, paths, enabled) {
1237
1569
  running: resources().browsers.get(agentId)?.browser.running ?? false,
1238
1570
  profilePresent: existsSync10(paths.browserDir(agentId))
1239
1571
  };
1572
+ const launchError = launchErrors.get(agentId);
1573
+ if (config.attach) {
1574
+ status2.browser = {
1575
+ name: config.attachUrl ?? "The running Chrome or Chromium",
1576
+ mode: "attached"
1577
+ };
1578
+ if (launchError) status2.error = launchError;
1579
+ return status2;
1580
+ }
1240
1581
  try {
1241
1582
  const { name } = findBrowserExecutable(config.executablePath);
1242
1583
  status2.browser = { name, mode: config.headless ? "headless" : "headed" };
1243
- const launchError = launchErrors.get(agentId);
1244
1584
  if (launchError) status2.error = launchError;
1245
1585
  } catch (error) {
1246
- status2.error = errorMessage(error);
1586
+ status2.error = (config.executablePath ? null : browserDownloadNote()) ?? launchError ?? errorMessage(error);
1247
1587
  }
1248
1588
  return status2;
1249
1589
  }
1250
- function text(value) {
1590
+ function text2(value) {
1251
1591
  return [{ type: "text", text: capText(value) }];
1252
1592
  }
1253
1593
  function firstLine(error) {
@@ -1272,8 +1612,8 @@ async function checkUrl(url, config) {
1272
1612
  if (reason) throw new Error(`navigation blocked: ${reason}`);
1273
1613
  }
1274
1614
  async function activePage(session) {
1275
- const pages = session.browser.context.pages();
1276
- const page = pages.find((p) => tabId(session, p) === session.activeTab) ?? pages[0] ?? await session.browser.context.newPage();
1615
+ const pages = session.browser.pages();
1616
+ const page = pages.find((p) => tabId(session, p) === session.activeTab) ?? pages[0] ?? await session.browser.newPage();
1277
1617
  session.activeTab = tabId(session, page);
1278
1618
  return page;
1279
1619
  }
@@ -1307,7 +1647,7 @@ async function act(session, refs, action) {
1307
1647
  const page = await activePage(session);
1308
1648
  for (const ref of refs) {
1309
1649
  if (await page.locator(`aria-ref=${ref}`).count() === 0) {
1310
- return text(
1650
+ return text2(
1311
1651
  `Ref "${ref}" is not on the page any more, so nothing was done. Use a ref from this fresh snapshot:
1312
1652
 
1313
1653
  ${await freshSnapshot(session, page)}`
@@ -1317,14 +1657,14 @@ ${await freshSnapshot(session, page)}`
1317
1657
  try {
1318
1658
  await action(page);
1319
1659
  } catch (error) {
1320
- return text(
1660
+ return text2(
1321
1661
  `Could not act on ref "${refs.join(", ")}": ${firstLine(error)}
1322
1662
  The action may still have taken effect: check the page below before trying again, and never repeat a submission blindly.
1323
1663
 
1324
1664
  ` + await freshSnapshot(session, page)
1325
1665
  );
1326
1666
  }
1327
- return text(await freshSnapshot(session, page));
1667
+ return text2(await freshSnapshot(session, page));
1328
1668
  }
1329
1669
  async function runAction(session, action, args, config) {
1330
1670
  switch (action) {
@@ -1333,14 +1673,14 @@ async function runAction(session, action, args, config) {
1333
1673
  await checkUrl(url, config);
1334
1674
  const page = await activePage(session);
1335
1675
  await page.goto(url, { waitUntil: "domcontentloaded" });
1336
- return text(await freshSnapshot(session, page));
1676
+ return text2(await freshSnapshot(session, page));
1337
1677
  }
1338
1678
  case "snapshot": {
1339
- if (args.page !== void 0) return text(snapshotPage(session, args.page));
1679
+ if (args.page !== void 0) return text2(snapshotPage(session, args.page));
1340
1680
  const page = await activePage(session);
1341
- if (isBlank(page)) return text(NO_PAGE_HINT);
1681
+ if (isBlank(page)) return text2(NO_PAGE_HINT);
1342
1682
  const ref = args.ref === void 0 ? void 0 : elementRef(args.ref);
1343
- return text(await snapshot(session, page, ref));
1683
+ return text2(await snapshot(session, page, ref));
1344
1684
  }
1345
1685
  case "click": {
1346
1686
  const ref = elementRef(args.ref);
@@ -1387,18 +1727,18 @@ async function runAction(session, action, args, config) {
1387
1727
  const key2 = stringArg(args, "key");
1388
1728
  const page = await activePage(session);
1389
1729
  await page.keyboard.press(key2);
1390
- return text(await freshSnapshot(session, page));
1730
+ return text2(await freshSnapshot(session, page));
1391
1731
  }
1392
1732
  case "go_back": {
1393
1733
  const page = await activePage(session);
1394
1734
  await page.goBack({ waitUntil: "domcontentloaded" });
1395
- return text(await freshSnapshot(session, page));
1735
+ return text2(await freshSnapshot(session, page));
1396
1736
  }
1397
1737
  case "tabs":
1398
1738
  return tabs(session, args, config);
1399
1739
  case "take_screenshot": {
1400
1740
  const page = await activePage(session);
1401
- if (isBlank(page)) return text(NO_PAGE_HINT);
1741
+ if (isBlank(page)) return text2(NO_PAGE_HINT);
1402
1742
  const png = await page.screenshot({
1403
1743
  type: "png",
1404
1744
  fullPage: args.full_page === true,
@@ -1415,9 +1755,9 @@ async function runAction(session, action, args, config) {
1415
1755
  ];
1416
1756
  }
1417
1757
  case "console":
1418
- return text(session.console.join("\n") || "no console messages");
1758
+ return text2(session.console.join("\n") || "no console messages");
1419
1759
  case "network":
1420
- return text(
1760
+ return text2(
1421
1761
  session.network.map((r) => `${r.method} ${r.status ?? "..."} ${r.url}`).join("\n") || "no network requests recorded"
1422
1762
  );
1423
1763
  default:
@@ -1426,40 +1766,40 @@ async function runAction(session, action, args, config) {
1426
1766
  }
1427
1767
  async function tabs(session, args, config) {
1428
1768
  const op = stringArg(args, "op");
1429
- const { context } = session.browser;
1769
+ const { browser } = session;
1430
1770
  if (op === "list") {
1431
- const lines = context.pages().map((page2) => {
1771
+ const lines = browser.pages().map((page2) => {
1432
1772
  const id2 = tabId(session, page2);
1433
1773
  return `${id2 === session.activeTab ? "*" : " "} ${id2} ${clip(page2.url())}`;
1434
1774
  }).join("\n");
1435
- return text(lines);
1775
+ return text2(lines || "No tabs are open.");
1436
1776
  }
1437
1777
  if (op === "new") {
1438
- if (context.pages().length >= MAX_TABS) {
1778
+ if (browser.pages().length >= MAX_TABS) {
1439
1779
  throw new Error(`${MAX_TABS} tabs are already open; close one first`);
1440
1780
  }
1441
1781
  const url = typeof args.url === "string" && args.url ? args.url : void 0;
1442
1782
  if (url) await checkUrl(url, config);
1443
- const page2 = await context.newPage();
1783
+ const page2 = await browser.newPage();
1444
1784
  session.activeTab = tabId(session, page2);
1445
- if (!url) return text(`Opened ${session.activeTab} (about:blank).`);
1785
+ if (!url) return text2(`Opened ${session.activeTab} (about:blank).`);
1446
1786
  await page2.goto(url, { waitUntil: "domcontentloaded" });
1447
- return text(await freshSnapshot(session, page2));
1787
+ return text2(await freshSnapshot(session, page2));
1448
1788
  }
1449
1789
  const id = stringArg(args, "tabId");
1450
- const page = context.pages().find((p) => tabId(session, p) === id);
1790
+ const page = browser.pages().find((p) => tabId(session, p) === id);
1451
1791
  if (op === "select") {
1452
1792
  if (!page) throw new Error(`No open tab "${id}"; browser_tabs {"op":"list"} lists them.`);
1453
1793
  await page.bringToFront();
1454
1794
  session.activeTab = id;
1455
- return text(
1795
+ return text2(
1456
1796
  isBlank(page) ? `Selected ${id} (about:blank).` : await freshSnapshot(session, page)
1457
1797
  );
1458
1798
  }
1459
1799
  if (op === "close") {
1460
- if (!page) return text(`Tab "${id}" is not open.`);
1800
+ if (!page) return text2(`Tab "${id}" is not open.`);
1461
1801
  await page.close();
1462
- return text(`Closed ${id}.`);
1802
+ return text2(`Closed ${id}.`);
1463
1803
  }
1464
1804
  throw new Error(`unknown tabs op "${op}" (expected list, new, select or close)`);
1465
1805
  }
@@ -1468,7 +1808,9 @@ var init_pool2 = __esm({
1468
1808
  "../daemon/src/lib/browser/pool.ts"() {
1469
1809
  "use strict";
1470
1810
  init_resources();
1811
+ init_attach();
1471
1812
  init_executable();
1813
+ init_install();
1472
1814
  init_launch();
1473
1815
  init_proxy();
1474
1816
  init_snapshot();
@@ -2813,6 +3155,11 @@ var ATTENTION_KINDS = [
2813
3155
  "queue_interrupted"
2814
3156
  ];
2815
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
+ }
2816
3163
  var sources = [
2817
3164
  {
2818
3165
  kind: "lesson_proposal",
@@ -2827,7 +3174,7 @@ var sources = [
2827
3174
  severity: "action_required",
2828
3175
  title: "Lesson proposal ready",
2829
3176
  diagnostic: "A reviewed-learning proposal is waiting for approval or rejection.",
2830
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}/learning`,
3177
+ href: agentHref(r.agentId, "learning"),
2831
3178
  acknowledgeable: false
2832
3179
  })
2833
3180
  )
@@ -2846,7 +3193,7 @@ var sources = [
2846
3193
  severity: "error",
2847
3194
  title: r.status === "cancelled" ? "Agent review cancelled" : "Agent review failed",
2848
3195
  diagnostic: bounded(r.diagnostic, "The review stopped without completing."),
2849
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}/learning`,
3196
+ href: agentHref(r.agentId, "learning"),
2850
3197
  acknowledgeable: true
2851
3198
  })
2852
3199
  )
@@ -2866,7 +3213,7 @@ var sources = [
2866
3213
  severity: "error",
2867
3214
  title: "Scheduled trigger failed",
2868
3215
  diagnostic: bounded(r.diagnostic, "The scheduled Agent turn failed."),
2869
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}/triggers`,
3216
+ href: agentHref(r.agentId, "schedules"),
2870
3217
  acknowledgeable: true
2871
3218
  })
2872
3219
  )
@@ -2884,7 +3231,7 @@ var sources = [
2884
3231
  severity: "warning",
2885
3232
  title: "Agent message loop stopped",
2886
3233
  diagnostic: `Message chain stopped at hop ${r.attempted_hop} (limit ${r.max_hops}).`,
2887
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}/inbox`,
3234
+ href: agentHref(r.agentId, "mailbox"),
2888
3235
  acknowledgeable: true
2889
3236
  })
2890
3237
  )
@@ -2913,7 +3260,7 @@ var sources = [
2913
3260
  severity: "action_required",
2914
3261
  title: "Agent queue paused after a daemon restart",
2915
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.`,
2916
- href: `/agents/${encodeURIComponent(r.agentId ?? "")}`,
3263
+ href: agentHref(r.agentId),
2917
3264
  acknowledgeable: false
2918
3265
  })
2919
3266
  )
@@ -4341,7 +4688,7 @@ var SERVICES = [
4341
4688
  displayName: "Browser Automation",
4342
4689
  category: "service",
4343
4690
  team: "Browser",
4344
- 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.",
4691
+ 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.',
4345
4692
  fields: [
4346
4693
  {
4347
4694
  envVar: "BROWSER_ENABLED",
@@ -4355,14 +4702,28 @@ var SERVICES = [
4355
4702
  kind: "config",
4356
4703
  label: "Browser executable (optional)",
4357
4704
  placeholder: "/usr/bin/brave-browser",
4358
- description: "Absolute path to a Chromium-family browser. When unset, Bazilion uses the first installed Chrome, Brave, Edge or Chromium, then the Chromium that Playwright downloaded."
4705
+ description: "Absolute path to a Chromium-family browser. When unset, Bazilion uses the first installed Chrome, Brave, Edge or Chromium; when none is installed it downloads Chromium once."
4706
+ },
4707
+ {
4708
+ envVar: "BROWSER_ATTACH",
4709
+ kind: "config",
4710
+ label: "Use my running browser",
4711
+ placeholder: "false",
4712
+ description: "true makes Agents work in the Chrome or Chromium you already have open, with your logins, in tabs of their own. Allow it first in Chrome at chrome://inspect/#remote-debugging. Default false: each Agent gets a browser of its own."
4713
+ },
4714
+ {
4715
+ envVar: "BROWSER_ATTACH_URL",
4716
+ kind: "config",
4717
+ label: "Running browser address (optional)",
4718
+ placeholder: "http://127.0.0.1:9222",
4719
+ description: 'DevTools address of the browser to use when "Use my running browser" is on, for one started with --remote-debugging-port. When unset, Bazilion finds the running Chrome or Chromium itself.'
4359
4720
  },
4360
4721
  {
4361
4722
  envVar: "BROWSER_HEADLESS",
4362
4723
  kind: "config",
4363
4724
  label: "Headless",
4364
4725
  placeholder: "true",
4365
- description: "true (default) runs the browser without a window; false opens a visible browser window on the desktop the daemon runs in."
4726
+ description: "true (default) runs the browser without a window; false opens a visible browser window on the desktop the daemon runs in. Not used with a running browser."
4366
4727
  },
4367
4728
  {
4368
4729
  envVar: "BROWSER_ALLOW_PRIVATE_NETWORK",
@@ -4594,6 +4955,7 @@ var messages_exports = {};
4594
4955
  __export(messages_exports, {
4595
4956
  drainUnreadForAgent: () => drainUnreadForAgent,
4596
4957
  get: () => get10,
4958
+ listForTeam: () => listForTeam,
4597
4959
  listInbox: () => listInbox,
4598
4960
  listRecipientsWithUnread: () => listRecipientsWithUnread,
4599
4961
  markRead: () => markRead,
@@ -4645,6 +5007,14 @@ function listInbox(db, agentId, opts) {
4645
5007
  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";
4646
5008
  return db.raw.query(sql).all(agentId).map(toMessage);
4647
5009
  }
5010
+ function listForTeam(db, teamId, limit) {
5011
+ return db.raw.query(
5012
+ `SELECT m.* FROM messages m
5013
+ WHERE m.from_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5014
+ OR m.to_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5015
+ ORDER BY m.created_at DESC, m.id DESC LIMIT ?`
5016
+ ).all(teamId, teamId, limit).map(toMessage);
5017
+ }
4648
5018
  function markRead(db, id) {
4649
5019
  db.raw.run("UPDATE messages SET read_at = ? WHERE id = ? AND read_at IS NULL", [Date.now(), id]);
4650
5020
  }
@@ -5837,38 +6207,246 @@ async function authMiddleware(c, next) {
5837
6207
  await next();
5838
6208
  }
5839
6209
 
5840
- // ../daemon/src/lib/agent-cancel.ts
5841
- var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("bazilion.agent-cancel.registry");
5842
- var AgentTurnActiveError = class extends DomainError {
5843
- agentId;
5844
- constructor(agentId) {
5845
- super(409, "The Agent is busy with another turn.", "agent_turn_active");
5846
- this.agentId = agentId;
6210
+ // ../daemon/src/lib/activity.ts
6211
+ import { statSync as statSync3 } from "node:fs";
6212
+ import { join as join10 } from "node:path";
6213
+
6214
+ // ../daemon/src/core/repos/conversations.ts
6215
+ var columns = "id, agent_id AS agentId, title, created_at AS createdAt, updated_at AS updatedAt";
6216
+ var ConversationChangedError = class extends DomainError {
6217
+ constructor() {
6218
+ super(409, "The Agent switched to another conversation. Reload before trying again.");
5847
6219
  }
5848
6220
  };
5849
- function registry() {
5850
- const g = globalThis;
5851
- let r = g[REGISTRY_KEY];
5852
- if (!r) {
5853
- r = { active: /* @__PURE__ */ new Map(), idleWaiters: /* @__PURE__ */ new Map() };
5854
- g[REGISTRY_KEY] = r;
5855
- }
5856
- return r;
6221
+ function selectedId(db, agentId) {
6222
+ return db.raw.query(
6223
+ "SELECT conversation_id AS id FROM agent_conversation_selection WHERE agent_id = ?"
6224
+ ).get(agentId)?.id ?? null;
5857
6225
  }
5858
- var SHUTTING_DOWN = "daemon_shutting_down";
5859
- function registerAgent(agentId, controller) {
5860
- if (registry().stopping) throw new Error(SHUTTING_DOWN);
5861
- if (registry().active.has(agentId)) {
5862
- throw new AgentTurnActiveError(agentId);
5863
- }
5864
- registry().active.set(agentId, controller);
6226
+ function get16(db, agentId, id) {
6227
+ return db.raw.query(
6228
+ `SELECT ${columns} FROM agent_conversations WHERE agent_id = ? AND id = ?`
6229
+ ).get(agentId, id);
5865
6230
  }
5866
- function unregisterAgent(agentId) {
5867
- const state2 = registry();
5868
- if (!state2.active.delete(agentId)) return;
5869
- const waiters = state2.idleWaiters.get(agentId);
6231
+ function list11(db, agentId, limit = 20, offset = 0) {
6232
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
6233
+ throw new DomainError(400, "Invalid conversation pagination");
6234
+ const conversations = db.raw.query(
6235
+ `SELECT ${columns} FROM agent_conversations WHERE agent_id = ? ORDER BY created_at DESC, id LIMIT ? OFFSET ?`
6236
+ ).all(agentId, limit, offset);
6237
+ const total = db.raw.query(
6238
+ "SELECT COUNT(*) AS n FROM agent_conversations WHERE agent_id = ?"
6239
+ ).get(agentId)?.n ?? 0;
6240
+ return { conversations, selectedId: selectedId(db, agentId), total, offset, limit };
6241
+ }
6242
+ function validTitle(value) {
6243
+ if (typeof value !== "string" || !value.trim() || value.length > 200 || Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
6244
+ throw new DomainError(
6245
+ 400,
6246
+ "Conversation title must be 1\u2013200 characters without control characters"
6247
+ );
6248
+ return value.trim();
6249
+ }
6250
+ function create5(db, agentId, id, title) {
6251
+ const displayTitle = title === void 0 ? void 0 : validTitle(title);
6252
+ return db.raw.transaction(() => {
6253
+ const now = Date.now();
6254
+ db.raw.run(
6255
+ `INSERT INTO agent_conversations (id, agent_id, title, created_at, updated_at)
6256
+ VALUES (?, ?, ?, ?, ?)`,
6257
+ [id, agentId, displayTitle ?? `Conversation ${list11(db, agentId, 1).total + 1}`, now, now]
6258
+ );
6259
+ db.raw.run(
6260
+ `INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
6261
+ ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
6262
+ [agentId, id]
6263
+ );
6264
+ const conversation = get16(db, agentId, id);
6265
+ if (!conversation) throw new Error("Conversation not found");
6266
+ return conversation;
6267
+ })();
6268
+ }
6269
+ function select(db, agentId, id) {
6270
+ const conversation = get16(db, agentId, id);
6271
+ if (!conversation) throw new DomainError(404, "Conversation not found");
6272
+ db.raw.run(
6273
+ `INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
6274
+ ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
6275
+ [agentId, id]
6276
+ );
6277
+ return conversation;
6278
+ }
6279
+ function hasDefaultTitle(conversation) {
6280
+ return /^Conversation \d+$/.test(conversation.title);
6281
+ }
6282
+ function rename(db, agentId, id, title) {
6283
+ db.raw.run(
6284
+ "UPDATE agent_conversations SET title = ?, updated_at = ? WHERE agent_id = ? AND id = ?",
6285
+ [validTitle(title), Date.now(), agentId, id]
6286
+ );
6287
+ const conversation = get16(db, agentId, id);
6288
+ if (!conversation) throw new DomainError(404, "Conversation not found");
6289
+ return conversation;
6290
+ }
6291
+
6292
+ // ../daemon/src/core/repos/results.ts
6293
+ import { createHash as createHash3, randomUUID as randomUUID13 } from "node:crypto";
6294
+
6295
+ // ../daemon/src/core/tool-call-id.ts
6296
+ function isToolCallId(value) {
6297
+ return typeof value === "string" && value.length <= 256 && // A true end assertion also rejects a trailing newline (unlike JavaScript '$').
6298
+ /^[A-Za-z0-9._:-]+(?:\|[A-Za-z0-9._:-]+)?$(?![\s\S])/.test(value);
6299
+ }
6300
+
6301
+ // ../daemon/src/core/repos/results.ts
6302
+ var MAX_RESULT_BYTES = 25 * 1024 * 1024;
6303
+ var MAX_RETAINED_RESULT_BYTES = 1024 * 1024 * 1024;
6304
+ var columns2 = `id, team_id AS teamId, agent_id AS agentId, session_id AS sessionId,
6305
+ tool_call_id AS toolCallId, source_index AS sourceIndex, name, mime_type AS mimeType,
6306
+ byte_length AS byteLength, sha256, image_model AS imageModel, created_at AS createdAt`;
6307
+ function get17(db, id) {
6308
+ return db.raw.query(`SELECT ${columns2} FROM agent_results WHERE id = ?`).get(id);
6309
+ }
6310
+ function publish(db, input) {
6311
+ if (!isToolCallId(input.toolCallId)) throw new Error("Invalid result tool call");
6312
+ 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 === "..")
6313
+ throw new Error("Invalid result filename");
6314
+ if (typeof input.mimeType !== "string" || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(input.mimeType))
6315
+ throw new Error("Invalid result media type");
6316
+ if (input.bytes.byteLength > MAX_RESULT_BYTES)
6317
+ throw new Error("Result exceeds the 25 MiB per-file limit");
6318
+ const bytes = Buffer.from(input.bytes);
6319
+ const sourceIndex = input.sourceIndex ?? 0;
6320
+ return db.raw.transaction(() => {
6321
+ const existing = db.raw.query(
6322
+ `SELECT id FROM agent_results
6323
+ WHERE agent_id = ? AND session_id = ? AND tool_call_id = ? AND source_index = ?`
6324
+ ).get(input.agentId, input.sessionId, input.toolCallId, sourceIndex);
6325
+ if (existing) return get17(db, existing.id);
6326
+ const retained = db.raw.query(
6327
+ "SELECT coalesce(sum(byte_length), 0) AS bytes FROM agent_results"
6328
+ ).get()?.bytes ?? 0;
6329
+ if (retained + bytes.byteLength > MAX_RETAINED_RESULT_BYTES)
6330
+ throw new Error(
6331
+ "Result storage is full (1 GiB). Delete saved results before delivering more files."
6332
+ );
6333
+ const id = randomUUID13();
6334
+ db.raw.run(
6335
+ `INSERT INTO agent_results
6336
+ (id, team_id, agent_id, session_id, tool_call_id, source_index, name, mime_type,
6337
+ byte_length, sha256, image_model, created_at, bytes)
6338
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
6339
+ [
6340
+ id,
6341
+ input.teamId,
6342
+ input.agentId,
6343
+ input.sessionId,
6344
+ input.toolCallId,
6345
+ sourceIndex,
6346
+ input.name,
6347
+ input.mimeType,
6348
+ bytes.byteLength,
6349
+ createHash3("sha256").update(bytes).digest("hex"),
6350
+ input.imageModel ?? null,
6351
+ Date.now(),
6352
+ bytes
6353
+ ]
6354
+ );
6355
+ return get17(db, id);
6356
+ })();
6357
+ }
6358
+ function whereClause(filter) {
6359
+ const where = [];
6360
+ const params = [];
6361
+ for (const [column, value] of [
6362
+ ["team_id", filter.teamId],
6363
+ ["agent_id", filter.agentId],
6364
+ ["session_id", filter.sessionId]
6365
+ ]) {
6366
+ if (value === void 0) continue;
6367
+ where.push(`${column} = ?`);
6368
+ params.push(value);
6369
+ }
6370
+ return { sql: where.length ? `WHERE ${where.join(" AND ")}` : "", params };
6371
+ }
6372
+ function list12(db, opts = {}) {
6373
+ const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 50)));
6374
+ const offset = Math.max(0, Math.floor(opts.offset ?? 0));
6375
+ const { sql: filter, params } = whereClause(opts);
6376
+ const total = db.raw.query(`SELECT count(*) AS total FROM agent_results ${filter}`).get(...params)?.total ?? 0;
6377
+ const results = db.raw.query(
6378
+ `SELECT ${columns2} FROM agent_results ${filter} ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`
6379
+ ).all(...params, limit, offset);
6380
+ return { results, total, limit, offset };
6381
+ }
6382
+ function read(db, id) {
6383
+ const row = db.raw.query(
6384
+ "SELECT bytes, sha256 FROM agent_results WHERE id = ?"
6385
+ ).get(id);
6386
+ if (!row) throw new Error("Result not found");
6387
+ const bytes = Buffer.from(row.bytes);
6388
+ if (createHash3("sha256").update(bytes).digest("hex") !== row.sha256)
6389
+ throw new Error("Saved file failed its integrity check");
6390
+ return bytes;
6391
+ }
6392
+ function summaryByAgent(db) {
6393
+ const rows = db.raw.query(
6394
+ `SELECT agent_id AS agentId, count(*) AS count, max(created_at) AS lastAt
6395
+ FROM agent_results GROUP BY agent_id`
6396
+ ).all();
6397
+ return new Map(rows.map((row) => [row.agentId, { count: row.count, lastAt: row.lastAt }]));
6398
+ }
6399
+ function listForArchive(db, filter, maxBytes) {
6400
+ const { sql, params } = whereClause(filter);
6401
+ const all = db.raw.query(
6402
+ // Oldest first; files saved in the same millisecond keep the order they were saved in.
6403
+ `SELECT ${columns2} FROM agent_results ${sql} ORDER BY created_at, rowid`
6404
+ ).all(...params);
6405
+ const results = [];
6406
+ let bytes = 0;
6407
+ for (const result of all) {
6408
+ if (bytes + result.byteLength > maxBytes) return { results, truncated: true };
6409
+ bytes += result.byteLength;
6410
+ results.push(result);
6411
+ }
6412
+ return { results, truncated: false };
6413
+ }
6414
+ function remove10(db, id) {
6415
+ return db.raw.run("DELETE FROM agent_results WHERE id = ?", [id]).changes === 1;
6416
+ }
6417
+
6418
+ // ../daemon/src/lib/agent-cancel.ts
6419
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("bazilion.agent-cancel.registry");
6420
+ var AgentTurnActiveError = class extends DomainError {
6421
+ agentId;
6422
+ constructor(agentId) {
6423
+ super(409, "The Agent is busy with another turn.", "agent_turn_active");
6424
+ this.agentId = agentId;
6425
+ }
6426
+ };
6427
+ function registry() {
6428
+ const g = globalThis;
6429
+ let r = g[REGISTRY_KEY];
6430
+ if (!r) {
6431
+ r = { active: /* @__PURE__ */ new Map(), idleWaiters: /* @__PURE__ */ new Map() };
6432
+ g[REGISTRY_KEY] = r;
6433
+ }
6434
+ return r;
6435
+ }
6436
+ var SHUTTING_DOWN = "daemon_shutting_down";
6437
+ function registerAgent(agentId, controller) {
6438
+ if (registry().stopping) throw new Error(SHUTTING_DOWN);
6439
+ if (registry().active.has(agentId)) {
6440
+ throw new AgentTurnActiveError(agentId);
6441
+ }
6442
+ registry().active.set(agentId, controller);
6443
+ }
6444
+ function unregisterAgent(agentId) {
6445
+ const state2 = registry();
6446
+ if (!state2.active.delete(agentId)) return;
6447
+ const waiters = state2.idleWaiters.get(agentId);
5870
6448
  state2.idleWaiters.delete(agentId);
5871
- for (const resolve8 of waiters ?? []) resolve8();
6449
+ for (const resolve9 of waiters ?? []) resolve9();
5872
6450
  }
5873
6451
  function cancelAgent(agentId) {
5874
6452
  const { active } = registry();
@@ -5896,9 +6474,9 @@ function stopAgentTurns() {
5896
6474
  function waitForAgentIdle(agentId) {
5897
6475
  const state2 = registry();
5898
6476
  if (!state2.active.has(agentId)) return Promise.resolve();
5899
- return new Promise((resolve8) => {
6477
+ return new Promise((resolve9) => {
5900
6478
  const waiters = state2.idleWaiters.get(agentId) ?? /* @__PURE__ */ new Set();
5901
- waiters.add(resolve8);
6479
+ waiters.add(resolve9);
5902
6480
  state2.idleWaiters.set(agentId, waiters);
5903
6481
  });
5904
6482
  }
@@ -5917,32 +6495,252 @@ function isShuttingDownError(error) {
5917
6495
  return error instanceof Error && error.message === SHUTTING_DOWN;
5918
6496
  }
5919
6497
 
5920
- // ../daemon/src/lib/browser/config.ts
5921
- var FALSEY = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
5922
- function envBool(value, fallback) {
5923
- if (value === void 0 || value.trim() === "") return fallback;
5924
- return !FALSEY.has(value.trim().toLowerCase());
6498
+ // ../daemon/src/lib/bash-approval.ts
6499
+ var DEFAULT_TIMEOUT_MS = 12e4;
6500
+ var CommandApprovalRegistry = class {
6501
+ #pending = /* @__PURE__ */ new Map();
6502
+ #timeoutMs;
6503
+ constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
6504
+ this.#timeoutMs = timeoutMs;
6505
+ }
6506
+ begin(input, signal) {
6507
+ const approval = {
6508
+ id: input.id,
6509
+ turnId: input.turnId,
6510
+ toolCallId: input.toolCallId,
6511
+ agentId: input.agentId,
6512
+ teamId: input.teamId,
6513
+ command: input.command,
6514
+ risks: input.risks,
6515
+ status: "pending",
6516
+ expiresAt: Date.now() + this.#timeoutMs
6517
+ };
6518
+ const immediate = input.mode === "auto_deny" ? "auto_denied" : signal?.aborted ? "cancelled" : void 0;
6519
+ if (immediate) {
6520
+ const settled2 = logged({ ...approval, status: immediate });
6521
+ return { approval: settled2, settled: Promise.resolve(settled2) };
6522
+ }
6523
+ if (this.#pending.has(approval.id))
6524
+ throw new Error(`duplicate shell approval id: ${approval.id}`);
6525
+ const settled = new Promise((resolve9) => {
6526
+ const settle = (status2) => {
6527
+ this.#pending.delete(approval.id);
6528
+ clearTimeout(timer);
6529
+ signal?.removeEventListener("abort", onAbort);
6530
+ const result = logged({ ...approval, status: status2 });
6531
+ resolve9(result);
6532
+ return result;
6533
+ };
6534
+ const onAbort = () => settle("cancelled");
6535
+ const timer = setTimeout(() => settle("expired"), this.#timeoutMs);
6536
+ timer.unref();
6537
+ signal?.addEventListener("abort", onAbort, { once: true });
6538
+ this.#pending.set(approval.id, { approval, settle });
6539
+ });
6540
+ return { approval, settled };
6541
+ }
6542
+ list(agentId) {
6543
+ 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));
6544
+ }
6545
+ /** Answer a pending approval; undefined when there is none (unknown, or already settled). */
6546
+ respond(id, decision) {
6547
+ return this.#pending.get(id)?.settle(decision === "allow" ? "allowed" : "denied");
6548
+ }
6549
+ };
6550
+ function logged(approval) {
6551
+ console.info("bash approval decision", {
6552
+ approvalId: approval.id,
6553
+ agentId: approval.agentId,
6554
+ teamId: approval.teamId,
6555
+ riskCodes: [...new Set(approval.risks.map((risk) => risk.code))],
6556
+ status: approval.status
6557
+ });
6558
+ return approval;
5925
6559
  }
5926
- function envInt(value, fallback) {
5927
- const n = Number.parseInt(value ?? "", 10);
5928
- return Number.isFinite(n) && n > 0 ? n : fallback;
6560
+ var commandApprovalRegistry = new CommandApprovalRegistry();
6561
+
6562
+ // ../daemon/src/lib/questions.ts
6563
+ import { randomUUID as randomUUID14 } from "node:crypto";
6564
+ var QUESTION_WAIT_MS = 5 * 6e4;
6565
+ var QUESTION_LIMITS = Object.freeze({
6566
+ promptChars: 2e3,
6567
+ labelChars: 120,
6568
+ descriptionChars: 500,
6569
+ answerChars: 4096
6570
+ });
6571
+ function text(value, limit, what) {
6572
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${what} must be non-empty text`);
6573
+ if (value.length > limit) throw new Error(`${what} is longer than ${limit} characters`);
6574
+ return value;
5929
6575
  }
5930
- function isBrowserEnabled(env) {
5931
- return envBool(env.BROWSER_ENABLED, true);
6576
+ function parseQuestionInput(value) {
6577
+ const input = value ?? {};
6578
+ const prompt = text(input.prompt, QUESTION_LIMITS.promptChars, "The prompt");
6579
+ if (!Array.isArray(input.choices) || input.choices.length < 2 || input.choices.length > 4)
6580
+ throw new Error("ask_user needs 2 to 4 choices");
6581
+ const labels = /* @__PURE__ */ new Set();
6582
+ const choices = input.choices.map((raw, index) => {
6583
+ const choice = raw ?? {};
6584
+ const label = text(choice.label, QUESTION_LIMITS.labelChars, `Choice ${index + 1} label`);
6585
+ const key2 = label.normalize("NFKC").trim().toLowerCase();
6586
+ if (labels.has(key2)) throw new Error("Choice labels must be distinct");
6587
+ labels.add(key2);
6588
+ if (choice.description === void 0) return { label };
6589
+ const description = text(
6590
+ choice.description,
6591
+ QUESTION_LIMITS.descriptionChars,
6592
+ `Choice ${index + 1} description`
6593
+ );
6594
+ return { label, description };
6595
+ });
6596
+ const recommended = input.recommendedIndex;
6597
+ if (recommended === void 0) return { prompt, choices };
6598
+ if (typeof recommended !== "number" || !Number.isInteger(recommended))
6599
+ throw new Error("recommendedIndex must be a choice index");
6600
+ if (recommended < 0 || recommended >= choices.length)
6601
+ throw new Error("recommendedIndex must be a choice index");
6602
+ return { prompt, choices, recommendedIndex: recommended };
5932
6603
  }
5933
- function resolveBrowserConfig(env) {
5934
- const executablePath = env.BROWSER_EXECUTABLE_PATH?.trim();
5935
- return {
5936
- headless: envBool(env.BROWSER_HEADLESS, true),
5937
- ...executablePath ? { executablePath } : {},
5938
- allowPrivate: envBool(env.BROWSER_ALLOW_PRIVATE_NETWORK, false),
5939
- idleMs: envInt(env.BROWSER_IDLE_MS, 9e5),
5940
- maxSessions: envInt(env.BROWSER_MAX_SESSIONS, 4)
5941
- };
6604
+ function parseQuestionAnswer(value, question) {
6605
+ const answer = value ?? {};
6606
+ if (answer.kind === "skip") return { kind: "skip" };
6607
+ if (answer.kind === "text")
6608
+ return { kind: "text", text: text(answer.text, QUESTION_LIMITS.answerChars, "The answer") };
6609
+ const index = answer.index;
6610
+ if (answer.kind === "choice" && typeof index === "number" && Number.isInteger(index)) {
6611
+ if (index >= 0 && index < question.choices.length) return { kind: "choice", index };
6612
+ throw new Error(
6613
+ `Choice ${index + 1} does not exist; this question has ${question.choices.length} choices`
6614
+ );
6615
+ }
6616
+ throw new Error("An answer is a choice index, text or skip");
5942
6617
  }
6618
+ var QuestionRegistry = class {
6619
+ #pending = /* @__PURE__ */ new Map();
6620
+ #waitMs;
6621
+ constructor(waitMs = QUESTION_WAIT_MS) {
6622
+ this.#waitMs = waitMs;
6623
+ }
6624
+ /** Register a question. `result` settles on the first answer, the timeout or `signal`. */
6625
+ ask(context, input, signal) {
6626
+ const prompt = parseQuestionInput(input);
6627
+ if (this.list(context.agentId).length > 0)
6628
+ throw new Error("Another question from this Agent is still waiting for an answer");
6629
+ if (signal?.aborted) throw new Error("The turn has ended");
6630
+ const now = Date.now();
6631
+ const question = {
6632
+ id: randomUUID14(),
6633
+ agentId: context.agentId,
6634
+ conversationId: context.conversationId,
6635
+ question: prompt,
6636
+ createdAt: now,
6637
+ expiresAt: now + this.#waitMs
6638
+ };
6639
+ const { promise, resolve: resolve9 } = Promise.withResolvers();
6640
+ const cancel3 = () => finish3({ kind: "no_answer", reason: "cancelled" });
6641
+ const timer = setTimeout(() => finish3({ kind: "no_answer", reason: "expired" }), this.#waitMs);
6642
+ timer.unref();
6643
+ const finish3 = (outcome) => {
6644
+ if (!this.#pending.delete(question.id)) return false;
6645
+ clearTimeout(timer);
6646
+ signal?.removeEventListener("abort", cancel3);
6647
+ resolve9({ questionId: question.id, question: prompt, ...outcome });
6648
+ return true;
6649
+ };
6650
+ this.#pending.set(question.id, { question, result: promise, finish: finish3 });
6651
+ signal?.addEventListener("abort", cancel3, { once: true });
6652
+ return { question, result: promise };
6653
+ }
6654
+ list(agentId) {
6655
+ return [...this.#pending.values()].map((entry) => entry.question).filter((question) => agentId === void 0 || question.agentId === agentId);
6656
+ }
6657
+ get(id) {
6658
+ return this.#pending.get(id)?.question;
6659
+ }
6660
+ /** The outcome of a waiting question; undefined once it has settled. */
6661
+ settled(id) {
6662
+ return this.#pending.get(id)?.result;
6663
+ }
6664
+ /** Answer a waiting question. False when it is no longer waiting; throws on an invalid answer. */
6665
+ answer(agentId, id, value) {
6666
+ const entry = this.#pending.get(id);
6667
+ if (!entry || entry.question.agentId !== agentId) return false;
6668
+ const answer = parseQuestionAnswer(value, entry.question.question);
6669
+ return entry.finish(
6670
+ answer.kind === "skip" ? { kind: "no_answer", reason: "skipped" } : { kind: "answer", answer }
6671
+ );
6672
+ }
6673
+ };
6674
+ var questionRegistry = new QuestionRegistry();
5943
6675
 
5944
- // ../daemon/src/routes/agent-browser.ts
5945
- init_pool2();
6676
+ // ../daemon/src/lib/activity.ts
6677
+ var TARGET_CHARS = 160;
6678
+ var TARGET_KEYS = ["path", "command", "url", "query", "to", "key", "file"];
6679
+ var STEPS_KEY = /* @__PURE__ */ Symbol.for("bazilion.activity.steps");
6680
+ function steps() {
6681
+ const holder = globalThis;
6682
+ let map = holder[STEPS_KEY];
6683
+ if (!map) {
6684
+ map = /* @__PURE__ */ new Map();
6685
+ holder[STEPS_KEY] = map;
6686
+ }
6687
+ return map;
6688
+ }
6689
+ function stepTarget(rawArguments) {
6690
+ let args;
6691
+ try {
6692
+ args = JSON.parse(rawArguments);
6693
+ } catch {
6694
+ return null;
6695
+ }
6696
+ if (!args || typeof args !== "object") return null;
6697
+ for (const key2 of TARGET_KEYS) {
6698
+ const value = args[key2];
6699
+ if (typeof value === "string" && value.trim()) {
6700
+ const line = value.trim().split("\n")[0] ?? "";
6701
+ return line.length > TARGET_CHARS ? `${line.slice(0, TARGET_CHARS - 1)}\u2026` : line;
6702
+ }
6703
+ }
6704
+ return null;
6705
+ }
6706
+ function noteTurnFrame(agentId, frame) {
6707
+ if (frame.kind !== "event" || frame.event.type !== "tool_call") return;
6708
+ steps().set(agentId, { tool: frame.event.name, target: stepTarget(frame.event.arguments) });
6709
+ }
6710
+ function noteTurnEnd(agentId) {
6711
+ steps().delete(agentId);
6712
+ }
6713
+ function lastActivityAt(db, paths, agentId) {
6714
+ const conversationId = selectedId(db, agentId);
6715
+ if (!conversationId) return null;
6716
+ try {
6717
+ const file = join10(paths.agentDir(agentId), "sessions", `${conversationId}.jsonl`);
6718
+ return Math.floor(statSync3(file).mtimeMs);
6719
+ } catch {
6720
+ return null;
6721
+ }
6722
+ }
6723
+ function readActivity(db, paths) {
6724
+ const saved = summaryByAgent(db);
6725
+ const questions = questionRegistry.list();
6726
+ const approvals = commandApprovalRegistry.list();
6727
+ return list(db).map((agent) => {
6728
+ const working = isActiveAgent(agent.id);
6729
+ const produced = saved.get(agent.id);
6730
+ return {
6731
+ agentId: agent.id,
6732
+ teamId: agent.teamId,
6733
+ working,
6734
+ step: working ? steps().get(agent.id) ?? null : null,
6735
+ questions: questions.filter((question) => question.agentId === agent.id).length,
6736
+ approvals: approvals.filter((approval) => approval.agentId === agent.id).length,
6737
+ queuePaused: isPaused(db, agent.id) && pendingCount(db, agent.id) > 0,
6738
+ lastActivityAt: lastActivityAt(db, paths, agent.id),
6739
+ results: produced?.count ?? 0,
6740
+ lastResultAt: produced?.lastAt ?? null
6741
+ };
6742
+ });
6743
+ }
5946
6744
 
5947
6745
  // ../daemon/src/routes/http.ts
5948
6746
  import { Hono } from "hono";
@@ -5985,7 +6783,42 @@ async function jsonBody(c) {
5985
6783
  return body !== null && typeof body === "object" && !Array.isArray(body) ? body : null;
5986
6784
  }
5987
6785
 
6786
+ // ../daemon/src/routes/activity.ts
6787
+ var activityRouter = newRouter();
6788
+ activityRouter.get("/", (c) => {
6789
+ const { db, paths } = getCtx();
6790
+ return c.json({ agents: readActivity(db, paths) });
6791
+ });
6792
+
6793
+ // ../daemon/src/lib/browser/config.ts
6794
+ var FALSEY = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
6795
+ function envBool(value, fallback) {
6796
+ if (value === void 0 || value.trim() === "") return fallback;
6797
+ return !FALSEY.has(value.trim().toLowerCase());
6798
+ }
6799
+ function envInt(value, fallback) {
6800
+ const n = Number.parseInt(value ?? "", 10);
6801
+ return Number.isFinite(n) && n > 0 ? n : fallback;
6802
+ }
6803
+ function isBrowserEnabled(env) {
6804
+ return envBool(env.BROWSER_ENABLED, true);
6805
+ }
6806
+ function resolveBrowserConfig(env) {
6807
+ const executablePath = env.BROWSER_EXECUTABLE_PATH?.trim();
6808
+ const attachUrl = env.BROWSER_ATTACH_URL?.trim();
6809
+ return {
6810
+ headless: envBool(env.BROWSER_HEADLESS, true),
6811
+ ...executablePath ? { executablePath } : {},
6812
+ allowPrivate: envBool(env.BROWSER_ALLOW_PRIVATE_NETWORK, false),
6813
+ attach: envBool(env.BROWSER_ATTACH, false),
6814
+ ...attachUrl ? { attachUrl } : {},
6815
+ idleMs: envInt(env.BROWSER_IDLE_MS, 9e5),
6816
+ maxSessions: envInt(env.BROWSER_MAX_SESSIONS, 4)
6817
+ };
6818
+ }
6819
+
5988
6820
  // ../daemon/src/routes/agent-browser.ts
6821
+ init_pool2();
5989
6822
  var agentBrowserRouter = newRouter();
5990
6823
  agentBrowserRouter.get("/:id/browser", (c) => {
5991
6824
  const { db, paths, authToken } = getCtx();
@@ -6006,73 +6839,8 @@ agentBrowserRouter.delete("/:id/browser/profile", async (c) => {
6006
6839
 
6007
6840
  // ../daemon/src/routes/agent-chat.ts
6008
6841
  import { randomUUID as randomUUID19 } from "node:crypto";
6009
- import { existsSync as existsSync16, readFileSync as readFileSync9 } from "node:fs";
6010
- import { join as join24 } from "node:path";
6011
-
6012
- // ../daemon/src/core/repos/conversations.ts
6013
- var columns = "id, agent_id AS agentId, title, created_at AS createdAt, updated_at AS updatedAt";
6014
- var ConversationChangedError = class extends DomainError {
6015
- constructor() {
6016
- super(409, "The Agent switched to another conversation. Reload before trying again.");
6017
- }
6018
- };
6019
- function selectedId(db, agentId) {
6020
- return db.raw.query(
6021
- "SELECT conversation_id AS id FROM agent_conversation_selection WHERE agent_id = ?"
6022
- ).get(agentId)?.id ?? null;
6023
- }
6024
- function get16(db, agentId, id) {
6025
- return db.raw.query(
6026
- `SELECT ${columns} FROM agent_conversations WHERE agent_id = ? AND id = ?`
6027
- ).get(agentId, id);
6028
- }
6029
- function list11(db, agentId, limit = 20, offset = 0) {
6030
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100 || !Number.isSafeInteger(offset) || offset < 0)
6031
- throw new DomainError(400, "Invalid conversation pagination");
6032
- const conversations = db.raw.query(
6033
- `SELECT ${columns} FROM agent_conversations WHERE agent_id = ? ORDER BY created_at DESC, id LIMIT ? OFFSET ?`
6034
- ).all(agentId, limit, offset);
6035
- const total = db.raw.query(
6036
- "SELECT COUNT(*) AS n FROM agent_conversations WHERE agent_id = ?"
6037
- ).get(agentId)?.n ?? 0;
6038
- return { conversations, selectedId: selectedId(db, agentId), total, offset, limit };
6039
- }
6040
- function validTitle(value) {
6041
- if (typeof value !== "string" || !value.trim() || value.length > 200 || Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127))
6042
- throw new DomainError(
6043
- 400,
6044
- "Conversation title must be 1\u2013200 characters without control characters"
6045
- );
6046
- return value.trim();
6047
- }
6048
- function create5(db, agentId, id, title) {
6049
- const displayTitle = title === void 0 ? void 0 : validTitle(title);
6050
- return db.raw.transaction(() => {
6051
- const now = Date.now();
6052
- db.raw.run(
6053
- `INSERT INTO agent_conversations (id, agent_id, title, created_at, updated_at)
6054
- VALUES (?, ?, ?, ?, ?)`,
6055
- [id, agentId, displayTitle ?? `Conversation ${list11(db, agentId, 1).total + 1}`, now, now]
6056
- );
6057
- db.raw.run(
6058
- `INSERT INTO agent_conversation_selection (agent_id, conversation_id) VALUES (?, ?)
6059
- ON CONFLICT(agent_id) DO UPDATE SET conversation_id = excluded.conversation_id`,
6060
- [agentId, id]
6061
- );
6062
- const conversation = get16(db, agentId, id);
6063
- if (!conversation) throw new Error("Conversation not found");
6064
- return conversation;
6065
- })();
6066
- }
6067
- function rename(db, agentId, id, title) {
6068
- db.raw.run(
6069
- "UPDATE agent_conversations SET title = ?, updated_at = ? WHERE agent_id = ? AND id = ?",
6070
- [validTitle(title), Date.now(), agentId, id]
6071
- );
6072
- const conversation = get16(db, agentId, id);
6073
- if (!conversation) throw new DomainError(404, "Conversation not found");
6074
- return conversation;
6075
- }
6842
+ import { existsSync as existsSync16, readFileSync as readFileSync10 } from "node:fs";
6843
+ import { join as join27 } from "node:path";
6076
6844
 
6077
6845
  // ../daemon/src/runtime/auth/openai-codex.ts
6078
6846
  import { openaiCodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
@@ -6199,12 +6967,12 @@ import {
6199
6967
  mkdirSync as mkdirSync6,
6200
6968
  openSync,
6201
6969
  readdirSync as readdirSync4,
6202
- readFileSync as readFileSync7,
6970
+ readFileSync as readFileSync8,
6203
6971
  realpathSync as realpathSync2,
6204
6972
  rmSync as rmSync9,
6205
6973
  writeFileSync as writeFileSync5
6206
6974
  } from "node:fs";
6207
- import { dirname as dirname3, isAbsolute as isAbsolute2, join as join12, relative, resolve as resolve4, sep as sep2 } from "node:path";
6975
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join15, relative, resolve as resolve4, sep as sep2 } from "node:path";
6208
6976
  import { createStore, extractSnippet } from "@tobilu/qmd";
6209
6977
 
6210
6978
  // ../daemon/src/lib/native-module-error.ts
@@ -6250,7 +7018,7 @@ function getStore(dir, storeFactory) {
6250
7018
  if (!p) {
6251
7019
  p = withNativeModuleErrorBoundary(
6252
7020
  () => storeFactory({
6253
- dbPath: join12(dir, INDEX_FILENAME),
7021
+ dbPath: join15(dir, INDEX_FILENAME),
6254
7022
  config: {
6255
7023
  collections: {
6256
7024
  [COLLECTION_NAME]: { path: dir, pattern: PATTERN }
@@ -6328,7 +7096,7 @@ function inspectSafePath(root, path) {
6328
7096
  let current2 = root;
6329
7097
  const components = rel.split(sep2).filter(Boolean);
6330
7098
  for (let index = 0; index < components.length; index += 1) {
6331
- current2 = join12(current2, components[index]);
7099
+ current2 = join15(current2, components[index]);
6332
7100
  const info = lstatIfPresent(current2);
6333
7101
  if (!info) return void 0;
6334
7102
  if (info.isSymbolicLink()) {
@@ -6342,12 +7110,12 @@ function inspectSafePath(root, path) {
6342
7110
  return lstatIfPresent(path);
6343
7111
  }
6344
7112
  function ensureSafeParentDirectories(root, path) {
6345
- const parent = dirname3(path);
7113
+ const parent = dirname4(path);
6346
7114
  assertContained(root, parent);
6347
7115
  const rel = relative(root, parent);
6348
7116
  let current2 = root;
6349
7117
  for (const component2 of rel.split(sep2).filter(Boolean)) {
6350
- current2 = join12(current2, component2);
7118
+ current2 = join15(current2, component2);
6351
7119
  let info = lstatIfPresent(current2);
6352
7120
  if (!info) {
6353
7121
  mkdirSync6(current2);
@@ -6371,7 +7139,7 @@ function readSafeFile(root, path) {
6371
7139
  fd = openSync(path, constants2.O_RDONLY | constants2.O_NOFOLLOW);
6372
7140
  const stats = fstatSync(fd);
6373
7141
  if (!stats.isFile()) throw unsafeMemoryPath(path, "memory entry is not a regular file");
6374
- return { content: readFileSync7(fd, "utf8"), stats };
7142
+ return { content: readFileSync8(fd, "utf8"), stats };
6375
7143
  } catch (error) {
6376
7144
  if (error.code === "ELOOP") {
6377
7145
  throw unsafeMemoryPath(path, "symbolic links are not allowed");
@@ -6413,7 +7181,7 @@ function writeSafeFile(root, path, content) {
6413
7181
  function assertSafeTree(root, dir = root) {
6414
7182
  assertContained(root, realpathSync2(dir));
6415
7183
  for (const entry of readdirSync4(dir, { withFileTypes: true })) {
6416
- const full = join12(dir, entry.name);
7184
+ const full = join15(dir, entry.name);
6417
7185
  const info = lstatSync(full);
6418
7186
  if (info.isSymbolicLink()) {
6419
7187
  throw unsafeMemoryPath(full, "symbolic links are not allowed in memory storage");
@@ -6427,7 +7195,7 @@ function assertSafeTree(root, dir = root) {
6427
7195
  }
6428
7196
  function walkMd(root, dir, prefix, out) {
6429
7197
  for (const entry of readdirSync4(dir, { withFileTypes: true })) {
6430
- const full = join12(dir, entry.name);
7198
+ const full = join15(dir, entry.name);
6431
7199
  const info = lstatSync(full);
6432
7200
  if (info.isSymbolicLink()) {
6433
7201
  throw unsafeMemoryPath(full, "symbolic links are not allowed in memory storage");
@@ -6534,17 +7302,17 @@ function qmdBackend(root, options = {}) {
6534
7302
  // ../daemon/src/runtime/worker/runtime.ts
6535
7303
  import { mkdirSync as mkdirSync7, mkdtempSync as mkdtempSync2, rmSync as rmSync10 } from "node:fs";
6536
7304
  import { tmpdir as tmpdir2 } from "node:os";
6537
- import { join as join13 } from "node:path";
7305
+ import { join as join16 } from "node:path";
6538
7306
  var REDACTED_VALUE = "[REDACTED]";
6539
7307
  function createMinimalWorkerScratch(parentDir = tmpdir2()) {
6540
- const root = mkdtempSync2(join13(parentDir, "bazilion-worker-"));
7308
+ const root = mkdtempSync2(join16(parentDir, "bazilion-worker-"));
6541
7309
  const scratch = {
6542
7310
  root,
6543
- homeDir: join13(root, "home"),
6544
- tempDir: join13(root, "tmp"),
6545
- piAgentDir: join13(root, "pi"),
6546
- reviewCwd: join13(root, "review-work"),
6547
- reviewSessionDir: join13(root, "review-session")
7311
+ homeDir: join16(root, "home"),
7312
+ tempDir: join16(root, "tmp"),
7313
+ piAgentDir: join16(root, "pi"),
7314
+ reviewCwd: join16(root, "review-work"),
7315
+ reviewSessionDir: join16(root, "review-session")
6548
7316
  };
6549
7317
  try {
6550
7318
  for (const path of Object.values(scratch).slice(1)) {
@@ -6762,8 +7530,8 @@ function extractResultReferences(value) {
6762
7530
  }
6763
7531
 
6764
7532
  // ../daemon/src/runtime/pi/session.ts
6765
- import { existsSync as existsSync14, mkdirSync as mkdirSync10, statSync as statSync6, writeFileSync as writeFileSync7 } from "node:fs";
6766
- import { basename as basename5, join as join19 } from "node:path";
7533
+ import { existsSync as existsSync14, mkdirSync as mkdirSync10, statSync as statSync7, writeFileSync as writeFileSync7 } from "node:fs";
7534
+ import { basename as basename5, join as join22 } from "node:path";
6767
7535
  import {
6768
7536
  buildSessionContext,
6769
7537
  createAgentSession,
@@ -6867,7 +7635,7 @@ async function testProviderModel(spec) {
6867
7635
 
6868
7636
  // ../daemon/src/runtime/session/prompt.ts
6869
7637
  import { existsSync as existsSync11, readdirSync as readdirSync5 } from "node:fs";
6870
- import { join as join14 } from "node:path";
7638
+ import { join as join17 } from "node:path";
6871
7639
 
6872
7640
  // ../daemon/src/runtime/safe-files.ts
6873
7641
  import {
@@ -6877,13 +7645,13 @@ import {
6877
7645
  lstatSync as lstatSync2,
6878
7646
  mkdirSync as mkdirSync8,
6879
7647
  openSync as openSync2,
6880
- readFileSync as readFileSync8,
7648
+ readFileSync as readFileSync9,
6881
7649
  readlinkSync as readlinkSync2,
6882
7650
  readSync,
6883
7651
  realpathSync as realpathSync3,
6884
- statSync as statSync4
7652
+ statSync as statSync5
6885
7653
  } from "node:fs";
6886
- import { dirname as dirname4, isAbsolute as isAbsolute3, relative as relative2, resolve as resolve5, sep as sep3 } from "node:path";
7654
+ import { dirname as dirname5, isAbsolute as isAbsolute3, relative as relative2, resolve as resolve5, sep as sep3 } from "node:path";
6887
7655
  var ContainedFileError = class extends Error {
6888
7656
  reason;
6889
7657
  constructor(reason) {
@@ -6895,7 +7663,7 @@ var ContainedFileError = class extends Error {
6895
7663
  function readContainedFile(path, realRoot, maxBytes) {
6896
7664
  const real = realpathSync3(path);
6897
7665
  if (!isContained2(realRoot, real)) throw new ContainedFileError("outside");
6898
- const checked = statSync4(real);
7666
+ const checked = statSync5(real);
6899
7667
  if (!checked.isFile()) throw new ContainedFileError("not_file");
6900
7668
  if (checked.size > maxBytes) throw new ContainedFileError("too_large");
6901
7669
  const fd = openSync2(real, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK);
@@ -6951,7 +7719,7 @@ function ensureContainedRealDirectory(path, root, options = {}) {
6951
7719
  }
6952
7720
  } catch (error) {
6953
7721
  if (error.code !== "ENOENT" || !options.create) throw error;
6954
- const canonicalParent = realpathSync3(dirname4(requested));
7722
+ const canonicalParent = realpathSync3(dirname5(requested));
6955
7723
  if (!isContained2(canonicalRoot, canonicalParent)) throw new Error("directory escapes its root");
6956
7724
  mkdirSync8(requested, { recursive: true, mode: 448 });
6957
7725
  const entry = lstatSync2(requested);
@@ -6971,7 +7739,7 @@ function readRegularFileNoFollow(path) {
6971
7739
  try {
6972
7740
  fd = openSync2(path, constants3.O_RDONLY | noFollowFlag());
6973
7741
  if (!fstatSync2(fd).isFile()) throw new Error("target is not a regular file");
6974
- return readFileSync8(fd, "utf8");
7742
+ return readFileSync9(fd, "utf8");
6975
7743
  } finally {
6976
7744
  if (fd !== void 0) closeSync2(fd);
6977
7745
  }
@@ -6985,12 +7753,15 @@ function isContained2(root, candidate) {
6985
7753
  }
6986
7754
 
6987
7755
  // ../daemon/src/runtime/session/browser-guide.ts
6988
- function browserGuideSection() {
7756
+ function browserGuideSection(attached = false) {
6989
7757
  return [
6990
7758
  "# Browser",
6991
7759
  "",
6992
- "You have a browser of your own (`browser_*` tools). Its cookies and logins persist across turns.",
7760
+ attached ? "The `browser_*` tools work in the user's own running browser, signed in to their accounts. You see and drive only the tabs you open; their other tabs are not yours to see." : "You have a browser of your own (`browser_*` tools). Its cookies and logins persist across turns.",
6993
7761
  "",
7762
+ ...attached ? [
7763
+ "- On every site the user is signed in to, you act as them. Post, send, buy, delete or change settings only when the user asked for exactly that; otherwise ask first."
7764
+ ] : [],
6994
7765
  "- Read a page with `browser_snapshot`: an accessibility tree whose elements carry refs like `[ref=e5]`. Use `browser_take_screenshot` only when the visual layout matters.",
6995
7766
  "- Act with refs from the latest snapshot. Every action returns a fresh snapshot; take the next refs from it.",
6996
7767
  "- A link that opens a new tab does not switch to it: list the tabs with `browser_tabs` and select the new one.",
@@ -7010,9 +7781,9 @@ function loadPromptSkills(skillsDir, attachedNames) {
7010
7781
  const discovered = readdirSync5(skillsDir, { withFileTypes: true }).filter((entry) => entry.isDirectory() && attached.has(entry.name)).sort((a, b) => a.name.localeCompare(b.name));
7011
7782
  const loaded = [];
7012
7783
  for (const entry of discovered) {
7013
- const hostDir = join14(skillsDir, entry.name);
7784
+ const hostDir = join17(skillsDir, entry.name);
7014
7785
  try {
7015
- const parsed = parseSkillContent(readRegularFileNoFollow(join14(hostDir, "SKILL.md")));
7786
+ const parsed = parseSkillContent(readRegularFileNoFollow(join17(hostDir, "SKILL.md")));
7016
7787
  const safeLabel = entry.name.replace(/[^A-Za-z0-9._-]/g, "_") || "skill";
7017
7788
  loaded.push({
7018
7789
  name: entry.name,
@@ -7031,7 +7802,7 @@ function loadHomeDocuments(agentDir2) {
7031
7802
  const root = resolveRealDirectory(agentDir2);
7032
7803
  const read2 = (file) => {
7033
7804
  try {
7034
- return readRegularFileNoFollow(join14(root, file));
7805
+ return readRegularFileNoFollow(join17(root, file));
7035
7806
  } catch (error) {
7036
7807
  if (error.code === "ENOENT") return null;
7037
7808
  throw new Error(`private Agent home is unsafe at ${file}`);
@@ -7136,7 +7907,10 @@ ${contextBlocks.join("\n\n")}`
7136
7907
  });
7137
7908
  }
7138
7909
  if (options.browserGuide) {
7139
- parts.push({ id: "browser-guide", text: browserGuideSection() });
7910
+ parts.push({
7911
+ id: "browser-guide",
7912
+ text: browserGuideSection(options.browserGuide === "attached")
7913
+ });
7140
7914
  }
7141
7915
  const teamLines = [
7142
7916
  "# Team",
@@ -7197,8 +7971,8 @@ function boundReviewedLessons(lessons, maxCharacters = 8e3) {
7197
7971
  }
7198
7972
 
7199
7973
  // ../daemon/src/runtime/shell/docker.ts
7200
- import { spawn as spawn2 } from "node:child_process";
7201
- import { createHash as createHash3, randomUUID as randomUUID13 } from "node:crypto";
7974
+ import { spawn as spawn3 } from "node:child_process";
7975
+ import { createHash as createHash4, randomUUID as randomUUID15 } from "node:crypto";
7202
7976
  var CONTAINER_WORKSPACE = "/workspace";
7203
7977
  var DOCKER_CALL_TIMEOUT_MS = 5e3;
7204
7978
  var MAX_TIMER_MS = 2147483647;
@@ -7261,10 +8035,10 @@ function createDockerBashOperations(sandbox) {
7261
8035
  throw new Error("Invalid timeout: must be a positive number of seconds");
7262
8036
  if (signal?.aborted) throw new Error("aborted");
7263
8037
  const current2 = sandbox();
7264
- const name = `${current2.containerPrefix}${randomUUID13().replaceAll("-", "").slice(0, 12)}`;
8038
+ const name = `${current2.containerPrefix}${randomUUID15().replaceAll("-", "").slice(0, 12)}`;
7265
8039
  const args = dockerRunArgs(current2, name, command);
7266
- return new Promise((resolve8, reject2) => {
7267
- const child = spawn2("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
8040
+ return new Promise((resolve9, reject2) => {
8041
+ const child = spawn3("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
7268
8042
  let stopped;
7269
8043
  let settled = false;
7270
8044
  const stop = (reason) => {
@@ -7286,7 +8060,7 @@ function createDockerBashOperations(sandbox) {
7286
8060
  await removeContainers([name]);
7287
8061
  reject2(stopped);
7288
8062
  } else if (error) reject2(dockerError(error));
7289
- else resolve8({ exitCode });
8063
+ else resolve9({ exitCode });
7290
8064
  };
7291
8065
  child.stdout.on("data", onData);
7292
8066
  child.stderr.on("data", onData);
@@ -7305,10 +8079,10 @@ async function checkDockerImage(image) {
7305
8079
  }
7306
8080
  }
7307
8081
  function homeContainerPrefix(home) {
7308
- return `bazilion-${createHash3("sha256").update(home).digest("hex").slice(0, 12)}-`;
8082
+ return `bazilion-${createHash4("sha256").update(home).digest("hex").slice(0, 12)}-`;
7309
8083
  }
7310
8084
  function turnContainerPrefix(home) {
7311
- return `${homeContainerPrefix(home)}${randomUUID13().replaceAll("-", "").slice(0, 12)}-`;
8085
+ return `${homeContainerPrefix(home)}${randomUUID15().replaceAll("-", "").slice(0, 12)}-`;
7312
8086
  }
7313
8087
  async function removeDockerContainers(prefix) {
7314
8088
  try {
@@ -7332,8 +8106,8 @@ async function removeContainers(names) {
7332
8106
  });
7333
8107
  }
7334
8108
  function docker(args) {
7335
- return new Promise((resolve8, reject2) => {
7336
- const child = spawn2("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
8109
+ return new Promise((resolve9, reject2) => {
8110
+ const child = spawn3("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
7337
8111
  let stdout = "";
7338
8112
  let stderr = "";
7339
8113
  const timer = setTimeout(() => {
@@ -7352,7 +8126,7 @@ function docker(args) {
7352
8126
  });
7353
8127
  child.once("close", (code) => {
7354
8128
  clearTimeout(timer);
7355
- if (code === 0) resolve8(stdout.trim());
8129
+ if (code === 0) resolve9(stdout.trim());
7356
8130
  else reject2(new Error(stderr.trim() || `docker ${args[0]} exited with status ${code}`));
7357
8131
  });
7358
8132
  });
@@ -7362,8 +8136,8 @@ function dockerError(error) {
7362
8136
  }
7363
8137
 
7364
8138
  // ../daemon/src/runtime/shell/tooling.ts
7365
- import { existsSync as existsSync12, lstatSync as lstatSync3, mkdirSync as mkdirSync9, realpathSync as realpathSync4, statSync as statSync5 } from "node:fs";
7366
- import { dirname as dirname5, isAbsolute as isAbsolute4, join as join15, relative as relative3, sep as sep4 } from "node:path";
8139
+ import { existsSync as existsSync12, lstatSync as lstatSync3, mkdirSync as mkdirSync9, realpathSync as realpathSync4, statSync as statSync6 } from "node:fs";
8140
+ import { dirname as dirname6, isAbsolute as isAbsolute4, join as join18, relative as relative3, sep as sep4 } from "node:path";
7367
8141
  import {
7368
8142
  createBashToolDefinition,
7369
8143
  createLocalBashOperations,
@@ -7685,18 +8459,18 @@ function createSessionShellTools(cwd, env, options = {}) {
7685
8459
  };
7686
8460
  const sandbox = () => {
7687
8461
  const workspace = realpathSync4(cwd);
7688
- if (turn.cwd !== "." && !statSync5(join15(workspace, turn.cwd), { throwIfNoEntry: false })?.isDirectory())
8462
+ if (turn.cwd !== "." && !statSync6(join18(workspace, turn.cwd), { throwIfNoEntry: false })?.isDirectory())
7689
8463
  throw new Error(`Working directory does not exist: ${containerWorkdir(turn.cwd)}`);
7690
- mkdirSync9(join15(workspace, "memory"), { recursive: true });
8464
+ mkdirSync9(join18(workspace, "memory"), { recursive: true });
7691
8465
  return {
7692
8466
  image: turn.image,
7693
8467
  workspace,
7694
8468
  workdir: containerWorkdir(turn.cwd),
7695
8469
  readOnlyMounts: [
7696
- readOnlyMount(join15(workspace, "memory"), SANDBOX_MEMORY_DIR, workspace),
7697
- ...options.inputsDir && existsSync12(options.inputsDir) ? [readOnlyMount(options.inputsDir, SANDBOX_INPUTS_DIR, dirname5(options.inputsDir))] : [],
8470
+ readOnlyMount(join18(workspace, "memory"), SANDBOX_MEMORY_DIR, workspace),
8471
+ ...options.inputsDir && existsSync12(options.inputsDir) ? [readOnlyMount(options.inputsDir, SANDBOX_INPUTS_DIR, dirname6(options.inputsDir))] : [],
7698
8472
  ...(options.skillMounts ?? []).map(
7699
- (mount) => readOnlyMount(mount.source, mount.target, dirname5(mount.source))
8473
+ (mount) => readOnlyMount(mount.source, mount.target, dirname6(mount.source))
7700
8474
  )
7701
8475
  ],
7702
8476
  containerPrefix: turn.containerPrefix
@@ -7729,13 +8503,13 @@ function readOnlyMount(source, target, root) {
7729
8503
 
7730
8504
  // ../daemon/src/runtime/pi/session-file.ts
7731
8505
  import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSync3, openSync as openSync3, readSync as readSync2 } from "node:fs";
7732
- import { join as join16 } from "node:path";
8506
+ import { join as join19 } from "node:path";
7733
8507
  var MAX_SESSION_BYTES = 64 * 1024 * 1024;
7734
8508
  var MAX_HEADER_BYTES = 64 * 1024;
7735
8509
  function readStart(directory, id, limit) {
7736
8510
  if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error("Invalid conversation id");
7737
8511
  const fd = openSync3(
7738
- join16(directory, `${id}.jsonl`),
8512
+ join19(directory, `${id}.jsonl`),
7739
8513
  constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK
7740
8514
  );
7741
8515
  try {
@@ -7765,6 +8539,13 @@ function readSessionFile(directory, id) {
7765
8539
  checkHeader(entries[0], id);
7766
8540
  return entries;
7767
8541
  }
8542
+ function sessionHasEntries(directory, id) {
8543
+ const { bytes, size } = readStart(directory, id, MAX_HEADER_BYTES);
8544
+ if (size > bytes.length) return true;
8545
+ const text4 = bytes.toString("utf8");
8546
+ const end = text4.indexOf("\n");
8547
+ return end >= 0 && text4.slice(end + 1).trim().length > 0;
8548
+ }
7768
8549
  function readSessionHeader(directory, id) {
7769
8550
  const text4 = readStart(directory, id, MAX_HEADER_BYTES).bytes.toString("utf8");
7770
8551
  const end = text4.indexOf("\n");
@@ -7813,7 +8594,7 @@ function askUserTool(ask) {
7813
8594
 
7814
8595
  // ../daemon/src/runtime/tools/bootstrap.ts
7815
8596
  import { existsSync as existsSync13, rmSync as rmSync11 } from "node:fs";
7816
- import { join as join17 } from "node:path";
8597
+ import { join as join20 } from "node:path";
7817
8598
  function bootstrapTool(agentDir2) {
7818
8599
  return {
7819
8600
  def: {
@@ -7822,7 +8603,7 @@ function bootstrapTool(agentDir2) {
7822
8603
  parameters: { type: "object", properties: {} }
7823
8604
  },
7824
8605
  async invoke() {
7825
- const path = join17(agentDir2, "BOOTSTRAP.md");
8606
+ const path = join20(agentDir2, "BOOTSTRAP.md");
7826
8607
  if (existsSync13(path)) {
7827
8608
  rmSync11(path);
7828
8609
  return "BOOTSTRAP.md removed. Bootstrap is complete.";
@@ -7955,10 +8736,10 @@ function isWithin(root, candidate) {
7955
8736
  return rel === "" || rel !== ".." && !rel.startsWith(`..${sep5}`) && !isAbsolute5(rel);
7956
8737
  }
7957
8738
  function deliverFileTool(cwd, sink) {
7958
- const workspacePath = resolve6(cwd);
8739
+ const workspacePath2 = resolve6(cwd);
7959
8740
  let workspaceRealPath = null;
7960
8741
  try {
7961
- workspaceRealPath = realpathSync5(workspacePath);
8742
+ workspaceRealPath = realpathSync5(workspacePath2);
7962
8743
  } catch {
7963
8744
  }
7964
8745
  return {
@@ -7983,8 +8764,8 @@ function deliverFileTool(cwd, sink) {
7983
8764
  if (isAbsolute5(p)) {
7984
8765
  throw new Error(`deliver_file: path must stay within the workspace: ${p}`);
7985
8766
  }
7986
- const abs = resolve6(workspacePath, p);
7987
- if (!isWithin(workspacePath, abs)) {
8767
+ const abs = resolve6(workspacePath2, p);
8768
+ if (!isWithin(workspacePath2, abs)) {
7988
8769
  throw new Error(`deliver_file: path must stay within the workspace: ${p}`);
7989
8770
  }
7990
8771
  if (!workspaceRealPath) {
@@ -8022,7 +8803,7 @@ import {
8022
8803
  readdirSync as readdirSync6,
8023
8804
  writeFileSync as writeFileSync6
8024
8805
  } from "node:fs";
8025
- import { join as join18 } from "node:path";
8806
+ import { join as join21 } from "node:path";
8026
8807
  var HOME_FILES_READABLE = [
8027
8808
  "IDENTITY.md",
8028
8809
  "SOUL.md",
@@ -8143,7 +8924,7 @@ function resolvePrivateHomeRoot(agentDir2) {
8143
8924
  }
8144
8925
  }
8145
8926
  function privateHomeFile(homeRoot, file) {
8146
- return join18(homeRoot, file);
8927
+ return join21(homeRoot, file);
8147
8928
  }
8148
8929
  function rejectSymlinkOrNonFile(path) {
8149
8930
  const entry = lstatSync4(path);
@@ -8551,7 +9332,7 @@ var DEFAULT_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWe
8551
9332
  var DEFAULT_CACHE_TTL_MS = 15 * 6e4;
8552
9333
  var DEFAULT_CACHE_MAX = 100;
8553
9334
  var DEFAULT_MAX_LENGTH = 2e4;
8554
- var DEFAULT_TIMEOUT_MS = 3e4;
9335
+ var DEFAULT_TIMEOUT_MS2 = 3e4;
8555
9336
  var DEFAULT_MAX_BODY_BYTES = 3 * 1024 * 1024;
8556
9337
  var FIRECRAWL_FALLBACK_THRESHOLD = 200;
8557
9338
  var FIRECRAWL_DEFAULT_URL = "https://api.firecrawl.dev";
@@ -8708,7 +9489,7 @@ function webFetchTool(opts) {
8708
9489
  const allowPrivate = opts?.allowPrivate ?? false;
8709
9490
  const cacheTtlMs = opts?.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
8710
9491
  const cacheMax = opts?.cacheMax ?? DEFAULT_CACHE_MAX;
8711
- const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
9492
+ const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
8712
9493
  const maxBodyBytes = opts?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
8713
9494
  const cache = /* @__PURE__ */ new Map();
8714
9495
  return {
@@ -8926,7 +9707,7 @@ function turnSurface(opts) {
8926
9707
  const shellTools = createSessionShellTools(cwd, env, {
8927
9708
  docker: opts.docker,
8928
9709
  containerPrefix: homeContainerPrefix(paths.home),
8929
- inputsDir: join19(agent.agent.dir, "uploads"),
9710
+ inputsDir: join22(agent.agent.dir, "uploads"),
8930
9711
  skillMounts: promptSkills.map((skill) => ({ source: skill.hostDir, target: skill.sandboxDir })),
8931
9712
  approvalHost: opts.bashApprovalHost
8932
9713
  });
@@ -8949,7 +9730,7 @@ function turnSurface(opts) {
8949
9730
  skills: promptSkills,
8950
9731
  sandboxMode: shellTools.config.sandboxMode,
8951
9732
  // The guides ride along exactly when their tools are admitted.
8952
- ...opts.browserHost ? { browserGuide: true } : {},
9733
+ ...opts.browserHost ? { browserGuide: resolveBrowserConfig(env).attach ? "attached" : true } : {},
8953
9734
  ...opts.webSearchHost ? { searchGuide: true } : {}
8954
9735
  };
8955
9736
  return {
@@ -8967,7 +9748,7 @@ async function createBazilionSession(opts) {
8967
9748
  const { agent, paths } = opts;
8968
9749
  const { providerName, modelId } = parseModelString(agent.model);
8969
9750
  if (!existsSync14(agent.team.path)) mkdirSync10(agent.team.path, { recursive: true });
8970
- mkdirSync10(join19(paths.agentDir(agent.agent.id), "sessions"), { recursive: true });
9751
+ mkdirSync10(join22(paths.agentDir(agent.agent.id), "sessions"), { recursive: true });
8971
9752
  const sessionManager = openConversation(agent, paths, opts.conversation);
8972
9753
  const turn = turnSurface(opts);
8973
9754
  return openPiSession({
@@ -8979,7 +9760,7 @@ async function createBazilionSession(opts) {
8979
9760
  },
8980
9761
  reasoningLevel: agent.reasoningLevel,
8981
9762
  cwd: turn.modelCwd,
8982
- piAgentDir: join19(paths.home, "pi"),
9763
+ piAgentDir: join22(paths.home, "pi"),
8983
9764
  sessionManager,
8984
9765
  appendSystemPrompt: buildSystemPrompt(agent, turn.promptOptions),
8985
9766
  agentsFiles: (opts.repositoryInstructions ?? []).map((file) => ({
@@ -9037,7 +9818,7 @@ function toPiThinkingLevel(level) {
9037
9818
  }
9038
9819
  }
9039
9820
  function openConversation(agent, paths, target) {
9040
- const sessionDir = join19(paths.agentDir(agent.agent.id), "sessions");
9821
+ const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
9041
9822
  return SessionManager.open(
9042
9823
  explicitConversationFile(sessionDir, target),
9043
9824
  sessionDir,
@@ -9046,13 +9827,13 @@ function openConversation(agent, paths, target) {
9046
9827
  }
9047
9828
  function loadInitialMessages(agent, paths, target) {
9048
9829
  if (!target) return [];
9049
- const entries = readSessionFile(join19(paths.agentDir(agent.agent.id), "sessions"), target.id);
9830
+ const entries = readSessionFile(join22(paths.agentDir(agent.agent.id), "sessions"), target.id);
9050
9831
  return buildSessionContext(entries.filter((entry) => entry.type !== "session")).messages;
9051
9832
  }
9052
9833
  function loadSessionMessages(agent, paths, sessionId) {
9053
9834
  if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) return [];
9054
- const sessionDir = join19(paths.agentDir(agent.agent.id), "sessions");
9055
- const file = join19(sessionDir, `${sessionId}.jsonl`);
9835
+ const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
9836
+ const file = join22(sessionDir, `${sessionId}.jsonl`);
9056
9837
  if (!existsSync14(file) || !existsSync14(agent.team.path)) return [];
9057
9838
  try {
9058
9839
  return SessionManager.open(file, sessionDir).buildSessionContext().messages;
@@ -9061,12 +9842,12 @@ function loadSessionMessages(agent, paths, sessionId) {
9061
9842
  }
9062
9843
  }
9063
9844
  function loadSessionHead(agent, paths, target) {
9064
- const sessionDir = join19(paths.agentDir(agent.agent.id), "sessions");
9845
+ const sessionDir = join22(paths.agentDir(agent.agent.id), "sessions");
9065
9846
  if (!existsSync14(sessionDir)) return { file: null, size: 0 };
9066
9847
  const recent = target ? explicitConversationFile(sessionDir, target) : null;
9067
9848
  if (!recent) return { file: null, size: 0 };
9068
9849
  try {
9069
- const s = statSync6(recent);
9850
+ const s = statSync7(recent);
9070
9851
  return { file: basename5(recent), size: s.size };
9071
9852
  } catch {
9072
9853
  return { file: null, size: 0 };
@@ -9075,7 +9856,7 @@ function loadSessionHead(agent, paths, target) {
9075
9856
  function explicitConversationFile(directory, target) {
9076
9857
  if (!target) throw new Error("Explicit conversation target is required");
9077
9858
  readSessionHeader(directory, target.id);
9078
- return join19(directory, `${target.id}.jsonl`);
9859
+ return join22(directory, `${target.id}.jsonl`);
9079
9860
  }
9080
9861
 
9081
9862
  // ../daemon/src/runtime/providers/catalog.ts
@@ -9105,7 +9886,7 @@ async function listCatalogModels(providerName, env = process.env, signal) {
9105
9886
  }
9106
9887
 
9107
9888
  // ../daemon/src/runtime/worker/spawn.ts
9108
- import { spawn as spawn3 } from "node:child_process";
9889
+ import { spawn as spawn4 } from "node:child_process";
9109
9890
  import { existsSync as existsSync15 } from "node:fs";
9110
9891
  import { isAbsolute as isAbsolute6 } from "node:path";
9111
9892
  import { fileURLToPath } from "node:url";
@@ -9131,10 +9912,10 @@ async function refreshApiKeyForTurn(requestedProvider, turnProvider, host3, sign
9131
9912
  }
9132
9913
  function waitForRefresh(pending, signal) {
9133
9914
  if (!signal) return pending;
9134
- return new Promise((resolve8, reject2) => {
9915
+ return new Promise((resolve9, reject2) => {
9135
9916
  const onAbort = () => reject2(refreshCancelledError());
9136
9917
  signal.addEventListener("abort", onAbort, { once: true });
9137
- pending.then(resolve8, reject2).finally(() => signal.removeEventListener("abort", onAbort));
9918
+ pending.then(resolve9, reject2).finally(() => signal.removeEventListener("abort", onAbort));
9138
9919
  });
9139
9920
  }
9140
9921
  var ApiKeyRefreshCancelledError = class extends Error {
@@ -9192,7 +9973,7 @@ async function* runWorker(run) {
9192
9973
  if (!isAbsolute6(workerEntry)) throw new Error("worker entry path must be absolute");
9193
9974
  const serializedInput = JSON.stringify(run.input);
9194
9975
  opts.signal?.throwIfAborted();
9195
- const child = spawn3(process.execPath, workerSpawnArgs(workerEntry), {
9976
+ const child = spawn4(process.execPath, workerSpawnArgs(workerEntry), {
9196
9977
  env: run.env,
9197
9978
  detached: true,
9198
9979
  stdio: ["pipe", "pipe", "pipe", "ipc"]
@@ -9252,10 +10033,10 @@ async function* runWorker(run) {
9252
10033
  child.stderr?.destroy();
9253
10034
  }, EXIT_DRAIN_MS).unref();
9254
10035
  });
9255
- const exit = new Promise((resolve8) => {
10036
+ const exit = new Promise((resolve9) => {
9256
10037
  if (child.exitCode !== null || child.signalCode !== null) {
9257
- resolve8({ code: child.exitCode, signal: child.signalCode });
9258
- } else child.once("close", (code, signal) => resolve8({ code, signal }));
10038
+ resolve9({ code: child.exitCode, signal: child.signalCode });
10039
+ } else child.once("close", (code, signal) => resolve9({ code, signal }));
9259
10040
  });
9260
10041
  try {
9261
10042
  if (!child.stdout) throw new Error("worker spawn: stdout pipe missing");
@@ -9399,7 +10180,7 @@ var AsyncFrameQueue = class {
9399
10180
  const frame = this.#frames.shift();
9400
10181
  if (frame) return Promise.resolve({ done: false, value: frame });
9401
10182
  if (this.#ended) return Promise.resolve({ done: true, value: void 0 });
9402
- return new Promise((resolve8) => this.#waiters.push(resolve8));
10183
+ return new Promise((resolve9) => this.#waiters.push(resolve9));
9403
10184
  }
9404
10185
  };
9405
10186
  }
@@ -9493,208 +10274,44 @@ function assertProviderReady(db, authToken, model) {
9493
10274
  throw new ExecutionUnavailableError(error.message);
9494
10275
  }
9495
10276
  if (!findProvider(providerName)) {
9496
- throw new ExecutionUnavailableError(`unknown provider: ${providerName}`);
9497
- }
9498
- if (!providerState_exports.listEnabled(db).has(providerName)) {
9499
- throw new ExecutionUnavailableError(
9500
- `${providerName} provider is disabled \u2014 enable it on the /config page`
9501
- );
9502
- }
9503
- if (providerName === "openai-codex" && !hasCredentials(db, authToken)) {
9504
- throw new ExecutionUnavailableError(
9505
- "openai-codex is not connected \u2014 run `bazilion auth openai login` or click Connect on /config"
9506
- );
9507
- }
9508
- }
9509
- async function resolveAgentApiKey(db, authToken, agent) {
9510
- if (parseModelString(agent.model).providerName !== "openai-codex") return {};
9511
- return {
9512
- apiKey: await loadAccessToken(db, authToken),
9513
- refreshApiKey: async (requestedProvider) => {
9514
- if (requestedProvider !== "openai-codex") {
9515
- throw new Error(`unexpected refresh request for ${requestedProvider}`);
9516
- }
9517
- return loadAccessToken(db, authToken);
9518
- }
9519
- };
9520
- }
9521
-
9522
- // ../daemon/src/lib/bash-approval.ts
9523
- var DEFAULT_TIMEOUT_MS2 = 12e4;
9524
- var CommandApprovalRegistry = class {
9525
- #pending = /* @__PURE__ */ new Map();
9526
- #timeoutMs;
9527
- constructor(timeoutMs = DEFAULT_TIMEOUT_MS2) {
9528
- this.#timeoutMs = timeoutMs;
9529
- }
9530
- begin(input, signal) {
9531
- const approval = {
9532
- id: input.id,
9533
- turnId: input.turnId,
9534
- toolCallId: input.toolCallId,
9535
- agentId: input.agentId,
9536
- teamId: input.teamId,
9537
- command: input.command,
9538
- risks: input.risks,
9539
- status: "pending",
9540
- expiresAt: Date.now() + this.#timeoutMs
9541
- };
9542
- const immediate = input.mode === "auto_deny" ? "auto_denied" : signal?.aborted ? "cancelled" : void 0;
9543
- if (immediate) {
9544
- const settled2 = logged({ ...approval, status: immediate });
9545
- return { approval: settled2, settled: Promise.resolve(settled2) };
9546
- }
9547
- if (this.#pending.has(approval.id))
9548
- throw new Error(`duplicate shell approval id: ${approval.id}`);
9549
- const settled = new Promise((resolve8) => {
9550
- const settle = (status2) => {
9551
- this.#pending.delete(approval.id);
9552
- clearTimeout(timer);
9553
- signal?.removeEventListener("abort", onAbort);
9554
- const result = logged({ ...approval, status: status2 });
9555
- resolve8(result);
9556
- return result;
9557
- };
9558
- const onAbort = () => settle("cancelled");
9559
- const timer = setTimeout(() => settle("expired"), this.#timeoutMs);
9560
- timer.unref();
9561
- signal?.addEventListener("abort", onAbort, { once: true });
9562
- this.#pending.set(approval.id, { approval, settle });
9563
- });
9564
- return { approval, settled };
9565
- }
9566
- list(agentId) {
9567
- 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));
9568
- }
9569
- /** Answer a pending approval; undefined when there is none (unknown, or already settled). */
9570
- respond(id, decision) {
9571
- return this.#pending.get(id)?.settle(decision === "allow" ? "allowed" : "denied");
9572
- }
9573
- };
9574
- function logged(approval) {
9575
- console.info("bash approval decision", {
9576
- approvalId: approval.id,
9577
- agentId: approval.agentId,
9578
- teamId: approval.teamId,
9579
- riskCodes: [...new Set(approval.risks.map((risk) => risk.code))],
9580
- status: approval.status
9581
- });
9582
- return approval;
9583
- }
9584
- var commandApprovalRegistry = new CommandApprovalRegistry();
9585
-
9586
- // ../daemon/src/lib/browser/host.ts
9587
- init_pool2();
9588
- function createBrowserHost(config, turn) {
9589
- return {
9590
- invoke: (_workerAgentId, action, args) => invokeBrowserAction(turn.agentId, action, args, config, turn.paths, turn.signal)
9591
- };
9592
- }
9593
-
9594
- // ../daemon/src/lib/image-generation.ts
9595
- import { createModels } from "@earendil-works/pi-ai";
9596
- import { openrouterProvider } from "@earendil-works/pi-ai/providers/openrouter";
9597
-
9598
- // ../daemon/src/core/repos/results.ts
9599
- import { createHash as createHash4, randomUUID as randomUUID14 } from "node:crypto";
9600
-
9601
- // ../daemon/src/core/tool-call-id.ts
9602
- function isToolCallId(value) {
9603
- return typeof value === "string" && value.length <= 256 && // A true end assertion also rejects a trailing newline (unlike JavaScript '$').
9604
- /^[A-Za-z0-9._:-]+(?:\|[A-Za-z0-9._:-]+)?$(?![\s\S])/.test(value);
9605
- }
9606
-
9607
- // ../daemon/src/core/repos/results.ts
9608
- var MAX_RESULT_BYTES = 25 * 1024 * 1024;
9609
- var MAX_RETAINED_RESULT_BYTES = 1024 * 1024 * 1024;
9610
- var columns2 = `id, team_id AS teamId, agent_id AS agentId, session_id AS sessionId,
9611
- tool_call_id AS toolCallId, source_index AS sourceIndex, name, mime_type AS mimeType,
9612
- byte_length AS byteLength, sha256, image_model AS imageModel, created_at AS createdAt`;
9613
- function get17(db, id) {
9614
- return db.raw.query(`SELECT ${columns2} FROM agent_results WHERE id = ?`).get(id);
9615
- }
9616
- function publish(db, input) {
9617
- if (!isToolCallId(input.toolCallId)) throw new Error("Invalid result tool call");
9618
- 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 === "..")
9619
- throw new Error("Invalid result filename");
9620
- if (typeof input.mimeType !== "string" || !/^[a-z0-9.+-]+\/[a-z0-9.+-]+$/.test(input.mimeType))
9621
- throw new Error("Invalid result media type");
9622
- if (input.bytes.byteLength > MAX_RESULT_BYTES)
9623
- throw new Error("Result exceeds the 25 MiB per-file limit");
9624
- const bytes = Buffer.from(input.bytes);
9625
- const sourceIndex = input.sourceIndex ?? 0;
9626
- return db.raw.transaction(() => {
9627
- const existing = db.raw.query(
9628
- `SELECT id FROM agent_results
9629
- WHERE agent_id = ? AND session_id = ? AND tool_call_id = ? AND source_index = ?`
9630
- ).get(input.agentId, input.sessionId, input.toolCallId, sourceIndex);
9631
- if (existing) return get17(db, existing.id);
9632
- const retained = db.raw.query(
9633
- "SELECT coalesce(sum(byte_length), 0) AS bytes FROM agent_results"
9634
- ).get()?.bytes ?? 0;
9635
- if (retained + bytes.byteLength > MAX_RETAINED_RESULT_BYTES)
9636
- throw new Error(
9637
- "Result storage is full (1 GiB). Delete saved results before delivering more files."
9638
- );
9639
- const id = randomUUID14();
9640
- db.raw.run(
9641
- `INSERT INTO agent_results
9642
- (id, team_id, agent_id, session_id, tool_call_id, source_index, name, mime_type,
9643
- byte_length, sha256, image_model, created_at, bytes)
9644
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
9645
- [
9646
- id,
9647
- input.teamId,
9648
- input.agentId,
9649
- input.sessionId,
9650
- input.toolCallId,
9651
- sourceIndex,
9652
- input.name,
9653
- input.mimeType,
9654
- bytes.byteLength,
9655
- createHash4("sha256").update(bytes).digest("hex"),
9656
- input.imageModel ?? null,
9657
- Date.now(),
9658
- bytes
9659
- ]
9660
- );
9661
- return get17(db, id);
9662
- })();
9663
- }
9664
- function list12(db, opts = {}) {
9665
- const limit = Math.max(1, Math.min(100, Math.floor(opts.limit ?? 50)));
9666
- const offset = Math.max(0, Math.floor(opts.offset ?? 0));
9667
- const where = [];
9668
- const params = [];
9669
- if (opts.teamId !== void 0) {
9670
- where.push("team_id = ?");
9671
- params.push(opts.teamId);
10277
+ throw new ExecutionUnavailableError(`unknown provider: ${providerName}`);
9672
10278
  }
9673
- if (opts.agentId !== void 0) {
9674
- where.push("agent_id = ?");
9675
- params.push(opts.agentId);
10279
+ if (!providerState_exports.listEnabled(db).has(providerName)) {
10280
+ throw new ExecutionUnavailableError(
10281
+ `${providerName} provider is disabled \u2014 enable it on the /config page`
10282
+ );
10283
+ }
10284
+ if (providerName === "openai-codex" && !hasCredentials(db, authToken)) {
10285
+ throw new ExecutionUnavailableError(
10286
+ "openai-codex is not connected \u2014 run `bazilion auth openai login` or click Connect on /config"
10287
+ );
9676
10288
  }
9677
- const filter = where.length ? `WHERE ${where.join(" AND ")}` : "";
9678
- const total = db.raw.query(`SELECT count(*) AS total FROM agent_results ${filter}`).get(...params)?.total ?? 0;
9679
- const results = db.raw.query(
9680
- `SELECT ${columns2} FROM agent_results ${filter} ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`
9681
- ).all(...params, limit, offset);
9682
- return { results, total, limit, offset };
9683
10289
  }
9684
- function read(db, id) {
9685
- const row = db.raw.query(
9686
- "SELECT bytes, sha256 FROM agent_results WHERE id = ?"
9687
- ).get(id);
9688
- if (!row) throw new Error("Result not found");
9689
- const bytes = Buffer.from(row.bytes);
9690
- if (createHash4("sha256").update(bytes).digest("hex") !== row.sha256)
9691
- throw new Error("Saved file failed its integrity check");
9692
- return bytes;
10290
+ async function resolveAgentApiKey(db, authToken, agent) {
10291
+ if (parseModelString(agent.model).providerName !== "openai-codex") return {};
10292
+ return {
10293
+ apiKey: await loadAccessToken(db, authToken),
10294
+ refreshApiKey: async (requestedProvider) => {
10295
+ if (requestedProvider !== "openai-codex") {
10296
+ throw new Error(`unexpected refresh request for ${requestedProvider}`);
10297
+ }
10298
+ return loadAccessToken(db, authToken);
10299
+ }
10300
+ };
9693
10301
  }
9694
- function remove10(db, id) {
9695
- return db.raw.run("DELETE FROM agent_results WHERE id = ?", [id]).changes === 1;
10302
+
10303
+ // ../daemon/src/lib/browser/host.ts
10304
+ init_pool2();
10305
+ function createBrowserHost(config, turn) {
10306
+ return {
10307
+ invoke: (_workerAgentId, action, args) => invokeBrowserAction(turn.agentId, action, args, config, turn.paths, turn.signal)
10308
+ };
9696
10309
  }
9697
10310
 
10311
+ // ../daemon/src/lib/image-generation.ts
10312
+ import { createModels } from "@earendil-works/pi-ai";
10313
+ import { openrouterProvider } from "@earendil-works/pi-ai/providers/openrouter";
10314
+
9698
10315
  // ../daemon/src/lib/openai-responses.ts
9699
10316
  var OPENAI_RESPONSES_URL = "https://api.openai.com/v1/responses";
9700
10317
  var CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses";
@@ -9975,7 +10592,7 @@ async function resolveMcpForTurn(db, authToken, signal) {
9975
10592
  }
9976
10593
 
9977
10594
  // ../daemon/src/lib/agent-loop-guard.ts
9978
- import { randomUUID as randomUUID15 } from "node:crypto";
10595
+ import { randomUUID as randomUUID16 } from "node:crypto";
9979
10596
  var DEFAULT_MAX_HOPS = 8;
9980
10597
  function toEvent(row) {
9981
10598
  return {
@@ -10025,8 +10642,8 @@ function enforceMessageCausality(db, input) {
10025
10642
  const target = agents_exports.get(db, input.to);
10026
10643
  if (!source || !target) return null;
10027
10644
  const event = {
10028
- id: randomUUID15(),
10029
- causalChainId: input.causality.causalChainId ?? input.causality.parentMessageId ?? randomUUID15(),
10645
+ id: randomUUID16(),
10646
+ causalChainId: input.causality.causalChainId ?? input.causality.parentMessageId ?? randomUUID16(),
10030
10647
  parentMessageId: input.causality.parentMessageId,
10031
10648
  fromAgentId: input.from,
10032
10649
  toAgentId: input.to,
@@ -10148,120 +10765,6 @@ function createDbMessagingHost(db, opts = {}) {
10148
10765
  };
10149
10766
  }
10150
10767
 
10151
- // ../daemon/src/lib/questions.ts
10152
- import { randomUUID as randomUUID16 } from "node:crypto";
10153
- var QUESTION_WAIT_MS = 5 * 6e4;
10154
- var QUESTION_LIMITS = Object.freeze({
10155
- promptChars: 2e3,
10156
- labelChars: 120,
10157
- descriptionChars: 500,
10158
- answerChars: 4096
10159
- });
10160
- function text2(value, limit, what) {
10161
- if (typeof value !== "string" || !value.trim()) throw new Error(`${what} must be non-empty text`);
10162
- if (value.length > limit) throw new Error(`${what} is longer than ${limit} characters`);
10163
- return value;
10164
- }
10165
- function parseQuestionInput(value) {
10166
- const input = value ?? {};
10167
- const prompt = text2(input.prompt, QUESTION_LIMITS.promptChars, "The prompt");
10168
- if (!Array.isArray(input.choices) || input.choices.length < 2 || input.choices.length > 4)
10169
- throw new Error("ask_user needs 2 to 4 choices");
10170
- const labels = /* @__PURE__ */ new Set();
10171
- const choices = input.choices.map((raw, index) => {
10172
- const choice = raw ?? {};
10173
- const label = text2(choice.label, QUESTION_LIMITS.labelChars, `Choice ${index + 1} label`);
10174
- const key2 = label.normalize("NFKC").trim().toLowerCase();
10175
- if (labels.has(key2)) throw new Error("Choice labels must be distinct");
10176
- labels.add(key2);
10177
- if (choice.description === void 0) return { label };
10178
- const description = text2(
10179
- choice.description,
10180
- QUESTION_LIMITS.descriptionChars,
10181
- `Choice ${index + 1} description`
10182
- );
10183
- return { label, description };
10184
- });
10185
- const recommended = input.recommendedIndex;
10186
- if (recommended === void 0) return { prompt, choices };
10187
- if (typeof recommended !== "number" || !Number.isInteger(recommended))
10188
- throw new Error("recommendedIndex must be a choice index");
10189
- if (recommended < 0 || recommended >= choices.length)
10190
- throw new Error("recommendedIndex must be a choice index");
10191
- return { prompt, choices, recommendedIndex: recommended };
10192
- }
10193
- function parseQuestionAnswer(value, question) {
10194
- const answer = value ?? {};
10195
- if (answer.kind === "skip") return { kind: "skip" };
10196
- if (answer.kind === "text")
10197
- return { kind: "text", text: text2(answer.text, QUESTION_LIMITS.answerChars, "The answer") };
10198
- const index = answer.index;
10199
- if (answer.kind === "choice" && typeof index === "number" && Number.isInteger(index)) {
10200
- if (index >= 0 && index < question.choices.length) return { kind: "choice", index };
10201
- throw new Error(
10202
- `Choice ${index + 1} does not exist; this question has ${question.choices.length} choices`
10203
- );
10204
- }
10205
- throw new Error("An answer is a choice index, text or skip");
10206
- }
10207
- var QuestionRegistry = class {
10208
- #pending = /* @__PURE__ */ new Map();
10209
- #waitMs;
10210
- constructor(waitMs = QUESTION_WAIT_MS) {
10211
- this.#waitMs = waitMs;
10212
- }
10213
- /** Register a question. `result` settles on the first answer, the timeout or `signal`. */
10214
- ask(context, input, signal) {
10215
- const prompt = parseQuestionInput(input);
10216
- if (this.list(context.agentId).length > 0)
10217
- throw new Error("Another question from this Agent is still waiting for an answer");
10218
- if (signal?.aborted) throw new Error("The turn has ended");
10219
- const now = Date.now();
10220
- const question = {
10221
- id: randomUUID16(),
10222
- agentId: context.agentId,
10223
- conversationId: context.conversationId,
10224
- question: prompt,
10225
- createdAt: now,
10226
- expiresAt: now + this.#waitMs
10227
- };
10228
- const { promise, resolve: resolve8 } = Promise.withResolvers();
10229
- const cancel3 = () => finish3({ kind: "no_answer", reason: "cancelled" });
10230
- const timer = setTimeout(() => finish3({ kind: "no_answer", reason: "expired" }), this.#waitMs);
10231
- timer.unref();
10232
- const finish3 = (outcome) => {
10233
- if (!this.#pending.delete(question.id)) return false;
10234
- clearTimeout(timer);
10235
- signal?.removeEventListener("abort", cancel3);
10236
- resolve8({ questionId: question.id, question: prompt, ...outcome });
10237
- return true;
10238
- };
10239
- this.#pending.set(question.id, { question, result: promise, finish: finish3 });
10240
- signal?.addEventListener("abort", cancel3, { once: true });
10241
- return { question, result: promise };
10242
- }
10243
- list(agentId) {
10244
- return [...this.#pending.values()].map((entry) => entry.question).filter((question) => agentId === void 0 || question.agentId === agentId);
10245
- }
10246
- get(id) {
10247
- return this.#pending.get(id)?.question;
10248
- }
10249
- /** The outcome of a waiting question; undefined once it has settled. */
10250
- settled(id) {
10251
- return this.#pending.get(id)?.result;
10252
- }
10253
- /** Answer a waiting question. False when it is no longer waiting; throws on an invalid answer. */
10254
- answer(agentId, id, value) {
10255
- const entry = this.#pending.get(id);
10256
- if (!entry || entry.question.agentId !== agentId) return false;
10257
- const answer = parseQuestionAnswer(value, entry.question.question);
10258
- return entry.finish(
10259
- answer.kind === "skip" ? { kind: "no_answer", reason: "skipped" } : { kind: "answer", answer }
10260
- );
10261
- }
10262
- };
10263
- var questionRegistry = new QuestionRegistry();
10264
-
10265
10768
  // ../daemon/src/lib/result-host.ts
10266
10769
  function createResultHost(db, agent, conversationId, signal) {
10267
10770
  return {
@@ -10901,7 +11404,7 @@ function mirrorTypingStop(agentId) {
10901
11404
  // ../daemon/src/lib/attachments.ts
10902
11405
  import { randomUUID as randomUUID17 } from "node:crypto";
10903
11406
  import { closeSync as closeSync5, constants as constants6, fstatSync as fstatSync5, openSync as openSync5, writeFileSync as writeFileSync8 } from "node:fs";
10904
- import { join as join20, posix as posix2 } from "node:path";
11407
+ import { join as join23, posix as posix2 } from "node:path";
10905
11408
  var MAX_FILE_BYTES = 25 * 1024 * 1024;
10906
11409
  function safeName(name) {
10907
11410
  const base = name.split(/[\\/]/).pop() ?? "file";
@@ -10913,7 +11416,7 @@ function fmtBytes(n) {
10913
11416
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
10914
11417
  }
10915
11418
  function prepareInputFilesDirectory(agentDir2) {
10916
- return ensureContainedRealDirectory(join20(agentDir2, "uploads"), agentDir2, { create: true });
11419
+ return ensureContainedRealDirectory(join23(agentDir2, "uploads"), agentDir2, { create: true });
10917
11420
  }
10918
11421
  function saveInputFiles(agentDir2, files, options = {}) {
10919
11422
  if (!files || files.length === 0) return "";
@@ -10927,7 +11430,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
10927
11430
  continue;
10928
11431
  }
10929
11432
  const filename = `${randomUUID17().slice(0, 8)}-${safeName(label)}`;
10930
- const path = join20(dir, filename);
11433
+ const path = join23(dir, filename);
10931
11434
  let fd;
10932
11435
  try {
10933
11436
  fd = openSync5(
@@ -10950,7 +11453,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
10950
11453
 
10951
11454
  // ../daemon/src/lib/coding-environment.ts
10952
11455
  import { lstatSync as lstatSync5 } from "node:fs";
10953
- import { join as join21 } from "node:path";
11456
+ import { join as join24 } from "node:path";
10954
11457
 
10955
11458
  // ../daemon/src/core/coding-environment/config.ts
10956
11459
  var CodingEnvironmentValidationError = class extends DomainError {
@@ -11007,7 +11510,7 @@ function setTeamCodingEnvironment(db, team, input, env = process.env) {
11007
11510
  const environment = validateCodingEnvironment(input);
11008
11511
  let path = team.path;
11009
11512
  for (const part of environment.cwd === "." ? [] : environment.cwd.split("/")) {
11010
- path = join21(path, part);
11513
+ path = join24(path, part);
11011
11514
  if (!lstatSync5(path, { throwIfNoEntry: false })?.isDirectory())
11012
11515
  throw new CodingEnvironmentValidationError(
11013
11516
  "The directory must be an existing directory inside the Team"
@@ -11028,17 +11531,17 @@ function dockerTurn(db, paths, agent, env) {
11028
11531
  // ../daemon/src/lib/conversation-target.ts
11029
11532
  import { randomUUID as randomUUID18 } from "node:crypto";
11030
11533
  import { writeFileSync as writeFileSync9 } from "node:fs";
11031
- import { join as join22 } from "node:path";
11534
+ import { join as join25 } from "node:path";
11032
11535
  import { SessionManager as SessionManager2 } from "@earendil-works/pi-coding-agent";
11033
11536
  function sessionsDir(paths, agentId) {
11034
- return join22(paths.agentDir(agentId), "sessions");
11537
+ return join25(paths.agentDir(agentId), "sessions");
11035
11538
  }
11036
11539
  function startConversation(db, paths, agentId, title) {
11037
11540
  const agent = resolveAgent(db, paths, agentId);
11038
11541
  if (title !== void 0) validTitle(title);
11039
11542
  const id = randomUUID18();
11040
11543
  const header = SessionManager2.inMemory(agent.team.path, { id }).getHeader();
11041
- writeFileSync9(join22(sessionsDir(paths, agentId), `${id}.jsonl`), `${JSON.stringify(header)}
11544
+ writeFileSync9(join25(sessionsDir(paths, agentId), `${id}.jsonl`), `${JSON.stringify(header)}
11042
11545
  `, {
11043
11546
  flag: "wx",
11044
11547
  mode: 384
@@ -11051,6 +11554,34 @@ function resolveConversationTarget(db, paths, agentId, pinnedId) {
11051
11554
  readSessionHeader(sessionsDir(paths, agentId), id);
11052
11555
  return { id };
11053
11556
  }
11557
+ function selectConversation(db, paths, agentId, id) {
11558
+ if (!get16(db, agentId, id)) throw new DomainError(404, "Conversation not found");
11559
+ try {
11560
+ readSessionHeader(sessionsDir(paths, agentId), id);
11561
+ } catch {
11562
+ throw new DomainError(409, "That conversation has no readable history, so it cannot continue.");
11563
+ }
11564
+ return select(db, agentId, id);
11565
+ }
11566
+ var TITLE_CHARS = 60;
11567
+ function titleFromMessage(message) {
11568
+ const line = message.split("\n").map((part) => part.replace(/\s+/g, " ").trim()).find((part) => part.length > 0);
11569
+ if (!line) return null;
11570
+ const clean = Array.from(line).filter((char) => char.charCodeAt(0) >= 32 && char.charCodeAt(0) !== 127).join("").trim();
11571
+ if (!clean) return null;
11572
+ if (clean.length <= TITLE_CHARS) return clean;
11573
+ const cut = clean.slice(0, TITLE_CHARS);
11574
+ const space = cut.lastIndexOf(" ");
11575
+ return `${(space > TITLE_CHARS / 2 ? cut.slice(0, space) : cut).trimEnd()}\u2026`;
11576
+ }
11577
+ function titleConversationFromMessage(db, paths, agentId, conversationId, message) {
11578
+ const conversation = get16(db, agentId, conversationId);
11579
+ if (!conversation || !hasDefaultTitle(conversation)) return;
11580
+ if (conversation.updatedAt !== conversation.createdAt) return;
11581
+ if (sessionHasEntries(sessionsDir(paths, agentId), conversationId)) return;
11582
+ const title = titleFromMessage(message);
11583
+ if (title) rename(db, agentId, conversationId, title);
11584
+ }
11054
11585
  function selectedConversationTarget(db, agentId) {
11055
11586
  const id = selectedId(db, agentId);
11056
11587
  return id ? { id } : null;
@@ -11058,7 +11589,7 @@ function selectedConversationTarget(db, agentId) {
11058
11589
 
11059
11590
  // ../daemon/src/lib/repository-instructions.ts
11060
11591
  import { realpathSync as realpathSync6 } from "node:fs";
11061
- import { join as join23 } from "node:path";
11592
+ import { join as join26 } from "node:path";
11062
11593
  var MAX_FILE_BYTES2 = 128 * 1024;
11063
11594
  var SKIPPED = {
11064
11595
  outside: "it resolves outside the Team workspace",
@@ -11078,7 +11609,7 @@ function loadRepositoryInstructions(root, cwd = ".") {
11078
11609
  for (let depth = 0; depth <= parts.length; depth++) {
11079
11610
  const path = [...parts.slice(0, depth), "AGENTS.md"].join("/");
11080
11611
  try {
11081
- const content = readContainedFile(join23(realRoot, path), realRoot, MAX_FILE_BYTES2);
11612
+ const content = readContainedFile(join26(realRoot, path), realRoot, MAX_FILE_BYTES2);
11082
11613
  instructions.push({ path, content: content.toString("utf8") });
11083
11614
  } catch (error) {
11084
11615
  if (error instanceof ContainedFileError) {
@@ -11111,6 +11642,9 @@ async function prepareAgentTurn(request) {
11111
11642
  registerAgent(agentId, controller);
11112
11643
  registered = true;
11113
11644
  }
11645
+ if (request.origin === "http" || request.origin === "telegram") {
11646
+ titleConversationFromMessage(db, paths, agentId, conversation.id, request.message);
11647
+ }
11114
11648
  const env = mergeSecretsIntoEnv(db, authToken);
11115
11649
  const docker2 = resolveShellSecurityConfig(env).sandboxMode === "docker" ? dockerTurn(db, paths, agent, env) : void 0;
11116
11650
  const repositoryInstructions = loadRepositoryInstructions(agent.team.path, docker2?.cwd ?? ".");
@@ -11362,12 +11896,14 @@ async function* runAgentTurn(turn) {
11362
11896
  );
11363
11897
  });
11364
11898
  if (frame.kind === "done") completed = true;
11899
+ noteTurnFrame(agentId, frame);
11365
11900
  yield frame;
11366
11901
  }
11367
11902
  if (completed && (turn.request.origin === "http" || turn.request.origin === "telegram")) {
11368
11903
  agentReviews_exports.recordSuccessfulUserTurn(db, agentId);
11369
11904
  }
11370
11905
  } finally {
11906
+ noteTurnEnd(agentId);
11371
11907
  mirrorTypingStop(agentId);
11372
11908
  if (turn.docker) await removeDockerContainers(turn.docker.containerPrefix);
11373
11909
  releasePreparedAgentTurn(turn);
@@ -11716,7 +12252,7 @@ agentChatRouter.post("/:id/chat/compact", async (c) => {
11716
12252
  const { db, paths, authToken } = getCtx();
11717
12253
  const resolved = resolveAgent(db, paths, id);
11718
12254
  assertProviderReady(db, authToken, resolved.model);
11719
- const memory = qmdBackend(join24(resolved.team.path, "memory"));
12255
+ const memory = qmdBackend(join27(resolved.team.path, "memory"));
11720
12256
  await memory.init();
11721
12257
  const handle12 = await createBazilionSession({
11722
12258
  agent: resolved,
@@ -11774,9 +12310,9 @@ agentChatRouter.get(
11774
12310
  const env = mergeSecretsIntoEnv(db, authToken);
11775
12311
  const files = [];
11776
12312
  for (const file of CONTEXT_FILE_ORDER2) {
11777
- const path = join24(resolved.agent.dir, file);
12313
+ const path = join27(resolved.agent.dir, file);
11778
12314
  if (!existsSync16(path)) continue;
11779
- const content = readFileSync9(path, "utf8").trimEnd();
12315
+ const content = readFileSync10(path, "utf8").trimEnd();
11780
12316
  if (!content) continue;
11781
12317
  const chars = content.length + file.length + 6;
11782
12318
  files.push({ name: file, chars, tokens: estimateTokens2(chars) });
@@ -11789,7 +12325,7 @@ agentChatRouter.get(
11789
12325
  agent: resolved,
11790
12326
  paths,
11791
12327
  env,
11792
- memory: qmdBackend(join24(resolved.team.path, "memory")),
12328
+ memory: qmdBackend(join27(resolved.team.path, "memory")),
11793
12329
  messagingHost: createDbMessagingHost(db),
11794
12330
  userMdHost: createDbUserMdHost(db, paths),
11795
12331
  fileSink: reportOnly,
@@ -11819,7 +12355,7 @@ agentChatRouter.get(
11819
12355
  let blockChars = name.length + 2;
11820
12356
  if (match) {
11821
12357
  try {
11822
- blockChars = readFileSync9(match.skillFile, "utf8").length;
12358
+ blockChars = readFileSync10(match.skillFile, "utf8").length;
11823
12359
  } catch {
11824
12360
  }
11825
12361
  }
@@ -11893,7 +12429,7 @@ agentChatRouter.post("/:id/chat/truncate", async (c) => {
11893
12429
  });
11894
12430
 
11895
12431
  // ../daemon/src/routes/agent-learning.ts
11896
- import { join as join25 } from "node:path";
12432
+ import { join as join28 } from "node:path";
11897
12433
 
11898
12434
  // ../daemon/src/lib/lesson-decisions.ts
11899
12435
  var LessonProposalConflictError = class extends DomainError {
@@ -12092,7 +12628,7 @@ for (const decision of ["approve", "reject", "revoke"]) {
12092
12628
  const team = teams_exports.get(db, agent.teamId, paths);
12093
12629
  if (!team) return c.json({ error: `team not found: ${agent.teamId}` }, 404);
12094
12630
  const proposal = await runAgentLifecycleMutation(agent.id, async () => {
12095
- const memory = qmdBackend(join25(team.path, "memory"));
12631
+ const memory = qmdBackend(join28(team.path, "memory"));
12096
12632
  if (decision === "approve") return approveLessonProposal(db, memory, current2.id, version);
12097
12633
  if (decision === "reject") return rejectLessonProposal(db, current2.id, version);
12098
12634
  return revokeLessonProposal(db, memory, current2.id, version);
@@ -12120,7 +12656,7 @@ function withEvidenceExcerpts(proposals, agent, paths) {
12120
12656
  }
12121
12657
 
12122
12658
  // ../daemon/src/routes/agents.ts
12123
- import { join as join26 } from "node:path";
12659
+ import { join as join29 } from "node:path";
12124
12660
  init_pool2();
12125
12661
 
12126
12662
  // ../daemon/src/lib/telegram/config.ts
@@ -12395,7 +12931,7 @@ agentsRouter.get("/", (c) => {
12395
12931
  const includeArchived = c.req.query("includeArchived") === "true";
12396
12932
  const agents = agents_exports.list(getCtx().db, { includeArchived }).map((agent) => ({
12397
12933
  ...agent,
12398
- identity: loadIdentityFromFile(join26(agent.dir, "IDENTITY.md"))
12934
+ identity: loadIdentityFromFile(join29(agent.dir, "IDENTITY.md"))
12399
12935
  }));
12400
12936
  return c.json(agents);
12401
12937
  });
@@ -12529,7 +13065,7 @@ attentionRouter.delete(
12529
13065
  import { deleteCookie, setCookie } from "hono/cookie";
12530
13066
 
12531
13067
  // ../daemon/src/lib/openai-oauth-prompt.ts
12532
- import { spawn as spawn4 } from "node:child_process";
13068
+ import { spawn as spawn5 } from "node:child_process";
12533
13069
  import { createServer as createServer2 } from "node:net";
12534
13070
  var OPENAI_CODEX_CALLBACK_PORT = 1455;
12535
13071
  var WEB_OPENAI_LOGIN_TIMEOUT_MS = 10 * 6e4;
@@ -12537,9 +13073,9 @@ var DEVICE_CODE_FALLBACK = "`bazilion auth openai login --device-code` in a term
12537
13073
  async function preflightOpenAICodexCallback(host3 = process.env.PI_OAUTH_CALLBACK_HOST?.trim() || "127.0.0.1", port2 = OPENAI_CODEX_CALLBACK_PORT) {
12538
13074
  const server3 = createServer2();
12539
13075
  try {
12540
- await new Promise((resolve8, reject2) => {
13076
+ await new Promise((resolve9, reject2) => {
12541
13077
  server3.once("error", reject2);
12542
- server3.listen({ host: host3, port: port2, exclusive: true }, resolve8);
13078
+ server3.listen({ host: host3, port: port2, exclusive: true }, resolve9);
12543
13079
  });
12544
13080
  } catch (error) {
12545
13081
  const code = error.code;
@@ -12548,7 +13084,7 @@ async function preflightOpenAICodexCallback(host3 = process.env.PI_OAUTH_CALLBAC
12548
13084
  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}.`
12549
13085
  );
12550
13086
  } finally {
12551
- await new Promise((resolve8) => server3.close(() => resolve8()));
13087
+ await new Promise((resolve9) => server3.close(() => resolve9()));
12552
13088
  }
12553
13089
  }
12554
13090
  function openAICodexBrowserCommand(platform = process.platform) {
@@ -12561,7 +13097,7 @@ function launchOpenAICodexBrowser(url, onFailure) {
12561
13097
  `Could not open the OpenAI sign-in page with ${command}: ${detail}. Run ${DEVICE_CODE_FALLBACK}.`
12562
13098
  )
12563
13099
  );
12564
- const child = spawn4(command, [url], { stdio: "ignore", detached: true });
13100
+ const child = spawn5(command, [url], { stdio: "ignore", detached: true });
12565
13101
  child.once("error", (error) => fail2(error.message));
12566
13102
  child.once("exit", (code, signal) => {
12567
13103
  if (code !== 0) fail2(code === null ? `terminated by ${signal}` : `exited ${code}`);
@@ -12966,6 +13502,17 @@ conversationsRouter.get("/:agentId/conversations/:id", (c) => {
12966
13502
  );
12967
13503
  }
12968
13504
  });
13505
+ conversationsRouter.post("/:agentId/conversations/:id/select", async (c) => {
13506
+ const agentId = c.get("agentId");
13507
+ const id = c.req.param("id");
13508
+ const { db, paths } = getCtx();
13509
+ return c.json({
13510
+ conversation: await runAgentLifecycleMutation(
13511
+ agentId,
13512
+ () => selectConversation(db, paths, agentId, id)
13513
+ )
13514
+ });
13515
+ });
12969
13516
  conversationsRouter.patch("/:agentId/conversations/:id", async (c) => {
12970
13517
  const input = await jsonBody(c);
12971
13518
  return c.json({
@@ -13101,6 +13648,13 @@ mcpRouter.post("/:id/test", async (c) => {
13101
13648
 
13102
13649
  // ../daemon/src/routes/messages.ts
13103
13650
  var messagesRouter = newRouter();
13651
+ var teamMessagesRouter = newRouter();
13652
+ teamMessagesRouter.get("/:id/messages", (c) => {
13653
+ const limit = Math.min(Math.max(Number(c.req.query("limit")) || 100, 1), 500);
13654
+ return c.json({
13655
+ messages: messages_exports.listForTeam(getCtx().db, routeTeam(c).id, limit)
13656
+ });
13657
+ });
13104
13658
  messagesRouter.get("/:id", (c) => {
13105
13659
  const msg = messages_exports.get(getCtx().db, c.req.param("id"));
13106
13660
  if (!msg) return c.json({ error: `message not found: ${c.req.param("id")}` }, 404);
@@ -13155,24 +13709,24 @@ agentMessagesRouter.post("/:id/messages", async (c) => {
13155
13709
 
13156
13710
  // ../daemon/src/routes/misc.ts
13157
13711
  import { existsSync as existsSync17 } from "node:fs";
13158
- import { homedir as homedir3 } from "node:os";
13159
- import { join as join29 } from "node:path";
13712
+ import { homedir as homedir4 } from "node:os";
13713
+ import { join as join32 } from "node:path";
13160
13714
 
13161
13715
  // ../daemon/src/lib/backup.ts
13162
13716
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync13 } from "node:fs";
13163
13717
  import { tmpdir as tmpdir3 } from "node:os";
13164
- import { join as join28, resolve as resolve7 } from "node:path";
13718
+ import { join as join31, resolve as resolve7 } from "node:path";
13165
13719
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
13166
13720
  import { create as create6 } from "tar";
13167
13721
 
13168
13722
  // ../daemon/src/lib/daemon-liveness.ts
13169
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync10, rmSync as rmSync12, writeFileSync as writeFileSync10 } from "node:fs";
13170
- import { join as join27 } from "node:path";
13723
+ import { mkdirSync as mkdirSync11, readFileSync as readFileSync11, rmSync as rmSync12, writeFileSync as writeFileSync10 } from "node:fs";
13724
+ import { join as join30 } from "node:path";
13171
13725
  var DAEMON_PID_FILE = "daemon.pid";
13172
13726
  function runningDaemonPid(home) {
13173
13727
  let pid;
13174
13728
  try {
13175
- pid = Number.parseInt(readFileSync10(join27(home, DAEMON_PID_FILE), "utf8"), 10);
13729
+ pid = Number.parseInt(readFileSync11(join30(home, DAEMON_PID_FILE), "utf8"), 10);
13176
13730
  } catch (error) {
13177
13731
  if (error.code === "ENOENT") return null;
13178
13732
  throw error;
@@ -13189,12 +13743,12 @@ function assertDaemonStopped(home) {
13189
13743
  const pid = runningDaemonPid(home);
13190
13744
  if (pid !== null) {
13191
13745
  throw new Error(
13192
- `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${join27(home, DAEMON_PID_FILE)})`
13746
+ `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${join30(home, DAEMON_PID_FILE)})`
13193
13747
  );
13194
13748
  }
13195
13749
  }
13196
13750
  function claimDaemonPidFile(home) {
13197
- const path = join27(home, DAEMON_PID_FILE);
13751
+ const path = join30(home, DAEMON_PID_FILE);
13198
13752
  const content = `${process.pid}
13199
13753
  `;
13200
13754
  mkdirSync11(home, { recursive: true });
@@ -13208,7 +13762,7 @@ function claimDaemonPidFile(home) {
13208
13762
  }
13209
13763
  return () => {
13210
13764
  try {
13211
- if (readFileSync10(path, "utf8") === content) rmSync12(path);
13765
+ if (readFileSync11(path, "utf8") === content) rmSync12(path);
13212
13766
  } catch {
13213
13767
  }
13214
13768
  };
@@ -13223,10 +13777,10 @@ function createBackupSnapshot(db) {
13223
13777
  return snapshot2;
13224
13778
  }
13225
13779
  async function takeSnapshot(db) {
13226
- const directory = mkdtempSync3(join28(tmpdir3(), "bazilion-backup-"));
13780
+ const directory = mkdtempSync3(join31(tmpdir3(), "bazilion-backup-"));
13227
13781
  const cleanup = () => rmSync13(directory, { recursive: true, force: true });
13228
13782
  try {
13229
- const database = join28(directory, "bazilion.snapshot");
13783
+ const database = join31(directory, "bazilion.snapshot");
13230
13784
  await db.backupTo(database);
13231
13785
  const snapshot2 = new DatabaseSync2(database, { readOnly: true });
13232
13786
  try {
@@ -13325,7 +13879,7 @@ miscRouter.get("/health/details", async (c) => {
13325
13879
  } catch {
13326
13880
  }
13327
13881
  }
13328
- const openclawSkillsDir = join29(homedir3(), ".openclaw", "skills");
13882
+ const openclawSkillsDir = join32(homedir4(), ".openclaw", "skills");
13329
13883
  const providerSection = {
13330
13884
  // Hosted providers with credentials; local servers are reported below.
13331
13885
  configured: PROVIDERS.filter(
@@ -13733,8 +14287,8 @@ notificationsRouter.put("/", async (c) => {
13733
14287
  });
13734
14288
 
13735
14289
  // ../daemon/src/routes/profiles.ts
13736
- import { existsSync as existsSync18, readFileSync as readFileSync11, writeFileSync as writeFileSync11 } from "node:fs";
13737
- import { join as join30 } from "node:path";
14290
+ import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "node:fs";
14291
+ import { join as join33 } from "node:path";
13738
14292
  var profilesRouter = newRouter();
13739
14293
  profilesRouter.get("/", (c) => {
13740
14294
  const { db } = getCtx();
@@ -13817,13 +14371,13 @@ function profileFile(c) {
13817
14371
  if (!PROFILE_FILES.includes(file)) {
13818
14372
  return c.json({ error: `unsupported file: ${file}` }, 400);
13819
14373
  }
13820
- return join30(paths.profilesDir, id, file);
14374
+ return join33(paths.profilesDir, id, file);
13821
14375
  }
13822
14376
  profilesRouter.get("/:id/files/:file", (c) => {
13823
14377
  const path = profileFile(c);
13824
14378
  if (typeof path !== "string") return path;
13825
14379
  if (!existsSync18(path)) return c.json({ error: `file not present: ${c.req.param("file")}` }, 404);
13826
- return c.json({ content: readFileSync11(path, "utf8") });
14380
+ return c.json({ content: readFileSync12(path, "utf8") });
13827
14381
  });
13828
14382
  profilesRouter.put("/:id/files/:file", async (c) => {
13829
14383
  const body = await jsonBody(c);
@@ -13857,8 +14411,97 @@ questionsRouter.post("/:agentId/questions/:id/answer", async (c) => {
13857
14411
  return c.json({ ok: true });
13858
14412
  });
13859
14413
 
14414
+ // ../daemon/src/lib/zip.ts
14415
+ import { crc32 } from "node:zlib";
14416
+ var UTF8_NAMES = 2048;
14417
+ function dosDateTime(epochMs) {
14418
+ const d = new Date(epochMs);
14419
+ const year = Math.max(1980, d.getFullYear());
14420
+ return {
14421
+ time: d.getHours() << 11 | d.getMinutes() << 5 | d.getSeconds() >> 1,
14422
+ date: year - 1980 << 9 | d.getMonth() + 1 << 5 | d.getDate()
14423
+ };
14424
+ }
14425
+ function uniqueNames(names) {
14426
+ const seen = /* @__PURE__ */ new Map();
14427
+ return names.map((name) => {
14428
+ const count = (seen.get(name) ?? 0) + 1;
14429
+ seen.set(name, count);
14430
+ if (count === 1) return name;
14431
+ const dot = name.lastIndexOf(".");
14432
+ return dot > 0 ? `${name.slice(0, dot)} (${count})${name.slice(dot)}` : `${name} (${count})`;
14433
+ });
14434
+ }
14435
+ function localHeader(name, bytes, crc, epochMs) {
14436
+ const { time, date } = dosDateTime(epochMs);
14437
+ const header = Buffer.alloc(30);
14438
+ header.writeUInt32LE(67324752, 0);
14439
+ header.writeUInt16LE(20, 4);
14440
+ header.writeUInt16LE(UTF8_NAMES, 6);
14441
+ header.writeUInt16LE(0, 8);
14442
+ header.writeUInt16LE(time, 10);
14443
+ header.writeUInt16LE(date, 12);
14444
+ header.writeUInt32LE(crc, 14);
14445
+ header.writeUInt32LE(bytes.byteLength, 18);
14446
+ header.writeUInt32LE(bytes.byteLength, 22);
14447
+ header.writeUInt16LE(name.byteLength, 26);
14448
+ header.writeUInt16LE(0, 28);
14449
+ return Buffer.concat([header, name]);
14450
+ }
14451
+ function centralHeader(name, size, crc, epochMs, offset) {
14452
+ const { time, date } = dosDateTime(epochMs);
14453
+ const header = Buffer.alloc(46);
14454
+ header.writeUInt32LE(33639248, 0);
14455
+ header.writeUInt16LE(20, 4);
14456
+ header.writeUInt16LE(20, 6);
14457
+ header.writeUInt16LE(UTF8_NAMES, 8);
14458
+ header.writeUInt16LE(0, 10);
14459
+ header.writeUInt16LE(time, 12);
14460
+ header.writeUInt16LE(date, 14);
14461
+ header.writeUInt32LE(crc, 16);
14462
+ header.writeUInt32LE(size, 20);
14463
+ header.writeUInt32LE(size, 24);
14464
+ header.writeUInt16LE(name.byteLength, 28);
14465
+ header.writeUInt32LE(offset, 42);
14466
+ return Buffer.concat([header, name]);
14467
+ }
14468
+ function zipStream(entries) {
14469
+ const names = uniqueNames(entries.map((entry) => entry.name));
14470
+ const directory = [];
14471
+ let offset = 0;
14472
+ let index = 0;
14473
+ return new ReadableStream({
14474
+ pull(controller) {
14475
+ const entry = entries[index];
14476
+ if (entry) {
14477
+ const name = Buffer.from(names[index] ?? entry.name, "utf8");
14478
+ const bytes = entry.read();
14479
+ const crc = crc32(bytes);
14480
+ const header = localHeader(name, bytes, crc, entry.modifiedAt);
14481
+ directory.push(centralHeader(name, bytes.byteLength, crc, entry.modifiedAt, offset));
14482
+ offset += header.byteLength + bytes.byteLength;
14483
+ index++;
14484
+ controller.enqueue(header);
14485
+ controller.enqueue(bytes);
14486
+ return;
14487
+ }
14488
+ const central = Buffer.concat(directory);
14489
+ const end = Buffer.alloc(22);
14490
+ end.writeUInt32LE(101010256, 0);
14491
+ end.writeUInt16LE(entries.length, 8);
14492
+ end.writeUInt16LE(entries.length, 10);
14493
+ end.writeUInt32LE(central.byteLength, 12);
14494
+ end.writeUInt32LE(offset, 16);
14495
+ controller.enqueue(central);
14496
+ controller.enqueue(end);
14497
+ controller.close();
14498
+ }
14499
+ });
14500
+ }
14501
+
13860
14502
  // ../daemon/src/routes/results.ts
13861
14503
  var resultsRouter = newRouter();
14504
+ var MAX_ARCHIVE_BYTES = 512 * 1024 * 1024;
13862
14505
  resultsRouter.use("*", async (c, next) => {
13863
14506
  c.header("X-Content-Type-Options", "nosniff");
13864
14507
  await next();
@@ -13873,11 +14516,45 @@ resultsRouter.get("/", (c) => {
13873
14516
  list12(getCtx().db, {
13874
14517
  teamId: c.req.query("teamId"),
13875
14518
  agentId: c.req.query("agentId"),
14519
+ sessionId: c.req.query("sessionId"),
13876
14520
  limit,
13877
14521
  offset
13878
14522
  })
13879
14523
  );
13880
14524
  });
14525
+ resultsRouter.get("/archive", (c) => {
14526
+ const db = getCtx().db;
14527
+ const filter = {
14528
+ teamId: c.req.query("teamId"),
14529
+ agentId: c.req.query("agentId"),
14530
+ sessionId: c.req.query("sessionId")
14531
+ };
14532
+ if (!filter.teamId && !filter.agentId && !filter.sessionId) {
14533
+ return c.json({ error: "teamId, agentId or sessionId is required" }, 400);
14534
+ }
14535
+ const selected = listForArchive(db, filter, MAX_ARCHIVE_BYTES);
14536
+ if (selected.truncated) {
14537
+ return c.json(
14538
+ { error: "These files are larger than 512 MiB together. Narrow the selection." },
14539
+ 413
14540
+ );
14541
+ }
14542
+ if (selected.results.length === 0) return c.json({ error: "No saved files match" }, 404);
14543
+ const name = `bazilion-${filter.teamId ?? "files"}.zip`.replace(/[^\w.-]/g, "-");
14544
+ c.header("Content-Type", "application/zip");
14545
+ c.header("Content-Disposition", `attachment; filename="${name}"`);
14546
+ c.header("Content-Security-Policy", "default-src 'none'; sandbox");
14547
+ return c.body(
14548
+ zipStream(
14549
+ selected.results.map((result) => ({
14550
+ name: result.name,
14551
+ modifiedAt: result.createdAt,
14552
+ // Read when the stream reaches the file; a failed integrity check ends the download.
14553
+ read: () => new Uint8Array(read(db, result.id))
14554
+ }))
14555
+ )
14556
+ );
14557
+ });
13881
14558
  resultsRouter.get("/:id", (c) => {
13882
14559
  const result = get17(getCtx().db, c.req.param("id"));
13883
14560
  if (!result) return c.json({ error: "Result not found" }, 404);
@@ -13927,6 +14604,7 @@ resultsRouter.get("/:id/preview", (c) => {
13927
14604
  return c.json({ error: "File content does not match its image type. Use Download." }, 415);
13928
14605
  c.header("Content-Type", text4 ? "text/plain; charset=utf-8" : result.mimeType);
13929
14606
  c.header("Content-Security-Policy", "default-src 'none'; sandbox");
14607
+ c.header("Cache-Control", "private, max-age=3600");
13930
14608
  return c.body(new Uint8Array(bytes));
13931
14609
  } catch {
13932
14610
  return c.json({ error: "Saved file failed integrity verification" }, 409);
@@ -13957,8 +14635,8 @@ shellApprovalsRouter.post("/:id", async (c) => {
13957
14635
 
13958
14636
  // ../daemon/src/routes/skills.ts
13959
14637
  import { mkdtempSync as mkdtempSync4, rmSync as rmSync14, writeFileSync as writeFileSync12 } from "node:fs";
13960
- import { homedir as homedir4, tmpdir as tmpdir4 } from "node:os";
13961
- import { join as join31 } from "node:path";
14638
+ import { homedir as homedir5, tmpdir as tmpdir4 } from "node:os";
14639
+ import { join as join34 } from "node:path";
13962
14640
  var MAX_ZIP_BYTES = 50 * 1024 * 1024;
13963
14641
  var skillsRouter = newRouter();
13964
14642
  skillsRouter.get("/", (c) => {
@@ -14051,8 +14729,8 @@ async function parseImportInput(request) {
14051
14729
  if (!filename.toLowerCase().endsWith(".zip")) {
14052
14730
  throw new Error("uploaded file must be a .zip archive");
14053
14731
  }
14054
- const tmpDir = mkdtempSync4(join31(tmpdir4(), "bazilion-skill-upload-"));
14055
- const zipPath = join31(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
14732
+ const tmpDir = mkdtempSync4(join34(tmpdir4(), "bazilion-skill-upload-"));
14733
+ const zipPath = join34(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
14056
14734
  const buf = Buffer.from(await file.arrayBuffer());
14057
14735
  writeFileSync12(zipPath, buf);
14058
14736
  const forceField = form.get("force");
@@ -14068,7 +14746,7 @@ async function parseImportInput(request) {
14068
14746
  const { source } = body;
14069
14747
  if (typeof source !== "string" || !source) throw new Error("source is required");
14070
14748
  return {
14071
- source: source === "openclaw" ? join31(homedir4(), ".openclaw", "skills") : source,
14749
+ source: source === "openclaw" ? join34(homedir5(), ".openclaw", "skills") : source,
14072
14750
  force: Boolean(body.force),
14073
14751
  tempZipPath: null,
14074
14752
  sourceLabel: source
@@ -14138,7 +14816,7 @@ teamCodingEnvironmentRouter.put("/:id/coding-environment", async (c) => {
14138
14816
  });
14139
14817
 
14140
14818
  // ../daemon/src/routes/team-memory.ts
14141
- import { join as join32 } from "node:path";
14819
+ import { join as join35 } from "node:path";
14142
14820
  var teamMemoryRouter = newRouter();
14143
14821
  teamMemoryRouter.onError((error, c) => {
14144
14822
  const safe = sanitizeNativeModuleError(error, { subject: "Bazilion memory" });
@@ -14146,7 +14824,7 @@ teamMemoryRouter.onError((error, c) => {
14146
14824
  return onRouteError(safe, c);
14147
14825
  });
14148
14826
  async function openMemory(c) {
14149
- const mem = qmdBackend(join32(routeTeam(c).path, "memory"));
14827
+ const mem = qmdBackend(join35(routeTeam(c).path, "memory"));
14150
14828
  await mem.init();
14151
14829
  return mem;
14152
14830
  }
@@ -14212,7 +14890,7 @@ import {
14212
14890
  readSync as readSync3,
14213
14891
  realpathSync as realpathSync7
14214
14892
  } from "node:fs";
14215
- import { join as join33 } from "node:path";
14893
+ import { join as join36 } from "node:path";
14216
14894
  var hash = (value) => createHash6("sha256").update(value).digest("hex");
14217
14895
  var ContextReadError = class extends Error {
14218
14896
  code;
@@ -14250,12 +14928,12 @@ var ContextDirectory = class _ContextDirectory {
14250
14928
  this.parent = parent;
14251
14929
  if (parent) component(registeredPath);
14252
14930
  parent?.assertOpen();
14253
- const canonicalPath = parent ? join33(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
14931
+ const canonicalPath = parent ? join36(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
14254
14932
  this.canonicalPath = canonicalPath;
14255
14933
  let fd;
14256
14934
  try {
14257
14935
  fd = openSync6(
14258
- parent ? join33(parent.path, registeredPath) : canonicalPath,
14936
+ parent ? join36(parent.path, registeredPath) : canonicalPath,
14259
14937
  constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW
14260
14938
  );
14261
14939
  const stat = fstatSync6(fd, { bigint: true });
@@ -14293,7 +14971,7 @@ var ContextDirectory = class _ContextDirectory {
14293
14971
  component(name);
14294
14972
  this.assertOpen();
14295
14973
  try {
14296
- return lstatSync6(join33(this.path, name));
14974
+ return lstatSync6(join36(this.path, name));
14297
14975
  } catch (error) {
14298
14976
  if (error.code === "ENOENT") return null;
14299
14977
  throw new ContextReadError("unreadable");
@@ -14301,7 +14979,7 @@ var ContextDirectory = class _ContextDirectory {
14301
14979
  }
14302
14980
  observe(name) {
14303
14981
  try {
14304
- return lstatSync6(join33(this.path, name), { bigint: true });
14982
+ return lstatSync6(join36(this.path, name), { bigint: true });
14305
14983
  } catch (error) {
14306
14984
  if (error.code === "ENOENT") return null;
14307
14985
  throw new ContextReadError("unreadable");
@@ -14342,7 +15020,7 @@ var ContextDirectory = class _ContextDirectory {
14342
15020
  let fd;
14343
15021
  try {
14344
15022
  fd = openSync6(
14345
- join33(this.path, name),
15023
+ join36(this.path, name),
14346
15024
  constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK
14347
15025
  );
14348
15026
  const before = fstatSync6(fd, { bigint: true });
@@ -14368,7 +15046,7 @@ var ContextDirectory = class _ContextDirectory {
14368
15046
  }
14369
15047
  validate(skipGit = false, names) {
14370
15048
  this.assertOpen();
14371
- const currentPath = this.parent ? join33(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
15049
+ const currentPath = this.parent ? join36(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
14372
15050
  const stat = lstatSync6(currentPath, { bigint: true });
14373
15051
  if (!stat.isDirectory() || identity(stat) !== identity(this.originalIdentity))
14374
15052
  throw new ContextReadError("root_changed");
@@ -14796,7 +15474,7 @@ async function readOrNull(captured, args) {
14796
15474
  import { execFile } from "node:child_process";
14797
15475
  import { mkdirSync as mkdirSync12, mkdtempSync as mkdtempSync5, rmSync as rmSync15, writeFileSync as writeFileSync13 } from "node:fs";
14798
15476
  import { tmpdir as tmpdir5 } from "node:os";
14799
- import { join as join34 } from "node:path";
15477
+ import { join as join37 } from "node:path";
14800
15478
  var INSPECTION_BUDGET_MS = 5e3;
14801
15479
  var METADATA_BUDGET_MS = 2500;
14802
15480
  var METADATA_BYTES = 64 * 1024 * 1024;
@@ -14825,7 +15503,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
14825
15503
  const dir = git.directory("info");
14826
15504
  if (dir.entry("sparse-checkout")) throw new ContextReadError("unsupported_git_metadata");
14827
15505
  }
14828
- const scratch = mkdtempSync5(join34(tmpdir5(), "bazilion-context-git-"));
15506
+ const scratch = mkdtempSync5(join37(tmpdir5(), "bazilion-context-git-"));
14829
15507
  let cleaned = false;
14830
15508
  const cleanup = () => {
14831
15509
  if (cleaned) return;
@@ -14836,7 +15514,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
14836
15514
  if (Date.now() - start2 >= budgetMs) throw new ContextReadError("git_timeout");
14837
15515
  };
14838
15516
  try {
14839
- const rawGit = (args) => new Promise((resolve8, reject2) => {
15517
+ const rawGit = (args) => new Promise((resolve9, reject2) => {
14840
15518
  if (cleaned) throw new ContextReadError("unreadable");
14841
15519
  checkBudget();
14842
15520
  execFile(
@@ -14859,7 +15537,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
14859
15537
  maxBuffer: RUN_MAX_BUFFER,
14860
15538
  encoding: "utf8"
14861
15539
  },
14862
- (error, stdout) => error ? reject2(error) : resolve8(stdout)
15540
+ (error, stdout) => error ? reject2(error) : resolve9(stdout)
14863
15541
  );
14864
15542
  });
14865
15543
  const inspectionArgs = (args) => [
@@ -14886,7 +15564,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
14886
15564
  if (capturedConfig) {
14887
15565
  bytes += capturedConfig.length;
14888
15566
  count++;
14889
- const configPath = join34(scratch, "captured-config");
15567
+ const configPath = join37(scratch, "captured-config");
14890
15568
  writeFileSync13(configPath, capturedConfig, { mode: 384 });
14891
15569
  const config = await rawGit([
14892
15570
  "config",
@@ -14939,8 +15617,8 @@ objectformat = ${value}`
14939
15617
  const exclude = git.directory("info").read("exclude", METADATA_READ);
14940
15618
  if (exclude) {
14941
15619
  bytes += exclude.length;
14942
- mkdirSync12(join34(scratch, "info"), { mode: 448 });
14943
- writeFileSync13(join34(scratch, "info", "exclude"), exclude, { mode: 384 });
15620
+ mkdirSync12(join37(scratch, "info"), { mode: 448 });
15621
+ writeFileSync13(join37(scratch, "info", "exclude"), exclude, { mode: 384 });
14944
15622
  }
14945
15623
  }
14946
15624
  const copy = (source, destination, depth) => {
@@ -14953,13 +15631,13 @@ objectformat = ${value}`
14953
15631
  if (name === "alternates" || name === "http-alternates")
14954
15632
  throw new ContextReadError("unsupported_git_metadata");
14955
15633
  if (entry.isDirectory()) {
14956
- mkdirSync12(join34(destination, name), { mode: 448 });
14957
- copy(source.directory(name), join34(destination, name), depth + 1);
15634
+ mkdirSync12(join37(destination, name), { mode: 448 });
15635
+ copy(source.directory(name), join37(destination, name), depth + 1);
14958
15636
  } else {
14959
15637
  const content = source.read(name, METADATA_BYTES - bytes);
14960
15638
  if (!content) throw new ContextReadError("source_changed");
14961
15639
  bytes += content.length;
14962
- writeFileSync13(join34(destination, name), content, { mode: 384 });
15640
+ writeFileSync13(join37(destination, name), content, { mode: 384 });
14963
15641
  }
14964
15642
  }
14965
15643
  };
@@ -14968,16 +15646,16 @@ objectformat = ${value}`
14968
15646
  if (content) {
14969
15647
  count++;
14970
15648
  bytes += content.length;
14971
- writeFileSync13(join34(scratch, name), content, { mode: 384 });
15649
+ writeFileSync13(join37(scratch, name), content, { mode: 384 });
14972
15650
  }
14973
15651
  }
14974
15652
  for (const name of ["refs", "objects"]) {
14975
- mkdirSync12(join34(scratch, name), { mode: 448 });
14976
- if (git.entry(name)) copy(git.directory(name), join34(scratch, name), 0);
15653
+ mkdirSync12(join37(scratch, name), { mode: 448 });
15654
+ if (git.entry(name)) copy(git.directory(name), join37(scratch, name), 0);
14977
15655
  }
14978
15656
  if (git.list().some((name) => name.startsWith("sharedindex.")))
14979
15657
  throw new ContextReadError("unsupported_git_metadata");
14980
- writeFileSync13(join34(scratch, "config"), `${configLines.join("\n")}
15658
+ writeFileSync13(join37(scratch, "config"), `${configLines.join("\n")}
14981
15659
  `, { mode: 384 });
14982
15660
  const validate2 = () => git.validate();
14983
15661
  validate2();
@@ -14988,6 +15666,77 @@ objectformat = ${value}`
14988
15666
  }
14989
15667
  }
14990
15668
 
15669
+ // ../daemon/src/lib/git-review/authors.ts
15670
+ import { realpathSync as realpathSync8 } from "node:fs";
15671
+ import { isAbsolute as isAbsolute7, join as join38, relative as relative5, resolve as resolve8, sep as sep6 } from "node:path";
15672
+ var FILE_TOOLS = /* @__PURE__ */ new Set(["write", "edit"]);
15673
+ var CONVERSATIONS_PER_AGENT = 5;
15674
+ var SANDBOX_ROOT = "/workspace";
15675
+ function workspacePath(path, cwd, roots) {
15676
+ const absolute = isAbsolute7(path) ? path : resolve8(cwd, path);
15677
+ for (const root of roots) {
15678
+ const inside = relative5(root, absolute);
15679
+ if (inside && !inside.startsWith("..") && !isAbsolute7(inside)) {
15680
+ return inside.split(sep6).join("/");
15681
+ }
15682
+ }
15683
+ return null;
15684
+ }
15685
+ function readChangeAuthors(db, paths, team, changedPaths) {
15686
+ const wanted = new Set(changedPaths);
15687
+ const authors = {};
15688
+ if (wanted.size === 0) return authors;
15689
+ const roots = [team.path, SANDBOX_ROOT];
15690
+ try {
15691
+ roots.push(realpathSync8(team.path));
15692
+ } catch {
15693
+ }
15694
+ const members = list(db, { includeArchived: true }).filter((agent) => agent.teamId === team.id);
15695
+ for (const agent of members) {
15696
+ const directory = join38(paths.agentDir(agent.id), "sessions");
15697
+ const recent = list11(db, agent.id, CONVERSATIONS_PER_AGENT, 0).conversations;
15698
+ for (const conversation of recent) {
15699
+ let lines;
15700
+ try {
15701
+ lines = readSessionFile(directory, conversation.id);
15702
+ } catch {
15703
+ continue;
15704
+ }
15705
+ const cwd = lines[0]?.cwd ?? team.path;
15706
+ const failed = /* @__PURE__ */ new Set();
15707
+ for (const line of lines) {
15708
+ const message = line.message;
15709
+ if (message?.role === "toolResult" && message.isError && message.toolCallId) {
15710
+ failed.add(message.toolCallId);
15711
+ }
15712
+ }
15713
+ for (const line of lines) {
15714
+ if (line.type !== "message" || line.message?.role !== "assistant") continue;
15715
+ if (!Array.isArray(line.message.content)) continue;
15716
+ const at = Date.parse(line.timestamp ?? "");
15717
+ if (!Number.isFinite(at)) continue;
15718
+ for (const part of line.message.content) {
15719
+ if (part?.type !== "toolCall" || !part.name || !FILE_TOOLS.has(part.name)) continue;
15720
+ if (part.id && failed.has(part.id)) continue;
15721
+ const target = part.arguments?.path;
15722
+ if (typeof target !== "string") continue;
15723
+ const path = workspacePath(target, cwd, roots);
15724
+ if (!path || !wanted.has(path)) continue;
15725
+ const known = authors[path];
15726
+ if (known && known.at >= at) continue;
15727
+ authors[path] = {
15728
+ agentId: agent.id,
15729
+ agentName: agent.name,
15730
+ conversationId: conversation.id,
15731
+ at
15732
+ };
15733
+ }
15734
+ }
15735
+ }
15736
+ }
15737
+ return authors;
15738
+ }
15739
+
14991
15740
  // ../daemon/src/lib/git-review/service.ts
14992
15741
  var ReviewUnavailableError = class extends DomainError {
14993
15742
  constructor(code, message) {
@@ -15040,12 +15789,20 @@ async function readTeamReview(db, paths, teamId, input = {}) {
15040
15789
  const listed = await listChanges(captured, base, identity2, input.limits);
15041
15790
  return input.patches ? attachPatches(captured, listed, input.limits, input.patchPath) : listed;
15042
15791
  });
15043
- return { teamId: team.id, changes };
15792
+ if (!input.authors) return { teamId: team.id, changes };
15793
+ const changedPaths = changes.changes.map((change) => change.path);
15794
+ return {
15795
+ teamId: team.id,
15796
+ changes,
15797
+ authors: readChangeAuthors(db, paths, team, changedPaths)
15798
+ };
15044
15799
  }
15045
15800
 
15046
15801
  // ../daemon/src/lib/git-review/feedback.ts
15047
15802
  var FEEDBACK_NOTE_CHARS = 2e3;
15803
+ var FEEDBACK_COMMENTS = 20;
15048
15804
  var EXCERPT_CHARS = 4e3;
15805
+ var EXCERPT_CHARS_EACH = 1600;
15049
15806
  async function queueReviewFeedback(db, paths, teamId, request) {
15050
15807
  const team = requireTeam(db, paths, teamId);
15051
15808
  const agent = get(db, request.agentId);
@@ -15054,31 +15811,77 @@ async function queueReviewFeedback(db, paths, teamId, request) {
15054
15811
  const message = await withRepository(team.path, async (captured) => {
15055
15812
  const base = await resolveComparisonBase(captured, request.base ?? "HEAD");
15056
15813
  const listed = await listChanges(captured, base, await readRepositoryIdentity(captured));
15057
- const withPatch = await attachPatches(captured, listed, void 0, request.path);
15058
- const change = withPatch.changes.find((entry) => entry.path === request.path);
15059
- if (!change) throw new DomainError(400, "That path is not changed since this baseline.");
15060
- return composeFeedbackMessage(change, base, request.note);
15814
+ const changes = /* @__PURE__ */ new Map();
15815
+ for (const { path } of request.comments) {
15816
+ if (changes.has(path)) continue;
15817
+ const withPatch = await attachPatches(captured, listed, void 0, path);
15818
+ const change = withPatch.changes.find((entry) => entry.path === path);
15819
+ if (!change) throw new DomainError(400, "That path is not changed since this baseline.");
15820
+ changes.set(path, change);
15821
+ }
15822
+ return composeFeedbackMessage(request, changes, base);
15061
15823
  });
15062
15824
  const item = await enqueueUserInput(agent.id, { message, attachments: [] }, { db, paths });
15063
15825
  return { message, item };
15064
15826
  }
15065
- function composeFeedbackMessage(change, base, note) {
15827
+ function hunkForLine(patch, line) {
15828
+ const lines = patch.split("\n");
15829
+ const starts = [];
15830
+ lines.forEach((text4, index) => {
15831
+ if (text4.startsWith("@@")) starts.push(index);
15832
+ });
15833
+ for (const [position, start2] of starts.entries()) {
15834
+ const header = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(lines[start2] ?? "");
15835
+ if (!header) continue;
15836
+ const first = Number(header[1]);
15837
+ const count = header[2] === void 0 ? 1 : Number(header[2]);
15838
+ if (line < first || line >= first + Math.max(count, 1)) continue;
15839
+ return lines.slice(start2, starts[position + 1] ?? lines.length).join("\n");
15840
+ }
15841
+ return null;
15842
+ }
15843
+ function place(comment, change) {
15066
15844
  const file = change.previousPath ? `${change.previousPath} -> ${change.path}` : change.path;
15067
- const lines = [
15068
- `Review feedback on ${file} (${change.status} since ${base.requestedRef}, ${base.resolvedOid.slice(0, 12)}).`
15069
- ];
15070
- const trimmed = note?.trim();
15071
- if (trimmed) lines.push("", trimmed.slice(0, FEEDBACK_NOTE_CHARS));
15845
+ return comment.line === void 0 ? file : `${file}, line ${comment.line}`;
15846
+ }
15847
+ function commentBody(comment, change, room) {
15848
+ const lines = [];
15849
+ const note = comment.note?.trim();
15850
+ if (note) lines.push("", note.slice(0, FEEDBACK_NOTE_CHARS));
15072
15851
  if (change.patch === null) {
15073
15852
  lines.push("", `No diff text (${change.contentOmitted ?? "unavailable"}).`);
15074
- } else {
15075
- const excerpt = change.patch.slice(0, EXCERPT_CHARS);
15076
- const fence = "`".repeat(
15077
- Math.max(3, ...(excerpt.match(/`+/g) ?? []).map((run) => run.length + 1))
15078
- );
15079
- lines.push("", `${fence}diff`, excerpt.trimEnd(), fence);
15080
- if (change.patch.length > EXCERPT_CHARS) lines.push("(diff excerpt truncated)");
15853
+ return lines;
15081
15854
  }
15855
+ const source = comment.line === void 0 ? change.patch : hunkForLine(change.patch, comment.line) ?? change.patch;
15856
+ const excerpt = source.slice(0, room);
15857
+ const fence = "`".repeat(
15858
+ Math.max(3, ...(excerpt.match(/`+/g) ?? []).map((run) => run.length + 1))
15859
+ );
15860
+ lines.push("", `${fence}diff`, excerpt.trimEnd(), fence);
15861
+ if (source.length > room) lines.push("(diff excerpt truncated)");
15862
+ return lines;
15863
+ }
15864
+ function composeFeedbackMessage(request, changes, base) {
15865
+ const since = `since ${base.requestedRef}, ${base.resolvedOid.slice(0, 12)}`;
15866
+ const overall = request.note?.trim();
15867
+ const [only] = request.comments;
15868
+ if (request.comments.length === 1 && only && !overall) {
15869
+ const change = changes.get(only.path);
15870
+ return [
15871
+ `Review feedback on ${place(only, change)} (${change.status} ${since}).`,
15872
+ ...commentBody(only, change, EXCERPT_CHARS)
15873
+ ].join("\n");
15874
+ }
15875
+ const lines = [`Review feedback: ${request.comments.length} comments (${since}).`];
15876
+ if (overall) lines.push("", overall.slice(0, FEEDBACK_NOTE_CHARS));
15877
+ request.comments.forEach((comment, index) => {
15878
+ const change = changes.get(comment.path);
15879
+ lines.push(
15880
+ "",
15881
+ `${index + 1}. ${place(comment, change)} (${change.status})`,
15882
+ ...commentBody(comment, change, EXCERPT_CHARS_EACH)
15883
+ );
15884
+ });
15082
15885
  return lines.join("\n");
15083
15886
  }
15084
15887
 
@@ -15094,25 +15897,39 @@ teamReviewRouter.get("/:id/review", async (c) => {
15094
15897
  const review = await readTeamReview(db, paths, c.req.param("id"), {
15095
15898
  ...base === void 0 ? {} : { base },
15096
15899
  patches: c.req.query("patches") === "1",
15097
- ...patchPath === void 0 ? {} : { patchPath }
15900
+ ...patchPath === void 0 ? {} : { patchPath },
15901
+ authors: c.req.query("authors") === "1"
15098
15902
  });
15099
15903
  return c.json(review);
15100
15904
  });
15905
+ var validNote = (note) => note === void 0 || typeof note === "string" && note.length <= FEEDBACK_NOTE_CHARS;
15906
+ function validComment(value) {
15907
+ const comment = value ?? {};
15908
+ 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);
15909
+ }
15101
15910
  teamReviewRouter.post("/:id/review/feedback", async (c) => {
15102
15911
  const body = await jsonBody(c);
15103
- if (!body || typeof body.path !== "string" || body.path.length === 0 || body.path.length > 4096 || typeof body.agentId !== "string" || body.agentId.length === 0) {
15104
- return c.json({ error: "path and agentId are required" }, 400);
15912
+ if (!body || typeof body.agentId !== "string" || body.agentId.length === 0) {
15913
+ return c.json({ error: "agentId is required" }, 400);
15105
15914
  }
15106
- if (body.note !== void 0 && (typeof body.note !== "string" || body.note.length > FEEDBACK_NOTE_CHARS)) {
15107
- return c.json({ error: "Invalid feedback note" }, 400);
15915
+ if (!Array.isArray(body.comments) || body.comments.length === 0 || body.comments.length > FEEDBACK_COMMENTS || !body.comments.every(validComment)) {
15916
+ return c.json(
15917
+ { error: `comments must be 1 to ${FEEDBACK_COMMENTS} entries of { path, line?, note? }` },
15918
+ 400
15919
+ );
15108
15920
  }
15921
+ if (!validNote(body.note)) return c.json({ error: "Invalid feedback note" }, 400);
15109
15922
  if (body.base !== void 0 && typeof body.base !== "string") {
15110
15923
  return c.json({ error: "Invalid comparison base" }, 400);
15111
15924
  }
15112
15925
  const { db, paths } = getCtx();
15113
15926
  const queued = await queueReviewFeedback(db, paths, c.req.param("id"), {
15114
- path: body.path,
15115
15927
  agentId: body.agentId,
15928
+ comments: body.comments.map((comment) => ({
15929
+ path: comment.path,
15930
+ ...comment.line === void 0 ? {} : { line: comment.line },
15931
+ ...comment.note === void 0 ? {} : { note: comment.note }
15932
+ })),
15116
15933
  ...body.note === void 0 ? {} : { note: body.note },
15117
15934
  ...body.base === void 0 ? {} : { base: body.base }
15118
15935
  });
@@ -17160,11 +17977,13 @@ function createApp() {
17160
17977
  app2.route("/api/teams", teamMemoryRouter);
17161
17978
  app2.route("/api/teams", teamPolicyRouter);
17162
17979
  app2.route("/api/teams", teamReviewRouter);
17980
+ app2.route("/api/teams", teamMessagesRouter);
17163
17981
  app2.route("/api/teams", teamCodingEnvironmentRouter);
17164
17982
  app2.route("/api/teams", teamTelegramRouter);
17165
17983
  app2.route("/api/team-templates", teamTemplatesRouter);
17166
17984
  app2.route("/api/results", resultsRouter);
17167
17985
  app2.route("/api/attention", attentionRouter);
17986
+ app2.route("/api/activity", activityRouter);
17168
17987
  app2.route("/api/notifications", notificationsRouter);
17169
17988
  app2.route("/api/shell-approvals", shellApprovalsRouter);
17170
17989
  app2.route("/api/profiles", profilesRouter);
@@ -17180,6 +17999,7 @@ function createApp() {
17180
17999
  }
17181
18000
 
17182
18001
  // ../daemon/src/index.ts
18002
+ init_install();
17183
18003
  init_resources();
17184
18004
 
17185
18005
  // ../daemon/src/lib/review-provider.ts
@@ -17794,6 +18614,9 @@ var server2 = serve({ fetch: app.fetch, hostname: host2, port }, (info) => {
17794
18614
  maybeStartTelegramBot(db, authToken).catch((err) => {
17795
18615
  console.error("telegram: background start failed:", err instanceof Error ? err.message : err);
17796
18616
  });
18617
+ const env = mergeSecretsIntoEnv(db, authToken);
18618
+ const browser = resolveBrowserConfig(env);
18619
+ if (isBrowserEnabled(env) && !browser.attach) prepareBrowser(browser.executablePath);
17797
18620
  });
17798
18621
  var shutdown = (signal) => {
17799
18622
  if (shuttingDown) return;