bazilion 0.54.0 → 0.56.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 (188) hide show
  1. package/dist/cli.js +201 -41
  2. package/dist/cli.js.map +1 -1
  3. package/dist/daemon.js +1561 -522
  4. package/dist/daemon.js.map +1 -1
  5. package/dist/web/client/assets/AddProviderDialog-DZ9mXFdq.js +1 -0
  6. package/dist/web/client/assets/AgentTemplateParts-BfG3a-ri.js +1 -0
  7. package/dist/web/client/assets/{Button-UiegBKOK.js → Button-CoKQRO-s.js} +1 -1
  8. package/dist/web/client/assets/ConfigPage-Ch-DSJUO.js +1 -0
  9. package/dist/web/client/assets/ConfirmDialog-B_jXAPmh.js +1 -0
  10. package/dist/web/client/assets/ConnectionsView-D1Liebtf.js +1 -0
  11. package/dist/web/client/assets/ManagePage-kd7iWYEL.js +1 -0
  12. package/dist/web/client/assets/SectionTabs-Dc0bNn-J.js +1 -0
  13. package/dist/web/client/assets/{Segmented-MYKKTuZO.js → Segmented-iylzLwE6.js} +1 -1
  14. package/dist/web/client/assets/SkillsParts-C5T7sYDA.js +1 -0
  15. package/dist/web/client/assets/{SpawnTeamModal-DG5UbJNK.js → SpawnTeamModal-DatFF4f_.js} +1 -1
  16. package/dist/web/client/assets/{TeamForm-DGlxWv4e.js → TeamForm-l-N_PYeE.js} +1 -1
  17. package/dist/web/client/assets/TeamThread-BWmIQiAh.js +1 -0
  18. package/dist/web/client/assets/{UnsavedChangesGuard-BmdwLH99.js → UnsavedChangesGuard-vQBdMl8h.js} +1 -1
  19. package/dist/web/client/assets/_id-C6SADaiD.js +1 -0
  20. package/dist/web/client/assets/_id-CC9r0qsr.js +1 -0
  21. package/dist/web/client/assets/{access-C8d8vaQ6.js → access-BbQFbTPh.js} +1 -1
  22. package/dist/web/client/assets/{agent-actions-BgE9fKHH.js → agent-actions-B-9KIwn6.js} +1 -1
  23. package/dist/web/client/assets/agents-BXwzmHu8.js +1 -0
  24. package/dist/web/client/assets/agents-BtETzVIY.js +1 -0
  25. package/dist/web/client/assets/arrow-right-BqqfPqVi.js +1 -0
  26. package/dist/web/client/assets/attention-BMrZJ9ui.js +1 -0
  27. package/dist/web/client/assets/{bot-Bb--PFVU.js → bot-BHky7KAX.js} +1 -1
  28. package/dist/web/client/assets/chart-column-DTsDbzL0.js +1 -0
  29. package/dist/web/client/assets/chevron-right-D1shxvdo.js +1 -0
  30. package/dist/web/client/assets/config-B2ZDYo52.js +1 -0
  31. package/dist/web/client/assets/createLucideIcon-CZHSSDYA.js +1 -0
  32. package/dist/web/client/assets/{download-C4t9l5wR.js → download-Dr0PgyMr.js} +1 -1
  33. package/dist/web/client/assets/es2015-D1pnOGPG.js +41 -0
  34. package/dist/web/client/assets/{file-text-DzbjpYrV.js → file-text-D6OTHixJ.js} +1 -1
  35. package/dist/web/client/assets/{images-DSYgPKM7.js → images-BULrW-FC.js} +1 -1
  36. package/dist/web/client/assets/index-B-N6NIX4.js +14 -0
  37. package/dist/web/client/assets/{key-round-BpK4-E3T.js → key-round-DmSZN0Kq.js} +1 -1
  38. package/dist/web/client/assets/{list-checks-JNXcmws9.js → list-checks-DdTdAQXS.js} +1 -1
  39. package/dist/web/client/assets/login-DM3q-V4R.js +1 -0
  40. package/dist/web/client/assets/{manage-SRGSx8n2.js → manage-R57MUzsY.js} +1 -1
  41. package/dist/web/client/assets/{mcp-BUWu4TvS.js → mcp-CSHrVH1t.js} +1 -1
  42. package/dist/web/client/assets/{message-square-DM2MP9vF.js → message-square-B_pULba_.js} +1 -1
  43. package/dist/web/client/assets/{network-BJ4iPjQO.js → network-BqmVqC4_.js} +1 -1
  44. package/dist/web/client/assets/parts-68zf8Fgw.js +1 -0
  45. package/dist/web/client/assets/plus-CEKaHPBw.js +1 -0
  46. package/dist/web/client/assets/preload-helper-CZOd_z6l.js +1 -0
  47. package/dist/web/client/assets/routes-DOoeKVwr.js +85 -0
  48. package/dist/web/client/assets/skills-CPZftp9O.js +1 -0
  49. package/dist/web/client/assets/{square-terminal-Dmm6cV-G.js → square-terminal-CYfGBHPC.js} +1 -1
  50. package/dist/web/client/assets/{style-CA2GAk9b.js → style-Bm9QsFpy.js} +1 -1
  51. package/dist/web/client/assets/styles-B-kTTvCo.css +2 -0
  52. package/dist/web/client/assets/{system-zQ0NnQML.js → system-Dd2P9eqE.js} +1 -1
  53. package/dist/web/client/assets/teams-7FEpSZg1.js +1 -0
  54. package/dist/web/client/assets/teams-ClirFbDV.js +1 -0
  55. package/dist/web/client/assets/telegram-BJnT5THs.js +1 -0
  56. package/dist/web/client/assets/tools-DqNXLMpc.js +1 -0
  57. package/dist/web/client/assets/usage-BC_TStVj.js +1 -0
  58. package/dist/web/client/assets/{use-resource-CQaIZbpy.js → use-resource-Bn0Sx7r6.js} +1 -1
  59. package/dist/web/client/assets/{users-round-BJrym3FG.js → users-round-cxQ5HF-C.js} +1 -1
  60. package/dist/web/client/assets/welcome-g8wtn_or.js +1 -0
  61. package/dist/web/client/assets/{wrench-GbE1M1RJ.js → wrench-BLEJjETg.js} +1 -1
  62. package/dist/web/server/assets/{AddProviderDialog-Nc5mc_P6.js → AddProviderDialog-DtkjBMv4.js} +5 -2
  63. package/dist/web/server/assets/AgentAvatar-8gTAy_tP.js +37 -0
  64. package/dist/web/server/assets/{AgentTemplateParts-DZK_r3nQ.js → AgentTemplateParts-CxWyovvM.js} +6 -2
  65. package/dist/web/server/assets/Button-Dsnw22OF.js +17 -0
  66. package/dist/web/server/assets/{ConfigPage-CxzL-gTm.js → ConfigPage-usZi48Zr.js} +2 -2
  67. package/dist/web/server/assets/{ConfirmDialog-4xeCXKHe.js → ConfirmDialog-DAcSBHkT.js} +3 -1
  68. package/dist/web/server/assets/{ConnectionsView-B02FjNsM.js → ConnectionsView-Dy6uYSRI.js} +9 -7
  69. package/dist/web/server/assets/Dialog-DTeF-nOZ.js +85 -0
  70. package/dist/web/server/assets/{ManagePage-BfCWE8Lj.js → ManagePage-Dy1EdovO.js} +2 -2
  71. package/dist/web/server/assets/{SectionTabs-CWQ5orUW.js → SectionTabs-BVrMn76H.js} +2 -1
  72. package/dist/web/server/assets/{SkillsParts-D58l8voo.js → SkillsParts-Cw05b3al.js} +6 -2
  73. package/dist/web/server/assets/SpawnDialog-BAE8W91z.js +125 -0
  74. package/dist/web/server/assets/{SpawnTeamModal-RjzAeX_Q.js → SpawnTeamModal-CgBY0HuN.js} +6 -2
  75. package/dist/web/server/assets/{TeamForm-DdOgIMiV.js → TeamForm-JyO5xJXX.js} +6 -2
  76. package/dist/web/server/assets/{TeamThread-D-PvO3fu.js → TeamThread-5o48EbXL.js} +52 -4
  77. package/dist/web/server/assets/{UnsavedChangesGuard-Bb5frygQ.js → UnsavedChangesGuard-CJQGu45L.js} +1 -1
  78. package/dist/web/server/assets/{_id-C1_l6oSR.js → _id-BE_RSvuN.js} +14 -9
  79. package/dist/web/server/assets/{_id-CHvYQhWt.js → _id-BNvm89oJ.js} +2 -2
  80. package/dist/web/server/assets/{_id-De3Bm0SG.js → _id-BW6sVrvw.js} +1 -1
  81. package/dist/web/server/assets/{_id-BPjVkcNb.js → _id-BfjTS4JO.js} +15 -9
  82. package/dist/web/server/assets/{_id-BKzOw78O.js → _id-BpumuCYL.js} +1 -1
  83. package/dist/web/server/assets/{_id-BUfy-GwH.js → _id-C54t_nX6.js} +2 -2
  84. package/dist/web/server/assets/_tanstack-start-manifest_v-BPwQX_5b.js +275 -0
  85. package/dist/web/server/assets/{access-CNfvQ3NB.js → access-6FWih7nC.js} +7 -4
  86. package/dist/web/server/assets/{access-WWspT0v4.js → access-BhAMfi7U.js} +1 -1
  87. package/dist/web/server/assets/{access-Cm_izIIC.js → access-DEyq3uP_.js} +2 -2
  88. package/dist/web/server/assets/activity-Czfq-5_F.js +471 -0
  89. package/dist/web/server/assets/{agent-actions-COnfW5AU.js → agent-actions-ChH7Mne4.js} +1 -1
  90. package/dist/web/server/assets/{agents-CRtMfKqX.js → agents-3hBjrd8B.js} +1 -1
  91. package/dist/web/server/assets/{agents-NOkh61dV.js → agents-BXuglv4G.js} +12 -6
  92. package/dist/web/server/assets/{agents-C7UmTjfO.js → agents-DhenbitX.js} +2 -2
  93. package/dist/web/server/assets/{agents-D0hfGIMK.js → agents-KJcDMj0Y.js} +9 -6
  94. package/dist/web/server/assets/{agents-DzpqlIuJ.js → agents-ncyhVx-T.js} +2 -2
  95. package/dist/web/server/assets/{agents-DQowl6Ly.js → agents-rTDlRZa5.js} +1 -1
  96. package/dist/web/server/assets/{attention-Cx9ZWPOO.js → attention-CDdOCOio.js} +3 -2
  97. package/dist/web/server/assets/{attention-CRvxt22X.js → attention-DM__BzWY.js} +24 -9
  98. package/dist/web/server/assets/{attention-CgWhXjX7.js → attention-X0U6ZmiA.js} +2 -1
  99. package/dist/web/server/assets/{auth-dJnrFW6y.js → auth-BexhV8Yq.js} +1 -1
  100. package/dist/web/server/assets/{config-B5CS8juO.js → config-Cld8Q8N7.js} +2 -2
  101. package/dist/web/server/assets/{config-X7qWbbpH.js → config-Cx5ri2DL2.js} +1 -1
  102. package/dist/web/server/assets/{config-D117117T.js → config-DpgYAXQ3.js} +9 -6
  103. package/dist/web/server/assets/createSsrRpc-6LHNEsSK.js +16 -0
  104. package/dist/web/server/assets/{daemon-client-B_ZRIIrT.js → daemon-client-RxAllljf.js} +1 -1
  105. package/dist/web/server/assets/form-BEjeiSy3.js +416 -0
  106. package/dist/web/server/assets/live-DbJeq6KP.js +263 -0
  107. package/dist/web/server/assets/{login-va4EtvA8.js → login-BJdJ219n.js} +1 -1
  108. package/dist/web/server/assets/{login-IF0Gbsuq.js → login-C4lL4AxI.js} +2 -2
  109. package/dist/web/server/assets/{manage-Ce6cI4eW.js → manage-C6ucNYZW.js} +2 -1
  110. package/dist/web/server/assets/{mcp-C96PBxpb.js → mcp-BXnWQOwM.js} +7 -4
  111. package/dist/web/server/assets/{mcp-C97uAZe1.js → mcp-C8VLspco.js} +1 -1
  112. package/dist/web/server/assets/{mcp-Bm9U6x7N.js → mcp-DwCzj7eO.js} +2 -2
  113. package/dist/web/server/assets/open-groups-BMGYUTtY.js +12 -0
  114. package/dist/web/server/assets/{page-title-CwcbXMhx.js → page-title-PTpFHXWo.js} +6 -3
  115. package/dist/web/server/assets/parts-k9M-atPa.js +436 -0
  116. package/dist/web/server/assets/{router-8Iq19GOz.js → router-BttfLktO.js} +354 -114
  117. package/dist/web/server/assets/{routes-Kwam6JmS.js → routes-A7UcreVX.js} +9 -6
  118. package/dist/web/server/assets/{routes-BLo-fWbQ.js → routes-B9jw-MJ8.js} +1286 -331
  119. package/dist/web/server/assets/{routes-BXvYYFrN.js → routes-BX2FV8rS.js} +3 -3
  120. package/dist/web/server/assets/{skills-DSezIdDc.js → skills-BVAH93cd.js} +8 -6
  121. package/dist/web/server/assets/{skills-DWzlT_hC.js → skills-Cd5Cfdaz.js} +1 -1
  122. package/dist/web/server/assets/{skills-BqCnA-74.js → skills-y3GsyKce.js} +2 -2
  123. package/dist/web/server/assets/src-vrZVrV9u.js +103 -0
  124. package/dist/web/server/assets/{start-DhW7sy23.js → start-Dl8gQ-95.js} +1 -1
  125. package/dist/web/server/assets/{style-C2hIPY_Y.js → style-BQ3H9I7Y.js} +1 -1
  126. package/dist/web/server/assets/{system-CcLCmkIC.js → system-BJPKqM6b.js} +2 -2
  127. package/dist/web/server/assets/{system-E0VePdzO.js → system-C7mejQSc.js} +3 -3
  128. package/dist/web/server/assets/{system-D3th6n2E.js → system-LsLcuVzY.js} +1 -1
  129. package/dist/web/server/assets/{teams-CdCmBJIj.js → teams-B6gbflsZ.js} +10 -6
  130. package/dist/web/server/assets/{teams-CQVV18D3.js → teams-C7kXMNgc.js} +10 -6
  131. package/dist/web/server/assets/{teams-BopOP4x7.js → teams-CPXoTggb.js} +1 -1
  132. package/dist/web/server/assets/{teams-70u1XQTr.js → teams-CeLLd2Mf.js} +1 -1
  133. package/dist/web/server/assets/{teams-DScFp8mK.js → teams-CiX8LUQo.js} +2 -2
  134. package/dist/web/server/assets/{teams-DxA-vnzY.js → teams-D-XdIkCr.js} +2 -2
  135. package/dist/web/server/assets/{telegram-CGol0CKX2.js → telegram-D7TW3LNZ.js} +1 -1
  136. package/dist/web/server/assets/{telegram-DJ8s_91Y.js → telegram-D8_V7_sW.js} +286 -272
  137. package/dist/web/server/assets/{telegram-DR7xijeS.js → telegram-DA2dwLID.js} +2 -2
  138. package/dist/web/server/assets/{tools-V6kezUpL.js → tools-CckcG9Jl.js} +5 -3
  139. package/dist/web/server/assets/{tools-CsH9DI-4.js → tools-CluiJywK.js} +2 -2
  140. package/dist/web/server/assets/{tools-C-wwWjLI.js → tools-D1BBVkRh.js} +1 -1
  141. package/dist/web/server/assets/usage-CrYyvPgf.js +46 -0
  142. package/dist/web/server/assets/usage-PNNb3pPj.js +465 -0
  143. package/dist/web/server/assets/{use-resource-CjcJwn7F.js → use-resource-BUA9qGGY.js} +1 -1
  144. package/dist/web/server/assets/{welcome-CxXMI4HI.js → welcome-CUTYf8UG.js} +1 -1
  145. package/dist/web/server/assets/{welcome-Ya8TkL4v.js → welcome-CYhh3iUU.js} +8 -6
  146. package/dist/web/server/assets/{welcome-BpmcD-ia.js → welcome-CwzLt6Rp.js} +2 -2
  147. package/dist/web/server/assets/workspace-0XPILV1W.js +82 -0
  148. package/dist/web/server/server.js +20 -20
  149. package/dist/web-server.js +4 -0
  150. package/dist/web-server.js.map +1 -1
  151. package/dist/worker.js +40 -15
  152. package/dist/worker.js.map +1 -1
  153. package/package.json +4 -4
  154. package/dist/web/client/assets/AddProviderDialog-CkwSq3C7.js +0 -1
  155. package/dist/web/client/assets/AgentTemplateParts-CEn_4qVs.js +0 -1
  156. package/dist/web/client/assets/ConfigPage-CUbHBhzx.js +0 -1
  157. package/dist/web/client/assets/ConfirmDialog-VqBOFZEp.js +0 -1
  158. package/dist/web/client/assets/ConnectionsView-ByARMcWP.js +0 -1
  159. package/dist/web/client/assets/ManagePage-BJWZd1ts.js +0 -1
  160. package/dist/web/client/assets/SectionTabs-ViZKm3-B.js +0 -1
  161. package/dist/web/client/assets/SkillsParts-UvNK5SYP.js +0 -1
  162. package/dist/web/client/assets/TeamThread-mkwODO0S.js +0 -1
  163. package/dist/web/client/assets/_id-CvcxNmBH.js +0 -1
  164. package/dist/web/client/assets/_id-UyBk7gRl.js +0 -1
  165. package/dist/web/client/assets/agents-CgtzqBpD.js +0 -1
  166. package/dist/web/client/assets/agents-D7W4BT8r.js +0 -1
  167. package/dist/web/client/assets/arrow-right-D0HKRb7U.js +0 -1
  168. package/dist/web/client/assets/attention-D9mQWoKt.js +0 -1
  169. package/dist/web/client/assets/chevron-right-bs0TUSl2.js +0 -1
  170. package/dist/web/client/assets/config-Dw6GWf38.js +0 -1
  171. package/dist/web/client/assets/createLucideIcon-DkniuEtD.js +0 -1
  172. package/dist/web/client/assets/index-YW0gXPfk.js +0 -14
  173. package/dist/web/client/assets/login-DcQJk5-U.js +0 -1
  174. package/dist/web/client/assets/parts-LZxl9Gvc.js +0 -41
  175. package/dist/web/client/assets/plus-CLGNN5QX.js +0 -1
  176. package/dist/web/client/assets/routes-BxIIyGho.js +0 -85
  177. package/dist/web/client/assets/skills-C7DzIwFJ.js +0 -1
  178. package/dist/web/client/assets/styles-C3CDSGAr.css +0 -2
  179. package/dist/web/client/assets/teams-BEIJHObN.js +0 -1
  180. package/dist/web/client/assets/teams-DlOc7Ods.js +0 -1
  181. package/dist/web/client/assets/telegram-DKHq5DpE.js +0 -1
  182. package/dist/web/client/assets/tools-BKIpLaiC.js +0 -1
  183. package/dist/web/client/assets/welcome-CyS4Hrd-.js +0 -1
  184. package/dist/web/server/assets/Rail-3gbidhyv.js +0 -605
  185. package/dist/web/server/assets/SpawnDialog-MJWwppgC.js +0 -1648
  186. package/dist/web/server/assets/_tanstack-start-manifest_v-CR3jm1nY.js +0 -256
  187. package/dist/web/server/assets/createSsrRpc-CwTd0zrB.js +0 -72
  188. package/dist/web/server/assets/public-origin-BpDkdS5Q.js +0 -34
package/dist/daemon.js CHANGED
@@ -1019,11 +1019,11 @@ function runInstaller() {
1019
1019
  }
1020
1020
  );
1021
1021
  let output = "";
1022
- const keep = (chunk) => {
1022
+ const keep2 = (chunk) => {
1023
1023
  output = (output + chunk.toString("utf8")).slice(-2e3);
1024
1024
  };
1025
- child.stdout.on("data", keep);
1026
- child.stderr.on("data", keep);
1025
+ child.stdout.on("data", keep2);
1026
+ child.stderr.on("data", keep2);
1027
1027
  child.once("error", reject2);
1028
1028
  child.once("exit", (code, signal) => {
1029
1029
  if (code === 0) resolve9();
@@ -1902,6 +1902,35 @@ function isLoopbackHost(hostname) {
1902
1902
  return ["127.0.0.1", "localhost", "[::1]", "::1"].includes(hostname);
1903
1903
  }
1904
1904
 
1905
+ // ../../packages/api-types/src/results.ts
1906
+ var TEXT_PREVIEW_MAX_BYTES = 256 * 1024;
1907
+ var TEXT_TYPES = /* @__PURE__ */ new Set([
1908
+ "application/json",
1909
+ "application/ld+json",
1910
+ "application/xml",
1911
+ "application/yaml",
1912
+ "application/x-yaml",
1913
+ "application/toml",
1914
+ "application/javascript",
1915
+ "application/x-sh",
1916
+ "application/sql",
1917
+ "application/x-ndjson"
1918
+ ]);
1919
+ var TEXT_EXTENSIONS = new Set(
1920
+ "txt md markdown csv tsv json jsonl ndjson yaml yml toml ini cfg conf log xml css scss js mjs cjs jsx ts tsx py rb go rs java kt swift c h cc cpp hpp cs php sh bash zsh fish ps1 sql r lua pl tex diff patch vue svelte graphql proto dockerfile makefile".split(" ")
1921
+ );
1922
+ var ACTIVE_TYPES = /* @__PURE__ */ new Set(["text/html", "application/xhtml+xml", "image/svg+xml"]);
1923
+ function isTextPreview(result) {
1924
+ if (result.byteLength > TEXT_PREVIEW_MAX_BYTES) return false;
1925
+ const type = result.mimeType.toLowerCase();
1926
+ if (ACTIVE_TYPES.has(type)) return false;
1927
+ if (type.startsWith("text/") || TEXT_TYPES.has(type) || /\+(json|xml)$/.test(type)) return true;
1928
+ if (type !== "application/octet-stream") return false;
1929
+ const name = result.name.toLowerCase();
1930
+ const extension = name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : name;
1931
+ return TEXT_EXTENSIONS.has(extension);
1932
+ }
1933
+
1905
1934
  // ../daemon/src/index.ts
1906
1935
  import { serve } from "@hono/node-server";
1907
1936
 
@@ -2689,6 +2718,25 @@ function unarchiveAgent(db, id) {
2689
2718
  unarchive(db, agent.id);
2690
2719
  }
2691
2720
 
2721
+ // ../daemon/src/core/attention.ts
2722
+ import { createHash } from "node:crypto";
2723
+
2724
+ // ../daemon/src/core/provider-failure-kind.ts
2725
+ var UNREACHABLE = /connection error|econnrefused|enotfound|ehostunreach|enetunreach|etimedout|econnreset|fetch failed|bad port|socket hang up|getaddrinfo|und_err|request aborted|request timed out/;
2726
+ var CREDENTIALS = /invalid.{0,12}api.?key|incorrect api key|invalid x-api-key|invalid_api_key|authentication_error|unauthorized|invalid.{0,12}(access )?token/;
2727
+ var MODEL = /model_not_found|no models loaded|not found, try pulling|not_found_error.{0,40}\bmodel\b|\bmodel\b.{0,80}(not found|does not exist|do not have access|not available|is not supported)|(must be verified|not have access|no access).{0,60}\bmodel\b/;
2728
+ var LIMIT = /insufficient|quota|rate.?limit|billing|\bcredits?\b|overloaded/;
2729
+ function classifyProviderFailure(message, timedOut = false) {
2730
+ const text4 = message.toLowerCase();
2731
+ const status2 = /^(\d{3})\b/.exec(text4)?.[1];
2732
+ if (timedOut || UNREACHABLE.test(text4)) return "unreachable";
2733
+ if (status2 === "401" || CREDENTIALS.test(text4)) return "credentials";
2734
+ if (MODEL.test(text4)) return "model";
2735
+ if (status2 === "402" || status2 === "429" || LIMIT.test(text4)) return "limit";
2736
+ if (status2 === "403") return "credentials";
2737
+ return "other";
2738
+ }
2739
+
2692
2740
  // ../daemon/src/core/repos/user-queue.ts
2693
2741
  import { randomUUID as randomUUID4 } from "node:crypto";
2694
2742
  var QUEUE_LIMITS = Object.freeze({
@@ -2944,13 +2992,44 @@ function agentsWithPending(db) {
2944
2992
  ).all().map((row) => row.agentId);
2945
2993
  }
2946
2994
 
2995
+ // ../daemon/src/core/turn-failures.ts
2996
+ var KEY = /* @__PURE__ */ Symbol.for("bazilion.turn-failures");
2997
+ var MAX_KEPT = 200;
2998
+ var KEPT_MS = 14 * 864e5;
2999
+ function store() {
3000
+ const holder = globalThis;
3001
+ holder[KEY] ??= [];
3002
+ return holder[KEY];
3003
+ }
3004
+ function rememberTurnFailure(failure) {
3005
+ const kept = store();
3006
+ const at = kept.findIndex((entry) => entry.id === failure.id);
3007
+ const first = at >= 0 ? kept[at] : void 0;
3008
+ if (at >= 0) kept.splice(at, 1);
3009
+ kept.push(first ? { ...failure, at: first.at } : failure);
3010
+ const since = failure.at - KEPT_MS;
3011
+ const fresh = kept.filter((entry) => entry.at >= since || entry.id === failure.id).slice(-MAX_KEPT);
3012
+ kept.splice(0, kept.length, ...fresh);
3013
+ }
3014
+ function forgetTurnFailure(id) {
3015
+ const kept = store();
3016
+ const at = kept.findIndex((entry) => entry.id === id);
3017
+ if (at < 0) return false;
3018
+ kept.splice(at, 1);
3019
+ return true;
3020
+ }
3021
+ function rememberedTurnFailures() {
3022
+ return store();
3023
+ }
3024
+
2947
3025
  // ../daemon/src/core/attention.ts
2948
3026
  var RECORDED_ATTENTION_KINDS = [
2949
3027
  "lesson_proposal",
2950
3028
  "review_failure",
2951
3029
  "trigger_failure",
2952
3030
  "agent_loop_break",
2953
- "queue_interrupted"
3031
+ "queue_interrupted",
3032
+ "turn_failure"
2954
3033
  ];
2955
3034
  var WAITING_ATTENTION_KINDS = [
2956
3035
  "agent_question",
@@ -2967,6 +3046,98 @@ function agentHref(agentId, section) {
2967
3046
  if (section) query.set("section", section);
2968
3047
  return `/?${query}`;
2969
3048
  }
3049
+ var CAUSE_LEAD = {
3050
+ credentials: "The provider refused the credentials",
3051
+ limit: "A usage or rate limit was reached",
3052
+ unreachable: "The model could not be reached",
3053
+ model: "The model is not available",
3054
+ other: "The turn failed"
3055
+ };
3056
+ var ORIGIN_TITLE = {
3057
+ http: "Follow-up failed",
3058
+ telegram: "Telegram message failed",
3059
+ inbox: "Turn for new mail failed"
3060
+ };
3061
+ var ORIGIN_COUNT = {
3062
+ http: ["follow-up", "follow-ups"],
3063
+ telegram: ["Telegram message", "Telegram messages"],
3064
+ inbox: ["turn for new mail", "turns for new mail"]
3065
+ };
3066
+ function turnFailureCause(reason) {
3067
+ const kind = classifyProviderFailure(reason);
3068
+ if (kind !== "other") return kind;
3069
+ const shape = reason.toLowerCase().replace(/\b(?=[\w-]*\d)[\w-]{8,}\b|[0-9a-f]{8,}|\d+/g, "#").replace(/\s+/g, " ").slice(0, 120);
3070
+ return `other-${createHash("sha256").update(shape).digest("hex").slice(0, 12)}`;
3071
+ }
3072
+ function turnFailures(db) {
3073
+ const queued = db.raw.query(
3074
+ `SELECT q.id, q.agent_id agentId, a.name agentName, a.team_id teamId, t.name teamName,
3075
+ q.source origin, COALESCE(q.finished_at, q.updated_at) at, q.diagnostic reason
3076
+ FROM user_queue_items q JOIN agents a ON a.id = q.agent_id JOIN teams t ON t.id = a.team_id
3077
+ WHERE q.status = 'failed' AND (q.diagnostic IS NULL OR q.diagnostic != ?)`
3078
+ ).all(INTERRUPTED_BY_RESTART);
3079
+ const agents = new Map(
3080
+ db.raw.query(
3081
+ "SELECT a.id, a.name, a.team_id teamId, t.name teamName FROM agents a JOIN teams t ON t.id = a.team_id"
3082
+ ).all().map((agent) => [agent.id, agent])
3083
+ );
3084
+ const remembered = rememberedTurnFailures().flatMap((failure) => {
3085
+ const agent = agents.get(failure.agentId);
3086
+ return agent ? [
3087
+ {
3088
+ id: failure.id,
3089
+ agentId: agent.id,
3090
+ agentName: agent.name,
3091
+ teamId: agent.teamId,
3092
+ teamName: agent.teamName,
3093
+ origin: failure.origin,
3094
+ at: failure.at,
3095
+ reason: failure.reason
3096
+ }
3097
+ ] : [];
3098
+ });
3099
+ const acknowledged = new Map(
3100
+ db.raw.query(
3101
+ "SELECT source_id, acknowledged_at FROM attention_acknowledgements WHERE source_kind = 'turn_failure'"
3102
+ ).all().map((row) => [row.source_id, row.acknowledged_at])
3103
+ );
3104
+ const groups = /* @__PURE__ */ new Map();
3105
+ for (const failure of [...queued, ...remembered]) {
3106
+ const id = `${failure.agentId}:${turnFailureCause(failure.reason ?? "")}`;
3107
+ groups.set(id, [...groups.get(id) ?? [], failure]);
3108
+ }
3109
+ return [...groups].map(([sourceId, all]) => {
3110
+ const ack = acknowledged.get(sourceId) ?? null;
3111
+ const since = all.filter((failure) => ack === null || failure.at > ack);
3112
+ const counted = (since.length > 0 ? since : all).toSorted((a, b) => a.at - b.at);
3113
+ const first = counted[0];
3114
+ const latest = counted.at(-1);
3115
+ const reason = bounded(latest.reason, "The turn ended without a reply.");
3116
+ const origins = /* @__PURE__ */ new Map();
3117
+ for (const failure of counted)
3118
+ origins.set(failure.origin, (origins.get(failure.origin) ?? 0) + 1);
3119
+ const breakdown = [...origins].map(([origin, n]) => `${n} ${ORIGIN_COUNT[origin][n === 1 ? 0 : 1]}`).join(", ");
3120
+ return {
3121
+ kind: "turn_failure",
3122
+ severity: "error",
3123
+ sourceId,
3124
+ occurredAt: first.at,
3125
+ updatedAt: latest.at,
3126
+ agentId: latest.agentId,
3127
+ agentName: latest.agentName,
3128
+ teamId: latest.teamId,
3129
+ teamName: latest.teamName,
3130
+ title: counted.length === 1 ? ORIGIN_TITLE[latest.origin] : `${counted.length} background turns failed`,
3131
+ diagnostic: `${CAUSE_LEAD[classifyProviderFailure(reason)]}: ${reason}${counted.length > 1 ? ` (${breakdown})` : ""}`,
3132
+ href: agentHref(
3133
+ latest.agentId,
3134
+ origins.size === 1 && origins.has("inbox") ? "mailbox" : void 0
3135
+ ),
3136
+ acknowledgeable: true,
3137
+ acknowledged_at: since.length > 0 ? null : ack
3138
+ };
3139
+ });
3140
+ }
2970
3141
  var sources = [
2971
3142
  {
2972
3143
  kind: "lesson_proposal",
@@ -3072,7 +3243,8 @@ var sources = [
3072
3243
  })
3073
3244
  )
3074
3245
  )
3075
- }
3246
+ },
3247
+ { kind: "turn_failure", query: turnFailures }
3076
3248
  ];
3077
3249
  function normalize(row) {
3078
3250
  const { acknowledged_at, ...item } = row;
@@ -3112,13 +3284,17 @@ function projectAttention(db, options = {}, waiting = []) {
3112
3284
  }
3113
3285
  function attentionSummary(db, waiting = []) {
3114
3286
  const projected = projectAttention(db, { state: "open", limit: 1e5 }, waiting);
3287
+ return summarizeAttention(projected.items, projected.degraded);
3288
+ }
3289
+ function summarizeAttention(items, degraded) {
3290
+ const open2 = items.filter((item) => item.acknowledgedAt === null);
3115
3291
  const bySeverity = { action_required: 0, error: 0, warning: 0 };
3116
3292
  const byKind = Object.fromEntries(ATTENTION_KINDS.map((kind) => [kind, 0]));
3117
- for (const item of projected.items) {
3293
+ for (const item of open2) {
3118
3294
  bySeverity[item.severity]++;
3119
3295
  byKind[item.kind]++;
3120
3296
  }
3121
- return { openTotal: projected.items.length, bySeverity, byKind, degraded: projected.degraded };
3297
+ return { openTotal: open2.length, bySeverity, byKind, degraded };
3122
3298
  }
3123
3299
  function acknowledgeAttention(db, key2, acknowledged) {
3124
3300
  const parsed = parseAttentionKey(key2);
@@ -3135,7 +3311,7 @@ function acknowledgeAttention(db, key2, acknowledged) {
3135
3311
  throw new DomainError(409, "action-required items must be resolved at their source");
3136
3312
  if (acknowledged)
3137
3313
  db.raw.run(
3138
- `INSERT INTO attention_acknowledgements (source_kind, source_id, acknowledged_at) VALUES (?, ?, ?) ON CONFLICT(source_kind, source_id) DO NOTHING`,
3314
+ `INSERT INTO attention_acknowledgements (source_kind, source_id, acknowledged_at) VALUES (?, ?, ?) ON CONFLICT(source_kind, source_id) DO UPDATE SET acknowledged_at = excluded.acknowledged_at`,
3139
3315
  [parsed.kind, parsed.sourceId, Date.now()]
3140
3316
  );
3141
3317
  else
@@ -3159,7 +3335,7 @@ function acknowledgeAllAttention(db) {
3159
3335
  const now = Date.now();
3160
3336
  for (const item of items)
3161
3337
  db.raw.run(
3162
- `INSERT INTO attention_acknowledgements (source_kind, source_id, acknowledged_at) VALUES (?, ?, ?) ON CONFLICT(source_kind, source_id) DO NOTHING`,
3338
+ `INSERT INTO attention_acknowledgements (source_kind, source_id, acknowledged_at) VALUES (?, ?, ?) ON CONFLICT(source_kind, source_id) DO UPDATE SET acknowledged_at = excluded.acknowledged_at`,
3163
3339
  [item.kind, item.sourceId, now]
3164
3340
  );
3165
3341
  return items.length;
@@ -3260,14 +3436,14 @@ function replaceCuratedModels(db, provider, models) {
3260
3436
  import { dirname } from "node:path";
3261
3437
  import { backup, DatabaseSync } from "node:sqlite";
3262
3438
  function wrap(rawDb) {
3263
- const cache = /* @__PURE__ */ new Map();
3439
+ const cache2 = /* @__PURE__ */ new Map();
3264
3440
  let transactionDepth = 0;
3265
3441
  let savepointSequence = 0;
3266
3442
  function getStmt(sql) {
3267
- let s = cache.get(sql);
3443
+ let s = cache2.get(sql);
3268
3444
  if (!s) {
3269
3445
  s = rawDb.prepare(sql);
3270
- cache.set(sql, s);
3446
+ cache2.set(sql, s);
3271
3447
  }
3272
3448
  return s;
3273
3449
  }
@@ -3656,10 +3832,16 @@ function validateSlug(s) {
3656
3832
  );
3657
3833
  }
3658
3834
  }
3835
+ function templateName(value) {
3836
+ const name = value.trim();
3837
+ if (!name) throw new DomainError(400, "A template needs a name");
3838
+ return name;
3839
+ }
3659
3840
 
3660
3841
  // ../daemon/src/core/profile/create.ts
3661
3842
  function createProfile(db, paths, input) {
3662
3843
  validateSlug(input.id);
3844
+ const name = input.name === void 0 ? input.id : templateName(input.name);
3663
3845
  if (get5(db, input.id))
3664
3846
  throw new DomainError(400, `profile already exists: ${input.id}`);
3665
3847
  const dir = paths.profileDir(input.id);
@@ -3683,7 +3865,7 @@ function createProfile(db, paths, input) {
3683
3865
  const skillsMode = input.skillsMode ?? "selected";
3684
3866
  const profile = insert4(db, {
3685
3867
  id: input.id,
3686
- name: input.name ?? input.id,
3868
+ name,
3687
3869
  defaultModel: input.defaultModel,
3688
3870
  skillsMode
3689
3871
  });
@@ -3991,7 +4173,7 @@ function updateProfile(db, id, input) {
3991
4173
  if (!existing) throw new DomainError(404, `profile not found: ${id}`);
3992
4174
  const nextSkillsMode = input.skillsMode ?? existing.skillsMode;
3993
4175
  const next = {
3994
- name: input.name ?? existing.name,
4176
+ name: input.name === void 0 ? existing.name : templateName(input.name),
3995
4177
  defaultModel: input.defaultModel ?? existing.defaultModel,
3996
4178
  skillsMode: nextSkillsMode
3997
4179
  };
@@ -4168,6 +4350,7 @@ function apiKey(id, displayName, envVar, options = {}) {
4168
4350
  id,
4169
4351
  displayName,
4170
4352
  ...options.hint ? { hint: options.hint } : {},
4353
+ ...options.plan ? { plan: true } : {},
4171
4354
  keyEnv: [envVar],
4172
4355
  ...options.modelsUrl ? { modelsUrl: options.modelsUrl } : {},
4173
4356
  fields: [
@@ -4201,8 +4384,9 @@ var PROVIDERS = [
4201
4384
  hint: "Use your ChatGPT Plus, Pro or Team plan. No API key.",
4202
4385
  // Credentials come from the OAuth flow (/api/auth/openai), not from fields.
4203
4386
  fields: [],
4387
+ plan: true,
4204
4388
  popular: true,
4205
- suggested: ["gpt-6.1-sol", "gpt-6-luna"]
4389
+ suggested: ["gpt-6.2-sol", "gpt-6-luna"]
4206
4390
  },
4207
4391
  {
4208
4392
  ...apiKey("openai", "OpenAI", "OPENAI_API_KEY", {
@@ -4210,13 +4394,14 @@ var PROVIDERS = [
4210
4394
  placeholder: "sk-..."
4211
4395
  }),
4212
4396
  popular: true,
4213
- suggested: ["gpt-6.1-sol", "gpt-6-luna"]
4397
+ suggested: ["gpt-6.2-sol", "gpt-6-luna"]
4214
4398
  },
4215
4399
  {
4216
4400
  id: "anthropic",
4217
4401
  displayName: "Anthropic",
4218
4402
  hint: "Claude models \xB7 console.anthropic.com",
4219
4403
  keyEnv: ["ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],
4404
+ planEnv: "ANTHROPIC_OAUTH_TOKEN",
4220
4405
  fields: [
4221
4406
  { envVar: "ANTHROPIC_API_KEY", kind: "secret", label: "API key", placeholder: "sk-ant-..." },
4222
4407
  {
@@ -4295,6 +4480,7 @@ var PROVIDERS = [
4295
4480
  displayName: "GitHub Copilot",
4296
4481
  hint: "Use a GitHub Copilot subscription to call Claude/GPT/Gemini via Copilot",
4297
4482
  keyEnv: ["COPILOT_GITHUB_TOKEN"],
4483
+ plan: true,
4298
4484
  fields: [
4299
4485
  {
4300
4486
  envVar: "COPILOT_GITHUB_TOKEN",
@@ -4347,34 +4533,43 @@ var PROVIDERS = [
4347
4533
  apiKey("minimax-cn", "MiniMax (CN)", "MINIMAX_CN_API_KEY", {
4348
4534
  hint: "MiniMax M2/M3 family via the China endpoint"
4349
4535
  }),
4350
- apiKey("qwen-token-plan", "Qwen Token Plan", "QWEN_TOKEN_PLAN_API_KEY", {
4351
- hint: "Coding-model subscription endpoint in Singapore"
4536
+ // Each plan has its own key; Pi also reads the older shared QWEN_TOKEN_PLAN_API_KEY.
4537
+ apiKey("qwen-token-plan", "Qwen Token Plan Team", "QWEN_TOKEN_PLAN_TEAM_API_KEY", {
4538
+ hint: "Team coding-model subscription \xB7 international endpoint",
4539
+ plan: true
4352
4540
  }),
4353
- apiKey("qwen-token-plan-cn", "Qwen Token Plan (CN)", "QWEN_TOKEN_PLAN_CN_API_KEY", {
4354
- hint: "Coding-model subscription endpoint in China"
4355
- }),
4356
- apiKey("qwen-token-plan-individual", "Qwen Token Plan (Individual)", "QWEN_TOKEN_PLAN_API_KEY", {
4357
- hint: "Individual subscription models via the international endpoint"
4541
+ apiKey("qwen-token-plan-cn", "Qwen Token Plan Team (CN)", "QWEN_TOKEN_PLAN_TEAM_CN_API_KEY", {
4542
+ hint: "Team coding-model subscription \xB7 China endpoint",
4543
+ plan: true
4358
4544
  }),
4545
+ apiKey(
4546
+ "qwen-token-plan-individual",
4547
+ "Qwen Token Plan Individual",
4548
+ "QWEN_TOKEN_PLAN_INDIVIDUAL_API_KEY",
4549
+ { hint: "Individual subscription \xB7 international endpoint", plan: true }
4550
+ ),
4359
4551
  apiKey(
4360
4552
  "qwen-token-plan-individual-cn",
4361
- "Qwen Token Plan (Individual, CN)",
4362
- "QWEN_TOKEN_PLAN_CN_API_KEY",
4363
- { hint: "Individual subscription models via the China endpoint" }
4553
+ "Qwen Token Plan Individual (CN)",
4554
+ "QWEN_TOKEN_PLAN_INDIVIDUAL_CN_API_KEY",
4555
+ { hint: "Individual subscription \xB7 China endpoint", plan: true }
4364
4556
  ),
4365
4557
  apiKey("xiaomi", "Xiaomi MiMo", "XIAOMI_API_KEY", {
4366
4558
  hint: "API billing endpoint \xB7 platform.xiaomimimo.com"
4367
4559
  }),
4368
4560
  apiKey("xiaomi-token-plan-ams", "Xiaomi MiMo Token Plan (AMS)", "XIAOMI_TOKEN_PLAN_AMS_API_KEY", {
4369
4561
  hint: "MiMo token-plan endpoint in Amsterdam",
4562
+ plan: true,
4370
4563
  modelsUrl: "https://token-plan-ams.xiaomimimo.com/v1"
4371
4564
  }),
4372
4565
  apiKey("xiaomi-token-plan-cn", "Xiaomi MiMo Token Plan (CN)", "XIAOMI_TOKEN_PLAN_CN_API_KEY", {
4373
4566
  hint: "MiMo token-plan endpoint in China",
4567
+ plan: true,
4374
4568
  modelsUrl: "https://token-plan-cn.xiaomimimo.com/v1"
4375
4569
  }),
4376
4570
  apiKey("xiaomi-token-plan-sgp", "Xiaomi MiMo Token Plan (SGP)", "XIAOMI_TOKEN_PLAN_SGP_API_KEY", {
4377
4571
  hint: "MiMo token-plan endpoint in Singapore",
4572
+ plan: true,
4378
4573
  modelsUrl: "https://token-plan-sgp.xiaomimimo.com/v1"
4379
4574
  }),
4380
4575
  apiKey("ant-ling", "Ant Ling", "ANT_LING_API_KEY", {
@@ -4480,7 +4675,7 @@ var PROVIDERS = [
4480
4675
  displayName: "llama.cpp",
4481
4676
  hint: "Local inference \xB7 llama.cpp llama-server (OpenAI-compat /v1 endpoint)",
4482
4677
  urlEnv: "LLAMACPP_URL",
4483
- url: "http://127.0.0.1:8080/v1",
4678
+ url: "http://127.0.0.1:9931/v1",
4484
4679
  keyEnv: "LLAMACPP_API_KEY",
4485
4680
  local: { key: "no-key", authHeader: true },
4486
4681
  keyField: {
@@ -5136,7 +5331,7 @@ function get10(db, id) {
5136
5331
  return row ? toMessage(row) : null;
5137
5332
  }
5138
5333
  function listInbox(db, agentId, opts) {
5139
- 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";
5334
+ const sql = opts?.unreadOnly ? "SELECT * FROM messages WHERE to_agent_id = ? AND read_at IS NULL ORDER BY created_at ASC, rowid ASC" : "SELECT * FROM messages WHERE to_agent_id = ? ORDER BY created_at ASC, rowid ASC";
5140
5335
  return db.raw.query(sql).all(agentId).map(toMessage);
5141
5336
  }
5142
5337
  function listForTeam(db, teamId, limit) {
@@ -5144,7 +5339,7 @@ function listForTeam(db, teamId, limit) {
5144
5339
  `SELECT m.* FROM messages m
5145
5340
  WHERE m.from_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5146
5341
  OR m.to_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5147
- ORDER BY m.created_at DESC, m.id DESC LIMIT ?`
5342
+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT ?`
5148
5343
  ).all(teamId, teamId, limit).map(toMessage);
5149
5344
  }
5150
5345
  function markRead(db, id) {
@@ -5171,7 +5366,7 @@ function drainUnreadForAgent(db, agentId) {
5171
5366
  const rows = db.raw.query(
5172
5367
  `SELECT * FROM messages
5173
5368
  WHERE to_agent_id = ? AND read_at IS NULL
5174
- ORDER BY created_at ASC`
5369
+ ORDER BY created_at ASC, rowid ASC`
5175
5370
  ).all(agentId);
5176
5371
  if (rows.length === 0) return [];
5177
5372
  const now = Date.now();
@@ -5378,10 +5573,10 @@ __export(telegram_pairing_exports, {
5378
5573
  reset: () => reset,
5379
5574
  status: () => status
5380
5575
  });
5381
- import { createHash, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
5576
+ import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
5382
5577
  var TTL_MS = 10 * 6e4;
5383
5578
  function digest(code) {
5384
- return createHash("sha256").update(code, "utf8").digest();
5579
+ return createHash2("sha256").update(code, "utf8").digest();
5385
5580
  }
5386
5581
  function create2(db) {
5387
5582
  if (status(db).paired) throw new DomainError(409, "Telegram already has a paired owner");
@@ -5632,7 +5827,7 @@ __export(webTokens_exports, {
5632
5827
  rejectionReason: () => rejectionReason,
5633
5828
  revoke: () => revoke2
5634
5829
  });
5635
- import { createHash as createHash2, randomBytes as randomBytes3, randomUUID as randomUUID10 } from "node:crypto";
5830
+ import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID10 } from "node:crypto";
5636
5831
  function toToken(r) {
5637
5832
  return {
5638
5833
  id: r.id,
@@ -5645,7 +5840,7 @@ function toToken(r) {
5645
5840
  };
5646
5841
  }
5647
5842
  function hashToken(token) {
5648
- return createHash2("sha256").update(token).digest("hex");
5843
+ return createHash3("sha256").update(token).digest("hex");
5649
5844
  }
5650
5845
  function create3(db, label, opts = {}) {
5651
5846
  const id = randomUUID10();
@@ -6301,6 +6496,17 @@ function isSetupOpen(path) {
6301
6496
  }
6302
6497
  return false;
6303
6498
  }
6499
+ function credentialCheck(c) {
6500
+ const bearer = extractBearer(c.req.header("authorization"));
6501
+ const sessionCookie = getCookie(
6502
+ c,
6503
+ publicOriginConfig(process.env.BAZILION_PUBLIC_ORIGIN).sessionCookie
6504
+ );
6505
+ return () => {
6506
+ if (bearer) return authenticateToken(bearer) !== null;
6507
+ return Boolean(sessionCookie && webSessions_exports.authenticate(getCtx().db, sessionCookie));
6508
+ };
6509
+ }
6304
6510
  async function authMiddleware(c, next) {
6305
6511
  const path = c.req.path;
6306
6512
  if (PUBLIC_PATHS.has(path)) {
@@ -6424,7 +6630,7 @@ function rename(db, agentId, id, title) {
6424
6630
  }
6425
6631
 
6426
6632
  // ../daemon/src/core/repos/results.ts
6427
- import { createHash as createHash3, randomUUID as randomUUID13 } from "node:crypto";
6633
+ import { createHash as createHash4, randomUUID as randomUUID13 } from "node:crypto";
6428
6634
 
6429
6635
  // ../daemon/src/core/tool-call-id.ts
6430
6636
  function isToolCallId(value) {
@@ -6480,7 +6686,7 @@ function publish(db, input) {
6480
6686
  input.name,
6481
6687
  input.mimeType,
6482
6688
  bytes.byteLength,
6483
- createHash3("sha256").update(bytes).digest("hex"),
6689
+ createHash4("sha256").update(bytes).digest("hex"),
6484
6690
  input.imageModel ?? null,
6485
6691
  Date.now(),
6486
6692
  bytes
@@ -6519,7 +6725,7 @@ function read(db, id) {
6519
6725
  ).get(id);
6520
6726
  if (!row) throw new Error("Result not found");
6521
6727
  const bytes = Buffer.from(row.bytes);
6522
- if (createHash3("sha256").update(bytes).digest("hex") !== row.sha256)
6728
+ if (createHash4("sha256").update(bytes).digest("hex") !== row.sha256)
6523
6729
  throw new Error("Saved file failed its integrity check");
6524
6730
  return bytes;
6525
6731
  }
@@ -6549,6 +6755,16 @@ function remove10(db, id) {
6549
6755
  return db.raw.run("DELETE FROM agent_results WHERE id = ?", [id]).changes === 1;
6550
6756
  }
6551
6757
 
6758
+ // ../daemon/src/lib/live-signal.ts
6759
+ var listeners = /* @__PURE__ */ new Set();
6760
+ function signalLiveChange() {
6761
+ for (const listener of listeners) listener();
6762
+ }
6763
+ function onLiveChange(listener) {
6764
+ listeners.add(listener);
6765
+ return () => listeners.delete(listener);
6766
+ }
6767
+
6552
6768
  // ../daemon/src/lib/agent-cancel.ts
6553
6769
  var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("bazilion.agent-cancel.registry");
6554
6770
  var AgentTurnActiveError = class extends DomainError {
@@ -6574,6 +6790,7 @@ function registerAgent(agentId, controller) {
6574
6790
  throw new AgentTurnActiveError(agentId);
6575
6791
  }
6576
6792
  registry().active.set(agentId, controller);
6793
+ signalLiveChange();
6577
6794
  }
6578
6795
  function unregisterAgent(agentId) {
6579
6796
  const state2 = registry();
@@ -6581,6 +6798,7 @@ function unregisterAgent(agentId) {
6581
6798
  const waiters = state2.idleWaiters.get(agentId);
6582
6799
  state2.idleWaiters.delete(agentId);
6583
6800
  for (const resolve9 of waiters ?? []) resolve9();
6801
+ signalLiveChange();
6584
6802
  }
6585
6803
  function cancelAgent(agentId) {
6586
6804
  const { active } = registry();
@@ -6630,7 +6848,7 @@ function isShuttingDownError(error) {
6630
6848
  }
6631
6849
 
6632
6850
  // ../daemon/src/lib/bash-approval.ts
6633
- var DEFAULT_TIMEOUT_MS = 12e4;
6851
+ var DEFAULT_TIMEOUT_MS = 5 * 6e4;
6634
6852
  var CommandApprovalRegistry = class {
6635
6853
  #pending = /* @__PURE__ */ new Map();
6636
6854
  #timeoutMs;
@@ -6657,26 +6875,34 @@ var CommandApprovalRegistry = class {
6657
6875
  }
6658
6876
  if (this.#pending.has(approval.id))
6659
6877
  throw new Error(`duplicate shell approval id: ${approval.id}`);
6660
- const settled = new Promise((resolve9) => {
6661
- const settle = (status2) => {
6662
- this.#pending.delete(approval.id);
6663
- clearTimeout(timer);
6664
- signal?.removeEventListener("abort", onAbort);
6665
- const result = logged({ ...approval, status: status2 });
6666
- resolve9(result);
6667
- return result;
6668
- };
6669
- const onAbort = () => settle("cancelled");
6670
- const timer = setTimeout(() => settle("expired"), this.#timeoutMs);
6671
- timer.unref();
6672
- signal?.addEventListener("abort", onAbort, { once: true });
6673
- this.#pending.set(approval.id, { approval, settle });
6674
- });
6878
+ const { promise: settled, resolve: resolve9 } = Promise.withResolvers();
6879
+ const settle = (status2) => {
6880
+ this.#pending.delete(approval.id);
6881
+ clearTimeout(timer);
6882
+ signal?.removeEventListener("abort", onAbort);
6883
+ const result = logged({ ...approval, status: status2 });
6884
+ resolve9(result);
6885
+ signalLiveChange();
6886
+ return result;
6887
+ };
6888
+ const onAbort = () => settle("cancelled");
6889
+ const timer = setTimeout(() => settle("expired"), this.#timeoutMs);
6890
+ timer.unref();
6891
+ signal?.addEventListener("abort", onAbort, { once: true });
6892
+ this.#pending.set(approval.id, { approval, settle, settled });
6893
+ signalLiveChange();
6675
6894
  return { approval, settled };
6676
6895
  }
6677
6896
  list(agentId) {
6678
6897
  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));
6679
6898
  }
6899
+ get(id) {
6900
+ return this.#pending.get(id)?.approval;
6901
+ }
6902
+ /** The outcome of a pending approval; undefined once it has settled. */
6903
+ settled(id) {
6904
+ return this.#pending.get(id)?.settled;
6905
+ }
6680
6906
  /** Answer a pending approval; undefined when there is none (unknown, or already settled). */
6681
6907
  respond(id, decision) {
6682
6908
  return this.#pending.get(id)?.settle(decision === "allow" ? "allowed" : "denied");
@@ -6780,9 +7006,11 @@ var QuestionRegistry = class {
6780
7006
  clearTimeout(timer);
6781
7007
  signal?.removeEventListener("abort", cancel3);
6782
7008
  resolve9({ questionId: question.id, question: prompt, ...outcome });
7009
+ signalLiveChange();
6783
7010
  return true;
6784
7011
  };
6785
7012
  this.#pending.set(question.id, { question, result: promise, finish: finish3 });
7013
+ signalLiveChange();
6786
7014
  signal?.addEventListener("abort", cancel3, { once: true });
6787
7015
  return { question, result: promise };
6788
7016
  }
@@ -6841,9 +7069,11 @@ function stepTarget(rawArguments) {
6841
7069
  function noteTurnFrame(agentId, frame) {
6842
7070
  if (frame.kind !== "event" || frame.event.type !== "tool_call") return;
6843
7071
  steps().set(agentId, { tool: frame.event.name, target: stepTarget(frame.event.arguments) });
7072
+ signalLiveChange();
6844
7073
  }
6845
7074
  function noteTurnEnd(agentId) {
6846
7075
  steps().delete(agentId);
7076
+ signalLiveChange();
6847
7077
  }
6848
7078
  function lastActivityAt(db, paths, agentId) {
6849
7079
  const conversationId = selectedId(db, agentId);
@@ -6861,6 +7091,7 @@ function readActivity(db, paths) {
6861
7091
  const approvals = commandApprovalRegistry.list();
6862
7092
  return list(db).map((agent) => {
6863
7093
  const working = isActiveAgent(agent.id);
7094
+ const pending = pendingCount(db, agent.id);
6864
7095
  const produced = saved.get(agent.id);
6865
7096
  return {
6866
7097
  agentId: agent.id,
@@ -6869,7 +7100,8 @@ function readActivity(db, paths) {
6869
7100
  step: working ? steps().get(agent.id) ?? null : null,
6870
7101
  questions: questions.filter((question) => question.agentId === agent.id).length,
6871
7102
  approvals: approvals.filter((approval) => approval.agentId === agent.id).length,
6872
- queuePaused: isPaused(db, agent.id) && pendingCount(db, agent.id) > 0,
7103
+ queuePaused: isPaused(db, agent.id) && pending > 0,
7104
+ followUps: pending,
6873
7105
  lastActivityAt: lastActivityAt(db, paths, agent.id),
6874
7106
  results: produced?.count ?? 0,
6875
7107
  lastResultAt: produced?.lastAt ?? null
@@ -6895,7 +7127,9 @@ function onRouteError(error, c) {
6895
7127
  return c.json({ error: error.message || "Internal error" }, 500);
6896
7128
  }
6897
7129
  function routeAgent(c, param = "id") {
6898
- const ref = c.req.param(param) ?? "";
7130
+ return routeAgentRef(c.req.param(param) ?? "");
7131
+ }
7132
+ function routeAgentRef(ref) {
6899
7133
  const { db } = getCtx();
6900
7134
  const agent = get(db, ref);
6901
7135
  if (agent) return agent;
@@ -7359,8 +7593,8 @@ function qmdBackend(root, options = {}) {
7359
7593
  async init() {
7360
7594
  const safe = safeRoot();
7361
7595
  assertSafeTree(safe);
7362
- const store = await getStore(safe, storeFactory);
7363
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7596
+ const store2 = await getStore(safe, storeFactory);
7597
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7364
7598
  },
7365
7599
  async read(key2) {
7366
7600
  const safe = safeRoot();
@@ -7378,17 +7612,17 @@ function qmdBackend(root, options = {}) {
7378
7612
  const path = safeKey(safe, key2);
7379
7613
  const stats = writeSafeFile(safe, path, content);
7380
7614
  assertSafeTree(safe);
7381
- const store = await getStore(safe, storeFactory);
7382
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7615
+ const store2 = await getStore(safe, storeFactory);
7616
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7383
7617
  return { key: key2, content, updatedAt: stats.mtimeMs };
7384
7618
  },
7385
7619
  async search(query, opts) {
7386
7620
  const limit = opts?.limit ?? 10;
7387
7621
  const safe = safeRoot();
7388
7622
  assertSafeTree(safe);
7389
- const store = await getStore(safe, storeFactory);
7623
+ const store2 = await getStore(safe, storeFactory);
7390
7624
  const results = await withNativeModuleErrorBoundary(
7391
- () => store.searchLex(query, {
7625
+ () => store2.searchLex(query, {
7392
7626
  limit,
7393
7627
  collection: COLLECTION_NAME
7394
7628
  }),
@@ -7428,8 +7662,8 @@ function qmdBackend(root, options = {}) {
7428
7662
  rmSync9(path);
7429
7663
  }
7430
7664
  assertSafeTree(safe);
7431
- const store = await getStore(safe, storeFactory);
7432
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7665
+ const store2 = await getStore(safe, storeFactory);
7666
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7433
7667
  }
7434
7668
  };
7435
7669
  }
@@ -7817,9 +8051,9 @@ function readContainedFile(path, realRoot, maxBytes) {
7817
8051
  const buffer = Buffer.alloc(maxBytes + 1);
7818
8052
  let length = 0;
7819
8053
  while (length < buffer.length) {
7820
- const count = readSync(fd, buffer, length, buffer.length - length, null);
7821
- if (count === 0) break;
7822
- length += count;
8054
+ const count2 = readSync(fd, buffer, length, buffer.length - length, null);
8055
+ if (count2 === 0) break;
8056
+ length += count2;
7823
8057
  }
7824
8058
  if (length > maxBytes) throw new ContainedFileError("too_large");
7825
8059
  return buffer.subarray(0, length);
@@ -8107,7 +8341,7 @@ function boundReviewedLessons(lessons, maxCharacters = 8e3) {
8107
8341
 
8108
8342
  // ../daemon/src/runtime/shell/docker.ts
8109
8343
  import { spawn as spawn3 } from "node:child_process";
8110
- import { createHash as createHash4, randomUUID as randomUUID15 } from "node:crypto";
8344
+ import { createHash as createHash5, randomUUID as randomUUID15 } from "node:crypto";
8111
8345
  var CONTAINER_WORKSPACE = "/workspace";
8112
8346
  var DOCKER_CALL_TIMEOUT_MS = 5e3;
8113
8347
  var MAX_TIMER_MS = 2147483647;
@@ -8214,7 +8448,7 @@ async function checkDockerImage(image) {
8214
8448
  }
8215
8449
  }
8216
8450
  function homeContainerPrefix(home) {
8217
- return `bazilion-${createHash4("sha256").update(home).digest("hex").slice(0, 12)}-`;
8451
+ return `bazilion-${createHash5("sha256").update(home).digest("hex").slice(0, 12)}-`;
8218
8452
  }
8219
8453
  function turnContainerPrefix(home) {
8220
8454
  return `${homeContainerPrefix(home)}${randomUUID15().replaceAll("-", "").slice(0, 12)}-`;
@@ -8641,7 +8875,7 @@ import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSyn
8641
8875
  import { join as join19 } from "node:path";
8642
8876
  var MAX_SESSION_BYTES = 64 * 1024 * 1024;
8643
8877
  var MAX_HEADER_BYTES = 64 * 1024;
8644
- function readStart(directory, id, limit) {
8878
+ function readStart(directory, id, limit, refuseOver) {
8645
8879
  if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error("Invalid conversation id");
8646
8880
  const fd = openSync3(
8647
8881
  join19(directory, `${id}.jsonl`),
@@ -8650,14 +8884,16 @@ function readStart(directory, id, limit) {
8650
8884
  try {
8651
8885
  const stat = fstatSync3(fd);
8652
8886
  if (!stat.isFile()) throw new Error("Session file is not a regular file");
8887
+ if (refuseOver !== void 0 && stat.size > refuseOver)
8888
+ throw new Error("Session file is larger than 64 MiB");
8653
8889
  const bytes = Buffer.alloc(Math.min(stat.size, limit));
8654
- let count = 0;
8655
- while (count < bytes.length) {
8656
- const n = readSync2(fd, bytes, count, bytes.length - count, count);
8890
+ let count2 = 0;
8891
+ while (count2 < bytes.length) {
8892
+ const n = readSync2(fd, bytes, count2, bytes.length - count2, count2);
8657
8893
  if (n === 0) break;
8658
- count += n;
8894
+ count2 += n;
8659
8895
  }
8660
- return { bytes: bytes.subarray(0, count), size: stat.size };
8896
+ return { bytes: bytes.subarray(0, count2), size: stat.size };
8661
8897
  } finally {
8662
8898
  closeSync3(fd);
8663
8899
  }
@@ -8666,14 +8902,19 @@ function checkHeader(entry, id) {
8666
8902
  if (entry?.type !== "session" || entry.id !== id)
8667
8903
  throw new Error("Session file does not belong to this conversation");
8668
8904
  }
8669
- function readSessionFile(directory, id) {
8670
- const { bytes, size } = readStart(directory, id, MAX_SESSION_BYTES);
8671
- if (size > MAX_SESSION_BYTES) throw new Error("Session file is larger than 64 MiB");
8905
+ function readSessionText(directory, id) {
8906
+ const { bytes } = readStart(directory, id, MAX_SESSION_BYTES, MAX_SESSION_BYTES);
8672
8907
  const text4 = bytes.toString("utf8");
8673
- const entries = text4.slice(0, text4.lastIndexOf("\n") + 1).split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
8908
+ return text4.slice(0, text4.lastIndexOf("\n") + 1);
8909
+ }
8910
+ function parseSessionText(text4, id) {
8911
+ const entries = text4.split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
8674
8912
  checkHeader(entries[0], id);
8675
8913
  return entries;
8676
8914
  }
8915
+ function readSessionFile(directory, id) {
8916
+ return parseSessionText(readSessionText(directory, id), id);
8917
+ }
8677
8918
  function sessionHasEntries(directory, id) {
8678
8919
  const { bytes, size } = readStart(directory, id, MAX_HEADER_BYTES);
8679
8920
  if (size > bytes.length) return true;
@@ -9509,8 +9750,8 @@ async function readBodyCapped(res, maxBytes) {
9509
9750
  if (done) break;
9510
9751
  if (!value) continue;
9511
9752
  if (total + value.byteLength > maxBytes) {
9512
- const keep = maxBytes - total;
9513
- if (keep > 0) chunks.push(value.subarray(0, keep));
9753
+ const keep2 = maxBytes - total;
9754
+ if (keep2 > 0) chunks.push(value.subarray(0, keep2));
9514
9755
  truncated = true;
9515
9756
  try {
9516
9757
  await reader.cancel();
@@ -9569,23 +9810,23 @@ async function firecrawlScrape(url, mode2, env, fetchFn, timeoutMs) {
9569
9810
  clearTimeout(t);
9570
9811
  }
9571
9812
  }
9572
- function cacheGet(cache, key2) {
9573
- const entry = cache.get(key2);
9813
+ function cacheGet(cache2, key2) {
9814
+ const entry = cache2.get(key2);
9574
9815
  if (!entry) return null;
9575
9816
  if (entry.expiresAt < Date.now()) {
9576
- cache.delete(key2);
9817
+ cache2.delete(key2);
9577
9818
  return null;
9578
9819
  }
9579
- cache.delete(key2);
9580
- cache.set(key2, entry);
9820
+ cache2.delete(key2);
9821
+ cache2.set(key2, entry);
9581
9822
  return entry.value;
9582
9823
  }
9583
- function cacheSet(cache, key2, value, ttlMs, maxEntries) {
9584
- cache.set(key2, { value, expiresAt: Date.now() + ttlMs });
9585
- while (cache.size > maxEntries) {
9586
- const oldest = cache.keys().next().value;
9824
+ function cacheSet(cache2, key2, value, ttlMs, maxEntries) {
9825
+ cache2.set(key2, { value, expiresAt: Date.now() + ttlMs });
9826
+ while (cache2.size > maxEntries) {
9827
+ const oldest = cache2.keys().next().value;
9587
9828
  if (!oldest) break;
9588
- cache.delete(oldest);
9829
+ cache2.delete(oldest);
9589
9830
  }
9590
9831
  }
9591
9832
  function webSearchTool(host3) {
@@ -9626,7 +9867,7 @@ function webFetchTool(opts) {
9626
9867
  const cacheMax = opts?.cacheMax ?? DEFAULT_CACHE_MAX;
9627
9868
  const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
9628
9869
  const maxBodyBytes = opts?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
9629
- const cache = /* @__PURE__ */ new Map();
9870
+ const cache2 = /* @__PURE__ */ new Map();
9630
9871
  return {
9631
9872
  def: {
9632
9873
  name: "web_fetch",
@@ -9654,7 +9895,7 @@ function webFetchTool(opts) {
9654
9895
  const maxLen = typeof args.max_length === "number" ? args.max_length : DEFAULT_MAX_LENGTH;
9655
9896
  const mode2 = args.extract_mode === "text" ? "text" : "markdown";
9656
9897
  const cacheKey = `${mode2}|${url}`;
9657
- const cached = cacheGet(cache, cacheKey);
9898
+ const cached = cacheGet(cache2, cacheKey);
9658
9899
  if (cached) return formatOutput(cached, maxLen);
9659
9900
  let result = null;
9660
9901
  try {
@@ -9713,7 +9954,7 @@ function webFetchTool(opts) {
9713
9954
  extracted = { ...extracted, text: `[final URL: ${result.finalUrl}]
9714
9955
 
9715
9956
  ${extracted.text}` };
9716
- cacheSet(cache, cacheKey, extracted, cacheTtlMs, cacheMax);
9957
+ cacheSet(cache2, cacheKey, extracted, cacheTtlMs, cacheMax);
9717
9958
  return formatOutput(extracted, maxLen);
9718
9959
  } catch (err) {
9719
9960
  if (err instanceof SsrFBlockedError) throw new Error(`web_fetch: ${err.message}`);
@@ -10958,19 +11199,6 @@ function setTelegramLive(live) {
10958
11199
  current = live;
10959
11200
  }
10960
11201
 
10961
- // ../daemon/src/lib/telegram/loop-guard.ts
10962
- var MAX_LINES = 30;
10963
- var WINDOW_MS = 6e4;
10964
- var _outbound = /* @__PURE__ */ new Map();
10965
- function allowTelegramOutboundNoise(agentId) {
10966
- const now = Date.now();
10967
- const hits = (_outbound.get(agentId) ?? []).filter((at) => now - at < WINDOW_MS);
10968
- const allowed = hits.length < MAX_LINES;
10969
- if (allowed) hits.push(now);
10970
- _outbound.set(agentId, hits);
10971
- return allowed;
10972
- }
10973
-
10974
11202
  // ../daemon/src/lib/telegram/markdown.ts
10975
11203
  import { marked } from "marked";
10976
11204
 
@@ -11259,11 +11487,107 @@ function sleep2(ms) {
11259
11487
  return new Promise((r) => setTimeout(r, ms));
11260
11488
  }
11261
11489
 
11490
+ // ../daemon/src/lib/telegram/approvals.ts
11491
+ var APPROVAL_TELEGRAM_DELAY_MS = 3e4;
11492
+ var CALLBACK = /^ba:([0-9a-f-]{36}):(a|d)$/;
11493
+ var COMMAND_CHARS = 1500;
11494
+ function promptBody(agentName, approval) {
11495
+ const risks = [...new Set(approval.risks.map((risk) => risk.message))].join(" ");
11496
+ return [
11497
+ `\u26A0\uFE0F ${agentName} wants to run a command that needs your approval:`,
11498
+ clip2(approval.command, COMMAND_CHARS),
11499
+ risks ? `Why it asks: ${clip2(risks, 500)}` : ""
11500
+ ].filter(Boolean).join("\n\n");
11501
+ }
11502
+ function outcomeLine(status2) {
11503
+ switch (status2) {
11504
+ case "allowed":
11505
+ return "Allowed once.";
11506
+ case "denied":
11507
+ return "Denied.";
11508
+ case "expired":
11509
+ return "No answer in time: denied.";
11510
+ default:
11511
+ return "The turn ended before an answer.";
11512
+ }
11513
+ }
11514
+ function scheduleApprovalPrompt(approval, delayMs = APPROVAL_TELEGRAM_DELAY_MS) {
11515
+ if (approval.status !== "pending") return;
11516
+ const timer = setTimeout(() => void sendApprovalPrompt(approval), delayMs);
11517
+ timer.unref();
11518
+ void commandApprovalRegistry.settled(approval.id)?.finally(() => clearTimeout(timer));
11519
+ }
11520
+ async function sendApprovalPrompt(approval) {
11521
+ const settled = commandApprovalRegistry.settled(approval.id);
11522
+ const live = telegramLive();
11523
+ if (!commandApprovalRegistry.get(approval.id) || !settled || !live) return false;
11524
+ const agent = agents_exports.get(live.db, approval.agentId);
11525
+ const topicId = agent ? agents_exports.getTelegramTopicId(live.db, agent.id) : null;
11526
+ if (!agent || topicId === null) return false;
11527
+ const body = promptBody(agent.name, approval);
11528
+ const keyboard = {
11529
+ inline_keyboard: [
11530
+ [
11531
+ { text: "Allow once", callback_data: `ba:${approval.id}:a` },
11532
+ { text: "Deny", callback_data: `ba:${approval.id}:d` }
11533
+ ]
11534
+ ]
11535
+ };
11536
+ const sent = await enqueueOutbound(
11537
+ live.chatId,
11538
+ () => live.api.sendMessage(live.chatId, body, {
11539
+ message_thread_id: topicId,
11540
+ reply_markup: keyboard
11541
+ })
11542
+ ).catch(() => null);
11543
+ if (!sent) return false;
11544
+ void settled.then((result) => {
11545
+ const current2 = telegramLive();
11546
+ if (!current2 || current2.chatId !== live.chatId) return;
11547
+ return enqueueOutbound(
11548
+ current2.chatId,
11549
+ () => current2.api.editMessageText(
11550
+ current2.chatId,
11551
+ sent.message_id,
11552
+ `${body}
11553
+
11554
+ ${outcomeLine(result.status)}`,
11555
+ { reply_markup: { inline_keyboard: [] } }
11556
+ )
11557
+ );
11558
+ }).catch(() => void 0);
11559
+ return true;
11560
+ }
11561
+ function approvalCallback(data) {
11562
+ const match = data?.match(CALLBACK);
11563
+ if (!match?.[1] || !match[2]) return null;
11564
+ return { approvalId: match[1], decision: match[2] === "a" ? "allow" : "deny" };
11565
+ }
11566
+ function decideFromTelegram(db, userId, approvalId, decision) {
11567
+ if (get12(db, userId)?.role !== "owner") return "Only the owner can decide on a command.";
11568
+ const settled = commandApprovalRegistry.respond(approvalId, decision);
11569
+ if (!settled) return "That command is no longer waiting.";
11570
+ return settled.status === "allowed" ? "Allowed once." : "Denied.";
11571
+ }
11572
+
11573
+ // ../daemon/src/lib/telegram/loop-guard.ts
11574
+ var MAX_LINES = 30;
11575
+ var WINDOW_MS = 6e4;
11576
+ var _outbound = /* @__PURE__ */ new Map();
11577
+ function allowTelegramOutboundNoise(agentId) {
11578
+ const now = Date.now();
11579
+ const hits = (_outbound.get(agentId) ?? []).filter((at) => now - at < WINDOW_MS);
11580
+ const allowed = hits.length < MAX_LINES;
11581
+ if (allowed) hits.push(now);
11582
+ _outbound.set(agentId, hits);
11583
+ return allowed;
11584
+ }
11585
+
11262
11586
  // ../daemon/src/lib/telegram/questions.ts
11263
- var CALLBACK = /^bq:([0-9a-f-]{36}):(\d|s)$/;
11587
+ var CALLBACK2 = /^bq:([0-9a-f-]{36}):(\d|s)$/;
11264
11588
  var FOOTER = "Tap a choice, or reply to this message with your own answer.";
11265
11589
  var prompts = /* @__PURE__ */ new Map();
11266
- function promptBody(question) {
11590
+ function promptBody2(question) {
11267
11591
  const { prompt, choices, recommendedIndex } = question.question;
11268
11592
  const options = choices.map(
11269
11593
  (choice, index) => `${index + 1}. ${choice.label}${index === recommendedIndex ? " (recommended)" : ""}${choice.description ? ` \u2014 ${choice.description}` : ""}`
@@ -11273,7 +11597,7 @@ function promptBody(question) {
11273
11597
 
11274
11598
  ${clip2(options, TELEGRAM_SAFE_BUDGET / 2)}`;
11275
11599
  }
11276
- function outcomeLine(result) {
11600
+ function outcomeLine2(result) {
11277
11601
  if (result.kind === "answer")
11278
11602
  return result.answer.kind === "choice" ? `Answered: ${result.question.choices[result.answer.index]?.label ?? ""}` : `Answered: ${clip2(result.answer.text, 500)}`;
11279
11603
  if (result.reason === "skipped") return "Skipped.";
@@ -11282,7 +11606,7 @@ function outcomeLine(result) {
11282
11606
  async function sendQuestionPrompt(live, topicId, question) {
11283
11607
  const settled = questionRegistry.settled(question.id);
11284
11608
  if (!settled) return;
11285
- const body = promptBody(question);
11609
+ const body = promptBody2(question);
11286
11610
  const keyboard = {
11287
11611
  inline_keyboard: [
11288
11612
  ...question.question.choices.map((choice, index) => [
@@ -11308,7 +11632,7 @@ ${FOOTER}`, {
11308
11632
  prompts.delete(sent.message_id);
11309
11633
  const current2 = telegramLive();
11310
11634
  if (!current2 || current2.chatId !== live.chatId) return;
11311
- const outcome = outcomeLine(result);
11635
+ const outcome = outcomeLine2(result);
11312
11636
  const text4 = `${clip2(body, TELEGRAM_SAFE_BUDGET - outcome.length - 2)}
11313
11637
 
11314
11638
  ${outcome}`;
@@ -11321,7 +11645,7 @@ ${outcome}`;
11321
11645
  }).catch(() => void 0);
11322
11646
  }
11323
11647
  function questionCallback(data) {
11324
- const match = data?.match(CALLBACK);
11648
+ const match = data?.match(CALLBACK2);
11325
11649
  if (!match?.[1] || !match[2]) return null;
11326
11650
  return {
11327
11651
  questionId: match[1],
@@ -11377,6 +11701,10 @@ async function mirrorAgentTurnFrame(agentId, frame) {
11377
11701
  if (frame.kind === "event" && frame.event.type === "file") {
11378
11702
  await mirrorFile(live, topicId, agent.id, frame.event);
11379
11703
  }
11704
+ if (frame.kind === "event" && frame.event.type === "command_approval") {
11705
+ scheduleApprovalPrompt(frame.event.approval);
11706
+ return;
11707
+ }
11380
11708
  if (frame.kind === "event" && frame.event.type === "agent_question") {
11381
11709
  await sendQuestionPrompt(live, topicId, frame.event.question).catch(
11382
11710
  () => logMirrorAdapterFailure("telegram_mirror_question_failed", agent.id)
@@ -11837,10 +12165,10 @@ function releasePreparedAgentTurn(turn) {
11837
12165
  }
11838
12166
 
11839
12167
  // ../daemon/src/lib/user-md-host.ts
11840
- import { createHash as createHash5 } from "node:crypto";
12168
+ import { createHash as createHash6 } from "node:crypto";
11841
12169
  var USER_MD_MAX_BYTES = 12e3;
11842
12170
  function computeEtag(content) {
11843
- return createHash5("sha256").update(content, "utf8").digest("hex").slice(0, 16);
12171
+ return createHash6("sha256").update(content, "utf8").digest("hex").slice(0, 16);
11844
12172
  }
11845
12173
  function createDbUserMdHost(db, paths) {
11846
12174
  return {
@@ -11918,13 +12246,13 @@ function createWebSearchHost(opts) {
11918
12246
  const query = typeof args?.query === "string" ? args.query.trim() : "";
11919
12247
  if (!query || query.length > 512)
11920
12248
  throw new Error("web_search needs a query of 1\u2013512 characters");
11921
- const count = Number.isInteger(args.count) && args.count >= 1 ? Math.min(args.count, 10) : 5;
12249
+ const count2 = Number.isInteger(args.count) && args.count >= 1 ? Math.min(args.count, 10) : 5;
11922
12250
  const signal = AbortSignal.any([opts.signal, AbortSignal.timeout(DEADLINE_MS2)]);
11923
12251
  const env = opts.env();
11924
12252
  try {
11925
12253
  if (opts.backend === "brave") {
11926
12254
  const body = await getJson(
11927
- `https://api.search.brave.com/res/v1/web/search?${new URLSearchParams({ q: query, count: String(count) })}`,
12255
+ `https://api.search.brave.com/res/v1/web/search?${new URLSearchParams({ q: query, count: String(count2) })}`,
11928
12256
  { "x-subscription-token": env.BRAVE_API_KEY ?? "" },
11929
12257
  signal,
11930
12258
  fetchImpl
@@ -11932,7 +12260,7 @@ function createWebSearchHost(opts) {
11932
12260
  const rows = body.web?.results;
11933
12261
  return {
11934
12262
  backend: "brave",
11935
- results: (Array.isArray(rows) ? rows : []).slice(0, count).map((row) => ({
12263
+ results: (Array.isArray(rows) ? rows : []).slice(0, count2).map((row) => ({
11936
12264
  title: text3(row?.title, 200),
11937
12265
  url: text3(row?.url, 2048),
11938
12266
  snippet: text3(row?.description, 300)
@@ -11949,14 +12277,14 @@ function createWebSearchHost(opts) {
11949
12277
  );
11950
12278
  return {
11951
12279
  backend: "searxng",
11952
- results: (Array.isArray(body.results) ? body.results : []).slice(0, count).map((row) => ({
12280
+ results: (Array.isArray(body.results) ? body.results : []).slice(0, count2).map((row) => ({
11953
12281
  title: text3(row?.title, 200),
11954
12282
  url: text3(row?.url, 2048),
11955
12283
  snippet: text3(row?.content, 300)
11956
12284
  }))
11957
12285
  };
11958
12286
  }
11959
- return await hostedSearch(opts, query, count, signal, fetchImpl, env);
12287
+ return await hostedSearch(opts, query, count2, signal, fetchImpl, env);
11960
12288
  } catch (error) {
11961
12289
  if (opts.signal.aborted) throw new Error("web_search: cancelled");
11962
12290
  if (signal.aborted) throw new Error("web_search: no answer within 30 seconds");
@@ -11965,14 +12293,14 @@ function createWebSearchHost(opts) {
11965
12293
  }
11966
12294
  };
11967
12295
  }
11968
- async function hostedSearch(opts, query, count, signal, fetchImpl, env) {
12296
+ async function hostedSearch(opts, query, count2, signal, fetchImpl, env) {
11969
12297
  const codex = opts.backend === "openai-codex";
11970
12298
  const output = await responsesStream(
11971
12299
  codex ? CODEX_RESPONSES_URL : OPENAI_RESPONSES_URL,
11972
12300
  codex ? codexHeaders(await opts.codexToken()) : { authorization: `Bearer ${env.OPENAI_API_KEY ?? ""}` },
11973
12301
  {
11974
12302
  model: parseModelString(opts.model).modelId,
11975
- instructions: `Search the web for the query and answer concisely, citing up to ${count} sources.`,
12303
+ instructions: `Search the web for the query and answer concisely, citing up to ${count2} sources.`,
11976
12304
  input: [{ role: "user", content: [{ type: "input_text", text: query }] }],
11977
12305
  tools: [{ type: "web_search" }],
11978
12306
  tool_choice: { type: "web_search" }
@@ -11998,7 +12326,7 @@ async function hostedSearch(opts, query, count, signal, fetchImpl, env) {
11998
12326
  return {
11999
12327
  backend: opts.backend,
12000
12328
  answer: answer.join("\n").trim(),
12001
- results: results.slice(0, count)
12329
+ results: results.slice(0, count2)
12002
12330
  };
12003
12331
  }
12004
12332
 
@@ -12558,8 +12886,8 @@ agentChatRouter.get(
12558
12886
  agentChatRouter.post("/:id/chat/truncate", async (c) => {
12559
12887
  const body = await jsonBody(c);
12560
12888
  if (!body) return c.json({ error: "invalid JSON body" }, 400);
12561
- const keep = Number(body.keepCount);
12562
- if (!Number.isInteger(keep) || keep < 0) {
12889
+ const keep2 = Number(body.keepCount);
12890
+ if (!Number.isInteger(keep2) || keep2 < 0) {
12563
12891
  return c.json({ error: "keepCount must be a non-negative integer" }, 400);
12564
12892
  }
12565
12893
  return withSelectedConversation(c, (id, target) => {
@@ -12570,7 +12898,7 @@ agentChatRouter.post("/:id/chat/truncate", async (c) => {
12570
12898
  const conversation = openConversation(resolveAgent(db, paths, id), paths, target);
12571
12899
  const messageEntries = conversation.getBranch().filter((e) => e.type === "message" && e.message.role !== "system");
12572
12900
  const before = messageEntries.length;
12573
- const after = Math.max(0, Math.min(keep, before));
12901
+ const after = Math.max(0, Math.min(keep2, before));
12574
12902
  if (after === before) return c.json({ before, after });
12575
12903
  const lastKept = messageEntries[after - 1];
12576
12904
  if (lastKept) conversation.branch(lastKept.id);
@@ -13269,18 +13597,21 @@ attentionRouter.get("/summary", (c) => {
13269
13597
  const db = getCtx().db;
13270
13598
  return c.json(attentionSummary(db, waitingAttention(db)));
13271
13599
  });
13272
- attentionRouter.post(
13273
- "/acknowledge-all",
13274
- (c) => c.json({ acknowledged: acknowledgeAllAttention(getCtx().db) })
13275
- );
13276
- attentionRouter.post(
13277
- "/:key/acknowledge",
13278
- (c) => c.json({ item: acknowledgeAttention(getCtx().db, c.req.param("key"), true) })
13279
- );
13280
- attentionRouter.delete(
13281
- "/:key/acknowledgement",
13282
- (c) => c.json({ item: acknowledgeAttention(getCtx().db, c.req.param("key"), false) })
13283
- );
13600
+ attentionRouter.post("/acknowledge-all", (c) => {
13601
+ const acknowledged = acknowledgeAllAttention(getCtx().db);
13602
+ signalLiveChange();
13603
+ return c.json({ acknowledged });
13604
+ });
13605
+ attentionRouter.post("/:key/acknowledge", (c) => {
13606
+ const item = acknowledgeAttention(getCtx().db, c.req.param("key"), true);
13607
+ signalLiveChange();
13608
+ return c.json({ item });
13609
+ });
13610
+ attentionRouter.delete("/:key/acknowledgement", (c) => {
13611
+ const item = acknowledgeAttention(getCtx().db, c.req.param("key"), false);
13612
+ signalLiveChange();
13613
+ return c.json({ item });
13614
+ });
13284
13615
 
13285
13616
  // ../daemon/src/routes/auth-login.ts
13286
13617
  import { deleteCookie, setCookie } from "hono/cookie";
@@ -13388,26 +13719,12 @@ function writeProviderCheck(db, providerId, check) {
13388
13719
  if (check) checks[providerId] = check;
13389
13720
  else if (providerId in checks) delete checks[providerId];
13390
13721
  else return;
13391
- const store = openConfig(db);
13392
- if (Object.keys(checks).length === 0) store.remove(PROVIDER_CHECKS_KEY);
13393
- else store.set(PROVIDER_CHECKS_KEY, JSON.stringify(checks));
13722
+ const store2 = openConfig(db);
13723
+ if (Object.keys(checks).length === 0) store2.remove(PROVIDER_CHECKS_KEY);
13724
+ else store2.set(PROVIDER_CHECKS_KEY, JSON.stringify(checks));
13394
13725
  }
13395
13726
 
13396
13727
  // ../daemon/src/lib/provider-failure.ts
13397
- var UNREACHABLE = /connection error|econnrefused|enotfound|ehostunreach|enetunreach|etimedout|econnreset|fetch failed|bad port|socket hang up|getaddrinfo|und_err|request aborted|request timed out/;
13398
- var CREDENTIALS = /invalid.{0,12}api.?key|incorrect api key|invalid x-api-key|invalid_api_key|authentication_error|unauthorized|invalid.{0,12}(access )?token/;
13399
- var MODEL = /model_not_found|no models loaded|not found, try pulling|not_found_error.{0,40}\bmodel\b|\bmodel\b.{0,80}(not found|does not exist|do not have access|not available|is not supported)|(must be verified|not have access|no access).{0,60}\bmodel\b/;
13400
- var LIMIT = /insufficient|quota|rate.?limit|billing|\bcredits?\b|overloaded/;
13401
- function classifyProviderFailure(message, timedOut = false) {
13402
- const text4 = message.toLowerCase();
13403
- const status2 = /^(\d{3})\b/.exec(text4)?.[1];
13404
- if (timedOut || UNREACHABLE.test(text4)) return "unreachable";
13405
- if (status2 === "401" || CREDENTIALS.test(text4)) return "credentials";
13406
- if (MODEL.test(text4)) return "model";
13407
- if (status2 === "402" || status2 === "429" || LIMIT.test(text4)) return "limit";
13408
- if (status2 === "403") return "credentials";
13409
- return "other";
13410
- }
13411
13728
  function redactDetail(message, secrets) {
13412
13729
  let detail = message;
13413
13730
  for (const secret of secrets) {
@@ -13641,9 +13958,9 @@ function fieldStates(fields2, stored, env = process.env) {
13641
13958
  });
13642
13959
  }
13643
13960
  function writeSetting(db, authToken, field, value) {
13644
- const store = field.kind === "config" ? openConfig(db) : openSecrets(db, authToken);
13645
- if (value === "") store.remove(field.envVar);
13646
- else store.set(field.envVar, value);
13961
+ const store2 = field.kind === "config" ? openConfig(db) : openSecrets(db, authToken);
13962
+ if (value === "") store2.remove(field.envVar);
13963
+ else store2.set(field.envVar, value);
13647
13964
  }
13648
13965
 
13649
13966
  // ../daemon/src/lib/provider-setup.ts
@@ -14523,104 +14840,689 @@ configRouter.delete("/fields/:envVar", (c) => {
14523
14840
  return c.body(null, 204);
14524
14841
  });
14525
14842
 
14526
- // ../daemon/src/routes/conversations.ts
14527
- var conversationsRouter = newRouter();
14528
- conversationsRouter.use("/:agentId/conversations/*", async (c, next) => {
14529
- c.set("agentId", routeAgent(c, "agentId").id);
14530
- await next();
14531
- });
14532
- conversationsRouter.get(
14533
- "/:agentId/conversations",
14534
- (c) => c.json(
14535
- list11(
14536
- getCtx().db,
14537
- c.get("agentId"),
14538
- Number(c.req.query("limit") ?? 20),
14539
- Number(c.req.query("offset") ?? 0)
14540
- )
14541
- )
14542
- );
14543
- conversationsRouter.post("/:agentId/conversations", async (c) => {
14544
- const input = await jsonBody(c);
14545
- const agentId = c.get("agentId");
14546
- const { db, paths } = getCtx();
14547
- return c.json(
14548
- await runAgentLifecycleMutation(
14549
- agentId,
14550
- () => startConversation(db, paths, agentId, input?.title)
14551
- )
14843
+ // ../daemon/src/lib/conversation-search.ts
14844
+ import { join as join30 } from "node:path";
14845
+ import { buildSessionContext as buildSessionContext2 } from "@earendil-works/pi-coding-agent";
14846
+ var INBOX_WAKE_PREFIX = "[[bazilion:inbox-wake]]\n";
14847
+ var MAX_WORDS = 8;
14848
+ var MAX_SEARCH_HITS = 50;
14849
+ var BEFORE = 24;
14850
+ var AFTER = 140;
14851
+ function searchWords(query) {
14852
+ const words = [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))];
14853
+ if (words.join("").length < 2) throw new DomainError(400, "Search for at least two characters");
14854
+ if (words.length > MAX_WORDS) throw new DomainError(400, `Search for at most ${MAX_WORDS} words`);
14855
+ return words;
14856
+ }
14857
+ function plainText(markdown) {
14858
+ return markdown.replace(/^\s*```.*$/gm, " ").replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/^\s{0,3}#{1,6}\s+/gm, "").replace(/^\s*>\s?/gm, "").replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm, "").replace(/^\s*\|?(?:\s*:?-{3,}:?\s*\|)+\s*:?-*:?\s*$/gm, " ").replace(/\|/g, " ").replace(/(\*\*|__|`)/g, "").replace(/(^|[\s(])[*_]([^*_\s][^*_]*?)[*_](?=[\s).,;:!?]|$)/g, "$1$2");
14859
+ }
14860
+ function snippetOf(text4, words) {
14861
+ const flat = plainText(text4).replace(/\s+/g, " ").trim();
14862
+ const lower = flat.toLowerCase();
14863
+ const at = Math.min(
14864
+ ...words.map((word) => lower.indexOf(word)).filter((index) => index >= 0),
14865
+ flat.length
14552
14866
  );
14553
- });
14554
- conversationsRouter.get("/:agentId/conversations/:id", (c) => {
14555
- const { db, paths, authToken } = getCtx();
14556
- const agentId = c.get("agentId");
14557
- const id = c.req.param("id");
14558
- const conversation = get16(db, agentId, id);
14559
- if (!conversation) return c.json({ error: "Conversation not found" }, 404);
14560
- try {
14561
- const messages = piMessagesToProviderView(
14562
- loadInitialMessages(resolveAgent(db, paths, agentId), paths, { id }),
14563
- envSecretValues(mergeSecretsIntoEnv(db, authToken))
14564
- );
14565
- return c.json({ conversation, messages });
14566
- } catch {
14567
- return c.json(
14568
- {
14569
- error: "Conversation history is missing, corrupt or unavailable",
14570
- conversation
14571
- },
14572
- 409
14573
- );
14574
- }
14575
- });
14576
- conversationsRouter.post("/:agentId/conversations/:id/select", async (c) => {
14577
- const agentId = c.get("agentId");
14578
- const id = c.req.param("id");
14579
- const { db, paths } = getCtx();
14580
- return c.json({
14581
- conversation: await runAgentLifecycleMutation(
14582
- agentId,
14583
- () => selectConversation(db, paths, agentId, id)
14584
- )
14585
- });
14586
- });
14587
- conversationsRouter.patch("/:agentId/conversations/:id", async (c) => {
14588
- const input = await jsonBody(c);
14589
- return c.json({
14590
- conversation: rename(
14591
- getCtx().db,
14592
- c.get("agentId"),
14593
- c.req.param("id"),
14594
- input?.title
14595
- )
14596
- });
14597
- });
14598
-
14599
- // ../daemon/src/routes/mcp.ts
14600
- init_pool();
14601
- var mcpRouter = newRouter();
14602
- var TRANSPORTS = /* @__PURE__ */ new Set(["stdio", "http"]);
14603
- function validate(input) {
14604
- if (!input.name || !/^[a-zA-Z0-9_]+$/.test(input.name)) {
14605
- return "name is required and must match [a-zA-Z0-9_]+ (letters, digits, underscore)";
14606
- }
14607
- if (!TRANSPORTS.has(input.transport)) return "transport must be stdio or http";
14608
- if (input.transport === "stdio") {
14609
- if (!input.command) return "stdio transport requires a command";
14610
- } else {
14611
- if (!input.url) return "http transport requires a url";
14867
+ const start2 = Math.max(0, at - BEFORE);
14868
+ const end = Math.min(flat.length, at + AFTER);
14869
+ return `${start2 > 0 ? "\u2026" : ""}${flat.slice(start2, end).trim()}${end < flat.length ? "\u2026" : ""}`;
14870
+ }
14871
+ async function searchConversations(db, paths, options) {
14872
+ const words = searchWords(options.query);
14873
+ const limit = Math.min(Math.max(options.limit ?? 20, 1), MAX_SEARCH_HITS);
14874
+ const raw = words.map((word) => JSON.stringify(word).slice(1, -1));
14875
+ const rows = db.raw.query(
14876
+ `SELECT c.id, c.agent_id agentId, c.title, a.name agentName, a.status = 'archived' archived,
14877
+ a.team_id teamId, t.name teamName, s.conversation_id selected
14878
+ FROM agent_conversations c JOIN agents a ON a.id = c.agent_id JOIN teams t ON t.id = a.team_id
14879
+ LEFT JOIN agent_conversation_selection s ON s.agent_id = c.agent_id
14880
+ WHERE (? IS NULL OR c.agent_id = ?)
14881
+ ORDER BY c.updated_at DESC`
14882
+ ).all(options.agentId ?? null, options.agentId ?? null);
14883
+ const hits = [];
14884
+ let unreadable = 0;
14885
+ for (const row of rows) {
14886
+ await new Promise((resolve9) => setImmediate(resolve9));
14887
+ if (options.signal?.aborted) break;
14888
+ const directory = join30(paths.agentDir(row.agentId), "sessions");
14889
+ let text4;
14612
14890
  try {
14613
- const url = new URL(input.url);
14614
- if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash)
14615
- return "http requires an HTTP(S) endpoint without embedded credentials or fragment";
14891
+ text4 = readSessionText(directory, row.id);
14616
14892
  } catch {
14617
- return "http requires a valid endpoint URL";
14893
+ unreadable++;
14894
+ continue;
14895
+ }
14896
+ const lower = text4.toLowerCase();
14897
+ if (!raw.every((word) => lower.includes(word))) continue;
14898
+ let messages;
14899
+ try {
14900
+ const entries = parseSessionText(text4, row.id);
14901
+ messages = buildSessionContext2(entries.filter((entry) => entry.type !== "session")).messages;
14902
+ } catch {
14903
+ unreadable++;
14904
+ continue;
14905
+ }
14906
+ let nth = 0;
14907
+ for (const message of messages) {
14908
+ if (message.role !== "user" && message.role !== "assistant") continue;
14909
+ const [shown] = piMessagesToProviderView([message], options.secrets ?? []);
14910
+ if (!shown) continue;
14911
+ const content = redactExactValues(
14912
+ shown.content.startsWith(INBOX_WAKE_PREFIX) ? shown.content.slice(INBOX_WAKE_PREFIX.length) : shown.content,
14913
+ options.secrets ?? []
14914
+ );
14915
+ const found = plainText(content).toLowerCase();
14916
+ if (!words.every((word) => found.includes(word))) continue;
14917
+ const at = message.timestamp;
14918
+ hits.push({
14919
+ agentId: row.agentId,
14920
+ agentName: row.agentName,
14921
+ teamId: row.teamId,
14922
+ teamName: row.teamName,
14923
+ archived: Boolean(row.archived),
14924
+ conversationId: row.id,
14925
+ conversationTitle: row.title,
14926
+ active: row.selected === row.id,
14927
+ role: message.role,
14928
+ at: typeof at === "number" && Number.isFinite(at) ? at : null,
14929
+ snippet: snippetOf(content, words),
14930
+ nth: nth++
14931
+ });
14618
14932
  }
14619
14933
  }
14620
- return null;
14934
+ hits.sort((a, b) => (b.at ?? 0) - (a.at ?? 0));
14935
+ return { words, hits: hits.slice(0, limit), truncated: hits.length > limit, unreadable };
14621
14936
  }
14622
- mcpRouter.get("/", (c) => {
14623
- const { db } = getCtx();
14937
+
14938
+ // ../daemon/src/lib/usage.ts
14939
+ import { closeSync as closeSync6, constants as constants7, fstatSync as fstatSync6, openSync as openSync6, readdirSync as readdirSync7, readSync as readSync3 } from "node:fs";
14940
+ import { join as join31 } from "node:path";
14941
+ var CONVERSATION_FILE = /^([0-9a-f-]{36})\.jsonl$/i;
14942
+ var READ_CHUNK = 1024 * 1024;
14943
+ var CACHE_KEY = /* @__PURE__ */ Symbol.for("bazilion.usage.files");
14944
+ function cache() {
14945
+ const holder = globalThis;
14946
+ holder[CACHE_KEY] ??= /* @__PURE__ */ new Map();
14947
+ return holder[CACHE_KEY];
14948
+ }
14949
+ var count = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
14950
+ function toRecord(usage, at, provider, model) {
14951
+ if (!usage || typeof usage !== "object") return null;
14952
+ const input = count(usage.input);
14953
+ const output = count(usage.output);
14954
+ const cacheRead = count(usage.cacheRead);
14955
+ const cacheWrite = count(usage.cacheWrite);
14956
+ const total = count(usage.totalTokens) || input + output + cacheRead + cacheWrite;
14957
+ const cost = count(usage.cost?.total);
14958
+ if (total === 0 && cost === 0) return null;
14959
+ return {
14960
+ at,
14961
+ calls: 1,
14962
+ provider,
14963
+ model,
14964
+ input,
14965
+ output,
14966
+ cacheRead,
14967
+ cacheWrite,
14968
+ total,
14969
+ cost,
14970
+ billed: usage.cost?.totalFromProvider === true
14971
+ };
14972
+ }
14973
+ function usageOfLine(line, file) {
14974
+ let entry;
14975
+ try {
14976
+ entry = JSON.parse(line);
14977
+ } catch {
14978
+ return null;
14979
+ }
14980
+ if (!entry || typeof entry !== "object") return null;
14981
+ const at = (typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN) || (typeof entry.message?.timestamp === "number" ? entry.message.timestamp : 0);
14982
+ if (!Number.isFinite(at) || at <= 0) return null;
14983
+ if (entry.type === "message" && entry.message?.role === "assistant") {
14984
+ const provider = typeof entry.message.provider === "string" ? entry.message.provider : "";
14985
+ const model = typeof entry.message.model === "string" ? entry.message.model : "";
14986
+ if (provider && model) file.lastModel = { provider, model };
14987
+ return toRecord(entry.message.usage, at, provider || "unknown", model || "unknown");
14988
+ }
14989
+ if (entry.type === "usage") {
14990
+ const provider = typeof entry.provider === "string" ? entry.provider : "unknown";
14991
+ const model = typeof entry.model === "string" ? entry.model : "unknown";
14992
+ return toRecord(entry.usage, at, provider, model);
14993
+ }
14994
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
14995
+ const last = file.lastModel ?? { provider: "unknown", model: "unknown" };
14996
+ return toRecord(entry.usage, at, last.provider, last.model);
14997
+ }
14998
+ return null;
14999
+ }
15000
+ var QUARTER_HOUR = 15 * 6e4;
15001
+ function keep(file, record) {
15002
+ const at = Math.floor(record.at / QUARTER_HOUR) * QUARTER_HOUR;
15003
+ const key2 = `${at}|${record.provider}|${record.model}|${record.billed}`;
15004
+ const kept = file.totals.get(key2);
15005
+ if (!kept) {
15006
+ file.totals.set(key2, { ...record, at });
15007
+ return;
15008
+ }
15009
+ kept.calls += record.calls;
15010
+ kept.input += record.input;
15011
+ kept.output += record.output;
15012
+ kept.cacheRead += record.cacheRead;
15013
+ kept.cacheWrite += record.cacheWrite;
15014
+ kept.total += record.total;
15015
+ kept.cost += record.cost;
15016
+ }
15017
+ function scanFile(path) {
15018
+ const files = cache();
15019
+ const fd = openSync6(path, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
15020
+ try {
15021
+ const stat = fstatSync6(fd);
15022
+ if (!stat.isFile()) throw new Error("not a regular file");
15023
+ let file = files.get(path);
15024
+ if (!file || file.dev !== stat.dev || file.ino !== stat.ino || stat.size < file.offset) {
15025
+ file = { dev: stat.dev, ino: stat.ino, offset: 0, totals: /* @__PURE__ */ new Map(), lastModel: null };
15026
+ files.set(path, file);
15027
+ }
15028
+ let pending = Buffer.alloc(0);
15029
+ let position = file.offset;
15030
+ const chunk = Buffer.alloc(READ_CHUNK);
15031
+ while (position < stat.size) {
15032
+ const n = readSync3(fd, chunk, 0, Math.min(READ_CHUNK, stat.size - position), position);
15033
+ if (n === 0) break;
15034
+ position += n;
15035
+ const bytes = pending.length ? Buffer.concat([pending, chunk.subarray(0, n)]) : chunk;
15036
+ const length = pending.length ? bytes.length : n;
15037
+ const end = bytes.lastIndexOf(10, length - 1);
15038
+ if (end < 0) {
15039
+ pending = Buffer.from(bytes.subarray(0, length));
15040
+ continue;
15041
+ }
15042
+ for (const line of bytes.subarray(0, end).toString("utf8").split("\n")) {
15043
+ if (!line.trim()) continue;
15044
+ const record = usageOfLine(line, file);
15045
+ if (record) keep(file, record);
15046
+ }
15047
+ pending = Buffer.from(bytes.subarray(end + 1, length));
15048
+ file.offset = position - pending.length;
15049
+ }
15050
+ return file;
15051
+ } finally {
15052
+ closeSync6(fd);
15053
+ }
15054
+ }
15055
+ function scanUsage(paths, agentIds, options = {}) {
15056
+ const conversations = [];
15057
+ let unreadable = 0;
15058
+ const seen = /* @__PURE__ */ new Set();
15059
+ for (const agentId of agentIds) {
15060
+ const directory = join31(paths.agentDir(agentId), "sessions");
15061
+ let names;
15062
+ try {
15063
+ names = readdirSync7(directory);
15064
+ } catch {
15065
+ continue;
15066
+ }
15067
+ for (const name of names) {
15068
+ const id = CONVERSATION_FILE.exec(name)?.[1];
15069
+ if (!id) continue;
15070
+ const path = join31(directory, name);
15071
+ seen.add(path);
15072
+ try {
15073
+ const totals = scanFile(path).totals;
15074
+ conversations.push({ agentId, conversationId: id, records: [...totals.values()] });
15075
+ } catch {
15076
+ unreadable++;
15077
+ }
15078
+ }
15079
+ }
15080
+ const listed = agentIds.map((id) => `${join31(paths.agentDir(id), "sessions")}/`);
15081
+ for (const path of cache().keys()) {
15082
+ if (seen.has(path)) continue;
15083
+ if (options.everyAgent || listed.some((prefix) => path.startsWith(prefix))) cache().delete(path);
15084
+ }
15085
+ return { conversations, unreadable };
15086
+ }
15087
+ var BY_PI_NAME = new Map(
15088
+ PROVIDERS.map((provider) => [provider.piName ?? provider.id, provider])
15089
+ );
15090
+ function planProviders(env) {
15091
+ return new Set(
15092
+ PROVIDERS.filter(
15093
+ (provider) => provider.plan || provider.planEnv && env[provider.planEnv]
15094
+ ).map((provider) => provider.piName ?? provider.id)
15095
+ );
15096
+ }
15097
+ var ALWAYS_PLANS = planProviders({});
15098
+ function billingOf(provider, plans = ALWAYS_PLANS) {
15099
+ if (BY_PI_NAME.get(provider)?.local) return "local";
15100
+ if (plans.has(provider)) return "plan";
15101
+ return "paid";
15102
+ }
15103
+ var emptyTotals = () => ({
15104
+ calls: 0,
15105
+ inputTokens: 0,
15106
+ outputTokens: 0,
15107
+ cacheReadTokens: 0,
15108
+ cacheWriteTokens: 0,
15109
+ totalTokens: 0,
15110
+ cost: 0,
15111
+ estimated: false,
15112
+ planTokens: 0,
15113
+ localTokens: 0,
15114
+ unpricedTokens: 0
15115
+ });
15116
+ function addRecord(totals, record, plans = ALWAYS_PLANS) {
15117
+ const billing = billingOf(record.provider, plans);
15118
+ totals.calls += record.calls;
15119
+ totals.inputTokens += record.input;
15120
+ totals.outputTokens += record.output;
15121
+ totals.cacheReadTokens += record.cacheRead;
15122
+ totals.cacheWriteTokens += record.cacheWrite;
15123
+ totals.totalTokens += record.total;
15124
+ if (billing === "plan") totals.planTokens += record.total;
15125
+ else if (billing === "local") totals.localTokens += record.total;
15126
+ else if (record.cost > 0) {
15127
+ totals.cost += record.cost;
15128
+ if (!record.billed) totals.estimated = true;
15129
+ } else totals.unpricedTokens += record.total;
15130
+ }
15131
+ var formatters = /* @__PURE__ */ new Map();
15132
+ function validTimeZone(value) {
15133
+ if (!value) return null;
15134
+ try {
15135
+ return new Intl.DateTimeFormat("en-CA", { timeZone: value }).resolvedOptions().timeZone;
15136
+ } catch {
15137
+ return null;
15138
+ }
15139
+ }
15140
+ function dayOf(at, timeZone) {
15141
+ let formatter = formatters.get(timeZone);
15142
+ if (!formatter) {
15143
+ formatter = new Intl.DateTimeFormat("en-CA", {
15144
+ timeZone,
15145
+ year: "numeric",
15146
+ month: "2-digit",
15147
+ day: "2-digit"
15148
+ });
15149
+ formatters.set(timeZone, formatter);
15150
+ }
15151
+ return formatter.format(at);
15152
+ }
15153
+ function shiftDay(day, offset) {
15154
+ const date = /* @__PURE__ */ new Date(`${day}T00:00:00Z`);
15155
+ date.setUTCDate(date.getUTCDate() + offset);
15156
+ return date.toISOString().slice(0, 10);
15157
+ }
15158
+ function agentRows(db) {
15159
+ return db.raw.query(
15160
+ `SELECT a.id, a.name, a.status, a.team_id, t.name team_name
15161
+ FROM agents a JOIN teams t ON t.id = a.team_id`
15162
+ ).all();
15163
+ }
15164
+ var bySpend = (a, b) => b.cost - a.cost || b.totalTokens - a.totalTokens;
15165
+ function usageReport(db, paths, query) {
15166
+ const plans = query.plans ?? ALWAYS_PLANS;
15167
+ const agents = agentRows(db);
15168
+ const shown = agents.filter(
15169
+ (agent) => (!query.agentId || agent.id === query.agentId) && (!query.teamId || agent.team_id === query.teamId)
15170
+ );
15171
+ const { conversations, unreadable } = scanUsage(
15172
+ paths,
15173
+ shown.map((agent) => agent.id),
15174
+ { everyAgent: shown.length === agents.length }
15175
+ );
15176
+ const to = dayOf(query.now ?? Date.now(), query.timeZone);
15177
+ const from = query.days === null ? null : shiftDay(to, -(query.days - 1));
15178
+ const totals = emptyTotals();
15179
+ const days = /* @__PURE__ */ new Map();
15180
+ const byAgent = /* @__PURE__ */ new Map();
15181
+ const byTeam = /* @__PURE__ */ new Map();
15182
+ const byModel = /* @__PURE__ */ new Map();
15183
+ if (from !== null) {
15184
+ for (let day = from; day <= to; day = shiftDay(day, 1)) days.set(day, { day, ...emptyTotals() });
15185
+ }
15186
+ const agentById = new Map(agents.map((agent) => [agent.id, agent]));
15187
+ for (const conversation of conversations) {
15188
+ const agent = agentById.get(conversation.agentId);
15189
+ if (!agent) continue;
15190
+ for (const record of conversation.records) {
15191
+ const day = dayOf(record.at, query.timeZone);
15192
+ if (from !== null && day < from || day > to) continue;
15193
+ addRecord(totals, record, plans);
15194
+ let dayTotals = days.get(day);
15195
+ if (!dayTotals) {
15196
+ dayTotals = { day, ...emptyTotals() };
15197
+ days.set(day, dayTotals);
15198
+ }
15199
+ addRecord(dayTotals, record, plans);
15200
+ let agentTotals = byAgent.get(agent.id);
15201
+ if (!agentTotals) {
15202
+ agentTotals = {
15203
+ agentId: agent.id,
15204
+ agentName: agent.name,
15205
+ teamId: agent.team_id,
15206
+ teamName: agent.team_name,
15207
+ archived: agent.status === "archived",
15208
+ ...emptyTotals()
15209
+ };
15210
+ byAgent.set(agent.id, agentTotals);
15211
+ }
15212
+ addRecord(agentTotals, record, plans);
15213
+ let teamTotals = byTeam.get(agent.team_id);
15214
+ if (!teamTotals) {
15215
+ teamTotals = { teamId: agent.team_id, teamName: agent.team_name, ...emptyTotals() };
15216
+ byTeam.set(agent.team_id, teamTotals);
15217
+ }
15218
+ addRecord(teamTotals, record, plans);
15219
+ const modelKey = `${record.provider}\0${record.model}`;
15220
+ let modelTotals = byModel.get(modelKey);
15221
+ if (!modelTotals) {
15222
+ modelTotals = {
15223
+ provider: record.provider,
15224
+ providerName: BY_PI_NAME.get(record.provider)?.displayName ?? record.provider,
15225
+ model: record.model,
15226
+ billing: billingOf(record.provider, plans),
15227
+ ...emptyTotals()
15228
+ };
15229
+ byModel.set(modelKey, modelTotals);
15230
+ }
15231
+ addRecord(modelTotals, record, plans);
15232
+ }
15233
+ }
15234
+ return {
15235
+ days: query.days,
15236
+ timeZone: query.timeZone,
15237
+ from,
15238
+ to,
15239
+ totals,
15240
+ byDay: [...days.values()].sort((a, b) => a.day.localeCompare(b.day)),
15241
+ byAgent: [...byAgent.values()].sort(bySpend),
15242
+ byTeam: [...byTeam.values()].sort(bySpend),
15243
+ byModel: [...byModel.values()].sort(bySpend),
15244
+ unreadable,
15245
+ scope: query.agentId ? {
15246
+ kind: "agent",
15247
+ id: query.agentId,
15248
+ name: agentById.get(query.agentId)?.name ?? query.agentId
15249
+ } : query.teamId ? {
15250
+ kind: "team",
15251
+ id: query.teamId,
15252
+ name: db.raw.query("SELECT name FROM teams WHERE id = ?").get(query.teamId)?.name ?? query.teamId
15253
+ } : null
15254
+ };
15255
+ }
15256
+ function conversationUsage2(paths, agentId, plans = ALWAYS_PLANS) {
15257
+ const usage = /* @__PURE__ */ new Map();
15258
+ for (const conversation of scanUsage(paths, [agentId]).conversations) {
15259
+ const totals = emptyTotals();
15260
+ for (const record of conversation.records) addRecord(totals, record, plans);
15261
+ usage.set(conversation.conversationId, {
15262
+ calls: totals.calls,
15263
+ totalTokens: totals.totalTokens,
15264
+ cost: totals.cost,
15265
+ estimated: totals.estimated,
15266
+ planTokens: totals.planTokens,
15267
+ localTokens: totals.localTokens
15268
+ });
15269
+ }
15270
+ return usage;
15271
+ }
15272
+
15273
+ // ../daemon/src/routes/conversations.ts
15274
+ var conversationsRouter = newRouter();
15275
+ var conversationSearchRouter = newRouter();
15276
+ conversationSearchRouter.get("/search", async (c) => {
15277
+ const { db, paths, authToken } = getCtx();
15278
+ const agent = c.req.query("agent");
15279
+ return c.json(
15280
+ await searchConversations(db, paths, {
15281
+ signal: c.req.raw.signal,
15282
+ query: c.req.query("q") ?? "",
15283
+ ...agent ? { agentId: routeAgentRef(agent).id } : {},
15284
+ limit: Number(c.req.query("limit") ?? 20) || 20,
15285
+ secrets: envSecretValues(mergeSecretsIntoEnv(db, authToken))
15286
+ })
15287
+ );
15288
+ });
15289
+ conversationsRouter.use("/:agentId/conversations/*", async (c, next) => {
15290
+ c.set("agentId", routeAgent(c, "agentId").id);
15291
+ await next();
15292
+ });
15293
+ conversationsRouter.get("/:agentId/conversations", (c) => {
15294
+ const { db, paths } = getCtx();
15295
+ const list13 = list11(
15296
+ db,
15297
+ c.get("agentId"),
15298
+ Number(c.req.query("limit") ?? 20),
15299
+ Number(c.req.query("offset") ?? 0)
15300
+ );
15301
+ const used = conversationUsage2(
15302
+ paths,
15303
+ c.get("agentId"),
15304
+ planProviders(mergeSecretsIntoEnv(db, getCtx().authToken))
15305
+ );
15306
+ const usage = {};
15307
+ for (const conversation of list13.conversations) {
15308
+ const found = used.get(conversation.id);
15309
+ if (found) usage[conversation.id] = found;
15310
+ }
15311
+ return c.json({ ...list13, usage });
15312
+ });
15313
+ conversationsRouter.post("/:agentId/conversations", async (c) => {
15314
+ const input = await jsonBody(c);
15315
+ const agentId = c.get("agentId");
15316
+ const { db, paths } = getCtx();
15317
+ return c.json(
15318
+ await runAgentLifecycleMutation(
15319
+ agentId,
15320
+ () => startConversation(db, paths, agentId, input?.title)
15321
+ )
15322
+ );
15323
+ });
15324
+ conversationsRouter.get("/:agentId/conversations/:id", (c) => {
15325
+ const { db, paths, authToken } = getCtx();
15326
+ const agentId = c.get("agentId");
15327
+ const id = c.req.param("id");
15328
+ const conversation = get16(db, agentId, id);
15329
+ if (!conversation) return c.json({ error: "Conversation not found" }, 404);
15330
+ try {
15331
+ const messages = piMessagesToProviderView(
15332
+ loadInitialMessages(resolveAgent(db, paths, agentId), paths, { id }),
15333
+ envSecretValues(mergeSecretsIntoEnv(db, authToken))
15334
+ );
15335
+ const usage = conversationUsage2(paths, agentId, planProviders(mergeSecretsIntoEnv(db, authToken))).get(
15336
+ id
15337
+ ) ?? null;
15338
+ return c.json({ conversation, messages, usage });
15339
+ } catch {
15340
+ return c.json(
15341
+ {
15342
+ error: "Conversation history is missing, corrupt or unavailable",
15343
+ conversation
15344
+ },
15345
+ 409
15346
+ );
15347
+ }
15348
+ });
15349
+ conversationsRouter.post("/:agentId/conversations/:id/select", async (c) => {
15350
+ const agentId = c.get("agentId");
15351
+ const id = c.req.param("id");
15352
+ const { db, paths } = getCtx();
15353
+ return c.json({
15354
+ conversation: await runAgentLifecycleMutation(
15355
+ agentId,
15356
+ () => selectConversation(db, paths, agentId, id)
15357
+ )
15358
+ });
15359
+ });
15360
+ conversationsRouter.patch("/:agentId/conversations/:id", async (c) => {
15361
+ const input = await jsonBody(c);
15362
+ return c.json({
15363
+ conversation: rename(
15364
+ getCtx().db,
15365
+ c.get("agentId"),
15366
+ c.req.param("id"),
15367
+ input?.title
15368
+ )
15369
+ });
15370
+ });
15371
+
15372
+ // ../daemon/src/routes/events.ts
15373
+ import { streamSSE } from "hono/streaming";
15374
+
15375
+ // ../daemon/src/lib/live.ts
15376
+ import { createHash as createHash7 } from "node:crypto";
15377
+ var CHECK_MS = 1e3;
15378
+ var ATTENTION_EVERY = 5;
15379
+ var SETTLE_MS = 25;
15380
+ function readLiveActivity() {
15381
+ const { db, paths } = getCtx();
15382
+ return { type: "activity", agents: readActivity(db, paths) };
15383
+ }
15384
+ function readLiveAttention() {
15385
+ const { db } = getCtx();
15386
+ const waiting = waitingAttention(db);
15387
+ const all = projectAttention(db, { state: "all", limit: 1e5 }, waiting);
15388
+ const revision = createHash7("sha256").update(
15389
+ all.items.map((item) => `${item.key}|${item.updatedAt}|${item.acknowledgedAt ?? ""}`).join("\n")
15390
+ ).update(JSON.stringify(all.degraded)).digest("hex").slice(0, 16);
15391
+ return {
15392
+ type: "attention",
15393
+ summary: summarizeAttention(all.items, all.degraded),
15394
+ revision,
15395
+ waiting: all.items.filter((item) => waiting.some((entry) => entry.key === item.key))
15396
+ };
15397
+ }
15398
+ var LiveFeed = class {
15399
+ #listeners = /* @__PURE__ */ new Set();
15400
+ #last = /* @__PURE__ */ new Map();
15401
+ #timer;
15402
+ #settle;
15403
+ #ticks = 0;
15404
+ #unsignal;
15405
+ /** Listen; the current state is sent first. Returns the function that stops listening. */
15406
+ subscribe(listener) {
15407
+ this.#listeners.add(listener);
15408
+ for (const event of this.#read()) listener(event);
15409
+ if (this.#listeners.size === 1) this.#start();
15410
+ return () => {
15411
+ this.#listeners.delete(listener);
15412
+ if (this.#listeners.size === 0) this.#stop();
15413
+ };
15414
+ }
15415
+ get listeners() {
15416
+ return this.#listeners.size;
15417
+ }
15418
+ #start() {
15419
+ this.#timer = setInterval(() => {
15420
+ this.#ticks++;
15421
+ this.#check(this.#ticks % ATTENTION_EVERY === 0);
15422
+ }, CHECK_MS);
15423
+ this.#timer.unref();
15424
+ this.#unsignal = onLiveChange(() => {
15425
+ this.#settle ??= setTimeout(() => {
15426
+ this.#settle = void 0;
15427
+ this.#check(true);
15428
+ }, SETTLE_MS);
15429
+ });
15430
+ }
15431
+ #stop() {
15432
+ clearInterval(this.#timer);
15433
+ clearTimeout(this.#settle);
15434
+ this.#timer = void 0;
15435
+ this.#settle = void 0;
15436
+ this.#unsignal?.();
15437
+ this.#unsignal = void 0;
15438
+ this.#last.clear();
15439
+ }
15440
+ #read(attention = true) {
15441
+ const events = [];
15442
+ try {
15443
+ events.push(readLiveActivity());
15444
+ } catch (error) {
15445
+ console.warn(`live feed: activity: ${error instanceof Error ? error.message : error}`);
15446
+ }
15447
+ if (!attention) return events;
15448
+ try {
15449
+ events.push(readLiveAttention());
15450
+ } catch (error) {
15451
+ console.warn(`live feed: attention: ${error instanceof Error ? error.message : error}`);
15452
+ }
15453
+ return events;
15454
+ }
15455
+ #check(attention) {
15456
+ if (this.#listeners.size === 0) return;
15457
+ for (const event of this.#read(attention)) {
15458
+ const json = JSON.stringify(event);
15459
+ if (this.#last.get(event.type) === json) continue;
15460
+ this.#last.set(event.type, json);
15461
+ for (const listener of this.#listeners) listener(event);
15462
+ }
15463
+ }
15464
+ };
15465
+ var FEED_KEY = /* @__PURE__ */ Symbol.for("bazilion.live.feed");
15466
+ function liveFeed() {
15467
+ const holder = globalThis;
15468
+ holder[FEED_KEY] ??= new LiveFeed();
15469
+ return holder[FEED_KEY];
15470
+ }
15471
+
15472
+ // ../daemon/src/routes/events.ts
15473
+ var keepaliveMs = 2e4;
15474
+ var eventsRouter = newRouter();
15475
+ eventsRouter.get("/", (c) => {
15476
+ const stillValid = credentialCheck(c);
15477
+ c.header("cache-control", "no-store");
15478
+ c.header("x-accel-buffering", "no");
15479
+ return streamSSE(c, async (stream) => {
15480
+ let id = 0;
15481
+ const unsubscribe = liveFeed().subscribe((event) => {
15482
+ void stream.writeSSE({ event: event.type, data: JSON.stringify(event), id: String(++id) });
15483
+ });
15484
+ let keepalive;
15485
+ try {
15486
+ await new Promise((resolve9) => {
15487
+ stream.onAbort(resolve9);
15488
+ c.req.raw.signal.addEventListener("abort", () => resolve9(), { once: true });
15489
+ keepalive = setInterval(() => {
15490
+ if (stillValid()) void stream.write(": keepalive\n\n");
15491
+ else resolve9();
15492
+ }, keepaliveMs);
15493
+ });
15494
+ } finally {
15495
+ clearInterval(keepalive);
15496
+ unsubscribe();
15497
+ }
15498
+ });
15499
+ });
15500
+
15501
+ // ../daemon/src/routes/mcp.ts
15502
+ init_pool();
15503
+ var mcpRouter = newRouter();
15504
+ var TRANSPORTS = /* @__PURE__ */ new Set(["stdio", "http"]);
15505
+ function validate(input) {
15506
+ if (!input.name || !/^[a-zA-Z0-9_]+$/.test(input.name)) {
15507
+ return "name is required and must match [a-zA-Z0-9_]+ (letters, digits, underscore)";
15508
+ }
15509
+ if (!TRANSPORTS.has(input.transport)) return "transport must be stdio or http";
15510
+ if (input.transport === "stdio") {
15511
+ if (!input.command) return "stdio transport requires a command";
15512
+ } else {
15513
+ if (!input.url) return "http transport requires a url";
15514
+ try {
15515
+ const url = new URL(input.url);
15516
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.hash)
15517
+ return "http requires an HTTP(S) endpoint without embedded credentials or fragment";
15518
+ } catch {
15519
+ return "http requires a valid endpoint URL";
15520
+ }
15521
+ }
15522
+ return null;
15523
+ }
15524
+ mcpRouter.get("/", (c) => {
15525
+ const { db } = getCtx();
14624
15526
  return c.json({ servers: mcpServers_exports.list(db) });
14625
15527
  });
14626
15528
  mcpRouter.post("/", async (c) => {
@@ -14781,23 +15683,23 @@ agentMessagesRouter.post("/:id/messages", async (c) => {
14781
15683
  // ../daemon/src/routes/misc.ts
14782
15684
  import { existsSync as existsSync17 } from "node:fs";
14783
15685
  import { homedir as homedir4 } from "node:os";
14784
- import { join as join32 } from "node:path";
15686
+ import { join as join34 } from "node:path";
14785
15687
 
14786
15688
  // ../daemon/src/lib/backup.ts
14787
15689
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync13 } from "node:fs";
14788
15690
  import { tmpdir as tmpdir3 } from "node:os";
14789
- import { join as join31, resolve as resolve7 } from "node:path";
15691
+ import { join as join33, resolve as resolve7 } from "node:path";
14790
15692
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
14791
15693
  import { create as create6 } from "tar";
14792
15694
 
14793
15695
  // ../daemon/src/lib/daemon-liveness.ts
14794
15696
  import { mkdirSync as mkdirSync11, readFileSync as readFileSync11, rmSync as rmSync12, writeFileSync as writeFileSync10 } from "node:fs";
14795
- import { join as join30 } from "node:path";
15697
+ import { join as join32 } from "node:path";
14796
15698
  var DAEMON_PID_FILE = "daemon.pid";
14797
15699
  function runningDaemonPid(home) {
14798
15700
  let pid;
14799
15701
  try {
14800
- pid = Number.parseInt(readFileSync11(join30(home, DAEMON_PID_FILE), "utf8"), 10);
15702
+ pid = Number.parseInt(readFileSync11(join32(home, DAEMON_PID_FILE), "utf8"), 10);
14801
15703
  } catch (error) {
14802
15704
  if (error.code === "ENOENT") return null;
14803
15705
  throw error;
@@ -14814,12 +15716,12 @@ function assertDaemonStopped(home) {
14814
15716
  const pid = runningDaemonPid(home);
14815
15717
  if (pid !== null) {
14816
15718
  throw new Error(
14817
- `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${join30(home, DAEMON_PID_FILE)})`
15719
+ `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${join32(home, DAEMON_PID_FILE)})`
14818
15720
  );
14819
15721
  }
14820
15722
  }
14821
15723
  function claimDaemonPidFile(home) {
14822
- const path = join30(home, DAEMON_PID_FILE);
15724
+ const path = join32(home, DAEMON_PID_FILE);
14823
15725
  const content = `${process.pid}
14824
15726
  `;
14825
15727
  mkdirSync11(home, { recursive: true });
@@ -14848,10 +15750,10 @@ function createBackupSnapshot(db) {
14848
15750
  return snapshot3;
14849
15751
  }
14850
15752
  async function takeSnapshot(db) {
14851
- const directory = mkdtempSync3(join31(tmpdir3(), "bazilion-backup-"));
15753
+ const directory = mkdtempSync3(join33(tmpdir3(), "bazilion-backup-"));
14852
15754
  const cleanup = () => rmSync13(directory, { recursive: true, force: true });
14853
15755
  try {
14854
- const database = join31(directory, "bazilion.snapshot");
15756
+ const database = join33(directory, "bazilion.snapshot");
14855
15757
  await db.backupTo(database);
14856
15758
  const snapshot3 = new DatabaseSync2(database, { readOnly: true });
14857
15759
  try {
@@ -14950,7 +15852,7 @@ miscRouter.get("/health/details", async (c) => {
14950
15852
  } catch {
14951
15853
  }
14952
15854
  }
14953
- const openclawSkillsDir = join32(homedir4(), ".openclaw", "skills");
15855
+ const openclawSkillsDir = join34(homedir4(), ".openclaw", "skills");
14954
15856
  const providerSection = {
14955
15857
  // Hosted providers with credentials; local servers are reported below.
14956
15858
  configured: PROVIDERS.filter(
@@ -15359,7 +16261,7 @@ notificationsRouter.put("/", async (c) => {
15359
16261
 
15360
16262
  // ../daemon/src/routes/profiles.ts
15361
16263
  import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "node:fs";
15362
- import { join as join33 } from "node:path";
16264
+ import { join as join35 } from "node:path";
15363
16265
  var profilesRouter = newRouter();
15364
16266
  profilesRouter.get("/", (c) => {
15365
16267
  const { db } = getCtx();
@@ -15441,7 +16343,7 @@ function profileFile(c) {
15441
16343
  if (!PROFILE_FILES.includes(file)) {
15442
16344
  return c.json({ error: `unsupported file: ${file}` }, 400);
15443
16345
  }
15444
- return join33(paths.profilesDir, id, file);
16346
+ return join35(paths.profilesDir, id, file);
15445
16347
  }
15446
16348
  profilesRouter.get("/:id/files/:file", (c) => {
15447
16349
  const path = profileFile(c);
@@ -15495,11 +16397,11 @@ function dosDateTime(epochMs) {
15495
16397
  function uniqueNames(names) {
15496
16398
  const seen = /* @__PURE__ */ new Map();
15497
16399
  return names.map((name) => {
15498
- const count = (seen.get(name) ?? 0) + 1;
15499
- seen.set(name, count);
15500
- if (count === 1) return name;
16400
+ const count2 = (seen.get(name) ?? 0) + 1;
16401
+ seen.set(name, count2);
16402
+ if (count2 === 1) return name;
15501
16403
  const dot = name.lastIndexOf(".");
15502
- return dot > 0 ? `${name.slice(0, dot)} (${count})${name.slice(dot)}` : `${name} (${count})`;
16404
+ return dot > 0 ? `${name.slice(0, dot)} (${count2})${name.slice(dot)}` : `${name} (${count2})`;
15503
16405
  });
15504
16406
  }
15505
16407
  function localHeader(name, bytes, crc, epochMs) {
@@ -15662,13 +16564,33 @@ resultsRouter.get("/:id/preview", (c) => {
15662
16564
  const db = getCtx().db;
15663
16565
  const result = get17(db, c.req.param("id"));
15664
16566
  if (!result) return c.json({ error: "Result not found" }, 404);
15665
- const text4 = ["text/plain", "text/markdown"].includes(result.mimeType);
16567
+ const text4 = isTextPreview(result);
15666
16568
  const image = ["image/png", "image/jpeg", "image/gif", "image/webp"].includes(result.mimeType);
15667
- if (!text4 && !image || result.byteLength > (text4 ? 256 * 1024 : 10 * 1024 * 1024)) {
16569
+ if (!text4 && (!image || result.byteLength > 10 * 1024 * 1024)) {
15668
16570
  return c.json({ error: "Preview is unavailable for this file. Use Download." }, 415);
15669
16571
  }
16572
+ const bytesParam = Number(c.req.query("bytes"));
16573
+ const cut = text4 && Number.isInteger(bytesParam) && bytesParam > 0 ? bytesParam : null;
15670
16574
  try {
15671
16575
  const bytes = read(db, result.id);
16576
+ if (text4) {
16577
+ let shown;
16578
+ try {
16579
+ shown = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
16580
+ } catch {
16581
+ return c.json({ error: "This file is not text. Use Download." }, 415);
16582
+ }
16583
+ if (shown.includes("\0"))
16584
+ return c.json({ error: "This file is not text. Use Download." }, 415);
16585
+ if (cut !== null && Buffer.byteLength(shown) > cut) {
16586
+ shown = Buffer.from(shown).subarray(0, cut).toString("utf8").replace(/\uFFFD$/, "");
16587
+ }
16588
+ c.header("Content-Type", "text/plain; charset=utf-8");
16589
+ c.header("X-Content-Type-Options", "nosniff");
16590
+ c.header("Content-Security-Policy", "default-src 'none'; sandbox");
16591
+ c.header("Cache-Control", "private, max-age=3600");
16592
+ return c.body(shown);
16593
+ }
15672
16594
  const magic = result.mimeType === "image/png" ? bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) : result.mimeType === "image/jpeg" ? bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 : result.mimeType === "image/gif" ? ["GIF87a", "GIF89a"].includes(bytes.subarray(0, 6).toString("ascii")) : result.mimeType === "image/webp" ? bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP" : false;
15673
16595
  if (image && !magic)
15674
16596
  return c.json({ error: "File content does not match its image type. Use Download." }, 415);
@@ -15706,7 +16628,7 @@ shellApprovalsRouter.post("/:id", async (c) => {
15706
16628
  // ../daemon/src/routes/skills.ts
15707
16629
  import { mkdtempSync as mkdtempSync4, rmSync as rmSync14, writeFileSync as writeFileSync12 } from "node:fs";
15708
16630
  import { homedir as homedir5, tmpdir as tmpdir4 } from "node:os";
15709
- import { join as join34 } from "node:path";
16631
+ import { join as join36 } from "node:path";
15710
16632
  var MAX_ZIP_BYTES = 50 * 1024 * 1024;
15711
16633
  var skillsRouter = newRouter();
15712
16634
  skillsRouter.get("/", (c) => {
@@ -15799,8 +16721,8 @@ async function parseImportInput(request) {
15799
16721
  if (!filename.toLowerCase().endsWith(".zip")) {
15800
16722
  throw new Error("uploaded file must be a .zip archive");
15801
16723
  }
15802
- const tmpDir = mkdtempSync4(join34(tmpdir4(), "bazilion-skill-upload-"));
15803
- const zipPath = join34(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
16724
+ const tmpDir = mkdtempSync4(join36(tmpdir4(), "bazilion-skill-upload-"));
16725
+ const zipPath = join36(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
15804
16726
  const buf = Buffer.from(await file.arrayBuffer());
15805
16727
  writeFileSync12(zipPath, buf);
15806
16728
  const forceField = form.get("force");
@@ -15816,7 +16738,7 @@ async function parseImportInput(request) {
15816
16738
  const { source } = body;
15817
16739
  if (typeof source !== "string" || !source) throw new Error("source is required");
15818
16740
  return {
15819
- source: source === "openclaw" ? join34(homedir5(), ".openclaw", "skills") : source,
16741
+ source: source === "openclaw" ? join36(homedir5(), ".openclaw", "skills") : source,
15820
16742
  force: Boolean(body.force),
15821
16743
  tempZipPath: null,
15822
16744
  sourceLabel: source
@@ -15886,7 +16808,7 @@ teamCodingEnvironmentRouter.put("/:id/coding-environment", async (c) => {
15886
16808
  });
15887
16809
 
15888
16810
  // ../daemon/src/routes/team-memory.ts
15889
- import { join as join35 } from "node:path";
16811
+ import { join as join37 } from "node:path";
15890
16812
  var teamMemoryRouter = newRouter();
15891
16813
  teamMemoryRouter.onError((error, c) => {
15892
16814
  const safe = sanitizeNativeModuleError(error, { subject: "Bazilion memory" });
@@ -15894,7 +16816,7 @@ teamMemoryRouter.onError((error, c) => {
15894
16816
  return onRouteError(safe, c);
15895
16817
  });
15896
16818
  async function openMemory(c) {
15897
- const mem = qmdBackend(join35(routeTeam(c).path, "memory"));
16819
+ const mem = qmdBackend(join37(routeTeam(c).path, "memory"));
15898
16820
  await mem.init();
15899
16821
  return mem;
15900
16822
  }
@@ -15949,19 +16871,19 @@ teamPolicyRouter.post("/:id/policy/save-as-template", async (c) => {
15949
16871
  });
15950
16872
 
15951
16873
  // ../daemon/src/lib/git/context-directory.ts
15952
- import { createHash as createHash6 } from "node:crypto";
16874
+ import { createHash as createHash8 } from "node:crypto";
15953
16875
  import {
15954
- closeSync as closeSync6,
15955
- constants as constants7,
15956
- fstatSync as fstatSync6,
16876
+ closeSync as closeSync7,
16877
+ constants as constants8,
16878
+ fstatSync as fstatSync7,
15957
16879
  lstatSync as lstatSync6,
15958
16880
  opendirSync,
15959
- openSync as openSync6,
15960
- readSync as readSync3,
16881
+ openSync as openSync7,
16882
+ readSync as readSync4,
15961
16883
  realpathSync as realpathSync7
15962
16884
  } from "node:fs";
15963
- import { join as join36 } from "node:path";
15964
- var hash = (value) => createHash6("sha256").update(value).digest("hex");
16885
+ import { join as join38 } from "node:path";
16886
+ var hash = (value) => createHash8("sha256").update(value).digest("hex");
15965
16887
  var ContextReadError = class extends Error {
15966
16888
  code;
15967
16889
  constructor(code) {
@@ -15998,30 +16920,42 @@ var ContextDirectory = class _ContextDirectory {
15998
16920
  this.parent = parent;
15999
16921
  if (parent) component(registeredPath);
16000
16922
  parent?.assertOpen();
16001
- const canonicalPath = parent ? join36(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
16923
+ const canonicalPath = parent ? join38(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
16002
16924
  this.canonicalPath = canonicalPath;
16003
16925
  let fd;
16004
16926
  try {
16005
- fd = openSync6(
16006
- parent ? join36(parent.path, registeredPath) : canonicalPath,
16007
- constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW
16927
+ fd = openSync7(
16928
+ parent ? join38(parent.path, registeredPath) : canonicalPath,
16929
+ constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW
16008
16930
  );
16009
- const stat = fstatSync6(fd, { bigint: true });
16931
+ const stat = fstatSync7(fd, { bigint: true });
16010
16932
  if (!stat.isDirectory() || stat.ino <= 0n) throw new ContextReadError("root_changed");
16011
16933
  this.fd = fd;
16012
16934
  this.originalIdentity = { dev: stat.dev, ino: stat.ino };
16013
16935
  this.identity = hash(identity(stat));
16014
16936
  fd = void 0;
16015
16937
  } finally {
16016
- if (fd !== void 0) closeSync6(fd);
16938
+ if (fd !== void 0) closeSync7(fd);
16017
16939
  }
16018
16940
  }
16019
16941
  get path() {
16020
- return FD_PATHS ? `/proc/self/fd/${this.fd}` : this.canonicalPath;
16942
+ return FD_PATHS ? `/proc/self/fd/${this.fd}` : this.checkedPath();
16021
16943
  }
16022
16944
  /** The worktree path handed to an external Git process (descriptor-pinned on Linux). */
16023
16945
  get gitWorktreePath() {
16024
- return FD_PATHS ? `/proc/${process.pid}/fd/${this.fd}` : this.canonicalPath;
16946
+ return FD_PATHS ? `/proc/${process.pid}/fd/${this.fd}` : this.checkedPath();
16947
+ }
16948
+ /** The canonical path, once it is seen to name the directory that was opened. */
16949
+ checkedPath() {
16950
+ let stat;
16951
+ try {
16952
+ stat = lstatSync6(this.canonicalPath, { bigint: true });
16953
+ } catch {
16954
+ throw new ContextReadError("root_changed");
16955
+ }
16956
+ if (!stat.isDirectory() || identity(stat) !== identity(this.originalIdentity))
16957
+ throw new ContextReadError("root_changed");
16958
+ return this.canonicalPath;
16025
16959
  }
16026
16960
  /** Every public method is synchronous, so one check on entry covers the whole call. */
16027
16961
  assertOpen() {
@@ -16040,16 +16974,18 @@ var ContextDirectory = class _ContextDirectory {
16040
16974
  entry(name) {
16041
16975
  component(name);
16042
16976
  this.assertOpen();
16977
+ const path = join38(this.path, name);
16043
16978
  try {
16044
- return lstatSync6(join36(this.path, name));
16979
+ return lstatSync6(path);
16045
16980
  } catch (error) {
16046
16981
  if (error.code === "ENOENT") return null;
16047
16982
  throw new ContextReadError("unreadable");
16048
16983
  }
16049
16984
  }
16050
16985
  observe(name) {
16986
+ const path = join38(this.path, name);
16051
16987
  try {
16052
- return lstatSync6(join36(this.path, name), { bigint: true });
16988
+ return lstatSync6(path, { bigint: true });
16053
16989
  } catch (error) {
16054
16990
  if (error.code === "ENOENT") return null;
16055
16991
  throw new ContextReadError("unreadable");
@@ -16089,38 +17025,39 @@ var ContextDirectory = class _ContextDirectory {
16089
17025
  if (entry.size > maxBytes) throw new ContextReadError("byte_limit");
16090
17026
  let fd;
16091
17027
  try {
16092
- fd = openSync6(
16093
- join36(this.path, name),
16094
- constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK
17028
+ fd = openSync7(
17029
+ join38(this.path, name),
17030
+ constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK
16095
17031
  );
16096
- const before = fstatSync6(fd, { bigint: true });
17032
+ const before = fstatSync7(fd, { bigint: true });
16097
17033
  if (!before.isFile() || stamp(entry) !== stamp(before))
16098
17034
  throw new ContextReadError("source_changed");
16099
17035
  const buffer = Buffer.alloc(Math.min(maxBytes, Number(before.size)) + 1);
16100
17036
  let size = 0;
16101
17037
  while (size < buffer.length) {
16102
- const count = readSync3(fd, buffer, size, buffer.length - size, null);
16103
- if (!count) break;
16104
- size += count;
17038
+ const count2 = readSync4(fd, buffer, size, buffer.length - size, null);
17039
+ if (!count2) break;
17040
+ size += count2;
16105
17041
  }
16106
- if (size > maxBytes || BigInt(size) !== before.size || stamp(fstatSync6(fd, { bigint: true })) !== stamp(before))
17042
+ if (size > maxBytes || BigInt(size) !== before.size || stamp(fstatSync7(fd, { bigint: true })) !== stamp(before))
16107
17043
  throw new ContextReadError("source_changed");
17044
+ if (!FD_PATHS) this.checkedPath();
16108
17045
  this.observedFiles.set(name, stamp(before));
16109
17046
  return buffer.subarray(0, size);
16110
17047
  } catch (error) {
16111
17048
  if (error instanceof ContextReadError) throw error;
16112
17049
  throw new ContextReadError("unreadable");
16113
17050
  } finally {
16114
- if (fd !== void 0) closeSync6(fd);
17051
+ if (fd !== void 0) closeSync7(fd);
16115
17052
  }
16116
17053
  }
16117
17054
  validate(skipGit = false, names) {
16118
17055
  this.assertOpen();
16119
- const currentPath = this.parent ? join36(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
17056
+ const currentPath = this.parent ? join38(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
16120
17057
  const stat = lstatSync6(currentPath, { bigint: true });
16121
17058
  if (!stat.isDirectory() || identity(stat) !== identity(this.originalIdentity))
16122
17059
  throw new ContextReadError("root_changed");
16123
- const retained = fstatSync6(this.fd, { bigint: true });
17060
+ const retained = fstatSync7(this.fd, { bigint: true });
16124
17061
  if (!retained.isDirectory() || identity(retained) !== identity(this.originalIdentity))
16125
17062
  throw new ContextReadError("root_changed");
16126
17063
  if (this.listing !== void 0 && JSON.stringify(this.listNames()) !== this.listing)
@@ -16147,7 +17084,7 @@ var ContextDirectory = class _ContextDirectory {
16147
17084
  }
16148
17085
  }
16149
17086
  try {
16150
- closeSync6(this.fd);
17087
+ closeSync7(this.fd);
16151
17088
  } catch (error) {
16152
17089
  failure ??= error;
16153
17090
  }
@@ -16224,18 +17161,18 @@ async function listChanges(captured, base, identity2, limits = REVIEW_LIMITS) {
16224
17161
  for (const header of parseRaw(raw)) {
16225
17162
  const scoped = reviewScope(header.path);
16226
17163
  if (!scoped.included) excludedTracked++;
16227
- const count = counts.get(header.path) ?? null;
17164
+ const count2 = counts.get(header.path) ?? null;
16228
17165
  entries.push({
16229
17166
  path: header.path,
16230
17167
  previousPath: header.previousPath,
16231
17168
  status: header.status,
16232
- binary: count?.binary ?? false,
16233
- addedLines: count?.added ?? null,
16234
- deletedLines: count?.deleted ?? null,
17169
+ binary: count2?.binary ?? false,
17170
+ addedLines: count2?.added ?? null,
17171
+ deletedLines: count2?.deleted ?? null,
16235
17172
  patch: null,
16236
17173
  patchTruncated: false,
16237
17174
  // A credential-shaped or Bazilion-owned tracked file may be listed, but never captured.
16238
- contentOmitted: scoped.included ? count?.binary ? "binary" : null : "excluded",
17175
+ contentOmitted: scoped.included ? count2?.binary ? "binary" : null : "excluded",
16239
17176
  excludedReason: scoped.included ? null : scoped.reason
16240
17177
  });
16241
17178
  }
@@ -16544,7 +17481,7 @@ async function readOrNull(captured, args) {
16544
17481
  import { execFile } from "node:child_process";
16545
17482
  import { mkdirSync as mkdirSync12, mkdtempSync as mkdtempSync5, rmSync as rmSync15, utimesSync, writeFileSync as writeFileSync13 } from "node:fs";
16546
17483
  import { tmpdir as tmpdir5 } from "node:os";
16547
- import { join as join37 } from "node:path";
17484
+ import { join as join39 } from "node:path";
16548
17485
  var INSPECTION_BUDGET_MS = 5e3;
16549
17486
  var METADATA_BUDGET_MS = 2500;
16550
17487
  var METADATA_BYTES = 64 * 1024 * 1024;
@@ -16560,7 +17497,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16560
17497
  const worktree = root.gitWorktreePath;
16561
17498
  const start2 = Date.now();
16562
17499
  let bytes = 0;
16563
- let count = 0;
17500
+ let count2 = 0;
16564
17501
  const marker = root.entry(".git");
16565
17502
  if (!marker?.isDirectory() || marker.isSymbolicLink())
16566
17503
  throw new ContextReadError("unsupported_git_metadata");
@@ -16573,7 +17510,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16573
17510
  const dir = git.directory("info");
16574
17511
  if (dir.entry("sparse-checkout")) throw new ContextReadError("unsupported_git_metadata");
16575
17512
  }
16576
- const scratch = mkdtempSync5(join37(tmpdir5(), "bazilion-context-git-"));
17513
+ const scratch = mkdtempSync5(join39(tmpdir5(), "bazilion-context-git-"));
16577
17514
  let cleaned = false;
16578
17515
  const cleanup = () => {
16579
17516
  if (cleaned) return;
@@ -16633,8 +17570,8 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16633
17570
  const configLines = ["[core]", "repositoryformatversion = 0", "bare = false", "filemode = true"];
16634
17571
  if (capturedConfig) {
16635
17572
  bytes += capturedConfig.length;
16636
- count++;
16637
- const configPath = join37(scratch, "captured-config");
17573
+ count2++;
17574
+ const configPath = join39(scratch, "captured-config");
16638
17575
  writeFileSync13(configPath, capturedConfig, { mode: 384 });
16639
17576
  const config = await rawGit([
16640
17577
  "config",
@@ -16687,27 +17624,27 @@ objectformat = ${value}`
16687
17624
  const exclude = git.directory("info").read("exclude", METADATA_READ);
16688
17625
  if (exclude) {
16689
17626
  bytes += exclude.length;
16690
- mkdirSync12(join37(scratch, "info"), { mode: 448 });
16691
- writeFileSync13(join37(scratch, "info", "exclude"), exclude, { mode: 384 });
17627
+ mkdirSync12(join39(scratch, "info"), { mode: 448 });
17628
+ writeFileSync13(join39(scratch, "info", "exclude"), exclude, { mode: 384 });
16692
17629
  }
16693
17630
  }
16694
17631
  const copy = (source, destination, depth) => {
16695
17632
  if (depth > METADATA_DEPTH) throw new ContextReadError("git_metadata_limit");
16696
17633
  for (const name of source.list()) {
16697
- if (++count > METADATA_ENTRIES || Date.now() - start2 > METADATA_BUDGET_MS)
17634
+ if (++count2 > METADATA_ENTRIES || Date.now() - start2 > METADATA_BUDGET_MS)
16698
17635
  throw new ContextReadError("git_metadata_limit");
16699
17636
  const entry = source.entry(name);
16700
17637
  if (!entry || entry.isSymbolicLink()) throw new ContextReadError("unsupported_git_metadata");
16701
17638
  if (name === "alternates" || name === "http-alternates")
16702
17639
  throw new ContextReadError("unsupported_git_metadata");
16703
17640
  if (entry.isDirectory()) {
16704
- mkdirSync12(join37(destination, name), { mode: 448 });
16705
- copy(source.directory(name), join37(destination, name), depth + 1);
17641
+ mkdirSync12(join39(destination, name), { mode: 448 });
17642
+ copy(source.directory(name), join39(destination, name), depth + 1);
16706
17643
  } else {
16707
17644
  const content = source.read(name, METADATA_BYTES - bytes);
16708
17645
  if (!content) throw new ContextReadError("source_changed");
16709
17646
  bytes += content.length;
16710
- writeFileSync13(join37(destination, name), content, { mode: 384 });
17647
+ writeFileSync13(join39(destination, name), content, { mode: 384 });
16711
17648
  }
16712
17649
  }
16713
17650
  };
@@ -16715,22 +17652,22 @@ objectformat = ${value}`
16715
17652
  const written = name === "index" ? git.entry(name) : null;
16716
17653
  const content = git.read(name, Math.min(METADATA_READ_LARGE, METADATA_BYTES - bytes));
16717
17654
  if (content) {
16718
- count++;
17655
+ count2++;
16719
17656
  bytes += content.length;
16720
- writeFileSync13(join37(scratch, name), content, { mode: 384 });
17657
+ writeFileSync13(join39(scratch, name), content, { mode: 384 });
16721
17658
  if (written) {
16722
17659
  const seconds = Math.floor(written.mtimeMs / 1e3);
16723
- utimesSync(join37(scratch, name), seconds, seconds);
17660
+ utimesSync(join39(scratch, name), seconds, seconds);
16724
17661
  }
16725
17662
  }
16726
17663
  }
16727
17664
  for (const name of ["refs", "objects"]) {
16728
- mkdirSync12(join37(scratch, name), { mode: 448 });
16729
- if (git.entry(name)) copy(git.directory(name), join37(scratch, name), 0);
17665
+ mkdirSync12(join39(scratch, name), { mode: 448 });
17666
+ if (git.entry(name)) copy(git.directory(name), join39(scratch, name), 0);
16730
17667
  }
16731
17668
  if (git.list().some((name) => name.startsWith("sharedindex.")))
16732
17669
  throw new ContextReadError("unsupported_git_metadata");
16733
- writeFileSync13(join37(scratch, "config"), `${configLines.join("\n")}
17670
+ writeFileSync13(join39(scratch, "config"), `${configLines.join("\n")}
16734
17671
  `, { mode: 384 });
16735
17672
  const validate2 = () => git.validate();
16736
17673
  validate2();
@@ -16743,7 +17680,7 @@ objectformat = ${value}`
16743
17680
 
16744
17681
  // ../daemon/src/lib/git-review/authors.ts
16745
17682
  import { realpathSync as realpathSync8 } from "node:fs";
16746
- import { isAbsolute as isAbsolute8, join as join38, relative as relative5, resolve as resolve8, sep as sep6 } from "node:path";
17683
+ import { isAbsolute as isAbsolute8, join as join40, relative as relative5, resolve as resolve8, sep as sep6 } from "node:path";
16747
17684
  var FILE_TOOLS = /* @__PURE__ */ new Set(["write", "edit"]);
16748
17685
  var CONVERSATIONS_PER_AGENT = 5;
16749
17686
  var SANDBOX_ROOT = "/workspace";
@@ -16768,7 +17705,7 @@ function readChangeAuthors(db, paths, team, changedPaths) {
16768
17705
  }
16769
17706
  const members = list(db, { includeArchived: true }).filter((agent) => agent.teamId === team.id);
16770
17707
  for (const agent of members) {
16771
- const directory = join38(paths.agentDir(agent.id), "sessions");
17708
+ const directory = join40(paths.agentDir(agent.id), "sessions");
16772
17709
  const recent = list11(db, agent.id, CONVERSATIONS_PER_AGENT, 0).conversations;
16773
17710
  for (const conversation of recent) {
16774
17711
  let lines;
@@ -16909,8 +17846,8 @@ function hunkForLine(patch, line) {
16909
17846
  const header = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(lines[start2] ?? "");
16910
17847
  if (!header) continue;
16911
17848
  const first = Number(header[1]);
16912
- const count = header[2] === void 0 ? 1 : Number(header[2]);
16913
- if (line < first || line >= first + Math.max(count, 1)) continue;
17849
+ const count2 = header[2] === void 0 ? 1 : Number(header[2]);
17850
+ if (line < first || line >= first + Math.max(count2, 1)) continue;
16914
17851
  return lines.slice(start2, starts[position + 1] ?? lines.length).join("\n");
16915
17852
  }
16916
17853
  return null;
@@ -17568,8 +18505,8 @@ Run <code>/talk ${htmlEscape(agent.name)}</code> after fixing the underlying iss
17568
18505
  };
17569
18506
  }
17570
18507
  function autoName(ctx, profile) {
17571
- const count = agents_exports.countByProfile(ctx.db, profile.id);
17572
- return `${profile.id}-${count + 1}`;
18508
+ const count2 = agents_exports.countByProfile(ctx.db, profile.id);
18509
+ return `${profile.id}-${count2 + 1}`;
17573
18510
  }
17574
18511
 
17575
18512
  // ../daemon/src/lib/telegram/commands/spawn-team.ts
@@ -17689,9 +18626,9 @@ var handle9 = async (ctx) => {
17689
18626
  }
17690
18627
  const lines = ["<b>bazilion teams</b>", ""];
17691
18628
  for (const g of teams) {
17692
- const count = agents_exports.countByTeam(ctx.db, g.id);
18629
+ const count2 = agents_exports.countByTeam(ctx.db, g.id);
17693
18630
  const label = `<code>${htmlEscape(g.id)}</code> \xB7 ${htmlEscape(g.name)}`;
17694
- lines.push(`${label} \u2014 ${count} agent${count === 1 ? "" : "s"}`);
18631
+ lines.push(`${label} \u2014 ${count2} agent${count2 === 1 ? "" : "s"}`);
17695
18632
  }
17696
18633
  return { text: lines.join("\n"), parseMode: "HTML" };
17697
18634
  };
@@ -18265,6 +19202,13 @@ async function routeCallback(deps, q) {
18265
19202
  await deps.api.answerCallbackQuery(q.id, { text: answerFromTelegram(answer.questionId, answer.answer) }).catch(() => void 0);
18266
19203
  return { kind: "question_answer" };
18267
19204
  }
19205
+ const decision = approvalCallback(data);
19206
+ if (decision) {
19207
+ await deps.api.answerCallbackQuery(q.id, {
19208
+ text: decideFromTelegram(deps.db, q.from.id, decision.approvalId, decision.decision)
19209
+ }).catch(() => void 0);
19210
+ return { kind: "approval_decision" };
19211
+ }
18268
19212
  if (data.startsWith(SPAWN_TEAM_CALLBACK_PREFIX)) {
18269
19213
  await deps.api.answerCallbackQuery(q.id, {}).catch(() => void 0);
18270
19214
  const templateId = data.slice(SPAWN_TEAM_CALLBACK_PREFIX.length);
@@ -18884,10 +19828,7 @@ function parseCron(expr) {
18884
19828
  };
18885
19829
  return parsed;
18886
19830
  }
18887
- function matchesCron(parsed, date) {
18888
- if (!parsed.minute.has(date.getMinutes())) return false;
18889
- if (!parsed.hour.has(date.getHours())) return false;
18890
- if (!parsed.month.has(date.getMonth() + 1)) return false;
19831
+ function dayMatches(parsed, date) {
18891
19832
  const domMatch = parsed.dom.has(date.getDate());
18892
19833
  const dowMatch = parsed.dow.has(date.getDay());
18893
19834
  if (parsed.domRestricted && parsed.dowRestricted) {
@@ -18897,189 +19838,38 @@ function matchesCron(parsed, date) {
18897
19838
  if (parsed.dowRestricted) return dowMatch;
18898
19839
  return true;
18899
19840
  }
19841
+ function matchesCron(parsed, date) {
19842
+ if (!parsed.minute.has(date.getMinutes())) return false;
19843
+ if (!parsed.hour.has(date.getHours())) return false;
19844
+ if (!parsed.month.has(date.getMonth() + 1)) return false;
19845
+ return dayMatches(parsed, date);
19846
+ }
19847
+ var LOOKAHEAD_YEARS = 5;
19848
+ function nextCronMatch(parsed, from) {
19849
+ const date = new Date(Math.ceil(from / 6e4) * 6e4);
19850
+ const limit = new Date(date);
19851
+ limit.setFullYear(limit.getFullYear() + LOOKAHEAD_YEARS);
19852
+ while (date <= limit) {
19853
+ if (!parsed.month.has(date.getMonth() + 1)) {
19854
+ date.setMonth(date.getMonth() + 1, 1);
19855
+ date.setHours(0, 0, 0, 0);
19856
+ } else if (!dayMatches(parsed, date)) {
19857
+ date.setDate(date.getDate() + 1);
19858
+ date.setHours(0, 0, 0, 0);
19859
+ } else if (!parsed.hour.has(date.getHours())) {
19860
+ date.setHours(date.getHours() + 1, 0, 0, 0);
19861
+ } else if (!parsed.minute.has(date.getMinutes())) {
19862
+ date.setTime(date.getTime() + 6e4);
19863
+ } else {
19864
+ return date.getTime();
19865
+ }
19866
+ }
19867
+ return null;
19868
+ }
18900
19869
  function validateCron(expr) {
18901
19870
  parseCron(expr);
18902
19871
  }
18903
19872
 
18904
- // ../daemon/src/routes/triggers.ts
18905
- var triggersRouter = newRouter();
18906
- function triggerExists(id) {
18907
- return triggers_exports.get(getCtx().db, id) !== null;
18908
- }
18909
- triggersRouter.get("/:id/dispatches", (c) => {
18910
- const id = c.req.param("id");
18911
- if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
18912
- const requestedLimit = Number(c.req.query("limit") ?? 20);
18913
- if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
18914
- return c.json({ error: "limit must be a positive integer" }, 400);
18915
- }
18916
- const limit = Math.min(100, requestedLimit);
18917
- return c.json({
18918
- dispatches: triggerDispatches_exports.listForTrigger(getCtx().db, id, limit)
18919
- });
18920
- });
18921
- triggersRouter.delete("/:id", (c) => {
18922
- const id = c.req.param("id");
18923
- if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
18924
- triggers_exports.remove(getCtx().db, id);
18925
- return c.body(null, 204);
18926
- });
18927
- triggersRouter.patch("/:id", async (c) => {
18928
- const id = c.req.param("id");
18929
- const body = await jsonBody(c);
18930
- if (!body) return c.json({ error: "invalid JSON body" }, 400);
18931
- if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
18932
- const { db } = getCtx();
18933
- if (typeof body.enabled === "boolean") triggers_exports.setEnabled(db, id, body.enabled);
18934
- return c.json({ trigger: triggers_exports.get(db, id) });
18935
- });
18936
- var agentTriggersRouter = newRouter();
18937
- agentTriggersRouter.get("/:id/triggers", (c) => {
18938
- const { db } = getCtx();
18939
- const triggers = triggers_exports.listForAgent(db, routeAgent(c).id);
18940
- return c.json({
18941
- triggers,
18942
- dispatches: triggers.flatMap(
18943
- (trigger) => triggerDispatches_exports.listForTrigger(db, trigger.id, 10)
18944
- )
18945
- });
18946
- });
18947
- agentTriggersRouter.post("/:id/triggers", async (c) => {
18948
- const body = await jsonBody(c);
18949
- if (!body) return c.json({ error: "invalid JSON body" }, 400);
18950
- if (typeof body.message !== "string" || !body.message.trim()) {
18951
- return c.json({ error: "message is required" }, 400);
18952
- }
18953
- const agentId = routeAgent(c).id;
18954
- const { db } = getCtx();
18955
- if (body.kind === "interval") {
18956
- const intervalSec = body.intervalSec;
18957
- if (typeof intervalSec !== "number" || !Number.isInteger(intervalSec) || intervalSec < 1) {
18958
- return c.json({ error: "intervalSec must be a whole number of seconds, at least 1" }, 400);
18959
- }
18960
- const trigger = triggers_exports.insert(db, {
18961
- agentId,
18962
- kind: "interval",
18963
- intervalSec,
18964
- cronExpr: null,
18965
- message: body.message,
18966
- enabled: body.enabled
18967
- });
18968
- return c.json({ trigger }, 201);
18969
- }
18970
- if (body.kind === "cron") {
18971
- if (typeof body.cronExpr !== "string" || !body.cronExpr.trim()) {
18972
- return c.json({ error: "cronExpr is required for kind=cron" }, 400);
18973
- }
18974
- try {
18975
- validateCron(body.cronExpr);
18976
- } catch (err) {
18977
- return c.json({ error: `invalid cron: ${err.message}` }, 400);
18978
- }
18979
- const trigger = triggers_exports.insert(db, {
18980
- agentId,
18981
- kind: "cron",
18982
- intervalSec: null,
18983
- cronExpr: body.cronExpr.trim(),
18984
- message: body.message,
18985
- enabled: body.enabled
18986
- });
18987
- return c.json({ trigger }, 201);
18988
- }
18989
- return c.json({ error: `invalid kind: ${body.kind}` }, 400);
18990
- });
18991
-
18992
- // ../daemon/src/routes/user-queue.ts
18993
- import { bodyLimit as bodyLimit3 } from "hono/body-limit";
18994
- var userQueueRouter = newRouter();
18995
- userQueueRouter.use("/:agentId/queue/*", bodyLimit3({ maxSize: 36 * 1024 * 1024 }));
18996
- userQueueRouter.use("/:agentId/queue/*", async (c, next) => {
18997
- c.set("agentId", routeAgent(c, "agentId").id);
18998
- await next();
18999
- });
19000
- userQueueRouter.get(
19001
- "/:agentId/queue",
19002
- (c) => c.json({
19003
- ...list4(getCtx().db, c.get("agentId")),
19004
- turnActive: isActiveAgent(c.get("agentId"))
19005
- })
19006
- );
19007
- userQueueRouter.post("/:agentId/queue", async (c) => {
19008
- const input = await jsonBody(c);
19009
- return c.json(
19010
- await enqueueUserInput(c.get("agentId"), {
19011
- message: input?.message,
19012
- attachments: input?.attachments ?? []
19013
- }),
19014
- 202
19015
- );
19016
- });
19017
- userQueueRouter.patch("/:agentId/queue/:id", async (c) => {
19018
- const input = await jsonBody(c);
19019
- return c.json(
19020
- edit(getCtx().db, c.get("agentId"), c.req.param("id"), input?.message)
19021
- );
19022
- });
19023
- userQueueRouter.delete("/:agentId/queue/:id", async (c) => {
19024
- const { item, origin } = remove4(getCtx().db, c.get("agentId"), c.req.param("id"));
19025
- if (item.status === "pending") await notifyTelegramQueueOutcome(item, origin, "removed");
19026
- return c.json(item);
19027
- });
19028
- userQueueRouter.post("/:agentId/queue/control", async (c) => {
19029
- const input = await jsonBody(c);
19030
- if (typeof input?.paused !== "boolean") return c.json({ error: "paused must be a boolean" }, 400);
19031
- setPaused(getCtx().db, c.get("agentId"), input.paused);
19032
- return c.json({ paused: input.paused });
19033
- });
19034
-
19035
- // ../daemon/src/app.ts
19036
- function createApp() {
19037
- const app2 = new Hono2();
19038
- app2.use("*", authMiddleware);
19039
- app2.use("/api/*", async (c, next) => {
19040
- await next();
19041
- if (!c.res.headers.has("cache-control")) c.res.headers.set("cache-control", "no-store");
19042
- });
19043
- app2.route("/api/agents", agentsRouter);
19044
- app2.route("/api/agents", agentChatRouter);
19045
- app2.route("/api/agents", agentBrowserRouter);
19046
- app2.route("/api/agents", agentLearningRouter);
19047
- app2.route("/api/agents", agentMessagesRouter);
19048
- app2.route("/api/agents", agentSkillsRouter);
19049
- app2.route("/api/agents", agentTelegramRouter);
19050
- app2.route("/api/agents", agentTriggersRouter);
19051
- app2.route("/api/agents", conversationsRouter);
19052
- app2.route("/api/agents", userQueueRouter);
19053
- app2.route("/api/agents", questionsRouter);
19054
- app2.route("/api/teams", teamsRouter);
19055
- app2.route("/api/teams", teamMemoryRouter);
19056
- app2.route("/api/teams", teamPolicyRouter);
19057
- app2.route("/api/teams", teamReviewRouter);
19058
- app2.route("/api/teams", teamMessagesRouter);
19059
- app2.route("/api/teams", teamCodingEnvironmentRouter);
19060
- app2.route("/api/teams", teamTelegramRouter);
19061
- app2.route("/api/team-templates", teamTemplatesRouter);
19062
- app2.route("/api/results", resultsRouter);
19063
- app2.route("/api/attention", attentionRouter);
19064
- app2.route("/api/activity", activityRouter);
19065
- app2.route("/api/notifications", notificationsRouter);
19066
- app2.route("/api/shell-approvals", shellApprovalsRouter);
19067
- app2.route("/api/profiles", profilesRouter);
19068
- app2.route("/api/skills", skillsRouter);
19069
- app2.route("/api/triggers", triggersRouter);
19070
- app2.route("/api/messages", messagesRouter);
19071
- app2.route("/api/mcp-servers", mcpRouter);
19072
- app2.route("/api/config/telegram", telegramRouter);
19073
- app2.route("/api/config", configRouter);
19074
- app2.route("/api", miscRouter);
19075
- app2.route("/api", authRouter);
19076
- return app2;
19077
- }
19078
-
19079
- // ../daemon/src/index.ts
19080
- init_install();
19081
- init_resources();
19082
-
19083
19873
  // ../daemon/src/lib/review-provider.ts
19084
19874
  function reviewEndpoint(providerName, env) {
19085
19875
  const raw = providerEndpoint(providerName, env);
@@ -19360,6 +20150,23 @@ function isDue(t, now, cronCache) {
19360
20150
  }
19361
20151
  return false;
19362
20152
  }
20153
+ function nextRunAt(t, now = Date.now()) {
20154
+ if (!t.enabled) return null;
20155
+ if (t.kind === "interval") {
20156
+ const every = (t.intervalSec ?? 0) * 1e3;
20157
+ if (every <= 0) return null;
20158
+ return Math.max((t.lastFiredAt ?? t.createdAt) + every, now);
20159
+ }
20160
+ if (!t.cronExpr) return null;
20161
+ let parsed;
20162
+ try {
20163
+ parsed = parseCron(t.cronExpr);
20164
+ } catch {
20165
+ return null;
20166
+ }
20167
+ const from = t.lastFiredAt && floorToMinute(t.lastFiredAt) === floorToMinute(now) ? floorToMinute(now) + 6e4 : floorToMinute(now);
20168
+ return nextCronMatch(parsed, from);
20169
+ }
19363
20170
  function scheduledOccurrence(t, now) {
19364
20171
  if (t.kind === "cron") return floorToMinute(now);
19365
20172
  const baseline = t.lastFiredAt ?? t.createdAt;
@@ -19442,9 +20249,9 @@ function decodeText2(payload) {
19442
20249
  }
19443
20250
  return payload;
19444
20251
  }
19445
- var INBOX_WAKE_PREFIX = "[[bazilion:inbox-wake]]\n";
20252
+ var INBOX_WAKE_PREFIX2 = "[[bazilion:inbox-wake]]\n";
19446
20253
  function buildInboxPrompt(agentId, messages, fromNames) {
19447
- const lines = [INBOX_WAKE_PREFIX.trimEnd()];
20254
+ const lines = [INBOX_WAKE_PREFIX2.trimEnd()];
19448
20255
  lines.push(
19449
20256
  `You have ${messages.length} new message${messages.length === 1 ? "" : "s"} in your inbox:`
19450
20257
  );
@@ -19530,12 +20337,26 @@ async function fireInboxWake(agentId) {
19530
20337
  }
19531
20338
  turnStarted = true;
19532
20339
  s.inboxBackoff.delete(agentId);
19533
- for await (const frame of runAgentTurn(preparedTurn)) {
19534
- if (frame.kind === "fatal") {
19535
- console.warn(
19536
- JSON.stringify({ event: "inbox_wake_failed", agentId, failure: "turn_failed" })
19537
- );
20340
+ if (forgetTurnFailure(`inbox-start:${agentId}`)) signalLiveChange();
20341
+ let failure = null;
20342
+ try {
20343
+ for await (const frame of runAgentTurn(preparedTurn)) {
20344
+ const frameFailure = turnFrameFailure(frame);
20345
+ if (frameFailure) failure ??= turnFailureReason(frameFailure);
19538
20346
  }
20347
+ } catch (error) {
20348
+ failure ??= turnFailureReason(error);
20349
+ }
20350
+ if (failure && !controller.signal.aborted) {
20351
+ console.warn(JSON.stringify({ event: "inbox_wake_failed", agentId, failure: "turn_failed" }));
20352
+ rememberTurnFailure({
20353
+ id: attemptId,
20354
+ agentId,
20355
+ origin: "inbox",
20356
+ at: Date.now(),
20357
+ reason: failure
20358
+ });
20359
+ signalLiveChange();
19539
20360
  }
19540
20361
  } catch (err) {
19541
20362
  if (!handoffStarted && registered) unregisterAgent(agentId);
@@ -19543,6 +20364,14 @@ async function fireInboxWake(agentId) {
19543
20364
  if (!turnStarted) {
19544
20365
  retryInMs = backoff ? Math.min(backoff.delayMs * 2, INBOX_RETRY_MAX_MS) : INBOX_RETRY_BASE_MS;
19545
20366
  s.inboxBackoff.set(agentId, { delayMs: retryInMs, nextAttemptAt: Date.now() + retryInMs });
20367
+ rememberTurnFailure({
20368
+ id: `inbox-start:${agentId}`,
20369
+ agentId,
20370
+ origin: "inbox",
20371
+ at: Date.now(),
20372
+ reason: turnFailureReason(err)
20373
+ });
20374
+ signalLiveChange();
19546
20375
  }
19547
20376
  console.warn(
19548
20377
  JSON.stringify({
@@ -19643,7 +20472,217 @@ function stopScheduler() {
19643
20472
  return s.stopPromise;
19644
20473
  }
19645
20474
 
20475
+ // ../daemon/src/routes/triggers.ts
20476
+ var triggersRouter = newRouter();
20477
+ function triggerExists(id) {
20478
+ return triggers_exports.get(getCtx().db, id) !== null;
20479
+ }
20480
+ triggersRouter.get("/:id/dispatches", (c) => {
20481
+ const id = c.req.param("id");
20482
+ if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
20483
+ const requestedLimit = Number(c.req.query("limit") ?? 20);
20484
+ if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
20485
+ return c.json({ error: "limit must be a positive integer" }, 400);
20486
+ }
20487
+ const limit = Math.min(100, requestedLimit);
20488
+ return c.json({
20489
+ dispatches: triggerDispatches_exports.listForTrigger(getCtx().db, id, limit)
20490
+ });
20491
+ });
20492
+ triggersRouter.delete("/:id", (c) => {
20493
+ const id = c.req.param("id");
20494
+ if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
20495
+ triggers_exports.remove(getCtx().db, id);
20496
+ return c.body(null, 204);
20497
+ });
20498
+ triggersRouter.patch("/:id", async (c) => {
20499
+ const id = c.req.param("id");
20500
+ const body = await jsonBody(c);
20501
+ if (!body) return c.json({ error: "invalid JSON body" }, 400);
20502
+ if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
20503
+ const { db } = getCtx();
20504
+ if (typeof body.enabled === "boolean") triggers_exports.setEnabled(db, id, body.enabled);
20505
+ return c.json({ trigger: triggers_exports.get(db, id) });
20506
+ });
20507
+ var agentTriggersRouter = newRouter();
20508
+ agentTriggersRouter.get("/:id/triggers", (c) => {
20509
+ const { db } = getCtx();
20510
+ const triggers = triggers_exports.listForAgent(db, routeAgent(c).id);
20511
+ const schedulerOff = process.env.BAZILION_SCHEDULER === "off";
20512
+ const now = Date.now();
20513
+ return c.json({
20514
+ triggers,
20515
+ dispatches: triggers.flatMap(
20516
+ (trigger) => triggerDispatches_exports.listForTrigger(db, trigger.id, 10)
20517
+ ),
20518
+ nextRuns: Object.fromEntries(
20519
+ triggers.map((trigger) => [trigger.id, schedulerOff ? null : nextRunAt(trigger, now)])
20520
+ ),
20521
+ schedulerOff
20522
+ });
20523
+ });
20524
+ agentTriggersRouter.post("/:id/triggers", async (c) => {
20525
+ const body = await jsonBody(c);
20526
+ if (!body) return c.json({ error: "invalid JSON body" }, 400);
20527
+ if (typeof body.message !== "string" || !body.message.trim()) {
20528
+ return c.json({ error: "message is required" }, 400);
20529
+ }
20530
+ const agentId = routeAgent(c).id;
20531
+ const { db } = getCtx();
20532
+ if (body.kind === "interval") {
20533
+ const intervalSec = body.intervalSec;
20534
+ if (typeof intervalSec !== "number" || !Number.isInteger(intervalSec) || intervalSec < 1) {
20535
+ return c.json({ error: "intervalSec must be a whole number of seconds, at least 1" }, 400);
20536
+ }
20537
+ const trigger = triggers_exports.insert(db, {
20538
+ agentId,
20539
+ kind: "interval",
20540
+ intervalSec,
20541
+ cronExpr: null,
20542
+ message: body.message,
20543
+ enabled: body.enabled
20544
+ });
20545
+ return c.json({ trigger }, 201);
20546
+ }
20547
+ if (body.kind === "cron") {
20548
+ if (typeof body.cronExpr !== "string" || !body.cronExpr.trim()) {
20549
+ return c.json({ error: "cronExpr is required for kind=cron" }, 400);
20550
+ }
20551
+ try {
20552
+ validateCron(body.cronExpr);
20553
+ } catch (err) {
20554
+ return c.json({ error: `invalid cron: ${err.message}` }, 400);
20555
+ }
20556
+ const trigger = triggers_exports.insert(db, {
20557
+ agentId,
20558
+ kind: "cron",
20559
+ intervalSec: null,
20560
+ cronExpr: body.cronExpr.trim(),
20561
+ message: body.message,
20562
+ enabled: body.enabled
20563
+ });
20564
+ return c.json({ trigger }, 201);
20565
+ }
20566
+ return c.json({ error: `invalid kind: ${body.kind}` }, 400);
20567
+ });
20568
+
20569
+ // ../daemon/src/routes/usage.ts
20570
+ var usageRouter = newRouter();
20571
+ var MAX_USAGE_DAYS = 3660;
20572
+ usageRouter.get("/", (c) => {
20573
+ const { db, paths } = getCtx();
20574
+ const rawDays = c.req.query("days") ?? "30";
20575
+ let days = null;
20576
+ if (rawDays !== "all") {
20577
+ days = Number(rawDays);
20578
+ if (!Number.isInteger(days) || days < 1 || days > MAX_USAGE_DAYS)
20579
+ throw new DomainError(400, `days must be a whole number from 1 to ${MAX_USAGE_DAYS}, or all`);
20580
+ }
20581
+ const rawZone = c.req.query("tz");
20582
+ const timeZone = rawZone ? validTimeZone(rawZone) : Intl.DateTimeFormat().resolvedOptions().timeZone;
20583
+ if (!timeZone) throw new DomainError(400, `unknown time zone: ${rawZone}`);
20584
+ const agentRef = c.req.query("agent");
20585
+ const agentId = agentRef ? routeAgentRef(agentRef).id : void 0;
20586
+ const teamRef = c.req.query("team");
20587
+ const teamId = teamRef ? get3(db, teamRef, paths)?.id : void 0;
20588
+ if (teamRef && !teamId) throw new DomainError(404, `team not found: ${teamRef}`);
20589
+ const plans = planProviders(mergeSecretsIntoEnv(db, getCtx().authToken));
20590
+ return c.json(usageReport(db, paths, { days, timeZone, agentId, teamId, plans }));
20591
+ });
20592
+
20593
+ // ../daemon/src/routes/user-queue.ts
20594
+ import { bodyLimit as bodyLimit3 } from "hono/body-limit";
20595
+ var userQueueRouter = newRouter();
20596
+ userQueueRouter.use("/:agentId/queue/*", bodyLimit3({ maxSize: 36 * 1024 * 1024 }));
20597
+ userQueueRouter.use("/:agentId/queue/*", async (c, next) => {
20598
+ c.set("agentId", routeAgent(c, "agentId").id);
20599
+ await next();
20600
+ });
20601
+ userQueueRouter.get(
20602
+ "/:agentId/queue",
20603
+ (c) => c.json({
20604
+ ...list4(getCtx().db, c.get("agentId")),
20605
+ turnActive: isActiveAgent(c.get("agentId"))
20606
+ })
20607
+ );
20608
+ userQueueRouter.post("/:agentId/queue", async (c) => {
20609
+ const input = await jsonBody(c);
20610
+ return c.json(
20611
+ await enqueueUserInput(c.get("agentId"), {
20612
+ message: input?.message,
20613
+ attachments: input?.attachments ?? []
20614
+ }),
20615
+ 202
20616
+ );
20617
+ });
20618
+ userQueueRouter.patch("/:agentId/queue/:id", async (c) => {
20619
+ const input = await jsonBody(c);
20620
+ return c.json(
20621
+ edit(getCtx().db, c.get("agentId"), c.req.param("id"), input?.message)
20622
+ );
20623
+ });
20624
+ userQueueRouter.delete("/:agentId/queue/:id", async (c) => {
20625
+ const { item, origin } = remove4(getCtx().db, c.get("agentId"), c.req.param("id"));
20626
+ if (item.status === "pending") await notifyTelegramQueueOutcome(item, origin, "removed");
20627
+ return c.json(item);
20628
+ });
20629
+ userQueueRouter.post("/:agentId/queue/control", async (c) => {
20630
+ const input = await jsonBody(c);
20631
+ if (typeof input?.paused !== "boolean") return c.json({ error: "paused must be a boolean" }, 400);
20632
+ setPaused(getCtx().db, c.get("agentId"), input.paused);
20633
+ return c.json({ paused: input.paused });
20634
+ });
20635
+
20636
+ // ../daemon/src/app.ts
20637
+ function createApp() {
20638
+ const app2 = new Hono2();
20639
+ app2.use("*", authMiddleware);
20640
+ app2.use("/api/*", async (c, next) => {
20641
+ await next();
20642
+ if (!c.res.headers.has("cache-control")) c.res.headers.set("cache-control", "no-store");
20643
+ });
20644
+ app2.route("/api/agents", agentsRouter);
20645
+ app2.route("/api/agents", agentChatRouter);
20646
+ app2.route("/api/agents", agentBrowserRouter);
20647
+ app2.route("/api/agents", agentLearningRouter);
20648
+ app2.route("/api/agents", agentMessagesRouter);
20649
+ app2.route("/api/agents", agentSkillsRouter);
20650
+ app2.route("/api/agents", agentTelegramRouter);
20651
+ app2.route("/api/agents", agentTriggersRouter);
20652
+ app2.route("/api/agents", conversationsRouter);
20653
+ app2.route("/api/agents", userQueueRouter);
20654
+ app2.route("/api/agents", questionsRouter);
20655
+ app2.route("/api/teams", teamsRouter);
20656
+ app2.route("/api/teams", teamMemoryRouter);
20657
+ app2.route("/api/teams", teamPolicyRouter);
20658
+ app2.route("/api/teams", teamReviewRouter);
20659
+ app2.route("/api/teams", teamMessagesRouter);
20660
+ app2.route("/api/teams", teamCodingEnvironmentRouter);
20661
+ app2.route("/api/teams", teamTelegramRouter);
20662
+ app2.route("/api/team-templates", teamTemplatesRouter);
20663
+ app2.route("/api/results", resultsRouter);
20664
+ app2.route("/api/attention", attentionRouter);
20665
+ app2.route("/api/activity", activityRouter);
20666
+ app2.route("/api/usage", usageRouter);
20667
+ app2.route("/api/conversations", conversationSearchRouter);
20668
+ app2.route("/api/events", eventsRouter);
20669
+ app2.route("/api/notifications", notificationsRouter);
20670
+ app2.route("/api/shell-approvals", shellApprovalsRouter);
20671
+ app2.route("/api/profiles", profilesRouter);
20672
+ app2.route("/api/skills", skillsRouter);
20673
+ app2.route("/api/triggers", triggersRouter);
20674
+ app2.route("/api/messages", messagesRouter);
20675
+ app2.route("/api/mcp-servers", mcpRouter);
20676
+ app2.route("/api/config/telegram", telegramRouter);
20677
+ app2.route("/api/config", configRouter);
20678
+ app2.route("/api", miscRouter);
20679
+ app2.route("/api", authRouter);
20680
+ return app2;
20681
+ }
20682
+
19646
20683
  // ../daemon/src/index.ts
20684
+ init_install();
20685
+ init_resources();
19647
20686
  var host2 = process.env.HOST ?? "127.0.0.1";
19648
20687
  var port = Number.parseInt(process.env.PORT ?? "4321", 10);
19649
20688
  var publicOrigin2 = publicOriginConfig(process.env.BAZILION_PUBLIC_ORIGIN);