bazilion 0.55.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 (191) hide show
  1. package/dist/cli.js +192 -37
  2. package/dist/cli.js.map +1 -1
  3. package/dist/daemon.js +1164 -412
  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-bTJUy9Qf.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-D7kPQGoh.js → SectionTabs-Dc0bNn-J.js} +1 -1
  13. package/dist/web/client/assets/{Segmented-oPkAHPO1.js → Segmented-iylzLwE6.js} +1 -1
  14. package/dist/web/client/assets/SkillsParts-C5T7sYDA.js +1 -0
  15. package/dist/web/client/assets/SpawnTeamModal-DatFF4f_.js +1 -0
  16. package/dist/web/client/assets/TeamForm-l-N_PYeE.js +1 -0
  17. package/dist/web/client/assets/TeamThread-BWmIQiAh.js +1 -0
  18. package/dist/web/client/assets/UnsavedChangesGuard-vQBdMl8h.js +1 -0
  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-BbQFbTPh.js +1 -0
  22. package/dist/web/client/assets/{agent-actions-CUee6aJq.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-BCone8es.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-jxSFpY0Q.js → createLucideIcon-CZHSSDYA.js} +1 -1
  32. package/dist/web/client/assets/{download-Dy88XavQ.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-DPsZ8-h9.js → file-text-D6OTHixJ.js} +1 -1
  35. package/dist/web/client/assets/{images-QBh_rL8b.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-C-I8fAG0.js → key-round-DmSZN0Kq.js} +1 -1
  38. package/dist/web/client/assets/{list-checks-C9Q-bjEi.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-BaIU5zKy.js → manage-R57MUzsY.js} +1 -1
  41. package/dist/web/client/assets/mcp-CSHrVH1t.js +1 -0
  42. package/dist/web/client/assets/{message-square-Bwf9cHOx.js → message-square-B_pULba_.js} +1 -1
  43. package/dist/web/client/assets/{network-B3FA93gC.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-DaNLwvEs.js → square-terminal-CYfGBHPC.js} +1 -1
  50. package/dist/web/client/assets/style-Bm9QsFpy.js +7 -0
  51. package/dist/web/client/assets/styles-B-kTTvCo.css +2 -0
  52. package/dist/web/client/assets/{system-CrTSr5_t.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-Bn0Sx7r6.js +1 -0
  59. package/dist/web/client/assets/{users-round-BElBVSnw.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-DotqSqSm.js → wrench-BLEJjETg.js} +1 -1
  62. package/dist/web/server/assets/{AddProviderDialog-BbpuvC2a.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-Ce7snK3m.js → AgentTemplateParts-CxWyovvM.js} +6 -2
  65. package/dist/web/server/assets/Button-Dsnw22OF.js +17 -0
  66. package/dist/web/server/assets/{ConfigPage-qP9ejjuw.js → ConfigPage-usZi48Zr.js} +2 -2
  67. package/dist/web/server/assets/{ConfirmDialog-Z-uYbE9B.js → ConfirmDialog-DAcSBHkT.js} +3 -1
  68. package/dist/web/server/assets/{ConnectionsView-CLIV7V5D.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-BR9FwVZM.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-DWpdydCJ.js → SkillsParts-Cw05b3al.js} +6 -2
  73. package/dist/web/server/assets/SpawnDialog-BAE8W91z.js +125 -0
  74. package/dist/web/server/assets/{SpawnTeamModal-C-YMvoaB.js → SpawnTeamModal-CgBY0HuN.js} +6 -2
  75. package/dist/web/server/assets/{TeamForm-CL45gBdt.js → TeamForm-JyO5xJXX.js} +6 -2
  76. package/dist/web/server/assets/{TeamThread-CVVH6kKj.js → TeamThread-5o48EbXL.js} +52 -4
  77. package/dist/web/server/assets/{UnsavedChangesGuard-CXK75QQp.js → UnsavedChangesGuard-CJQGu45L.js} +1 -1
  78. package/dist/web/server/assets/{_id-8zsImuGa.js → _id-BE_RSvuN.js} +14 -9
  79. package/dist/web/server/assets/{_id-d2OwovYV.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-2I4CSMQj.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-BpfoPuTv.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-CwZ27Wsl.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-CyUoElTP.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-C07Cp5Ue.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-vuXrAv1j.js → agents-BXuglv4G.js} +12 -6
  92. package/dist/web/server/assets/{agents-DTub-rJk.js → agents-DhenbitX.js} +2 -2
  93. package/dist/web/server/assets/{agents-CwzhpDPm.js → agents-KJcDMj0Y.js} +9 -6
  94. package/dist/web/server/assets/{agents-DCWEoaxY.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-BqCnJ1hg.js → attention-CDdOCOio.js} +2 -2
  97. package/dist/web/server/assets/{attention-DwGaur_w.js → attention-DM__BzWY.js} +8 -6
  98. package/dist/web/server/assets/{attention-Dki8rmGZ.js → attention-X0U6ZmiA.js} +1 -1
  99. package/dist/web/server/assets/{auth-dJnrFW6y.js → auth-BexhV8Yq.js} +1 -1
  100. package/dist/web/server/assets/{config-B9dJiji_.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-D3MR2VjE.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-CRd1yTH5.js → login-BJdJ219n.js} +1 -1
  108. package/dist/web/server/assets/{login-ZN6KV8n-.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-BQ15a9dG.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-CYQuYWGX.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-CVY-c2Pd.js → page-title-PTpFHXWo.js} +1 -1
  115. package/dist/web/server/assets/parts-k9M-atPa.js +436 -0
  116. package/dist/web/server/assets/{router-CPdWGKQ5.js → router-BttfLktO.js} +185 -77
  117. package/dist/web/server/assets/{routes-BPloBDc8.js → routes-A7UcreVX.js} +3 -3
  118. package/dist/web/server/assets/{routes-Dw1K3TQw.js → routes-B9jw-MJ8.js} +1175 -321
  119. package/dist/web/server/assets/{routes-xDPesCQu.js → routes-BX2FV8rS.js} +3 -3
  120. package/dist/web/server/assets/{skills-D0xrNc2_.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-6VSpEORe.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-aMybyKzc.js → style-BQ3H9I7Y.js} +1 -1
  126. package/dist/web/server/assets/{system-B5sPgdQW.js → system-BJPKqM6b.js} +2 -2
  127. package/dist/web/server/assets/{system-CXmiWyDG.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-yF3I_Zjq.js → teams-B6gbflsZ.js} +10 -6
  130. package/dist/web/server/assets/{teams-iXiCnN2i.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-ClRBVSYU.js → teams-CiX8LUQo.js} +2 -2
  134. package/dist/web/server/assets/{teams-Dq4RCxis.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-DwEgyR1x.js → telegram-D8_V7_sW.js} +286 -272
  137. package/dist/web/server/assets/{telegram-D9U9c1MN.js → telegram-DA2dwLID.js} +2 -2
  138. package/dist/web/server/assets/{tools-VPIKjr3y.js → tools-CckcG9Jl.js} +5 -3
  139. package/dist/web/server/assets/{tools-DflVIdDd.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-CbHGYti0.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-966nOyyK.js → welcome-CYhh3iUU.js} +8 -6
  146. package/dist/web/server/assets/{welcome-7DrYZVs6.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/worker.js +27 -6
  150. package/dist/worker.js.map +1 -1
  151. package/package.json +1 -1
  152. package/dist/web/client/assets/AddProviderDialog-DfFOaCjC.js +0 -1
  153. package/dist/web/client/assets/AgentTemplateParts-IMJmAQjN.js +0 -1
  154. package/dist/web/client/assets/ConfigPage-CzLHZa5o.js +0 -1
  155. package/dist/web/client/assets/ConfirmDialog-Cu_evkgc.js +0 -1
  156. package/dist/web/client/assets/ConnectionsView-D7Fmutl2.js +0 -1
  157. package/dist/web/client/assets/ManagePage-BfvlCrmz.js +0 -1
  158. package/dist/web/client/assets/SkillsParts-BuTxcCam.js +0 -1
  159. package/dist/web/client/assets/SpawnTeamModal-B1UnOvtp.js +0 -1
  160. package/dist/web/client/assets/TeamForm-DbzxtRjj.js +0 -1
  161. package/dist/web/client/assets/TeamThread-jpsWq6vI.js +0 -1
  162. package/dist/web/client/assets/UnsavedChangesGuard-BfyU9v9i.js +0 -1
  163. package/dist/web/client/assets/_id-BCNBLF-2.js +0 -1
  164. package/dist/web/client/assets/_id-D8_H79U2.js +0 -1
  165. package/dist/web/client/assets/access-CDWe1Kwy.js +0 -1
  166. package/dist/web/client/assets/agents-sE686DTf.js +0 -1
  167. package/dist/web/client/assets/agents-yrur1NDa.js +0 -1
  168. package/dist/web/client/assets/arrow-right-U66krZnr.js +0 -1
  169. package/dist/web/client/assets/attention-DYEHDfmx.js +0 -1
  170. package/dist/web/client/assets/chevron-right-CuqJFXTe.js +0 -1
  171. package/dist/web/client/assets/config-BHv886pr.js +0 -1
  172. package/dist/web/client/assets/index-GOthyyE-.js +0 -14
  173. package/dist/web/client/assets/login-Dhe15Uuc.js +0 -1
  174. package/dist/web/client/assets/mcp-A_Eo7x3q.js +0 -1
  175. package/dist/web/client/assets/parts-CpIfn_BH.js +0 -41
  176. package/dist/web/client/assets/plus-CQPjc8uR.js +0 -1
  177. package/dist/web/client/assets/routes-CTg_yjbY.js +0 -85
  178. package/dist/web/client/assets/skills-CLjtYtkA.js +0 -1
  179. package/dist/web/client/assets/style-mjEbxhf5.js +0 -7
  180. package/dist/web/client/assets/styles-DzcEC3Rd.css +0 -2
  181. package/dist/web/client/assets/teams-Bhje5n2h.js +0 -1
  182. package/dist/web/client/assets/teams-Cbgw0Qhv.js +0 -1
  183. package/dist/web/client/assets/telegram-HtUczmaA.js +0 -1
  184. package/dist/web/client/assets/tools-BpjFvmoX.js +0 -1
  185. package/dist/web/client/assets/use-resource-BnvgCpBi.js +0 -1
  186. package/dist/web/client/assets/welcome-D47LKWYO.js +0 -1
  187. package/dist/web/server/assets/Rail-b6EbjBB-.js +0 -605
  188. package/dist/web/server/assets/SpawnDialog-3wNx0W1R.js +0 -1851
  189. package/dist/web/server/assets/_tanstack-start-manifest_v-kkY_s_uR.js +0 -256
  190. package/dist/web/server/assets/createSsrRpc-qesavJv-.js +0 -72
  191. 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;
@@ -3139,7 +3311,7 @@ function acknowledgeAttention(db, key2, acknowledged) {
3139
3311
  throw new DomainError(409, "action-required items must be resolved at their source");
3140
3312
  if (acknowledged)
3141
3313
  db.raw.run(
3142
- `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`,
3143
3315
  [parsed.kind, parsed.sourceId, Date.now()]
3144
3316
  );
3145
3317
  else
@@ -3163,7 +3335,7 @@ function acknowledgeAllAttention(db) {
3163
3335
  const now = Date.now();
3164
3336
  for (const item of items)
3165
3337
  db.raw.run(
3166
- `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`,
3167
3339
  [item.kind, item.sourceId, now]
3168
3340
  );
3169
3341
  return items.length;
@@ -3264,14 +3436,14 @@ function replaceCuratedModels(db, provider, models) {
3264
3436
  import { dirname } from "node:path";
3265
3437
  import { backup, DatabaseSync } from "node:sqlite";
3266
3438
  function wrap(rawDb) {
3267
- const cache = /* @__PURE__ */ new Map();
3439
+ const cache2 = /* @__PURE__ */ new Map();
3268
3440
  let transactionDepth = 0;
3269
3441
  let savepointSequence = 0;
3270
3442
  function getStmt(sql) {
3271
- let s = cache.get(sql);
3443
+ let s = cache2.get(sql);
3272
3444
  if (!s) {
3273
3445
  s = rawDb.prepare(sql);
3274
- cache.set(sql, s);
3446
+ cache2.set(sql, s);
3275
3447
  }
3276
3448
  return s;
3277
3449
  }
@@ -3660,10 +3832,16 @@ function validateSlug(s) {
3660
3832
  );
3661
3833
  }
3662
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
+ }
3663
3840
 
3664
3841
  // ../daemon/src/core/profile/create.ts
3665
3842
  function createProfile(db, paths, input) {
3666
3843
  validateSlug(input.id);
3844
+ const name = input.name === void 0 ? input.id : templateName(input.name);
3667
3845
  if (get5(db, input.id))
3668
3846
  throw new DomainError(400, `profile already exists: ${input.id}`);
3669
3847
  const dir = paths.profileDir(input.id);
@@ -3687,7 +3865,7 @@ function createProfile(db, paths, input) {
3687
3865
  const skillsMode = input.skillsMode ?? "selected";
3688
3866
  const profile = insert4(db, {
3689
3867
  id: input.id,
3690
- name: input.name ?? input.id,
3868
+ name,
3691
3869
  defaultModel: input.defaultModel,
3692
3870
  skillsMode
3693
3871
  });
@@ -3995,7 +4173,7 @@ function updateProfile(db, id, input) {
3995
4173
  if (!existing) throw new DomainError(404, `profile not found: ${id}`);
3996
4174
  const nextSkillsMode = input.skillsMode ?? existing.skillsMode;
3997
4175
  const next = {
3998
- name: input.name ?? existing.name,
4176
+ name: input.name === void 0 ? existing.name : templateName(input.name),
3999
4177
  defaultModel: input.defaultModel ?? existing.defaultModel,
4000
4178
  skillsMode: nextSkillsMode
4001
4179
  };
@@ -4172,6 +4350,7 @@ function apiKey(id, displayName, envVar, options = {}) {
4172
4350
  id,
4173
4351
  displayName,
4174
4352
  ...options.hint ? { hint: options.hint } : {},
4353
+ ...options.plan ? { plan: true } : {},
4175
4354
  keyEnv: [envVar],
4176
4355
  ...options.modelsUrl ? { modelsUrl: options.modelsUrl } : {},
4177
4356
  fields: [
@@ -4205,6 +4384,7 @@ var PROVIDERS = [
4205
4384
  hint: "Use your ChatGPT Plus, Pro or Team plan. No API key.",
4206
4385
  // Credentials come from the OAuth flow (/api/auth/openai), not from fields.
4207
4386
  fields: [],
4387
+ plan: true,
4208
4388
  popular: true,
4209
4389
  suggested: ["gpt-6.2-sol", "gpt-6-luna"]
4210
4390
  },
@@ -4221,6 +4401,7 @@ var PROVIDERS = [
4221
4401
  displayName: "Anthropic",
4222
4402
  hint: "Claude models \xB7 console.anthropic.com",
4223
4403
  keyEnv: ["ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],
4404
+ planEnv: "ANTHROPIC_OAUTH_TOKEN",
4224
4405
  fields: [
4225
4406
  { envVar: "ANTHROPIC_API_KEY", kind: "secret", label: "API key", placeholder: "sk-ant-..." },
4226
4407
  {
@@ -4299,6 +4480,7 @@ var PROVIDERS = [
4299
4480
  displayName: "GitHub Copilot",
4300
4481
  hint: "Use a GitHub Copilot subscription to call Claude/GPT/Gemini via Copilot",
4301
4482
  keyEnv: ["COPILOT_GITHUB_TOKEN"],
4483
+ plan: true,
4302
4484
  fields: [
4303
4485
  {
4304
4486
  envVar: "COPILOT_GITHUB_TOKEN",
@@ -4353,36 +4535,41 @@ var PROVIDERS = [
4353
4535
  }),
4354
4536
  // Each plan has its own key; Pi also reads the older shared QWEN_TOKEN_PLAN_API_KEY.
4355
4537
  apiKey("qwen-token-plan", "Qwen Token Plan Team", "QWEN_TOKEN_PLAN_TEAM_API_KEY", {
4356
- hint: "Team coding-model subscription \xB7 international endpoint"
4538
+ hint: "Team coding-model subscription \xB7 international endpoint",
4539
+ plan: true
4357
4540
  }),
4358
4541
  apiKey("qwen-token-plan-cn", "Qwen Token Plan Team (CN)", "QWEN_TOKEN_PLAN_TEAM_CN_API_KEY", {
4359
- hint: "Team coding-model subscription \xB7 China endpoint"
4542
+ hint: "Team coding-model subscription \xB7 China endpoint",
4543
+ plan: true
4360
4544
  }),
4361
4545
  apiKey(
4362
4546
  "qwen-token-plan-individual",
4363
4547
  "Qwen Token Plan Individual",
4364
4548
  "QWEN_TOKEN_PLAN_INDIVIDUAL_API_KEY",
4365
- { hint: "Individual subscription \xB7 international endpoint" }
4549
+ { hint: "Individual subscription \xB7 international endpoint", plan: true }
4366
4550
  ),
4367
4551
  apiKey(
4368
4552
  "qwen-token-plan-individual-cn",
4369
4553
  "Qwen Token Plan Individual (CN)",
4370
4554
  "QWEN_TOKEN_PLAN_INDIVIDUAL_CN_API_KEY",
4371
- { hint: "Individual subscription \xB7 China endpoint" }
4555
+ { hint: "Individual subscription \xB7 China endpoint", plan: true }
4372
4556
  ),
4373
4557
  apiKey("xiaomi", "Xiaomi MiMo", "XIAOMI_API_KEY", {
4374
4558
  hint: "API billing endpoint \xB7 platform.xiaomimimo.com"
4375
4559
  }),
4376
4560
  apiKey("xiaomi-token-plan-ams", "Xiaomi MiMo Token Plan (AMS)", "XIAOMI_TOKEN_PLAN_AMS_API_KEY", {
4377
4561
  hint: "MiMo token-plan endpoint in Amsterdam",
4562
+ plan: true,
4378
4563
  modelsUrl: "https://token-plan-ams.xiaomimimo.com/v1"
4379
4564
  }),
4380
4565
  apiKey("xiaomi-token-plan-cn", "Xiaomi MiMo Token Plan (CN)", "XIAOMI_TOKEN_PLAN_CN_API_KEY", {
4381
4566
  hint: "MiMo token-plan endpoint in China",
4567
+ plan: true,
4382
4568
  modelsUrl: "https://token-plan-cn.xiaomimimo.com/v1"
4383
4569
  }),
4384
4570
  apiKey("xiaomi-token-plan-sgp", "Xiaomi MiMo Token Plan (SGP)", "XIAOMI_TOKEN_PLAN_SGP_API_KEY", {
4385
4571
  hint: "MiMo token-plan endpoint in Singapore",
4572
+ plan: true,
4386
4573
  modelsUrl: "https://token-plan-sgp.xiaomimimo.com/v1"
4387
4574
  }),
4388
4575
  apiKey("ant-ling", "Ant Ling", "ANT_LING_API_KEY", {
@@ -5144,7 +5331,7 @@ function get10(db, id) {
5144
5331
  return row ? toMessage(row) : null;
5145
5332
  }
5146
5333
  function listInbox(db, agentId, opts) {
5147
- 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";
5148
5335
  return db.raw.query(sql).all(agentId).map(toMessage);
5149
5336
  }
5150
5337
  function listForTeam(db, teamId, limit) {
@@ -5152,7 +5339,7 @@ function listForTeam(db, teamId, limit) {
5152
5339
  `SELECT m.* FROM messages m
5153
5340
  WHERE m.from_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5154
5341
  OR m.to_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5155
- ORDER BY m.created_at DESC, m.id DESC LIMIT ?`
5342
+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT ?`
5156
5343
  ).all(teamId, teamId, limit).map(toMessage);
5157
5344
  }
5158
5345
  function markRead(db, id) {
@@ -5179,7 +5366,7 @@ function drainUnreadForAgent(db, agentId) {
5179
5366
  const rows = db.raw.query(
5180
5367
  `SELECT * FROM messages
5181
5368
  WHERE to_agent_id = ? AND read_at IS NULL
5182
- ORDER BY created_at ASC`
5369
+ ORDER BY created_at ASC, rowid ASC`
5183
5370
  ).all(agentId);
5184
5371
  if (rows.length === 0) return [];
5185
5372
  const now = Date.now();
@@ -5386,10 +5573,10 @@ __export(telegram_pairing_exports, {
5386
5573
  reset: () => reset,
5387
5574
  status: () => status
5388
5575
  });
5389
- import { createHash, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
5576
+ import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
5390
5577
  var TTL_MS = 10 * 6e4;
5391
5578
  function digest(code) {
5392
- return createHash("sha256").update(code, "utf8").digest();
5579
+ return createHash2("sha256").update(code, "utf8").digest();
5393
5580
  }
5394
5581
  function create2(db) {
5395
5582
  if (status(db).paired) throw new DomainError(409, "Telegram already has a paired owner");
@@ -5640,7 +5827,7 @@ __export(webTokens_exports, {
5640
5827
  rejectionReason: () => rejectionReason,
5641
5828
  revoke: () => revoke2
5642
5829
  });
5643
- 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";
5644
5831
  function toToken(r) {
5645
5832
  return {
5646
5833
  id: r.id,
@@ -5653,7 +5840,7 @@ function toToken(r) {
5653
5840
  };
5654
5841
  }
5655
5842
  function hashToken(token) {
5656
- return createHash2("sha256").update(token).digest("hex");
5843
+ return createHash3("sha256").update(token).digest("hex");
5657
5844
  }
5658
5845
  function create3(db, label, opts = {}) {
5659
5846
  const id = randomUUID10();
@@ -6443,7 +6630,7 @@ function rename(db, agentId, id, title) {
6443
6630
  }
6444
6631
 
6445
6632
  // ../daemon/src/core/repos/results.ts
6446
- import { createHash as createHash3, randomUUID as randomUUID13 } from "node:crypto";
6633
+ import { createHash as createHash4, randomUUID as randomUUID13 } from "node:crypto";
6447
6634
 
6448
6635
  // ../daemon/src/core/tool-call-id.ts
6449
6636
  function isToolCallId(value) {
@@ -6499,7 +6686,7 @@ function publish(db, input) {
6499
6686
  input.name,
6500
6687
  input.mimeType,
6501
6688
  bytes.byteLength,
6502
- createHash3("sha256").update(bytes).digest("hex"),
6689
+ createHash4("sha256").update(bytes).digest("hex"),
6503
6690
  input.imageModel ?? null,
6504
6691
  Date.now(),
6505
6692
  bytes
@@ -6538,7 +6725,7 @@ function read(db, id) {
6538
6725
  ).get(id);
6539
6726
  if (!row) throw new Error("Result not found");
6540
6727
  const bytes = Buffer.from(row.bytes);
6541
- if (createHash3("sha256").update(bytes).digest("hex") !== row.sha256)
6728
+ if (createHash4("sha256").update(bytes).digest("hex") !== row.sha256)
6542
6729
  throw new Error("Saved file failed its integrity check");
6543
6730
  return bytes;
6544
6731
  }
@@ -6940,7 +7127,9 @@ function onRouteError(error, c) {
6940
7127
  return c.json({ error: error.message || "Internal error" }, 500);
6941
7128
  }
6942
7129
  function routeAgent(c, param = "id") {
6943
- const ref = c.req.param(param) ?? "";
7130
+ return routeAgentRef(c.req.param(param) ?? "");
7131
+ }
7132
+ function routeAgentRef(ref) {
6944
7133
  const { db } = getCtx();
6945
7134
  const agent = get(db, ref);
6946
7135
  if (agent) return agent;
@@ -7404,8 +7593,8 @@ function qmdBackend(root, options = {}) {
7404
7593
  async init() {
7405
7594
  const safe = safeRoot();
7406
7595
  assertSafeTree(safe);
7407
- const store = await getStore(safe, storeFactory);
7408
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7596
+ const store2 = await getStore(safe, storeFactory);
7597
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7409
7598
  },
7410
7599
  async read(key2) {
7411
7600
  const safe = safeRoot();
@@ -7423,17 +7612,17 @@ function qmdBackend(root, options = {}) {
7423
7612
  const path = safeKey(safe, key2);
7424
7613
  const stats = writeSafeFile(safe, path, content);
7425
7614
  assertSafeTree(safe);
7426
- const store = await getStore(safe, storeFactory);
7427
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7615
+ const store2 = await getStore(safe, storeFactory);
7616
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7428
7617
  return { key: key2, content, updatedAt: stats.mtimeMs };
7429
7618
  },
7430
7619
  async search(query, opts) {
7431
7620
  const limit = opts?.limit ?? 10;
7432
7621
  const safe = safeRoot();
7433
7622
  assertSafeTree(safe);
7434
- const store = await getStore(safe, storeFactory);
7623
+ const store2 = await getStore(safe, storeFactory);
7435
7624
  const results = await withNativeModuleErrorBoundary(
7436
- () => store.searchLex(query, {
7625
+ () => store2.searchLex(query, {
7437
7626
  limit,
7438
7627
  collection: COLLECTION_NAME
7439
7628
  }),
@@ -7473,8 +7662,8 @@ function qmdBackend(root, options = {}) {
7473
7662
  rmSync9(path);
7474
7663
  }
7475
7664
  assertSafeTree(safe);
7476
- const store = await getStore(safe, storeFactory);
7477
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7665
+ const store2 = await getStore(safe, storeFactory);
7666
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7478
7667
  }
7479
7668
  };
7480
7669
  }
@@ -7862,9 +8051,9 @@ function readContainedFile(path, realRoot, maxBytes) {
7862
8051
  const buffer = Buffer.alloc(maxBytes + 1);
7863
8052
  let length = 0;
7864
8053
  while (length < buffer.length) {
7865
- const count = readSync(fd, buffer, length, buffer.length - length, null);
7866
- if (count === 0) break;
7867
- length += count;
8054
+ const count2 = readSync(fd, buffer, length, buffer.length - length, null);
8055
+ if (count2 === 0) break;
8056
+ length += count2;
7868
8057
  }
7869
8058
  if (length > maxBytes) throw new ContainedFileError("too_large");
7870
8059
  return buffer.subarray(0, length);
@@ -8152,7 +8341,7 @@ function boundReviewedLessons(lessons, maxCharacters = 8e3) {
8152
8341
 
8153
8342
  // ../daemon/src/runtime/shell/docker.ts
8154
8343
  import { spawn as spawn3 } from "node:child_process";
8155
- import { createHash as createHash4, randomUUID as randomUUID15 } from "node:crypto";
8344
+ import { createHash as createHash5, randomUUID as randomUUID15 } from "node:crypto";
8156
8345
  var CONTAINER_WORKSPACE = "/workspace";
8157
8346
  var DOCKER_CALL_TIMEOUT_MS = 5e3;
8158
8347
  var MAX_TIMER_MS = 2147483647;
@@ -8259,7 +8448,7 @@ async function checkDockerImage(image) {
8259
8448
  }
8260
8449
  }
8261
8450
  function homeContainerPrefix(home) {
8262
- return `bazilion-${createHash4("sha256").update(home).digest("hex").slice(0, 12)}-`;
8451
+ return `bazilion-${createHash5("sha256").update(home).digest("hex").slice(0, 12)}-`;
8263
8452
  }
8264
8453
  function turnContainerPrefix(home) {
8265
8454
  return `${homeContainerPrefix(home)}${randomUUID15().replaceAll("-", "").slice(0, 12)}-`;
@@ -8686,7 +8875,7 @@ import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSyn
8686
8875
  import { join as join19 } from "node:path";
8687
8876
  var MAX_SESSION_BYTES = 64 * 1024 * 1024;
8688
8877
  var MAX_HEADER_BYTES = 64 * 1024;
8689
- function readStart(directory, id, limit) {
8878
+ function readStart(directory, id, limit, refuseOver) {
8690
8879
  if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error("Invalid conversation id");
8691
8880
  const fd = openSync3(
8692
8881
  join19(directory, `${id}.jsonl`),
@@ -8695,14 +8884,16 @@ function readStart(directory, id, limit) {
8695
8884
  try {
8696
8885
  const stat = fstatSync3(fd);
8697
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");
8698
8889
  const bytes = Buffer.alloc(Math.min(stat.size, limit));
8699
- let count = 0;
8700
- while (count < bytes.length) {
8701
- 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);
8702
8893
  if (n === 0) break;
8703
- count += n;
8894
+ count2 += n;
8704
8895
  }
8705
- return { bytes: bytes.subarray(0, count), size: stat.size };
8896
+ return { bytes: bytes.subarray(0, count2), size: stat.size };
8706
8897
  } finally {
8707
8898
  closeSync3(fd);
8708
8899
  }
@@ -8711,14 +8902,19 @@ function checkHeader(entry, id) {
8711
8902
  if (entry?.type !== "session" || entry.id !== id)
8712
8903
  throw new Error("Session file does not belong to this conversation");
8713
8904
  }
8714
- function readSessionFile(directory, id) {
8715
- const { bytes, size } = readStart(directory, id, MAX_SESSION_BYTES);
8716
- 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);
8717
8907
  const text4 = bytes.toString("utf8");
8718
- 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));
8719
8912
  checkHeader(entries[0], id);
8720
8913
  return entries;
8721
8914
  }
8915
+ function readSessionFile(directory, id) {
8916
+ return parseSessionText(readSessionText(directory, id), id);
8917
+ }
8722
8918
  function sessionHasEntries(directory, id) {
8723
8919
  const { bytes, size } = readStart(directory, id, MAX_HEADER_BYTES);
8724
8920
  if (size > bytes.length) return true;
@@ -9554,8 +9750,8 @@ async function readBodyCapped(res, maxBytes) {
9554
9750
  if (done) break;
9555
9751
  if (!value) continue;
9556
9752
  if (total + value.byteLength > maxBytes) {
9557
- const keep = maxBytes - total;
9558
- if (keep > 0) chunks.push(value.subarray(0, keep));
9753
+ const keep2 = maxBytes - total;
9754
+ if (keep2 > 0) chunks.push(value.subarray(0, keep2));
9559
9755
  truncated = true;
9560
9756
  try {
9561
9757
  await reader.cancel();
@@ -9614,23 +9810,23 @@ async function firecrawlScrape(url, mode2, env, fetchFn, timeoutMs) {
9614
9810
  clearTimeout(t);
9615
9811
  }
9616
9812
  }
9617
- function cacheGet(cache, key2) {
9618
- const entry = cache.get(key2);
9813
+ function cacheGet(cache2, key2) {
9814
+ const entry = cache2.get(key2);
9619
9815
  if (!entry) return null;
9620
9816
  if (entry.expiresAt < Date.now()) {
9621
- cache.delete(key2);
9817
+ cache2.delete(key2);
9622
9818
  return null;
9623
9819
  }
9624
- cache.delete(key2);
9625
- cache.set(key2, entry);
9820
+ cache2.delete(key2);
9821
+ cache2.set(key2, entry);
9626
9822
  return entry.value;
9627
9823
  }
9628
- function cacheSet(cache, key2, value, ttlMs, maxEntries) {
9629
- cache.set(key2, { value, expiresAt: Date.now() + ttlMs });
9630
- while (cache.size > maxEntries) {
9631
- 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;
9632
9828
  if (!oldest) break;
9633
- cache.delete(oldest);
9829
+ cache2.delete(oldest);
9634
9830
  }
9635
9831
  }
9636
9832
  function webSearchTool(host3) {
@@ -9671,7 +9867,7 @@ function webFetchTool(opts) {
9671
9867
  const cacheMax = opts?.cacheMax ?? DEFAULT_CACHE_MAX;
9672
9868
  const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
9673
9869
  const maxBodyBytes = opts?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
9674
- const cache = /* @__PURE__ */ new Map();
9870
+ const cache2 = /* @__PURE__ */ new Map();
9675
9871
  return {
9676
9872
  def: {
9677
9873
  name: "web_fetch",
@@ -9699,7 +9895,7 @@ function webFetchTool(opts) {
9699
9895
  const maxLen = typeof args.max_length === "number" ? args.max_length : DEFAULT_MAX_LENGTH;
9700
9896
  const mode2 = args.extract_mode === "text" ? "text" : "markdown";
9701
9897
  const cacheKey = `${mode2}|${url}`;
9702
- const cached = cacheGet(cache, cacheKey);
9898
+ const cached = cacheGet(cache2, cacheKey);
9703
9899
  if (cached) return formatOutput(cached, maxLen);
9704
9900
  let result = null;
9705
9901
  try {
@@ -9758,7 +9954,7 @@ function webFetchTool(opts) {
9758
9954
  extracted = { ...extracted, text: `[final URL: ${result.finalUrl}]
9759
9955
 
9760
9956
  ${extracted.text}` };
9761
- cacheSet(cache, cacheKey, extracted, cacheTtlMs, cacheMax);
9957
+ cacheSet(cache2, cacheKey, extracted, cacheTtlMs, cacheMax);
9762
9958
  return formatOutput(extracted, maxLen);
9763
9959
  } catch (err) {
9764
9960
  if (err instanceof SsrFBlockedError) throw new Error(`web_fetch: ${err.message}`);
@@ -11969,10 +12165,10 @@ function releasePreparedAgentTurn(turn) {
11969
12165
  }
11970
12166
 
11971
12167
  // ../daemon/src/lib/user-md-host.ts
11972
- import { createHash as createHash5 } from "node:crypto";
12168
+ import { createHash as createHash6 } from "node:crypto";
11973
12169
  var USER_MD_MAX_BYTES = 12e3;
11974
12170
  function computeEtag(content) {
11975
- return createHash5("sha256").update(content, "utf8").digest("hex").slice(0, 16);
12171
+ return createHash6("sha256").update(content, "utf8").digest("hex").slice(0, 16);
11976
12172
  }
11977
12173
  function createDbUserMdHost(db, paths) {
11978
12174
  return {
@@ -12050,13 +12246,13 @@ function createWebSearchHost(opts) {
12050
12246
  const query = typeof args?.query === "string" ? args.query.trim() : "";
12051
12247
  if (!query || query.length > 512)
12052
12248
  throw new Error("web_search needs a query of 1\u2013512 characters");
12053
- 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;
12054
12250
  const signal = AbortSignal.any([opts.signal, AbortSignal.timeout(DEADLINE_MS2)]);
12055
12251
  const env = opts.env();
12056
12252
  try {
12057
12253
  if (opts.backend === "brave") {
12058
12254
  const body = await getJson(
12059
- `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) })}`,
12060
12256
  { "x-subscription-token": env.BRAVE_API_KEY ?? "" },
12061
12257
  signal,
12062
12258
  fetchImpl
@@ -12064,7 +12260,7 @@ function createWebSearchHost(opts) {
12064
12260
  const rows = body.web?.results;
12065
12261
  return {
12066
12262
  backend: "brave",
12067
- results: (Array.isArray(rows) ? rows : []).slice(0, count).map((row) => ({
12263
+ results: (Array.isArray(rows) ? rows : []).slice(0, count2).map((row) => ({
12068
12264
  title: text3(row?.title, 200),
12069
12265
  url: text3(row?.url, 2048),
12070
12266
  snippet: text3(row?.description, 300)
@@ -12081,14 +12277,14 @@ function createWebSearchHost(opts) {
12081
12277
  );
12082
12278
  return {
12083
12279
  backend: "searxng",
12084
- 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) => ({
12085
12281
  title: text3(row?.title, 200),
12086
12282
  url: text3(row?.url, 2048),
12087
12283
  snippet: text3(row?.content, 300)
12088
12284
  }))
12089
12285
  };
12090
12286
  }
12091
- return await hostedSearch(opts, query, count, signal, fetchImpl, env);
12287
+ return await hostedSearch(opts, query, count2, signal, fetchImpl, env);
12092
12288
  } catch (error) {
12093
12289
  if (opts.signal.aborted) throw new Error("web_search: cancelled");
12094
12290
  if (signal.aborted) throw new Error("web_search: no answer within 30 seconds");
@@ -12097,14 +12293,14 @@ function createWebSearchHost(opts) {
12097
12293
  }
12098
12294
  };
12099
12295
  }
12100
- async function hostedSearch(opts, query, count, signal, fetchImpl, env) {
12296
+ async function hostedSearch(opts, query, count2, signal, fetchImpl, env) {
12101
12297
  const codex = opts.backend === "openai-codex";
12102
12298
  const output = await responsesStream(
12103
12299
  codex ? CODEX_RESPONSES_URL : OPENAI_RESPONSES_URL,
12104
12300
  codex ? codexHeaders(await opts.codexToken()) : { authorization: `Bearer ${env.OPENAI_API_KEY ?? ""}` },
12105
12301
  {
12106
12302
  model: parseModelString(opts.model).modelId,
12107
- 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.`,
12108
12304
  input: [{ role: "user", content: [{ type: "input_text", text: query }] }],
12109
12305
  tools: [{ type: "web_search" }],
12110
12306
  tool_choice: { type: "web_search" }
@@ -12130,7 +12326,7 @@ async function hostedSearch(opts, query, count, signal, fetchImpl, env) {
12130
12326
  return {
12131
12327
  backend: opts.backend,
12132
12328
  answer: answer.join("\n").trim(),
12133
- results: results.slice(0, count)
12329
+ results: results.slice(0, count2)
12134
12330
  };
12135
12331
  }
12136
12332
 
@@ -12690,8 +12886,8 @@ agentChatRouter.get(
12690
12886
  agentChatRouter.post("/:id/chat/truncate", async (c) => {
12691
12887
  const body = await jsonBody(c);
12692
12888
  if (!body) return c.json({ error: "invalid JSON body" }, 400);
12693
- const keep = Number(body.keepCount);
12694
- if (!Number.isInteger(keep) || keep < 0) {
12889
+ const keep2 = Number(body.keepCount);
12890
+ if (!Number.isInteger(keep2) || keep2 < 0) {
12695
12891
  return c.json({ error: "keepCount must be a non-negative integer" }, 400);
12696
12892
  }
12697
12893
  return withSelectedConversation(c, (id, target) => {
@@ -12702,7 +12898,7 @@ agentChatRouter.post("/:id/chat/truncate", async (c) => {
12702
12898
  const conversation = openConversation(resolveAgent(db, paths, id), paths, target);
12703
12899
  const messageEntries = conversation.getBranch().filter((e) => e.type === "message" && e.message.role !== "system");
12704
12900
  const before = messageEntries.length;
12705
- const after = Math.max(0, Math.min(keep, before));
12901
+ const after = Math.max(0, Math.min(keep2, before));
12706
12902
  if (after === before) return c.json({ before, after });
12707
12903
  const lastKept = messageEntries[after - 1];
12708
12904
  if (lastKept) conversation.branch(lastKept.id);
@@ -13523,26 +13719,12 @@ function writeProviderCheck(db, providerId, check) {
13523
13719
  if (check) checks[providerId] = check;
13524
13720
  else if (providerId in checks) delete checks[providerId];
13525
13721
  else return;
13526
- const store = openConfig(db);
13527
- if (Object.keys(checks).length === 0) store.remove(PROVIDER_CHECKS_KEY);
13528
- 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));
13529
13725
  }
13530
13726
 
13531
13727
  // ../daemon/src/lib/provider-failure.ts
13532
- 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/;
13533
- 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/;
13534
- 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/;
13535
- var LIMIT = /insufficient|quota|rate.?limit|billing|\bcredits?\b|overloaded/;
13536
- function classifyProviderFailure(message, timedOut = false) {
13537
- const text4 = message.toLowerCase();
13538
- const status2 = /^(\d{3})\b/.exec(text4)?.[1];
13539
- if (timedOut || UNREACHABLE.test(text4)) return "unreachable";
13540
- if (status2 === "401" || CREDENTIALS.test(text4)) return "credentials";
13541
- if (MODEL.test(text4)) return "model";
13542
- if (status2 === "402" || status2 === "429" || LIMIT.test(text4)) return "limit";
13543
- if (status2 === "403") return "credentials";
13544
- return "other";
13545
- }
13546
13728
  function redactDetail(message, secrets) {
13547
13729
  let detail = message;
13548
13730
  for (const secret of secrets) {
@@ -13776,9 +13958,9 @@ function fieldStates(fields2, stored, env = process.env) {
13776
13958
  });
13777
13959
  }
13778
13960
  function writeSetting(db, authToken, field, value) {
13779
- const store = field.kind === "config" ? openConfig(db) : openSecrets(db, authToken);
13780
- if (value === "") store.remove(field.envVar);
13781
- 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);
13782
13964
  }
13783
13965
 
13784
13966
  // ../daemon/src/lib/provider-setup.ts
@@ -14658,23 +14840,476 @@ configRouter.delete("/fields/:envVar", (c) => {
14658
14840
  return c.body(null, 204);
14659
14841
  });
14660
14842
 
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
14866
+ );
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;
14890
+ try {
14891
+ text4 = readSessionText(directory, row.id);
14892
+ } catch {
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
+ });
14932
+ }
14933
+ }
14934
+ hits.sort((a, b) => (b.at ?? 0) - (a.at ?? 0));
14935
+ return { words, hits: hits.slice(0, limit), truncated: hits.length > limit, unreadable };
14936
+ }
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
+
14661
15273
  // ../daemon/src/routes/conversations.ts
14662
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
+ });
14663
15289
  conversationsRouter.use("/:agentId/conversations/*", async (c, next) => {
14664
15290
  c.set("agentId", routeAgent(c, "agentId").id);
14665
15291
  await next();
14666
15292
  });
14667
- conversationsRouter.get(
14668
- "/:agentId/conversations",
14669
- (c) => c.json(
14670
- list11(
14671
- getCtx().db,
14672
- c.get("agentId"),
14673
- Number(c.req.query("limit") ?? 20),
14674
- Number(c.req.query("offset") ?? 0)
14675
- )
14676
- )
14677
- );
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
+ });
14678
15313
  conversationsRouter.post("/:agentId/conversations", async (c) => {
14679
15314
  const input = await jsonBody(c);
14680
15315
  const agentId = c.get("agentId");
@@ -14697,7 +15332,10 @@ conversationsRouter.get("/:agentId/conversations/:id", (c) => {
14697
15332
  loadInitialMessages(resolveAgent(db, paths, agentId), paths, { id }),
14698
15333
  envSecretValues(mergeSecretsIntoEnv(db, authToken))
14699
15334
  );
14700
- return c.json({ conversation, messages });
15335
+ const usage = conversationUsage2(paths, agentId, planProviders(mergeSecretsIntoEnv(db, authToken))).get(
15336
+ id
15337
+ ) ?? null;
15338
+ return c.json({ conversation, messages, usage });
14701
15339
  } catch {
14702
15340
  return c.json(
14703
15341
  {
@@ -14735,7 +15373,7 @@ conversationsRouter.patch("/:agentId/conversations/:id", async (c) => {
14735
15373
  import { streamSSE } from "hono/streaming";
14736
15374
 
14737
15375
  // ../daemon/src/lib/live.ts
14738
- import { createHash as createHash6 } from "node:crypto";
15376
+ import { createHash as createHash7 } from "node:crypto";
14739
15377
  var CHECK_MS = 1e3;
14740
15378
  var ATTENTION_EVERY = 5;
14741
15379
  var SETTLE_MS = 25;
@@ -14747,7 +15385,7 @@ function readLiveAttention() {
14747
15385
  const { db } = getCtx();
14748
15386
  const waiting = waitingAttention(db);
14749
15387
  const all = projectAttention(db, { state: "all", limit: 1e5 }, waiting);
14750
- const revision = createHash6("sha256").update(
15388
+ const revision = createHash7("sha256").update(
14751
15389
  all.items.map((item) => `${item.key}|${item.updatedAt}|${item.acknowledgedAt ?? ""}`).join("\n")
14752
15390
  ).update(JSON.stringify(all.degraded)).digest("hex").slice(0, 16);
14753
15391
  return {
@@ -15045,23 +15683,23 @@ agentMessagesRouter.post("/:id/messages", async (c) => {
15045
15683
  // ../daemon/src/routes/misc.ts
15046
15684
  import { existsSync as existsSync17 } from "node:fs";
15047
15685
  import { homedir as homedir4 } from "node:os";
15048
- import { join as join32 } from "node:path";
15686
+ import { join as join34 } from "node:path";
15049
15687
 
15050
15688
  // ../daemon/src/lib/backup.ts
15051
15689
  import { mkdtempSync as mkdtempSync3, rmSync as rmSync13 } from "node:fs";
15052
15690
  import { tmpdir as tmpdir3 } from "node:os";
15053
- import { join as join31, resolve as resolve7 } from "node:path";
15691
+ import { join as join33, resolve as resolve7 } from "node:path";
15054
15692
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
15055
15693
  import { create as create6 } from "tar";
15056
15694
 
15057
15695
  // ../daemon/src/lib/daemon-liveness.ts
15058
15696
  import { mkdirSync as mkdirSync11, readFileSync as readFileSync11, rmSync as rmSync12, writeFileSync as writeFileSync10 } from "node:fs";
15059
- import { join as join30 } from "node:path";
15697
+ import { join as join32 } from "node:path";
15060
15698
  var DAEMON_PID_FILE = "daemon.pid";
15061
15699
  function runningDaemonPid(home) {
15062
15700
  let pid;
15063
15701
  try {
15064
- pid = Number.parseInt(readFileSync11(join30(home, DAEMON_PID_FILE), "utf8"), 10);
15702
+ pid = Number.parseInt(readFileSync11(join32(home, DAEMON_PID_FILE), "utf8"), 10);
15065
15703
  } catch (error) {
15066
15704
  if (error.code === "ENOENT") return null;
15067
15705
  throw error;
@@ -15078,12 +15716,12 @@ function assertDaemonStopped(home) {
15078
15716
  const pid = runningDaemonPid(home);
15079
15717
  if (pid !== null) {
15080
15718
  throw new Error(
15081
- `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)})`
15082
15720
  );
15083
15721
  }
15084
15722
  }
15085
15723
  function claimDaemonPidFile(home) {
15086
- const path = join30(home, DAEMON_PID_FILE);
15724
+ const path = join32(home, DAEMON_PID_FILE);
15087
15725
  const content = `${process.pid}
15088
15726
  `;
15089
15727
  mkdirSync11(home, { recursive: true });
@@ -15112,10 +15750,10 @@ function createBackupSnapshot(db) {
15112
15750
  return snapshot3;
15113
15751
  }
15114
15752
  async function takeSnapshot(db) {
15115
- const directory = mkdtempSync3(join31(tmpdir3(), "bazilion-backup-"));
15753
+ const directory = mkdtempSync3(join33(tmpdir3(), "bazilion-backup-"));
15116
15754
  const cleanup = () => rmSync13(directory, { recursive: true, force: true });
15117
15755
  try {
15118
- const database = join31(directory, "bazilion.snapshot");
15756
+ const database = join33(directory, "bazilion.snapshot");
15119
15757
  await db.backupTo(database);
15120
15758
  const snapshot3 = new DatabaseSync2(database, { readOnly: true });
15121
15759
  try {
@@ -15214,7 +15852,7 @@ miscRouter.get("/health/details", async (c) => {
15214
15852
  } catch {
15215
15853
  }
15216
15854
  }
15217
- const openclawSkillsDir = join32(homedir4(), ".openclaw", "skills");
15855
+ const openclawSkillsDir = join34(homedir4(), ".openclaw", "skills");
15218
15856
  const providerSection = {
15219
15857
  // Hosted providers with credentials; local servers are reported below.
15220
15858
  configured: PROVIDERS.filter(
@@ -15623,7 +16261,7 @@ notificationsRouter.put("/", async (c) => {
15623
16261
 
15624
16262
  // ../daemon/src/routes/profiles.ts
15625
16263
  import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "node:fs";
15626
- import { join as join33 } from "node:path";
16264
+ import { join as join35 } from "node:path";
15627
16265
  var profilesRouter = newRouter();
15628
16266
  profilesRouter.get("/", (c) => {
15629
16267
  const { db } = getCtx();
@@ -15705,7 +16343,7 @@ function profileFile(c) {
15705
16343
  if (!PROFILE_FILES.includes(file)) {
15706
16344
  return c.json({ error: `unsupported file: ${file}` }, 400);
15707
16345
  }
15708
- return join33(paths.profilesDir, id, file);
16346
+ return join35(paths.profilesDir, id, file);
15709
16347
  }
15710
16348
  profilesRouter.get("/:id/files/:file", (c) => {
15711
16349
  const path = profileFile(c);
@@ -15759,11 +16397,11 @@ function dosDateTime(epochMs) {
15759
16397
  function uniqueNames(names) {
15760
16398
  const seen = /* @__PURE__ */ new Map();
15761
16399
  return names.map((name) => {
15762
- const count = (seen.get(name) ?? 0) + 1;
15763
- seen.set(name, count);
15764
- if (count === 1) return name;
16400
+ const count2 = (seen.get(name) ?? 0) + 1;
16401
+ seen.set(name, count2);
16402
+ if (count2 === 1) return name;
15765
16403
  const dot = name.lastIndexOf(".");
15766
- 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})`;
15767
16405
  });
15768
16406
  }
15769
16407
  function localHeader(name, bytes, crc, epochMs) {
@@ -15926,13 +16564,33 @@ resultsRouter.get("/:id/preview", (c) => {
15926
16564
  const db = getCtx().db;
15927
16565
  const result = get17(db, c.req.param("id"));
15928
16566
  if (!result) return c.json({ error: "Result not found" }, 404);
15929
- const text4 = ["text/plain", "text/markdown"].includes(result.mimeType);
16567
+ const text4 = isTextPreview(result);
15930
16568
  const image = ["image/png", "image/jpeg", "image/gif", "image/webp"].includes(result.mimeType);
15931
- if (!text4 && !image || result.byteLength > (text4 ? 256 * 1024 : 10 * 1024 * 1024)) {
16569
+ if (!text4 && (!image || result.byteLength > 10 * 1024 * 1024)) {
15932
16570
  return c.json({ error: "Preview is unavailable for this file. Use Download." }, 415);
15933
16571
  }
16572
+ const bytesParam = Number(c.req.query("bytes"));
16573
+ const cut = text4 && Number.isInteger(bytesParam) && bytesParam > 0 ? bytesParam : null;
15934
16574
  try {
15935
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
+ }
15936
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;
15937
16595
  if (image && !magic)
15938
16596
  return c.json({ error: "File content does not match its image type. Use Download." }, 415);
@@ -15970,7 +16628,7 @@ shellApprovalsRouter.post("/:id", async (c) => {
15970
16628
  // ../daemon/src/routes/skills.ts
15971
16629
  import { mkdtempSync as mkdtempSync4, rmSync as rmSync14, writeFileSync as writeFileSync12 } from "node:fs";
15972
16630
  import { homedir as homedir5, tmpdir as tmpdir4 } from "node:os";
15973
- import { join as join34 } from "node:path";
16631
+ import { join as join36 } from "node:path";
15974
16632
  var MAX_ZIP_BYTES = 50 * 1024 * 1024;
15975
16633
  var skillsRouter = newRouter();
15976
16634
  skillsRouter.get("/", (c) => {
@@ -16063,8 +16721,8 @@ async function parseImportInput(request) {
16063
16721
  if (!filename.toLowerCase().endsWith(".zip")) {
16064
16722
  throw new Error("uploaded file must be a .zip archive");
16065
16723
  }
16066
- const tmpDir = mkdtempSync4(join34(tmpdir4(), "bazilion-skill-upload-"));
16067
- 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, "_"));
16068
16726
  const buf = Buffer.from(await file.arrayBuffer());
16069
16727
  writeFileSync12(zipPath, buf);
16070
16728
  const forceField = form.get("force");
@@ -16080,7 +16738,7 @@ async function parseImportInput(request) {
16080
16738
  const { source } = body;
16081
16739
  if (typeof source !== "string" || !source) throw new Error("source is required");
16082
16740
  return {
16083
- source: source === "openclaw" ? join34(homedir5(), ".openclaw", "skills") : source,
16741
+ source: source === "openclaw" ? join36(homedir5(), ".openclaw", "skills") : source,
16084
16742
  force: Boolean(body.force),
16085
16743
  tempZipPath: null,
16086
16744
  sourceLabel: source
@@ -16150,7 +16808,7 @@ teamCodingEnvironmentRouter.put("/:id/coding-environment", async (c) => {
16150
16808
  });
16151
16809
 
16152
16810
  // ../daemon/src/routes/team-memory.ts
16153
- import { join as join35 } from "node:path";
16811
+ import { join as join37 } from "node:path";
16154
16812
  var teamMemoryRouter = newRouter();
16155
16813
  teamMemoryRouter.onError((error, c) => {
16156
16814
  const safe = sanitizeNativeModuleError(error, { subject: "Bazilion memory" });
@@ -16158,7 +16816,7 @@ teamMemoryRouter.onError((error, c) => {
16158
16816
  return onRouteError(safe, c);
16159
16817
  });
16160
16818
  async function openMemory(c) {
16161
- const mem = qmdBackend(join35(routeTeam(c).path, "memory"));
16819
+ const mem = qmdBackend(join37(routeTeam(c).path, "memory"));
16162
16820
  await mem.init();
16163
16821
  return mem;
16164
16822
  }
@@ -16213,19 +16871,19 @@ teamPolicyRouter.post("/:id/policy/save-as-template", async (c) => {
16213
16871
  });
16214
16872
 
16215
16873
  // ../daemon/src/lib/git/context-directory.ts
16216
- import { createHash as createHash7 } from "node:crypto";
16874
+ import { createHash as createHash8 } from "node:crypto";
16217
16875
  import {
16218
- closeSync as closeSync6,
16219
- constants as constants7,
16220
- fstatSync as fstatSync6,
16876
+ closeSync as closeSync7,
16877
+ constants as constants8,
16878
+ fstatSync as fstatSync7,
16221
16879
  lstatSync as lstatSync6,
16222
16880
  opendirSync,
16223
- openSync as openSync6,
16224
- readSync as readSync3,
16881
+ openSync as openSync7,
16882
+ readSync as readSync4,
16225
16883
  realpathSync as realpathSync7
16226
16884
  } from "node:fs";
16227
- import { join as join36 } from "node:path";
16228
- var hash = (value) => createHash7("sha256").update(value).digest("hex");
16885
+ import { join as join38 } from "node:path";
16886
+ var hash = (value) => createHash8("sha256").update(value).digest("hex");
16229
16887
  var ContextReadError = class extends Error {
16230
16888
  code;
16231
16889
  constructor(code) {
@@ -16262,22 +16920,22 @@ var ContextDirectory = class _ContextDirectory {
16262
16920
  this.parent = parent;
16263
16921
  if (parent) component(registeredPath);
16264
16922
  parent?.assertOpen();
16265
- const canonicalPath = parent ? join36(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
16923
+ const canonicalPath = parent ? join38(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
16266
16924
  this.canonicalPath = canonicalPath;
16267
16925
  let fd;
16268
16926
  try {
16269
- fd = openSync6(
16270
- parent ? join36(parent.path, registeredPath) : canonicalPath,
16271
- 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
16272
16930
  );
16273
- const stat = fstatSync6(fd, { bigint: true });
16931
+ const stat = fstatSync7(fd, { bigint: true });
16274
16932
  if (!stat.isDirectory() || stat.ino <= 0n) throw new ContextReadError("root_changed");
16275
16933
  this.fd = fd;
16276
16934
  this.originalIdentity = { dev: stat.dev, ino: stat.ino };
16277
16935
  this.identity = hash(identity(stat));
16278
16936
  fd = void 0;
16279
16937
  } finally {
16280
- if (fd !== void 0) closeSync6(fd);
16938
+ if (fd !== void 0) closeSync7(fd);
16281
16939
  }
16282
16940
  }
16283
16941
  get path() {
@@ -16316,7 +16974,7 @@ var ContextDirectory = class _ContextDirectory {
16316
16974
  entry(name) {
16317
16975
  component(name);
16318
16976
  this.assertOpen();
16319
- const path = join36(this.path, name);
16977
+ const path = join38(this.path, name);
16320
16978
  try {
16321
16979
  return lstatSync6(path);
16322
16980
  } catch (error) {
@@ -16325,7 +16983,7 @@ var ContextDirectory = class _ContextDirectory {
16325
16983
  }
16326
16984
  }
16327
16985
  observe(name) {
16328
- const path = join36(this.path, name);
16986
+ const path = join38(this.path, name);
16329
16987
  try {
16330
16988
  return lstatSync6(path, { bigint: true });
16331
16989
  } catch (error) {
@@ -16367,21 +17025,21 @@ var ContextDirectory = class _ContextDirectory {
16367
17025
  if (entry.size > maxBytes) throw new ContextReadError("byte_limit");
16368
17026
  let fd;
16369
17027
  try {
16370
- fd = openSync6(
16371
- join36(this.path, name),
16372
- 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
16373
17031
  );
16374
- const before = fstatSync6(fd, { bigint: true });
17032
+ const before = fstatSync7(fd, { bigint: true });
16375
17033
  if (!before.isFile() || stamp(entry) !== stamp(before))
16376
17034
  throw new ContextReadError("source_changed");
16377
17035
  const buffer = Buffer.alloc(Math.min(maxBytes, Number(before.size)) + 1);
16378
17036
  let size = 0;
16379
17037
  while (size < buffer.length) {
16380
- const count = readSync3(fd, buffer, size, buffer.length - size, null);
16381
- if (!count) break;
16382
- size += count;
17038
+ const count2 = readSync4(fd, buffer, size, buffer.length - size, null);
17039
+ if (!count2) break;
17040
+ size += count2;
16383
17041
  }
16384
- 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))
16385
17043
  throw new ContextReadError("source_changed");
16386
17044
  if (!FD_PATHS) this.checkedPath();
16387
17045
  this.observedFiles.set(name, stamp(before));
@@ -16390,16 +17048,16 @@ var ContextDirectory = class _ContextDirectory {
16390
17048
  if (error instanceof ContextReadError) throw error;
16391
17049
  throw new ContextReadError("unreadable");
16392
17050
  } finally {
16393
- if (fd !== void 0) closeSync6(fd);
17051
+ if (fd !== void 0) closeSync7(fd);
16394
17052
  }
16395
17053
  }
16396
17054
  validate(skipGit = false, names) {
16397
17055
  this.assertOpen();
16398
- 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);
16399
17057
  const stat = lstatSync6(currentPath, { bigint: true });
16400
17058
  if (!stat.isDirectory() || identity(stat) !== identity(this.originalIdentity))
16401
17059
  throw new ContextReadError("root_changed");
16402
- const retained = fstatSync6(this.fd, { bigint: true });
17060
+ const retained = fstatSync7(this.fd, { bigint: true });
16403
17061
  if (!retained.isDirectory() || identity(retained) !== identity(this.originalIdentity))
16404
17062
  throw new ContextReadError("root_changed");
16405
17063
  if (this.listing !== void 0 && JSON.stringify(this.listNames()) !== this.listing)
@@ -16426,7 +17084,7 @@ var ContextDirectory = class _ContextDirectory {
16426
17084
  }
16427
17085
  }
16428
17086
  try {
16429
- closeSync6(this.fd);
17087
+ closeSync7(this.fd);
16430
17088
  } catch (error) {
16431
17089
  failure ??= error;
16432
17090
  }
@@ -16503,18 +17161,18 @@ async function listChanges(captured, base, identity2, limits = REVIEW_LIMITS) {
16503
17161
  for (const header of parseRaw(raw)) {
16504
17162
  const scoped = reviewScope(header.path);
16505
17163
  if (!scoped.included) excludedTracked++;
16506
- const count = counts.get(header.path) ?? null;
17164
+ const count2 = counts.get(header.path) ?? null;
16507
17165
  entries.push({
16508
17166
  path: header.path,
16509
17167
  previousPath: header.previousPath,
16510
17168
  status: header.status,
16511
- binary: count?.binary ?? false,
16512
- addedLines: count?.added ?? null,
16513
- deletedLines: count?.deleted ?? null,
17169
+ binary: count2?.binary ?? false,
17170
+ addedLines: count2?.added ?? null,
17171
+ deletedLines: count2?.deleted ?? null,
16514
17172
  patch: null,
16515
17173
  patchTruncated: false,
16516
17174
  // A credential-shaped or Bazilion-owned tracked file may be listed, but never captured.
16517
- contentOmitted: scoped.included ? count?.binary ? "binary" : null : "excluded",
17175
+ contentOmitted: scoped.included ? count2?.binary ? "binary" : null : "excluded",
16518
17176
  excludedReason: scoped.included ? null : scoped.reason
16519
17177
  });
16520
17178
  }
@@ -16823,7 +17481,7 @@ async function readOrNull(captured, args) {
16823
17481
  import { execFile } from "node:child_process";
16824
17482
  import { mkdirSync as mkdirSync12, mkdtempSync as mkdtempSync5, rmSync as rmSync15, utimesSync, writeFileSync as writeFileSync13 } from "node:fs";
16825
17483
  import { tmpdir as tmpdir5 } from "node:os";
16826
- import { join as join37 } from "node:path";
17484
+ import { join as join39 } from "node:path";
16827
17485
  var INSPECTION_BUDGET_MS = 5e3;
16828
17486
  var METADATA_BUDGET_MS = 2500;
16829
17487
  var METADATA_BYTES = 64 * 1024 * 1024;
@@ -16839,7 +17497,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16839
17497
  const worktree = root.gitWorktreePath;
16840
17498
  const start2 = Date.now();
16841
17499
  let bytes = 0;
16842
- let count = 0;
17500
+ let count2 = 0;
16843
17501
  const marker = root.entry(".git");
16844
17502
  if (!marker?.isDirectory() || marker.isSymbolicLink())
16845
17503
  throw new ContextReadError("unsupported_git_metadata");
@@ -16852,7 +17510,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16852
17510
  const dir = git.directory("info");
16853
17511
  if (dir.entry("sparse-checkout")) throw new ContextReadError("unsupported_git_metadata");
16854
17512
  }
16855
- const scratch = mkdtempSync5(join37(tmpdir5(), "bazilion-context-git-"));
17513
+ const scratch = mkdtempSync5(join39(tmpdir5(), "bazilion-context-git-"));
16856
17514
  let cleaned = false;
16857
17515
  const cleanup = () => {
16858
17516
  if (cleaned) return;
@@ -16912,8 +17570,8 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16912
17570
  const configLines = ["[core]", "repositoryformatversion = 0", "bare = false", "filemode = true"];
16913
17571
  if (capturedConfig) {
16914
17572
  bytes += capturedConfig.length;
16915
- count++;
16916
- const configPath = join37(scratch, "captured-config");
17573
+ count2++;
17574
+ const configPath = join39(scratch, "captured-config");
16917
17575
  writeFileSync13(configPath, capturedConfig, { mode: 384 });
16918
17576
  const config = await rawGit([
16919
17577
  "config",
@@ -16966,27 +17624,27 @@ objectformat = ${value}`
16966
17624
  const exclude = git.directory("info").read("exclude", METADATA_READ);
16967
17625
  if (exclude) {
16968
17626
  bytes += exclude.length;
16969
- mkdirSync12(join37(scratch, "info"), { mode: 448 });
16970
- writeFileSync13(join37(scratch, "info", "exclude"), exclude, { mode: 384 });
17627
+ mkdirSync12(join39(scratch, "info"), { mode: 448 });
17628
+ writeFileSync13(join39(scratch, "info", "exclude"), exclude, { mode: 384 });
16971
17629
  }
16972
17630
  }
16973
17631
  const copy = (source, destination, depth) => {
16974
17632
  if (depth > METADATA_DEPTH) throw new ContextReadError("git_metadata_limit");
16975
17633
  for (const name of source.list()) {
16976
- if (++count > METADATA_ENTRIES || Date.now() - start2 > METADATA_BUDGET_MS)
17634
+ if (++count2 > METADATA_ENTRIES || Date.now() - start2 > METADATA_BUDGET_MS)
16977
17635
  throw new ContextReadError("git_metadata_limit");
16978
17636
  const entry = source.entry(name);
16979
17637
  if (!entry || entry.isSymbolicLink()) throw new ContextReadError("unsupported_git_metadata");
16980
17638
  if (name === "alternates" || name === "http-alternates")
16981
17639
  throw new ContextReadError("unsupported_git_metadata");
16982
17640
  if (entry.isDirectory()) {
16983
- mkdirSync12(join37(destination, name), { mode: 448 });
16984
- 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);
16985
17643
  } else {
16986
17644
  const content = source.read(name, METADATA_BYTES - bytes);
16987
17645
  if (!content) throw new ContextReadError("source_changed");
16988
17646
  bytes += content.length;
16989
- writeFileSync13(join37(destination, name), content, { mode: 384 });
17647
+ writeFileSync13(join39(destination, name), content, { mode: 384 });
16990
17648
  }
16991
17649
  }
16992
17650
  };
@@ -16994,22 +17652,22 @@ objectformat = ${value}`
16994
17652
  const written = name === "index" ? git.entry(name) : null;
16995
17653
  const content = git.read(name, Math.min(METADATA_READ_LARGE, METADATA_BYTES - bytes));
16996
17654
  if (content) {
16997
- count++;
17655
+ count2++;
16998
17656
  bytes += content.length;
16999
- writeFileSync13(join37(scratch, name), content, { mode: 384 });
17657
+ writeFileSync13(join39(scratch, name), content, { mode: 384 });
17000
17658
  if (written) {
17001
17659
  const seconds = Math.floor(written.mtimeMs / 1e3);
17002
- utimesSync(join37(scratch, name), seconds, seconds);
17660
+ utimesSync(join39(scratch, name), seconds, seconds);
17003
17661
  }
17004
17662
  }
17005
17663
  }
17006
17664
  for (const name of ["refs", "objects"]) {
17007
- mkdirSync12(join37(scratch, name), { mode: 448 });
17008
- 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);
17009
17667
  }
17010
17668
  if (git.list().some((name) => name.startsWith("sharedindex.")))
17011
17669
  throw new ContextReadError("unsupported_git_metadata");
17012
- writeFileSync13(join37(scratch, "config"), `${configLines.join("\n")}
17670
+ writeFileSync13(join39(scratch, "config"), `${configLines.join("\n")}
17013
17671
  `, { mode: 384 });
17014
17672
  const validate2 = () => git.validate();
17015
17673
  validate2();
@@ -17022,7 +17680,7 @@ objectformat = ${value}`
17022
17680
 
17023
17681
  // ../daemon/src/lib/git-review/authors.ts
17024
17682
  import { realpathSync as realpathSync8 } from "node:fs";
17025
- 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";
17026
17684
  var FILE_TOOLS = /* @__PURE__ */ new Set(["write", "edit"]);
17027
17685
  var CONVERSATIONS_PER_AGENT = 5;
17028
17686
  var SANDBOX_ROOT = "/workspace";
@@ -17047,7 +17705,7 @@ function readChangeAuthors(db, paths, team, changedPaths) {
17047
17705
  }
17048
17706
  const members = list(db, { includeArchived: true }).filter((agent) => agent.teamId === team.id);
17049
17707
  for (const agent of members) {
17050
- const directory = join38(paths.agentDir(agent.id), "sessions");
17708
+ const directory = join40(paths.agentDir(agent.id), "sessions");
17051
17709
  const recent = list11(db, agent.id, CONVERSATIONS_PER_AGENT, 0).conversations;
17052
17710
  for (const conversation of recent) {
17053
17711
  let lines;
@@ -17188,8 +17846,8 @@ function hunkForLine(patch, line) {
17188
17846
  const header = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(lines[start2] ?? "");
17189
17847
  if (!header) continue;
17190
17848
  const first = Number(header[1]);
17191
- const count = header[2] === void 0 ? 1 : Number(header[2]);
17192
- 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;
17193
17851
  return lines.slice(start2, starts[position + 1] ?? lines.length).join("\n");
17194
17852
  }
17195
17853
  return null;
@@ -17847,8 +18505,8 @@ Run <code>/talk ${htmlEscape(agent.name)}</code> after fixing the underlying iss
17847
18505
  };
17848
18506
  }
17849
18507
  function autoName(ctx, profile) {
17850
- const count = agents_exports.countByProfile(ctx.db, profile.id);
17851
- return `${profile.id}-${count + 1}`;
18508
+ const count2 = agents_exports.countByProfile(ctx.db, profile.id);
18509
+ return `${profile.id}-${count2 + 1}`;
17852
18510
  }
17853
18511
 
17854
18512
  // ../daemon/src/lib/telegram/commands/spawn-team.ts
@@ -17968,9 +18626,9 @@ var handle9 = async (ctx) => {
17968
18626
  }
17969
18627
  const lines = ["<b>bazilion teams</b>", ""];
17970
18628
  for (const g of teams) {
17971
- const count = agents_exports.countByTeam(ctx.db, g.id);
18629
+ const count2 = agents_exports.countByTeam(ctx.db, g.id);
17972
18630
  const label = `<code>${htmlEscape(g.id)}</code> \xB7 ${htmlEscape(g.name)}`;
17973
- lines.push(`${label} \u2014 ${count} agent${count === 1 ? "" : "s"}`);
18631
+ lines.push(`${label} \u2014 ${count2} agent${count2 === 1 ? "" : "s"}`);
17974
18632
  }
17975
18633
  return { text: lines.join("\n"), parseMode: "HTML" };
17976
18634
  };
@@ -19170,10 +19828,7 @@ function parseCron(expr) {
19170
19828
  };
19171
19829
  return parsed;
19172
19830
  }
19173
- function matchesCron(parsed, date) {
19174
- if (!parsed.minute.has(date.getMinutes())) return false;
19175
- if (!parsed.hour.has(date.getHours())) return false;
19176
- if (!parsed.month.has(date.getMonth() + 1)) return false;
19831
+ function dayMatches(parsed, date) {
19177
19832
  const domMatch = parsed.dom.has(date.getDate());
19178
19833
  const dowMatch = parsed.dow.has(date.getDay());
19179
19834
  if (parsed.domRestricted && parsed.dowRestricted) {
@@ -19183,219 +19838,67 @@ function matchesCron(parsed, date) {
19183
19838
  if (parsed.dowRestricted) return dowMatch;
19184
19839
  return true;
19185
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
+ }
19186
19869
  function validateCron(expr) {
19187
19870
  parseCron(expr);
19188
19871
  }
19189
19872
 
19190
- // ../daemon/src/routes/triggers.ts
19191
- var triggersRouter = newRouter();
19192
- function triggerExists(id) {
19193
- return triggers_exports.get(getCtx().db, id) !== null;
19873
+ // ../daemon/src/lib/review-provider.ts
19874
+ function reviewEndpoint(providerName, env) {
19875
+ const raw = providerEndpoint(providerName, env);
19876
+ if (!raw) return void 0;
19877
+ let url;
19878
+ try {
19879
+ url = new URL(raw);
19880
+ } catch {
19881
+ throw new ExecutionUnavailableError("Provider endpoint is invalid.");
19882
+ }
19883
+ if (url.username || url.password || url.hash) {
19884
+ throw new ExecutionUnavailableError("Provider endpoint contains unsafe URL fields.");
19885
+ }
19886
+ if (!findProvider(providerName)?.local && url.protocol !== "https:") {
19887
+ throw new ExecutionUnavailableError("Credential-bearing provider endpoints require HTTPS.");
19888
+ }
19889
+ return url.toString().replace(/\/$/, "");
19194
19890
  }
19195
- triggersRouter.get("/:id/dispatches", (c) => {
19196
- const id = c.req.param("id");
19197
- if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
19198
- const requestedLimit = Number(c.req.query("limit") ?? 20);
19199
- if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
19200
- return c.json({ error: "limit must be a positive integer" }, 400);
19201
- }
19202
- const limit = Math.min(100, requestedLimit);
19203
- return c.json({
19204
- dispatches: triggerDispatches_exports.listForTrigger(getCtx().db, id, limit)
19205
- });
19206
- });
19207
- triggersRouter.delete("/:id", (c) => {
19208
- const id = c.req.param("id");
19209
- if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
19210
- triggers_exports.remove(getCtx().db, id);
19211
- return c.body(null, 204);
19212
- });
19213
- triggersRouter.patch("/:id", async (c) => {
19214
- const id = c.req.param("id");
19215
- const body = await jsonBody(c);
19216
- if (!body) return c.json({ error: "invalid JSON body" }, 400);
19217
- if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
19218
- const { db } = getCtx();
19219
- if (typeof body.enabled === "boolean") triggers_exports.setEnabled(db, id, body.enabled);
19220
- return c.json({ trigger: triggers_exports.get(db, id) });
19221
- });
19222
- var agentTriggersRouter = newRouter();
19223
- agentTriggersRouter.get("/:id/triggers", (c) => {
19224
- const { db } = getCtx();
19225
- const triggers = triggers_exports.listForAgent(db, routeAgent(c).id);
19226
- return c.json({
19227
- triggers,
19228
- dispatches: triggers.flatMap(
19229
- (trigger) => triggerDispatches_exports.listForTrigger(db, trigger.id, 10)
19230
- )
19231
- });
19232
- });
19233
- agentTriggersRouter.post("/:id/triggers", async (c) => {
19234
- const body = await jsonBody(c);
19235
- if (!body) return c.json({ error: "invalid JSON body" }, 400);
19236
- if (typeof body.message !== "string" || !body.message.trim()) {
19237
- return c.json({ error: "message is required" }, 400);
19238
- }
19239
- const agentId = routeAgent(c).id;
19240
- const { db } = getCtx();
19241
- if (body.kind === "interval") {
19242
- const intervalSec = body.intervalSec;
19243
- if (typeof intervalSec !== "number" || !Number.isInteger(intervalSec) || intervalSec < 1) {
19244
- return c.json({ error: "intervalSec must be a whole number of seconds, at least 1" }, 400);
19245
- }
19246
- const trigger = triggers_exports.insert(db, {
19247
- agentId,
19248
- kind: "interval",
19249
- intervalSec,
19250
- cronExpr: null,
19251
- message: body.message,
19252
- enabled: body.enabled
19253
- });
19254
- return c.json({ trigger }, 201);
19255
- }
19256
- if (body.kind === "cron") {
19257
- if (typeof body.cronExpr !== "string" || !body.cronExpr.trim()) {
19258
- return c.json({ error: "cronExpr is required for kind=cron" }, 400);
19259
- }
19260
- try {
19261
- validateCron(body.cronExpr);
19262
- } catch (err) {
19263
- return c.json({ error: `invalid cron: ${err.message}` }, 400);
19264
- }
19265
- const trigger = triggers_exports.insert(db, {
19266
- agentId,
19267
- kind: "cron",
19268
- intervalSec: null,
19269
- cronExpr: body.cronExpr.trim(),
19270
- message: body.message,
19271
- enabled: body.enabled
19272
- });
19273
- return c.json({ trigger }, 201);
19274
- }
19275
- return c.json({ error: `invalid kind: ${body.kind}` }, 400);
19276
- });
19277
-
19278
- // ../daemon/src/routes/user-queue.ts
19279
- import { bodyLimit as bodyLimit3 } from "hono/body-limit";
19280
- var userQueueRouter = newRouter();
19281
- userQueueRouter.use("/:agentId/queue/*", bodyLimit3({ maxSize: 36 * 1024 * 1024 }));
19282
- userQueueRouter.use("/:agentId/queue/*", async (c, next) => {
19283
- c.set("agentId", routeAgent(c, "agentId").id);
19284
- await next();
19285
- });
19286
- userQueueRouter.get(
19287
- "/:agentId/queue",
19288
- (c) => c.json({
19289
- ...list4(getCtx().db, c.get("agentId")),
19290
- turnActive: isActiveAgent(c.get("agentId"))
19291
- })
19292
- );
19293
- userQueueRouter.post("/:agentId/queue", async (c) => {
19294
- const input = await jsonBody(c);
19295
- return c.json(
19296
- await enqueueUserInput(c.get("agentId"), {
19297
- message: input?.message,
19298
- attachments: input?.attachments ?? []
19299
- }),
19300
- 202
19301
- );
19302
- });
19303
- userQueueRouter.patch("/:agentId/queue/:id", async (c) => {
19304
- const input = await jsonBody(c);
19305
- return c.json(
19306
- edit(getCtx().db, c.get("agentId"), c.req.param("id"), input?.message)
19307
- );
19308
- });
19309
- userQueueRouter.delete("/:agentId/queue/:id", async (c) => {
19310
- const { item, origin } = remove4(getCtx().db, c.get("agentId"), c.req.param("id"));
19311
- if (item.status === "pending") await notifyTelegramQueueOutcome(item, origin, "removed");
19312
- return c.json(item);
19313
- });
19314
- userQueueRouter.post("/:agentId/queue/control", async (c) => {
19315
- const input = await jsonBody(c);
19316
- if (typeof input?.paused !== "boolean") return c.json({ error: "paused must be a boolean" }, 400);
19317
- setPaused(getCtx().db, c.get("agentId"), input.paused);
19318
- return c.json({ paused: input.paused });
19319
- });
19320
-
19321
- // ../daemon/src/app.ts
19322
- function createApp() {
19323
- const app2 = new Hono2();
19324
- app2.use("*", authMiddleware);
19325
- app2.use("/api/*", async (c, next) => {
19326
- await next();
19327
- if (!c.res.headers.has("cache-control")) c.res.headers.set("cache-control", "no-store");
19328
- });
19329
- app2.route("/api/agents", agentsRouter);
19330
- app2.route("/api/agents", agentChatRouter);
19331
- app2.route("/api/agents", agentBrowserRouter);
19332
- app2.route("/api/agents", agentLearningRouter);
19333
- app2.route("/api/agents", agentMessagesRouter);
19334
- app2.route("/api/agents", agentSkillsRouter);
19335
- app2.route("/api/agents", agentTelegramRouter);
19336
- app2.route("/api/agents", agentTriggersRouter);
19337
- app2.route("/api/agents", conversationsRouter);
19338
- app2.route("/api/agents", userQueueRouter);
19339
- app2.route("/api/agents", questionsRouter);
19340
- app2.route("/api/teams", teamsRouter);
19341
- app2.route("/api/teams", teamMemoryRouter);
19342
- app2.route("/api/teams", teamPolicyRouter);
19343
- app2.route("/api/teams", teamReviewRouter);
19344
- app2.route("/api/teams", teamMessagesRouter);
19345
- app2.route("/api/teams", teamCodingEnvironmentRouter);
19346
- app2.route("/api/teams", teamTelegramRouter);
19347
- app2.route("/api/team-templates", teamTemplatesRouter);
19348
- app2.route("/api/results", resultsRouter);
19349
- app2.route("/api/attention", attentionRouter);
19350
- app2.route("/api/activity", activityRouter);
19351
- app2.route("/api/events", eventsRouter);
19352
- app2.route("/api/notifications", notificationsRouter);
19353
- app2.route("/api/shell-approvals", shellApprovalsRouter);
19354
- app2.route("/api/profiles", profilesRouter);
19355
- app2.route("/api/skills", skillsRouter);
19356
- app2.route("/api/triggers", triggersRouter);
19357
- app2.route("/api/messages", messagesRouter);
19358
- app2.route("/api/mcp-servers", mcpRouter);
19359
- app2.route("/api/config/telegram", telegramRouter);
19360
- app2.route("/api/config", configRouter);
19361
- app2.route("/api", miscRouter);
19362
- app2.route("/api", authRouter);
19363
- return app2;
19364
- }
19365
-
19366
- // ../daemon/src/index.ts
19367
- init_install();
19368
- init_resources();
19369
-
19370
- // ../daemon/src/lib/review-provider.ts
19371
- function reviewEndpoint(providerName, env) {
19372
- const raw = providerEndpoint(providerName, env);
19373
- if (!raw) return void 0;
19374
- let url;
19375
- try {
19376
- url = new URL(raw);
19377
- } catch {
19378
- throw new ExecutionUnavailableError("Provider endpoint is invalid.");
19379
- }
19380
- if (url.username || url.password || url.hash) {
19381
- throw new ExecutionUnavailableError("Provider endpoint contains unsafe URL fields.");
19382
- }
19383
- if (!findProvider(providerName)?.local && url.protocol !== "https:") {
19384
- throw new ExecutionUnavailableError("Credential-bearing provider endpoints require HTTPS.");
19385
- }
19386
- return url.toString().replace(/\/$/, "");
19387
- }
19388
- function explicitCredentialEnv(providerName, env) {
19389
- const values = providerCredentialEnv(providerName, env) ?? {};
19390
- if (providerName === "bedrock") {
19391
- delete values.AWS_PROFILE;
19392
- const bearer = values.AWS_BEARER_TOKEN_BEDROCK;
19393
- const staticPair = values.AWS_ACCESS_KEY_ID && values.AWS_SECRET_ACCESS_KEY;
19394
- if (!bearer && !staticPair) {
19395
- throw new ExecutionUnavailableError(
19396
- "Bedrock learning reviews require an explicit bearer token or static key pair; AWS profiles are not read by the reviewer."
19397
- );
19398
- }
19891
+ function explicitCredentialEnv(providerName, env) {
19892
+ const values = providerCredentialEnv(providerName, env) ?? {};
19893
+ if (providerName === "bedrock") {
19894
+ delete values.AWS_PROFILE;
19895
+ const bearer = values.AWS_BEARER_TOKEN_BEDROCK;
19896
+ const staticPair = values.AWS_ACCESS_KEY_ID && values.AWS_SECRET_ACCESS_KEY;
19897
+ if (!bearer && !staticPair) {
19898
+ throw new ExecutionUnavailableError(
19899
+ "Bedrock learning reviews require an explicit bearer token or static key pair; AWS profiles are not read by the reviewer."
19900
+ );
19901
+ }
19399
19902
  }
19400
19903
  if (providerName === "google-vertex") {
19401
19904
  delete values.GOOGLE_APPLICATION_CREDENTIALS;
@@ -19647,6 +20150,23 @@ function isDue(t, now, cronCache) {
19647
20150
  }
19648
20151
  return false;
19649
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
+ }
19650
20170
  function scheduledOccurrence(t, now) {
19651
20171
  if (t.kind === "cron") return floorToMinute(now);
19652
20172
  const baseline = t.lastFiredAt ?? t.createdAt;
@@ -19729,9 +20249,9 @@ function decodeText2(payload) {
19729
20249
  }
19730
20250
  return payload;
19731
20251
  }
19732
- var INBOX_WAKE_PREFIX = "[[bazilion:inbox-wake]]\n";
20252
+ var INBOX_WAKE_PREFIX2 = "[[bazilion:inbox-wake]]\n";
19733
20253
  function buildInboxPrompt(agentId, messages, fromNames) {
19734
- const lines = [INBOX_WAKE_PREFIX.trimEnd()];
20254
+ const lines = [INBOX_WAKE_PREFIX2.trimEnd()];
19735
20255
  lines.push(
19736
20256
  `You have ${messages.length} new message${messages.length === 1 ? "" : "s"} in your inbox:`
19737
20257
  );
@@ -19817,12 +20337,26 @@ async function fireInboxWake(agentId) {
19817
20337
  }
19818
20338
  turnStarted = true;
19819
20339
  s.inboxBackoff.delete(agentId);
19820
- for await (const frame of runAgentTurn(preparedTurn)) {
19821
- if (frame.kind === "fatal") {
19822
- console.warn(
19823
- JSON.stringify({ event: "inbox_wake_failed", agentId, failure: "turn_failed" })
19824
- );
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);
19825
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();
19826
20360
  }
19827
20361
  } catch (err) {
19828
20362
  if (!handoffStarted && registered) unregisterAgent(agentId);
@@ -19830,6 +20364,14 @@ async function fireInboxWake(agentId) {
19830
20364
  if (!turnStarted) {
19831
20365
  retryInMs = backoff ? Math.min(backoff.delayMs * 2, INBOX_RETRY_MAX_MS) : INBOX_RETRY_BASE_MS;
19832
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();
19833
20375
  }
19834
20376
  console.warn(
19835
20377
  JSON.stringify({
@@ -19930,7 +20472,217 @@ function stopScheduler() {
19930
20472
  return s.stopPromise;
19931
20473
  }
19932
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
+
19933
20683
  // ../daemon/src/index.ts
20684
+ init_install();
20685
+ init_resources();
19934
20686
  var host2 = process.env.HOST ?? "127.0.0.1";
19935
20687
  var port = Number.parseInt(process.env.PORT ?? "4321", 10);
19936
20688
  var publicOrigin2 = publicOriginConfig(process.env.BAZILION_PUBLIC_ORIGIN);