bazilion 0.55.0 → 0.57.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 (193) hide show
  1. package/dist/cli.js +193 -37
  2. package/dist/cli.js.map +1 -1
  3. package/dist/daemon.js +1821 -788
  4. package/dist/daemon.js.map +1 -1
  5. package/dist/web/client/assets/AddProviderDialog-DwUu2FGE.js +1 -0
  6. package/dist/web/client/assets/AgentTemplateParts-C3BasVck.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-DFmHgEaL.js +1 -0
  9. package/dist/web/client/assets/ConfirmDialog-BCOfW63x.js +1 -0
  10. package/dist/web/client/assets/ConnectionsView-BbpY5YbI.js +1 -0
  11. package/dist/web/client/assets/ManagePage-BzyMHGqs.js +1 -0
  12. package/dist/web/client/assets/SectionTabs-C8H_LunZ.js +1 -0
  13. package/dist/web/client/assets/{Segmented-oPkAHPO1.js → Segmented-iylzLwE6.js} +1 -1
  14. package/dist/web/client/assets/SkillsParts-DoygBgF2.js +1 -0
  15. package/dist/web/client/assets/SpawnTeamModal-BVf4yN9X.js +1 -0
  16. package/dist/web/client/assets/TeamForm-Bfb5hVUX.js +1 -0
  17. package/dist/web/client/assets/TeamThread-BFmaBj82.js +1 -0
  18. package/dist/web/client/assets/UnsavedChangesGuard-BUsIHSxO.js +1 -0
  19. package/dist/web/client/assets/_id-BRD3kxrX.js +1 -0
  20. package/dist/web/client/assets/_id-BapVoTMJ.js +1 -0
  21. package/dist/web/client/assets/access-CqcKius1.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-BC_ITk28.js +1 -0
  24. package/dist/web/client/assets/agents-DQ8nQnD6.js +1 -0
  25. package/dist/web/client/assets/arrow-right-BqqfPqVi.js +1 -0
  26. package/dist/web/client/assets/attention-BnCihfi0.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-DYS8bkQl.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-DZDOQ3kj.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-CxXsZzDC.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-DFVsVP0s.js +1 -0
  40. package/dist/web/client/assets/{manage-BaIU5zKy.js → manage-CpXaObuS.js} +1 -1
  41. package/dist/web/client/assets/mcp-DslGDHmN.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-C104qEuC.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-D1wFPm0n.js +85 -0
  48. package/dist/web/client/assets/skills-DmIo3vN3.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-CqkCFvvz.js +7 -0
  51. package/dist/web/client/assets/styles-C7NsCHeU.css +2 -0
  52. package/dist/web/client/assets/{system-CrTSr5_t.js → system-CUW9JZ9c.js} +1 -1
  53. package/dist/web/client/assets/teams-DJzYsuh9.js +1 -0
  54. package/dist/web/client/assets/teams-DrhG8KiS.js +1 -0
  55. package/dist/web/client/assets/telegram-Bk_kg8hb.js +1 -0
  56. package/dist/web/client/assets/tools-z9Ixmuu2.js +1 -0
  57. package/dist/web/client/assets/usage-DGe3x1m7.js +1 -0
  58. package/dist/web/client/assets/use-resource-qjIkNQDY.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-DDKqxHkF.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-CpLDHOcA.js} +6 -3
  63. package/dist/web/server/assets/AgentAvatar-8gTAy_tP.js +37 -0
  64. package/dist/web/server/assets/{AgentTemplateParts-Ce7snK3m.js → AgentTemplateParts-Dh9F_-T_.js} +7 -3
  65. package/dist/web/server/assets/Button-Dsnw22OF.js +17 -0
  66. package/dist/web/server/assets/{ConfigPage-qP9ejjuw.js → ConfigPage-CrxctbtN.js} +2 -2
  67. package/dist/web/server/assets/{ConfirmDialog-Z-uYbE9B.js → ConfirmDialog-C89B8qKM.js} +3 -1
  68. package/dist/web/server/assets/{ConnectionsView-CLIV7V5D.js → ConnectionsView-DslcKQmA.js} +9 -7
  69. package/dist/web/server/assets/Dialog-_Gt_Nt86.js +85 -0
  70. package/dist/web/server/assets/{ManagePage-BR9FwVZM.js → ManagePage-DGYNJ6XG.js} +2 -2
  71. package/dist/web/server/assets/{ModelMenu-D-hTgYOO.js → ModelMenu-DEJoYASj.js} +13 -1
  72. package/dist/web/server/assets/{SectionTabs-CWQ5orUW.js → SectionTabs--vMBvaUz.js} +9 -2
  73. package/dist/web/server/assets/{SkillsParts-DWpdydCJ.js → SkillsParts-CqS2B45v.js} +7 -3
  74. package/dist/web/server/assets/SpawnDialog-BNKj2Lup.js +127 -0
  75. package/dist/web/server/assets/{SpawnTeamModal-C-YMvoaB.js → SpawnTeamModal-zcLxtFOO.js} +6 -2
  76. package/dist/web/server/assets/{TeamForm-CL45gBdt.js → TeamForm-XFP0l2TB.js} +11 -5
  77. package/dist/web/server/assets/{TeamThread-CVVH6kKj.js → TeamThread-gYV_ToRM.js} +59 -12
  78. package/dist/web/server/assets/{UnsavedChangesGuard-CXK75QQp.js → UnsavedChangesGuard-CB_TugFF.js} +1 -1
  79. package/dist/web/server/assets/{_id-d2OwovYV.js → _id-517adSuB.js} +2 -2
  80. package/dist/web/server/assets/{_id-BKzOw78O.js → _id-BTyd2i5U.js} +1 -1
  81. package/dist/web/server/assets/{_id-8zsImuGa.js → _id-BsQnL9LV.js} +14 -9
  82. package/dist/web/server/assets/{_id-2I4CSMQj.js → _id-CyinHJam.js} +17 -11
  83. package/dist/web/server/assets/{_id-De3Bm0SG.js → _id-D4RFNqaJ.js} +2 -2
  84. package/dist/web/server/assets/{_id-BpfoPuTv.js → _id-josYXBx3.js} +2 -2
  85. package/dist/web/server/assets/_tanstack-start-manifest_v-w2xn07aY.js +275 -0
  86. package/dist/web/server/assets/{access-WWspT0v4.js → access-B97-94Wt.js} +1 -1
  87. package/dist/web/server/assets/{access-CyUoElTP.js → access-BdQmjMJV.js} +2 -2
  88. package/dist/web/server/assets/{access-CwZ27Wsl.js → access-Cc7fMMod.js} +7 -4
  89. package/dist/web/server/assets/activity-Czfq-5_F.js +471 -0
  90. package/dist/web/server/assets/{agent-actions-C07Cp5Ue.js → agent-actions-ChH7Mne4.js} +1 -1
  91. package/dist/web/server/assets/{agents-DCWEoaxY.js → agents-BL918wVc.js} +2 -2
  92. package/dist/web/server/assets/{agents-vuXrAv1j.js → agents-BlUZqqJn.js} +14 -8
  93. package/dist/web/server/assets/{agents-CRtMfKqX.js → agents-BzJFjA2i.js} +2 -2
  94. package/dist/web/server/assets/{agents-CwzhpDPm.js → agents-CjrkaEz8.js} +11 -8
  95. package/dist/web/server/assets/{agents-DQowl6Ly.js → agents-Tg3zkmQv.js} +2 -2
  96. package/dist/web/server/assets/{agents-DTub-rJk.js → agents-uw32jPWx.js} +2 -2
  97. package/dist/web/server/assets/{attention-Dki8rmGZ.js → attention-2unmuO-q.js} +1 -1
  98. package/dist/web/server/assets/{attention-BqCnJ1hg.js → attention-C94WWwQe.js} +2 -2
  99. package/dist/web/server/assets/{attention-DwGaur_w.js → attention-a_OmC6L3.js} +9 -7
  100. package/dist/web/server/assets/{auth-dJnrFW6y.js → auth-DuIqEAed.js} +1 -1
  101. package/dist/web/server/assets/{config-B9dJiji_.js → config-BG1KOtwA.js} +2 -2
  102. package/dist/web/server/assets/{config-D3MR2VjE.js → config-Bhem9XER.js} +10 -7
  103. package/dist/web/server/assets/{config-X7qWbbpH.js → config-D1Li_7Yt2.js} +1 -1
  104. package/dist/web/server/assets/createSsrRpc-6LHNEsSK.js +16 -0
  105. package/dist/web/server/assets/{daemon-client-B_ZRIIrT.js → daemon-client-D-NWKQto.js} +1 -1
  106. package/dist/web/server/assets/form-Bwsyt9OY.js +416 -0
  107. package/dist/web/server/assets/live-DbJeq6KP.js +263 -0
  108. package/dist/web/server/assets/{login-CRd1yTH5.js → login-BJdJ219n.js} +1 -1
  109. package/dist/web/server/assets/{login-ZN6KV8n-.js → login-C4lL4AxI.js} +2 -2
  110. package/dist/web/server/assets/{manage-Ce6cI4eW.js → manage-C7ReF2ZZ.js} +3 -2
  111. package/dist/web/server/assets/{mcp-CYQuYWGX.js → mcp-BFixpBQk.js} +2 -2
  112. package/dist/web/server/assets/{mcp-BQ15a9dG.js → mcp-BTZkDvdc.js} +7 -4
  113. package/dist/web/server/assets/{mcp-C97uAZe1.js → mcp-Ceg9gzKE.js} +1 -1
  114. package/dist/web/server/assets/open-groups-C89TEK85.js +12 -0
  115. package/dist/web/server/assets/{page-title-CVY-c2Pd.js → page-title-PTpFHXWo.js} +1 -1
  116. package/dist/web/server/assets/parts-B0wbj_yK.js +436 -0
  117. package/dist/web/server/assets/{router-CPdWGKQ5.js → router-Ci_9VxDk.js} +244 -104
  118. package/dist/web/server/assets/{routes-BPloBDc8.js → routes-CVrH9qgo.js} +3 -3
  119. package/dist/web/server/assets/{routes-Dw1K3TQw.js → routes-D9Mw1_VV.js} +1453 -403
  120. package/dist/web/server/assets/{routes-xDPesCQu.js → routes-DsuaDPTO.js} +3 -3
  121. package/dist/web/server/assets/{skills-DWzlT_hC.js → skills-BNbZ75am.js} +1 -1
  122. package/dist/web/server/assets/{skills-6VSpEORe.js → skills-BWwEFc4a.js} +2 -2
  123. package/dist/web/server/assets/{skills-D0xrNc2_.js → skills-D5rnOmKJ.js} +9 -7
  124. package/dist/web/server/assets/src-BeMh8Fze.js +113 -0
  125. package/dist/web/server/assets/{start-DhW7sy23.js → start-2MvkBRdC.js} +1 -1
  126. package/dist/web/server/assets/{style-aMybyKzc.js → style-B3l0Wtlf.js} +1 -1
  127. package/dist/web/server/assets/{system-B5sPgdQW.js → system-Cr4C-YRw.js} +2 -2
  128. package/dist/web/server/assets/{system-CXmiWyDG.js → system-DT7AU0e6.js} +3 -3
  129. package/dist/web/server/assets/{system-D3th6n2E.js → system-DsmXkgqn.js} +1 -1
  130. package/dist/web/server/assets/{teams-ClRBVSYU.js → teams-BeStcDvQ.js} +2 -2
  131. package/dist/web/server/assets/{teams-yF3I_Zjq.js → teams-CsEBLW8-.js} +14 -8
  132. package/dist/web/server/assets/{teams-Dq4RCxis.js → teams-Dix5XVIx.js} +2 -2
  133. package/dist/web/server/assets/{teams-iXiCnN2i.js → teams-DjE0swAZ.js} +10 -6
  134. package/dist/web/server/assets/{teams-70u1XQTr.js → teams-Rk_RED7X.js} +1 -1
  135. package/dist/web/server/assets/{teams-BopOP4x7.js → teams-u6m6JzuU.js} +1 -1
  136. package/dist/web/server/assets/{telegram-DwEgyR1x.js → telegram-BjqABrl-.js} +287 -273
  137. package/dist/web/server/assets/{telegram-CGol0CKX2.js → telegram-CQpF3EHA.js} +1 -1
  138. package/dist/web/server/assets/{telegram-D9U9c1MN.js → telegram-DhzHgDfg.js} +2 -2
  139. package/dist/web/server/assets/{tools-C-wwWjLI.js → tools-DC69leH7.js} +1 -1
  140. package/dist/web/server/assets/{tools-DflVIdDd.js → tools-Dn6RnOFu.js} +2 -2
  141. package/dist/web/server/assets/{tools-VPIKjr3y.js → tools-x_DQTQtE.js} +6 -4
  142. package/dist/web/server/assets/usage-4zMG0sab.js +465 -0
  143. package/dist/web/server/assets/usage-mvQegG4l.js +46 -0
  144. package/dist/web/server/assets/{use-resource-CbHGYti0.js → use-resource-BjN1uJoL.js} +10 -2
  145. package/dist/web/server/assets/{welcome-7DrYZVs6.js → welcome-BuE9FRf4.js} +2 -2
  146. package/dist/web/server/assets/{welcome-CxXMI4HI.js → welcome-DYw35wl5.js} +1 -1
  147. package/dist/web/server/assets/{welcome-966nOyyK.js → welcome-DrYbWGd_.js} +8 -6
  148. package/dist/web/server/assets/workspace-0XPILV1W.js +82 -0
  149. package/dist/web/server/server.js +20 -20
  150. package/dist/worker.js +143 -18
  151. package/dist/worker.js.map +1 -1
  152. package/package.json +1 -1
  153. package/dist/web/client/assets/AddProviderDialog-DfFOaCjC.js +0 -1
  154. package/dist/web/client/assets/AgentTemplateParts-IMJmAQjN.js +0 -1
  155. package/dist/web/client/assets/ConfigPage-CzLHZa5o.js +0 -1
  156. package/dist/web/client/assets/ConfirmDialog-Cu_evkgc.js +0 -1
  157. package/dist/web/client/assets/ConnectionsView-D7Fmutl2.js +0 -1
  158. package/dist/web/client/assets/ManagePage-BfvlCrmz.js +0 -1
  159. package/dist/web/client/assets/SectionTabs-D7kPQGoh.js +0 -1
  160. package/dist/web/client/assets/SkillsParts-BuTxcCam.js +0 -1
  161. package/dist/web/client/assets/SpawnTeamModal-B1UnOvtp.js +0 -1
  162. package/dist/web/client/assets/TeamForm-DbzxtRjj.js +0 -1
  163. package/dist/web/client/assets/TeamThread-jpsWq6vI.js +0 -1
  164. package/dist/web/client/assets/UnsavedChangesGuard-BfyU9v9i.js +0 -1
  165. package/dist/web/client/assets/_id-BCNBLF-2.js +0 -1
  166. package/dist/web/client/assets/_id-D8_H79U2.js +0 -1
  167. package/dist/web/client/assets/access-CDWe1Kwy.js +0 -1
  168. package/dist/web/client/assets/agents-sE686DTf.js +0 -1
  169. package/dist/web/client/assets/agents-yrur1NDa.js +0 -1
  170. package/dist/web/client/assets/arrow-right-U66krZnr.js +0 -1
  171. package/dist/web/client/assets/attention-DYEHDfmx.js +0 -1
  172. package/dist/web/client/assets/chevron-right-CuqJFXTe.js +0 -1
  173. package/dist/web/client/assets/config-BHv886pr.js +0 -1
  174. package/dist/web/client/assets/index-GOthyyE-.js +0 -14
  175. package/dist/web/client/assets/login-Dhe15Uuc.js +0 -1
  176. package/dist/web/client/assets/mcp-A_Eo7x3q.js +0 -1
  177. package/dist/web/client/assets/parts-CpIfn_BH.js +0 -41
  178. package/dist/web/client/assets/plus-CQPjc8uR.js +0 -1
  179. package/dist/web/client/assets/routes-CTg_yjbY.js +0 -85
  180. package/dist/web/client/assets/skills-CLjtYtkA.js +0 -1
  181. package/dist/web/client/assets/style-mjEbxhf5.js +0 -7
  182. package/dist/web/client/assets/styles-DzcEC3Rd.css +0 -2
  183. package/dist/web/client/assets/teams-Bhje5n2h.js +0 -1
  184. package/dist/web/client/assets/teams-Cbgw0Qhv.js +0 -1
  185. package/dist/web/client/assets/telegram-HtUczmaA.js +0 -1
  186. package/dist/web/client/assets/tools-BpjFvmoX.js +0 -1
  187. package/dist/web/client/assets/use-resource-BnvgCpBi.js +0 -1
  188. package/dist/web/client/assets/welcome-D47LKWYO.js +0 -1
  189. package/dist/web/server/assets/Rail-b6EbjBB-.js +0 -605
  190. package/dist/web/server/assets/SpawnDialog-3wNx0W1R.js +0 -1851
  191. package/dist/web/server/assets/_tanstack-start-manifest_v-kkY_s_uR.js +0 -256
  192. package/dist/web/server/assets/createSsrRpc-qesavJv-.js +0 -72
  193. 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();
@@ -1843,6 +1843,15 @@ import { writeSync } from "node:fs";
1843
1843
 
1844
1844
  // ../../packages/api-types/src/entities.ts
1845
1845
  var DEFAULT_TEAM_ID = "default";
1846
+ var AGENT_NAME_MAX = 120;
1847
+ function agentNameProblem(name) {
1848
+ if (!name.trim()) return "A name cannot be empty.";
1849
+ if (name.length > AGENT_NAME_MAX) return `A name is at most ${AGENT_NAME_MAX} characters.`;
1850
+ if (/[\p{Cc}\p{Cf}\u2028\u2029]/u.test(name)) {
1851
+ return "A name is one line of text, without control characters.";
1852
+ }
1853
+ return null;
1854
+ }
1846
1855
  var DEFAULT_PROFILE_ID = "default";
1847
1856
  var OUTSIDE_TEAM = "outside";
1848
1857
  var REASONING_LEVELS = [
@@ -1902,6 +1911,35 @@ function isLoopbackHost(hostname) {
1902
1911
  return ["127.0.0.1", "localhost", "[::1]", "::1"].includes(hostname);
1903
1912
  }
1904
1913
 
1914
+ // ../../packages/api-types/src/results.ts
1915
+ var TEXT_PREVIEW_MAX_BYTES = 256 * 1024;
1916
+ var TEXT_TYPES = /* @__PURE__ */ new Set([
1917
+ "application/json",
1918
+ "application/ld+json",
1919
+ "application/xml",
1920
+ "application/yaml",
1921
+ "application/x-yaml",
1922
+ "application/toml",
1923
+ "application/javascript",
1924
+ "application/x-sh",
1925
+ "application/sql",
1926
+ "application/x-ndjson"
1927
+ ]);
1928
+ var TEXT_EXTENSIONS = new Set(
1929
+ "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(" ")
1930
+ );
1931
+ var ACTIVE_TYPES = /* @__PURE__ */ new Set(["text/html", "application/xhtml+xml", "image/svg+xml"]);
1932
+ function isTextPreview(result) {
1933
+ if (result.byteLength > TEXT_PREVIEW_MAX_BYTES) return false;
1934
+ const type = result.mimeType.toLowerCase();
1935
+ if (ACTIVE_TYPES.has(type)) return false;
1936
+ if (type.startsWith("text/") || TEXT_TYPES.has(type) || /\+(json|xml)$/.test(type)) return true;
1937
+ if (type !== "application/octet-stream") return false;
1938
+ const name = result.name.toLowerCase();
1939
+ const extension = name.includes(".") ? name.slice(name.lastIndexOf(".") + 1) : name;
1940
+ return TEXT_EXTENSIONS.has(extension);
1941
+ }
1942
+
1905
1943
  // ../daemon/src/index.ts
1906
1944
  import { serve } from "@hono/node-server";
1907
1945
 
@@ -2633,6 +2671,9 @@ function discoverSkills(paths) {
2633
2671
 
2634
2672
  // ../daemon/src/core/agent/spawn.ts
2635
2673
  function spawnAgent(db, paths, input) {
2674
+ const givenName = input.name?.trim() || void 0;
2675
+ const nameProblem = givenName === void 0 ? null : agentNameProblem(givenName);
2676
+ if (nameProblem) throw new DomainError(400, nameProblem);
2636
2677
  const loaded = loadProfile(db, input.profileId);
2637
2678
  const id = randomUUID3();
2638
2679
  const dir = paths.agentDir(id);
@@ -2663,7 +2704,7 @@ function spawnAgent(db, paths, input) {
2663
2704
  const agent = insert(db, {
2664
2705
  id,
2665
2706
  profileId: input.profileId,
2666
- name: input.name ?? loaded.profile.name,
2707
+ name: givenName ?? loaded.profile.name,
2667
2708
  modelOverride: input.modelOverride ?? null,
2668
2709
  reasoningLevel,
2669
2710
  status: "idle",
@@ -2689,6 +2730,25 @@ function unarchiveAgent(db, id) {
2689
2730
  unarchive(db, agent.id);
2690
2731
  }
2691
2732
 
2733
+ // ../daemon/src/core/attention.ts
2734
+ import { createHash } from "node:crypto";
2735
+
2736
+ // ../daemon/src/core/provider-failure-kind.ts
2737
+ 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/;
2738
+ 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/;
2739
+ 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/;
2740
+ var LIMIT = /insufficient|quota|rate.?limit|billing|\bcredits?\b|overloaded/;
2741
+ function classifyProviderFailure(message, timedOut = false) {
2742
+ const text4 = message.toLowerCase();
2743
+ const status2 = /^(\d{3})\b/.exec(text4)?.[1];
2744
+ if (timedOut || UNREACHABLE.test(text4)) return "unreachable";
2745
+ if (status2 === "401" || CREDENTIALS.test(text4)) return "credentials";
2746
+ if (MODEL.test(text4)) return "model";
2747
+ if (status2 === "402" || status2 === "429" || LIMIT.test(text4)) return "limit";
2748
+ if (status2 === "403") return "credentials";
2749
+ return "other";
2750
+ }
2751
+
2692
2752
  // ../daemon/src/core/repos/user-queue.ts
2693
2753
  import { randomUUID as randomUUID4 } from "node:crypto";
2694
2754
  var QUEUE_LIMITS = Object.freeze({
@@ -2944,13 +3004,44 @@ function agentsWithPending(db) {
2944
3004
  ).all().map((row) => row.agentId);
2945
3005
  }
2946
3006
 
3007
+ // ../daemon/src/core/turn-failures.ts
3008
+ var KEY = /* @__PURE__ */ Symbol.for("bazilion.turn-failures");
3009
+ var MAX_KEPT = 200;
3010
+ var KEPT_MS = 14 * 864e5;
3011
+ function store() {
3012
+ const holder = globalThis;
3013
+ holder[KEY] ??= [];
3014
+ return holder[KEY];
3015
+ }
3016
+ function rememberTurnFailure(failure) {
3017
+ const kept = store();
3018
+ const at = kept.findIndex((entry) => entry.id === failure.id);
3019
+ const first = at >= 0 ? kept[at] : void 0;
3020
+ if (at >= 0) kept.splice(at, 1);
3021
+ kept.push(first ? { ...failure, at: first.at } : failure);
3022
+ const since = failure.at - KEPT_MS;
3023
+ const fresh = kept.filter((entry) => entry.at >= since || entry.id === failure.id).slice(-MAX_KEPT);
3024
+ kept.splice(0, kept.length, ...fresh);
3025
+ }
3026
+ function forgetTurnFailure(id) {
3027
+ const kept = store();
3028
+ const at = kept.findIndex((entry) => entry.id === id);
3029
+ if (at < 0) return false;
3030
+ kept.splice(at, 1);
3031
+ return true;
3032
+ }
3033
+ function rememberedTurnFailures() {
3034
+ return store();
3035
+ }
3036
+
2947
3037
  // ../daemon/src/core/attention.ts
2948
3038
  var RECORDED_ATTENTION_KINDS = [
2949
3039
  "lesson_proposal",
2950
3040
  "review_failure",
2951
3041
  "trigger_failure",
2952
3042
  "agent_loop_break",
2953
- "queue_interrupted"
3043
+ "queue_interrupted",
3044
+ "turn_failure"
2954
3045
  ];
2955
3046
  var WAITING_ATTENTION_KINDS = [
2956
3047
  "agent_question",
@@ -2967,6 +3058,98 @@ function agentHref(agentId, section) {
2967
3058
  if (section) query.set("section", section);
2968
3059
  return `/?${query}`;
2969
3060
  }
3061
+ var CAUSE_LEAD = {
3062
+ credentials: "The provider refused the credentials",
3063
+ limit: "A usage or rate limit was reached",
3064
+ unreachable: "The model could not be reached",
3065
+ model: "The model is not available",
3066
+ other: "The turn failed"
3067
+ };
3068
+ var ORIGIN_TITLE = {
3069
+ http: "Follow-up failed",
3070
+ telegram: "Telegram message failed",
3071
+ inbox: "Turn for new mail failed"
3072
+ };
3073
+ var ORIGIN_COUNT = {
3074
+ http: ["follow-up", "follow-ups"],
3075
+ telegram: ["Telegram message", "Telegram messages"],
3076
+ inbox: ["turn for new mail", "turns for new mail"]
3077
+ };
3078
+ function turnFailureCause(reason) {
3079
+ const kind = classifyProviderFailure(reason);
3080
+ if (kind !== "other") return kind;
3081
+ const shape = reason.toLowerCase().replace(/\b(?=[\w-]*\d)[\w-]{8,}\b|[0-9a-f]{8,}|\d+/g, "#").replace(/\s+/g, " ").slice(0, 120);
3082
+ return `other-${createHash("sha256").update(shape).digest("hex").slice(0, 12)}`;
3083
+ }
3084
+ function turnFailures(db) {
3085
+ const queued = db.raw.query(
3086
+ `SELECT q.id, q.agent_id agentId, a.name agentName, a.team_id teamId, t.name teamName,
3087
+ q.source origin, COALESCE(q.finished_at, q.updated_at) at, q.diagnostic reason
3088
+ FROM user_queue_items q JOIN agents a ON a.id = q.agent_id JOIN teams t ON t.id = a.team_id
3089
+ WHERE q.status = 'failed' AND (q.diagnostic IS NULL OR q.diagnostic != ?)`
3090
+ ).all(INTERRUPTED_BY_RESTART);
3091
+ const agents = new Map(
3092
+ db.raw.query(
3093
+ "SELECT a.id, a.name, a.team_id teamId, t.name teamName FROM agents a JOIN teams t ON t.id = a.team_id"
3094
+ ).all().map((agent) => [agent.id, agent])
3095
+ );
3096
+ const remembered = rememberedTurnFailures().flatMap((failure) => {
3097
+ const agent = agents.get(failure.agentId);
3098
+ return agent ? [
3099
+ {
3100
+ id: failure.id,
3101
+ agentId: agent.id,
3102
+ agentName: agent.name,
3103
+ teamId: agent.teamId,
3104
+ teamName: agent.teamName,
3105
+ origin: failure.origin,
3106
+ at: failure.at,
3107
+ reason: failure.reason
3108
+ }
3109
+ ] : [];
3110
+ });
3111
+ const acknowledged = new Map(
3112
+ db.raw.query(
3113
+ "SELECT source_id, acknowledged_at FROM attention_acknowledgements WHERE source_kind = 'turn_failure'"
3114
+ ).all().map((row) => [row.source_id, row.acknowledged_at])
3115
+ );
3116
+ const groups = /* @__PURE__ */ new Map();
3117
+ for (const failure of [...queued, ...remembered]) {
3118
+ const id = `${failure.agentId}:${turnFailureCause(failure.reason ?? "")}`;
3119
+ groups.set(id, [...groups.get(id) ?? [], failure]);
3120
+ }
3121
+ return [...groups].map(([sourceId, all]) => {
3122
+ const ack = acknowledged.get(sourceId) ?? null;
3123
+ const since = all.filter((failure) => ack === null || failure.at > ack);
3124
+ const counted = (since.length > 0 ? since : all).toSorted((a, b) => a.at - b.at);
3125
+ const first = counted[0];
3126
+ const latest = counted.at(-1);
3127
+ const reason = bounded(latest.reason, "The turn ended without a reply.");
3128
+ const origins = /* @__PURE__ */ new Map();
3129
+ for (const failure of counted)
3130
+ origins.set(failure.origin, (origins.get(failure.origin) ?? 0) + 1);
3131
+ const breakdown = [...origins].map(([origin, n]) => `${n} ${ORIGIN_COUNT[origin][n === 1 ? 0 : 1]}`).join(", ");
3132
+ return {
3133
+ kind: "turn_failure",
3134
+ severity: "error",
3135
+ sourceId,
3136
+ occurredAt: first.at,
3137
+ updatedAt: latest.at,
3138
+ agentId: latest.agentId,
3139
+ agentName: latest.agentName,
3140
+ teamId: latest.teamId,
3141
+ teamName: latest.teamName,
3142
+ title: counted.length === 1 ? ORIGIN_TITLE[latest.origin] : `${counted.length} background turns failed`,
3143
+ diagnostic: `${CAUSE_LEAD[classifyProviderFailure(reason)]}: ${reason}${counted.length > 1 ? ` (${breakdown})` : ""}`,
3144
+ href: agentHref(
3145
+ latest.agentId,
3146
+ origins.size === 1 && origins.has("inbox") ? "mailbox" : void 0
3147
+ ),
3148
+ acknowledgeable: true,
3149
+ acknowledged_at: since.length > 0 ? null : ack
3150
+ };
3151
+ });
3152
+ }
2970
3153
  var sources = [
2971
3154
  {
2972
3155
  kind: "lesson_proposal",
@@ -3072,7 +3255,8 @@ var sources = [
3072
3255
  })
3073
3256
  )
3074
3257
  )
3075
- }
3258
+ },
3259
+ { kind: "turn_failure", query: turnFailures }
3076
3260
  ];
3077
3261
  function normalize(row) {
3078
3262
  const { acknowledged_at, ...item } = row;
@@ -3139,7 +3323,7 @@ function acknowledgeAttention(db, key2, acknowledged) {
3139
3323
  throw new DomainError(409, "action-required items must be resolved at their source");
3140
3324
  if (acknowledged)
3141
3325
  db.raw.run(
3142
- `INSERT INTO attention_acknowledgements (source_kind, source_id, acknowledged_at) VALUES (?, ?, ?) ON CONFLICT(source_kind, source_id) DO NOTHING`,
3326
+ `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
3327
  [parsed.kind, parsed.sourceId, Date.now()]
3144
3328
  );
3145
3329
  else
@@ -3163,7 +3347,7 @@ function acknowledgeAllAttention(db) {
3163
3347
  const now = Date.now();
3164
3348
  for (const item of items)
3165
3349
  db.raw.run(
3166
- `INSERT INTO attention_acknowledgements (source_kind, source_id, acknowledged_at) VALUES (?, ?, ?) ON CONFLICT(source_kind, source_id) DO NOTHING`,
3350
+ `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
3351
  [item.kind, item.sourceId, now]
3168
3352
  );
3169
3353
  return items.length;
@@ -3264,14 +3448,14 @@ function replaceCuratedModels(db, provider, models) {
3264
3448
  import { dirname } from "node:path";
3265
3449
  import { backup, DatabaseSync } from "node:sqlite";
3266
3450
  function wrap(rawDb) {
3267
- const cache = /* @__PURE__ */ new Map();
3451
+ const cache2 = /* @__PURE__ */ new Map();
3268
3452
  let transactionDepth = 0;
3269
3453
  let savepointSequence = 0;
3270
3454
  function getStmt(sql) {
3271
- let s = cache.get(sql);
3455
+ let s = cache2.get(sql);
3272
3456
  if (!s) {
3273
3457
  s = rawDb.prepare(sql);
3274
- cache.set(sql, s);
3458
+ cache2.set(sql, s);
3275
3459
  }
3276
3460
  return s;
3277
3461
  }
@@ -3660,10 +3844,16 @@ function validateSlug(s) {
3660
3844
  );
3661
3845
  }
3662
3846
  }
3847
+ function templateName(value) {
3848
+ const name = value.trim();
3849
+ if (!name) throw new DomainError(400, "A template needs a name");
3850
+ return name;
3851
+ }
3663
3852
 
3664
3853
  // ../daemon/src/core/profile/create.ts
3665
3854
  function createProfile(db, paths, input) {
3666
3855
  validateSlug(input.id);
3856
+ const name = input.name === void 0 ? input.id : templateName(input.name);
3667
3857
  if (get5(db, input.id))
3668
3858
  throw new DomainError(400, `profile already exists: ${input.id}`);
3669
3859
  const dir = paths.profileDir(input.id);
@@ -3687,7 +3877,7 @@ function createProfile(db, paths, input) {
3687
3877
  const skillsMode = input.skillsMode ?? "selected";
3688
3878
  const profile = insert4(db, {
3689
3879
  id: input.id,
3690
- name: input.name ?? input.id,
3880
+ name,
3691
3881
  defaultModel: input.defaultModel,
3692
3882
  skillsMode
3693
3883
  });
@@ -3995,7 +4185,7 @@ function updateProfile(db, id, input) {
3995
4185
  if (!existing) throw new DomainError(404, `profile not found: ${id}`);
3996
4186
  const nextSkillsMode = input.skillsMode ?? existing.skillsMode;
3997
4187
  const next = {
3998
- name: input.name ?? existing.name,
4188
+ name: input.name === void 0 ? existing.name : templateName(input.name),
3999
4189
  defaultModel: input.defaultModel ?? existing.defaultModel,
4000
4190
  skillsMode: nextSkillsMode
4001
4191
  };
@@ -4172,6 +4362,7 @@ function apiKey(id, displayName, envVar, options = {}) {
4172
4362
  id,
4173
4363
  displayName,
4174
4364
  ...options.hint ? { hint: options.hint } : {},
4365
+ ...options.plan ? { plan: true } : {},
4175
4366
  keyEnv: [envVar],
4176
4367
  ...options.modelsUrl ? { modelsUrl: options.modelsUrl } : {},
4177
4368
  fields: [
@@ -4205,6 +4396,7 @@ var PROVIDERS = [
4205
4396
  hint: "Use your ChatGPT Plus, Pro or Team plan. No API key.",
4206
4397
  // Credentials come from the OAuth flow (/api/auth/openai), not from fields.
4207
4398
  fields: [],
4399
+ plan: true,
4208
4400
  popular: true,
4209
4401
  suggested: ["gpt-6.2-sol", "gpt-6-luna"]
4210
4402
  },
@@ -4221,6 +4413,7 @@ var PROVIDERS = [
4221
4413
  displayName: "Anthropic",
4222
4414
  hint: "Claude models \xB7 console.anthropic.com",
4223
4415
  keyEnv: ["ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_API_KEY"],
4416
+ planEnv: "ANTHROPIC_OAUTH_TOKEN",
4224
4417
  fields: [
4225
4418
  { envVar: "ANTHROPIC_API_KEY", kind: "secret", label: "API key", placeholder: "sk-ant-..." },
4226
4419
  {
@@ -4299,6 +4492,7 @@ var PROVIDERS = [
4299
4492
  displayName: "GitHub Copilot",
4300
4493
  hint: "Use a GitHub Copilot subscription to call Claude/GPT/Gemini via Copilot",
4301
4494
  keyEnv: ["COPILOT_GITHUB_TOKEN"],
4495
+ plan: true,
4302
4496
  fields: [
4303
4497
  {
4304
4498
  envVar: "COPILOT_GITHUB_TOKEN",
@@ -4353,36 +4547,41 @@ var PROVIDERS = [
4353
4547
  }),
4354
4548
  // Each plan has its own key; Pi also reads the older shared QWEN_TOKEN_PLAN_API_KEY.
4355
4549
  apiKey("qwen-token-plan", "Qwen Token Plan Team", "QWEN_TOKEN_PLAN_TEAM_API_KEY", {
4356
- hint: "Team coding-model subscription \xB7 international endpoint"
4550
+ hint: "Team coding-model subscription \xB7 international endpoint",
4551
+ plan: true
4357
4552
  }),
4358
4553
  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"
4554
+ hint: "Team coding-model subscription \xB7 China endpoint",
4555
+ plan: true
4360
4556
  }),
4361
4557
  apiKey(
4362
4558
  "qwen-token-plan-individual",
4363
4559
  "Qwen Token Plan Individual",
4364
4560
  "QWEN_TOKEN_PLAN_INDIVIDUAL_API_KEY",
4365
- { hint: "Individual subscription \xB7 international endpoint" }
4561
+ { hint: "Individual subscription \xB7 international endpoint", plan: true }
4366
4562
  ),
4367
4563
  apiKey(
4368
4564
  "qwen-token-plan-individual-cn",
4369
4565
  "Qwen Token Plan Individual (CN)",
4370
4566
  "QWEN_TOKEN_PLAN_INDIVIDUAL_CN_API_KEY",
4371
- { hint: "Individual subscription \xB7 China endpoint" }
4567
+ { hint: "Individual subscription \xB7 China endpoint", plan: true }
4372
4568
  ),
4373
4569
  apiKey("xiaomi", "Xiaomi MiMo", "XIAOMI_API_KEY", {
4374
4570
  hint: "API billing endpoint \xB7 platform.xiaomimimo.com"
4375
4571
  }),
4376
4572
  apiKey("xiaomi-token-plan-ams", "Xiaomi MiMo Token Plan (AMS)", "XIAOMI_TOKEN_PLAN_AMS_API_KEY", {
4377
4573
  hint: "MiMo token-plan endpoint in Amsterdam",
4574
+ plan: true,
4378
4575
  modelsUrl: "https://token-plan-ams.xiaomimimo.com/v1"
4379
4576
  }),
4380
4577
  apiKey("xiaomi-token-plan-cn", "Xiaomi MiMo Token Plan (CN)", "XIAOMI_TOKEN_PLAN_CN_API_KEY", {
4381
4578
  hint: "MiMo token-plan endpoint in China",
4579
+ plan: true,
4382
4580
  modelsUrl: "https://token-plan-cn.xiaomimimo.com/v1"
4383
4581
  }),
4384
4582
  apiKey("xiaomi-token-plan-sgp", "Xiaomi MiMo Token Plan (SGP)", "XIAOMI_TOKEN_PLAN_SGP_API_KEY", {
4385
4583
  hint: "MiMo token-plan endpoint in Singapore",
4584
+ plan: true,
4386
4585
  modelsUrl: "https://token-plan-sgp.xiaomimimo.com/v1"
4387
4586
  }),
4388
4587
  apiKey("ant-ling", "Ant Ling", "ANT_LING_API_KEY", {
@@ -5144,7 +5343,7 @@ function get10(db, id) {
5144
5343
  return row ? toMessage(row) : null;
5145
5344
  }
5146
5345
  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";
5346
+ 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
5347
  return db.raw.query(sql).all(agentId).map(toMessage);
5149
5348
  }
5150
5349
  function listForTeam(db, teamId, limit) {
@@ -5152,7 +5351,7 @@ function listForTeam(db, teamId, limit) {
5152
5351
  `SELECT m.* FROM messages m
5153
5352
  WHERE m.from_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5154
5353
  OR m.to_agent_id IN (SELECT id FROM agents WHERE team_id = ?)
5155
- ORDER BY m.created_at DESC, m.id DESC LIMIT ?`
5354
+ ORDER BY m.created_at DESC, m.rowid DESC LIMIT ?`
5156
5355
  ).all(teamId, teamId, limit).map(toMessage);
5157
5356
  }
5158
5357
  function markRead(db, id) {
@@ -5179,7 +5378,7 @@ function drainUnreadForAgent(db, agentId) {
5179
5378
  const rows = db.raw.query(
5180
5379
  `SELECT * FROM messages
5181
5380
  WHERE to_agent_id = ? AND read_at IS NULL
5182
- ORDER BY created_at ASC`
5381
+ ORDER BY created_at ASC, rowid ASC`
5183
5382
  ).all(agentId);
5184
5383
  if (rows.length === 0) return [];
5185
5384
  const now = Date.now();
@@ -5386,10 +5585,10 @@ __export(telegram_pairing_exports, {
5386
5585
  reset: () => reset,
5387
5586
  status: () => status
5388
5587
  });
5389
- import { createHash, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
5588
+ import { createHash as createHash2, randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
5390
5589
  var TTL_MS = 10 * 6e4;
5391
5590
  function digest(code) {
5392
- return createHash("sha256").update(code, "utf8").digest();
5591
+ return createHash2("sha256").update(code, "utf8").digest();
5393
5592
  }
5394
5593
  function create2(db) {
5395
5594
  if (status(db).paired) throw new DomainError(409, "Telegram already has a paired owner");
@@ -5640,7 +5839,7 @@ __export(webTokens_exports, {
5640
5839
  rejectionReason: () => rejectionReason,
5641
5840
  revoke: () => revoke2
5642
5841
  });
5643
- import { createHash as createHash2, randomBytes as randomBytes3, randomUUID as randomUUID10 } from "node:crypto";
5842
+ import { createHash as createHash3, randomBytes as randomBytes3, randomUUID as randomUUID10 } from "node:crypto";
5644
5843
  function toToken(r) {
5645
5844
  return {
5646
5845
  id: r.id,
@@ -5653,7 +5852,7 @@ function toToken(r) {
5653
5852
  };
5654
5853
  }
5655
5854
  function hashToken(token) {
5656
- return createHash2("sha256").update(token).digest("hex");
5855
+ return createHash3("sha256").update(token).digest("hex");
5657
5856
  }
5658
5857
  function create3(db, label, opts = {}) {
5659
5858
  const id = randomUUID10();
@@ -6360,6 +6559,7 @@ async function authMiddleware(c, next) {
6360
6559
  }
6361
6560
 
6362
6561
  // ../daemon/src/lib/activity.ts
6562
+ import { createHash as createHash5 } from "node:crypto";
6363
6563
  import { statSync as statSync3 } from "node:fs";
6364
6564
  import { join as join10 } from "node:path";
6365
6565
 
@@ -6443,7 +6643,7 @@ function rename(db, agentId, id, title) {
6443
6643
  }
6444
6644
 
6445
6645
  // ../daemon/src/core/repos/results.ts
6446
- import { createHash as createHash3, randomUUID as randomUUID13 } from "node:crypto";
6646
+ import { createHash as createHash4, randomUUID as randomUUID13 } from "node:crypto";
6447
6647
 
6448
6648
  // ../daemon/src/core/tool-call-id.ts
6449
6649
  function isToolCallId(value) {
@@ -6499,7 +6699,7 @@ function publish(db, input) {
6499
6699
  input.name,
6500
6700
  input.mimeType,
6501
6701
  bytes.byteLength,
6502
- createHash3("sha256").update(bytes).digest("hex"),
6702
+ createHash4("sha256").update(bytes).digest("hex"),
6503
6703
  input.imageModel ?? null,
6504
6704
  Date.now(),
6505
6705
  bytes
@@ -6538,7 +6738,7 @@ function read(db, id) {
6538
6738
  ).get(id);
6539
6739
  if (!row) throw new Error("Result not found");
6540
6740
  const bytes = Buffer.from(row.bytes);
6541
- if (createHash3("sha256").update(bytes).digest("hex") !== row.sha256)
6741
+ if (createHash4("sha256").update(bytes).digest("hex") !== row.sha256)
6542
6742
  throw new Error("Saved file failed its integrity check");
6543
6743
  return bytes;
6544
6744
  }
@@ -6898,6 +7098,22 @@ function lastActivityAt(db, paths, agentId) {
6898
7098
  return null;
6899
7099
  }
6900
7100
  }
7101
+ var ROSTER_QUERIES = [
7102
+ "SELECT id, name, policy_mode, telegram_icon_color, telegram_topic_name_format FROM teams ORDER BY id",
7103
+ `SELECT id, profile_id, name, model_override, status, reasoning_level, review_enabled,
7104
+ review_every_n_turns, review_model, review_reasoning_level, team_id, telegram_icon_emoji,
7105
+ telegram_mirror_mode FROM agents ORDER BY id`,
7106
+ "SELECT id, name, updated_at FROM profiles ORDER BY id",
7107
+ "SELECT id, name, updated_at FROM team_templates ORDER BY id"
7108
+ ];
7109
+ function rosterRevision(db) {
7110
+ const hash2 = createHash5("sha256");
7111
+ for (const sql of ROSTER_QUERIES) {
7112
+ hash2.update(JSON.stringify(db.raw.query(sql).all()));
7113
+ hash2.update("\n");
7114
+ }
7115
+ return hash2.digest("hex").slice(0, 16);
7116
+ }
6901
7117
  function readActivity(db, paths) {
6902
7118
  const saved = summaryByAgent(db);
6903
7119
  const questions = questionRegistry.list();
@@ -6940,7 +7156,9 @@ function onRouteError(error, c) {
6940
7156
  return c.json({ error: error.message || "Internal error" }, 500);
6941
7157
  }
6942
7158
  function routeAgent(c, param = "id") {
6943
- const ref = c.req.param(param) ?? "";
7159
+ return routeAgentRef(c.req.param(param) ?? "");
7160
+ }
7161
+ function routeAgentRef(ref) {
6944
7162
  const { db } = getCtx();
6945
7163
  const agent = get(db, ref);
6946
7164
  if (agent) return agent;
@@ -6967,7 +7185,10 @@ async function jsonBody(c) {
6967
7185
  var activityRouter = newRouter();
6968
7186
  activityRouter.get("/", (c) => {
6969
7187
  const { db, paths } = getCtx();
6970
- return c.json({ agents: readActivity(db, paths) });
7188
+ return c.json({
7189
+ agents: readActivity(db, paths),
7190
+ roster: rosterRevision(db)
7191
+ });
6971
7192
  });
6972
7193
 
6973
7194
  // ../daemon/src/lib/browser/config.ts
@@ -7019,8 +7240,8 @@ agentBrowserRouter.delete("/:id/browser/profile", async (c) => {
7019
7240
 
7020
7241
  // ../daemon/src/routes/agent-chat.ts
7021
7242
  import { randomUUID as randomUUID19 } from "node:crypto";
7022
- import { existsSync as existsSync16, readFileSync as readFileSync10 } from "node:fs";
7023
- import { join as join27 } from "node:path";
7243
+ import { existsSync as existsSync17, readFileSync as readFileSync11 } from "node:fs";
7244
+ import { join as join28 } from "node:path";
7024
7245
 
7025
7246
  // ../daemon/src/runtime/auth/openai-codex.ts
7026
7247
  import { openaiCodexProvider } from "@earendil-works/pi-ai/providers/openai-codex";
@@ -7262,11 +7483,11 @@ function assertRootUnchanged(root, canonicalRoot) {
7262
7483
  function safeKey(root, key2) {
7263
7484
  const segments = key2.split(/[\\/]/);
7264
7485
  if (key2.length === 0 || key2.includes("\0") || isAbsolute2(key2) || /^[A-Za-z]:[\\/]/.test(key2) || key2.startsWith("\\\\") || segments.includes("..")) {
7265
- throw new Error(`unsafe memory key: ${key2}`);
7486
+ throw new DomainError(400, `unsafe memory key: ${key2}`);
7266
7487
  }
7267
- if (!key2.endsWith(".md")) throw new Error(`memory keys end in .md: ${key2}`);
7488
+ if (!key2.endsWith(".md")) throw new DomainError(400, `memory keys end in .md: ${key2}`);
7268
7489
  const candidate = resolve4(root, key2);
7269
- if (candidate === root) throw new Error(`unsafe memory key: ${key2}`);
7490
+ if (candidate === root) throw new DomainError(400, `unsafe memory key: ${key2}`);
7270
7491
  assertContained(root, candidate);
7271
7492
  return candidate;
7272
7493
  }
@@ -7404,8 +7625,8 @@ function qmdBackend(root, options = {}) {
7404
7625
  async init() {
7405
7626
  const safe = safeRoot();
7406
7627
  assertSafeTree(safe);
7407
- const store = await getStore(safe, storeFactory);
7408
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7628
+ const store2 = await getStore(safe, storeFactory);
7629
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7409
7630
  },
7410
7631
  async read(key2) {
7411
7632
  const safe = safeRoot();
@@ -7423,17 +7644,17 @@ function qmdBackend(root, options = {}) {
7423
7644
  const path = safeKey(safe, key2);
7424
7645
  const stats = writeSafeFile(safe, path, content);
7425
7646
  assertSafeTree(safe);
7426
- const store = await getStore(safe, storeFactory);
7427
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7647
+ const store2 = await getStore(safe, storeFactory);
7648
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7428
7649
  return { key: key2, content, updatedAt: stats.mtimeMs };
7429
7650
  },
7430
7651
  async search(query, opts) {
7431
7652
  const limit = opts?.limit ?? 10;
7432
7653
  const safe = safeRoot();
7433
7654
  assertSafeTree(safe);
7434
- const store = await getStore(safe, storeFactory);
7655
+ const store2 = await getStore(safe, storeFactory);
7435
7656
  const results = await withNativeModuleErrorBoundary(
7436
- () => store.searchLex(query, {
7657
+ () => store2.searchLex(query, {
7437
7658
  limit,
7438
7659
  collection: COLLECTION_NAME
7439
7660
  }),
@@ -7473,8 +7694,8 @@ function qmdBackend(root, options = {}) {
7473
7694
  rmSync9(path);
7474
7695
  }
7475
7696
  assertSafeTree(safe);
7476
- const store = await getStore(safe, storeFactory);
7477
- await withNativeModuleErrorBoundary(() => store.update(), QMD_NATIVE_ERROR_OPTIONS);
7697
+ const store2 = await getStore(safe, storeFactory);
7698
+ await withNativeModuleErrorBoundary(() => store2.update(), QMD_NATIVE_ERROR_OPTIONS);
7478
7699
  }
7479
7700
  };
7480
7701
  }
@@ -7677,6 +7898,8 @@ function piMessagesToProviderView(messages, secrets = []) {
7677
7898
  const toolCalls = extractAssistantToolCalls(am);
7678
7899
  const msg = { role: "assistant", content: text4 };
7679
7900
  if (toolCalls.length > 0) msg.toolCalls = toolCalls;
7901
+ if (am.stopReason === "aborted") msg.stopped = "cancelled";
7902
+ else if (am.stopReason === "error") msg.stopped = "failed";
7680
7903
  out.push(msg);
7681
7904
  break;
7682
7905
  }
@@ -7862,9 +8085,9 @@ function readContainedFile(path, realRoot, maxBytes) {
7862
8085
  const buffer = Buffer.alloc(maxBytes + 1);
7863
8086
  let length = 0;
7864
8087
  while (length < buffer.length) {
7865
- const count = readSync(fd, buffer, length, buffer.length - length, null);
7866
- if (count === 0) break;
7867
- length += count;
8088
+ const count2 = readSync(fd, buffer, length, buffer.length - length, null);
8089
+ if (count2 === 0) break;
8090
+ length += count2;
7868
8091
  }
7869
8092
  if (length > maxBytes) throw new ContainedFileError("too_large");
7870
8093
  return buffer.subarray(0, length);
@@ -7955,6 +8178,8 @@ function browserGuideSection(attached = false) {
7955
8178
 
7956
8179
  // ../daemon/src/runtime/session/prompt.ts
7957
8180
  var SANDBOX_SKILLS_DIR = "/skills";
8181
+ var MAX_LISTED_TEAMMATES = 40;
8182
+ var MAX_LISTED_OUTSIDE = 20;
7958
8183
  function loadPromptSkills(skillsDir, attachedNames) {
7959
8184
  if (!existsSync11(skillsDir) || attachedNames.length === 0) return [];
7960
8185
  const attached = new Set(attachedNames);
@@ -8019,7 +8244,16 @@ ${contextBlocks.join("\n\n")}`
8019
8244
  });
8020
8245
  }
8021
8246
  const bootstrap2 = homeDocuments["BOOTSTRAP.md"]?.trimEnd();
8022
- if (bootstrap2) {
8247
+ if (bootstrap2 && options.withOperator === false) {
8248
+ parts.push({
8249
+ id: "first-run",
8250
+ text: [
8251
+ "# First-Run Ritual",
8252
+ "",
8253
+ "You have not had your first conversation with the human yet; it waits until they talk to you. This turn was not started by them (a teammate wrote to you, or a schedule fired), so nobody is here to answer its questions: do not greet the human or ask who you are. Do the work this turn asks for, with what you know."
8254
+ ].join("\n")
8255
+ });
8256
+ } else if (bootstrap2) {
8023
8257
  parts.push({
8024
8258
  id: "first-run",
8025
8259
  text: [
@@ -8031,6 +8265,9 @@ ${contextBlocks.join("\n\n")}`
8031
8265
  "- Your first reply is ONLY a greeting + ONE question. No tool calls. Wait for the human to answer.",
8032
8266
  "- Each subsequent turn: at most one new question. Wait between turns.",
8033
8267
  "- Only after the ritual is complete (you have enough to write IDENTITY.md): call `home_write` once, then `bootstrap_done`.",
8268
+ ...agent.team.userMd.trim() ? [
8269
+ "- The Team's USER.md (under About the User) already says some things about the human: do not ask what it answers."
8270
+ ] : [],
8034
8271
  "",
8035
8272
  "## BOOTSTRAP.md",
8036
8273
  "",
@@ -8101,6 +8338,7 @@ ${contextBlocks.join("\n\n")}`
8101
8338
  "",
8102
8339
  "An `AGENTS.md` file in the workspace holds repository instructions that govern its own directory and everything below it. The ones from the workspace root down to your working directory are already in your project instructions; read any other `AGENTS.md` on the path to files you edit."
8103
8340
  ];
8341
+ teamLines.push("", ...teammateLines(agent, options));
8104
8342
  parts.push({ id: "team", text: teamLines.join("\n") });
8105
8343
  if (agent.team.userMd.trim()) {
8106
8344
  parts.push({
@@ -8136,6 +8374,44 @@ ${reviewedLessons.map((lesson) => `- ${lesson}`).join("\n")}`
8136
8374
  });
8137
8375
  return parts;
8138
8376
  }
8377
+ function teammateLines(agent, options) {
8378
+ const contacts = options.contacts ?? [];
8379
+ const line = (text4) => text4.replace(/[\p{Cc}\p{Cf}\u2028\u2029\s]+/gu, " ").trim();
8380
+ const entry = (contact, team) => `- ${line(contact.name)}: id ${contact.id}${team ? "" : `, Team ${line(contact.teamName)}`} (template ${line(contact.template)})`;
8381
+ const listed = (list13, max, team) => [
8382
+ ...list13.slice(0, max).map((contact) => entry(contact, team)),
8383
+ ...list13.length > max ? [`- and ${list13.length - max} more`] : []
8384
+ ];
8385
+ const teammates = contacts.filter((contact) => contact.teamId === agent.team.id);
8386
+ const reachable = teammates.filter((contact) => contact.canMessage);
8387
+ const unreachable = teammates.filter((contact) => !contact.canMessage);
8388
+ const outside = contacts.filter((contact) => contact.teamId !== agent.team.id);
8389
+ const create7 = options.canCreateAgents ? " When the human asks you to add teammates, create them with `agent_create`." : "";
8390
+ const lines = ["## Your teammates", ""];
8391
+ if (teammates.length === 0) {
8392
+ lines.push(`You are the only Agent in this Team so far.${create7}`);
8393
+ } else {
8394
+ lines.push(
8395
+ `Message an Agent with \`send_message\`: put its id (or its exact name) in \`to\`. These are current; do not ask the human for ids.${create7}`
8396
+ );
8397
+ if (reachable.length > 0) lines.push("", ...listed(reachable, MAX_LISTED_TEAMMATES, true));
8398
+ if (unreachable.length > 0) {
8399
+ lines.push(
8400
+ "",
8401
+ "In this restricted Team you have no connection to these teammates, so you cannot message them; the human can connect you in the Team's Connections view:",
8402
+ ...listed(unreachable, MAX_LISTED_TEAMMATES, true)
8403
+ );
8404
+ }
8405
+ }
8406
+ if (outside.length > 0) {
8407
+ lines.push(
8408
+ "",
8409
+ "Team Policy also lets you message these Agents of other Teams:",
8410
+ ...listed(outside, MAX_LISTED_OUTSIDE, false)
8411
+ );
8412
+ }
8413
+ return lines;
8414
+ }
8139
8415
  function boundReviewedLessons(lessons, maxCharacters = 8e3) {
8140
8416
  const selected = [];
8141
8417
  let used = 0;
@@ -8152,7 +8428,7 @@ function boundReviewedLessons(lessons, maxCharacters = 8e3) {
8152
8428
 
8153
8429
  // ../daemon/src/runtime/shell/docker.ts
8154
8430
  import { spawn as spawn3 } from "node:child_process";
8155
- import { createHash as createHash4, randomUUID as randomUUID15 } from "node:crypto";
8431
+ import { createHash as createHash6, randomUUID as randomUUID15 } from "node:crypto";
8156
8432
  var CONTAINER_WORKSPACE = "/workspace";
8157
8433
  var DOCKER_CALL_TIMEOUT_MS = 5e3;
8158
8434
  var MAX_TIMER_MS = 2147483647;
@@ -8259,7 +8535,7 @@ async function checkDockerImage(image) {
8259
8535
  }
8260
8536
  }
8261
8537
  function homeContainerPrefix(home) {
8262
- return `bazilion-${createHash4("sha256").update(home).digest("hex").slice(0, 12)}-`;
8538
+ return `bazilion-${createHash6("sha256").update(home).digest("hex").slice(0, 12)}-`;
8263
8539
  }
8264
8540
  function turnContainerPrefix(home) {
8265
8541
  return `${homeContainerPrefix(home)}${randomUUID15().replaceAll("-", "").slice(0, 12)}-`;
@@ -8686,7 +8962,7 @@ import { closeSync as closeSync3, constants as constants4, fstatSync as fstatSyn
8686
8962
  import { join as join19 } from "node:path";
8687
8963
  var MAX_SESSION_BYTES = 64 * 1024 * 1024;
8688
8964
  var MAX_HEADER_BYTES = 64 * 1024;
8689
- function readStart(directory, id, limit) {
8965
+ function readStart(directory, id, limit, refuseOver) {
8690
8966
  if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error("Invalid conversation id");
8691
8967
  const fd = openSync3(
8692
8968
  join19(directory, `${id}.jsonl`),
@@ -8695,14 +8971,16 @@ function readStart(directory, id, limit) {
8695
8971
  try {
8696
8972
  const stat = fstatSync3(fd);
8697
8973
  if (!stat.isFile()) throw new Error("Session file is not a regular file");
8974
+ if (refuseOver !== void 0 && stat.size > refuseOver)
8975
+ throw new Error("Session file is larger than 64 MiB");
8698
8976
  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);
8977
+ let count2 = 0;
8978
+ while (count2 < bytes.length) {
8979
+ const n = readSync2(fd, bytes, count2, bytes.length - count2, count2);
8702
8980
  if (n === 0) break;
8703
- count += n;
8981
+ count2 += n;
8704
8982
  }
8705
- return { bytes: bytes.subarray(0, count), size: stat.size };
8983
+ return { bytes: bytes.subarray(0, count2), size: stat.size };
8706
8984
  } finally {
8707
8985
  closeSync3(fd);
8708
8986
  }
@@ -8711,14 +8989,19 @@ function checkHeader(entry, id) {
8711
8989
  if (entry?.type !== "session" || entry.id !== id)
8712
8990
  throw new Error("Session file does not belong to this conversation");
8713
8991
  }
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");
8992
+ function readSessionText(directory, id) {
8993
+ const { bytes } = readStart(directory, id, MAX_SESSION_BYTES, MAX_SESSION_BYTES);
8717
8994
  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));
8995
+ return text4.slice(0, text4.lastIndexOf("\n") + 1);
8996
+ }
8997
+ function parseSessionText(text4, id) {
8998
+ const entries = text4.split("\n").filter((line) => line.trim()).map((line) => JSON.parse(line));
8719
8999
  checkHeader(entries[0], id);
8720
9000
  return entries;
8721
9001
  }
9002
+ function readSessionFile(directory, id) {
9003
+ return parseSessionText(readSessionText(directory, id), id);
9004
+ }
8722
9005
  function sessionHasEntries(directory, id) {
8723
9006
  const { bytes, size } = readStart(directory, id, MAX_HEADER_BYTES);
8724
9007
  if (size > bytes.length) return true;
@@ -9267,11 +9550,11 @@ function messagingTools(host3, fromAgentId) {
9267
9550
  {
9268
9551
  def: {
9269
9552
  name: "send_message",
9270
- description: `Send a message to another agent. Use the recipient's agent id (UUID). Use this ONLY for things the recipient needs to ACT on: delegating a task, asking a peer for information you cannot get yourself, escalating a decision. Do NOT use it for status updates or to announce changes to team-shared resources \u2014 USER.md and the team memory backend both propagate to every agent in the team automatically on their next turn, so messages like "I updated USER.md" or "I wrote a new memory note" are pure noise and will trigger an inbox-wake loop on the recipient.`,
9553
+ description: 'Send a message to another agent: `to` is its id, or its exact name (your teammates are listed in your instructions). Use this ONLY for things the recipient needs to ACT on: delegating a task, asking a peer for information you cannot get yourself, escalating a decision. Do NOT use it for status updates or to announce changes to team-shared resources \u2014 USER.md and the team memory backend both propagate to every agent in the team automatically on their next turn, so messages like "I updated USER.md" or "I wrote a new memory note" are pure noise and will trigger an inbox-wake loop on the recipient.',
9271
9554
  parameters: {
9272
9555
  type: "object",
9273
9556
  properties: {
9274
- to: { type: "string", description: "Recipient agent id" },
9557
+ to: { type: "string", description: "Recipient Agent id, or its exact name" },
9275
9558
  text: { type: "string", description: "Message text" },
9276
9559
  reply_to: {
9277
9560
  type: "string",
@@ -9286,9 +9569,6 @@ function messagingTools(host3, fromAgentId) {
9286
9569
  const text4 = String(args.text ?? "");
9287
9570
  if (!to) throw new Error('send_message: "to" is required');
9288
9571
  if (!text4) throw new Error('send_message: "text" is required');
9289
- if (!await host3.agentExists(to)) {
9290
- throw new Error(`send_message: agent not found: ${to}`);
9291
- }
9292
9572
  const replyTo = typeof args.reply_to === "string" ? args.reply_to : null;
9293
9573
  const { messageId } = await host3.sendMessage({
9294
9574
  from: fromAgentId,
@@ -9371,6 +9651,51 @@ function messagingTools(host3, fromAgentId) {
9371
9651
  ];
9372
9652
  }
9373
9653
 
9654
+ // ../daemon/src/runtime/tools/team.ts
9655
+ function agentCreateTool(host3) {
9656
+ return {
9657
+ def: {
9658
+ name: "agent_create",
9659
+ description: "Add a new Agent to your Team, when the operator asks you to (to build a team, or to hand part of the work to a specialist). It joins your Team, shares its workspace and memory, and starts knowing its role and that you made it: give it a clear name and say what it is for. It uses your model and Agent template unless you name others. In a restricted Team it is connected with you both ways. Message it afterwards with send_message, by the id this returns. Do not create Agents the operator did not ask for, or several for one job.",
9660
+ parameters: {
9661
+ type: "object",
9662
+ properties: {
9663
+ name: {
9664
+ type: "string",
9665
+ description: 'Its name, unique in your Team, e.g. "Lead Researcher"'
9666
+ },
9667
+ role: {
9668
+ type: "string",
9669
+ description: "What it is for and how it should work, in a few sentences: its job, what it delivers and to whom, and its limits"
9670
+ },
9671
+ template: {
9672
+ type: "string",
9673
+ description: "Optional: an Agent template id (default: your own)"
9674
+ },
9675
+ model: {
9676
+ type: "string",
9677
+ description: 'Optional: a model as "provider:model" (default: your own model)'
9678
+ }
9679
+ },
9680
+ required: ["name", "role"]
9681
+ }
9682
+ },
9683
+ async invoke(args) {
9684
+ const created = await host3.createAgent({
9685
+ name: String(args.name ?? ""),
9686
+ role: String(args.role ?? ""),
9687
+ ...typeof args.template === "string" && args.template ? { template: args.template } : {},
9688
+ ...typeof args.model === "string" && args.model ? { model: args.model } : {}
9689
+ });
9690
+ return [
9691
+ `Created ${created.name} (id ${created.id}) in ${created.teamName}, from the template ${created.template}, on ${created.model}.`,
9692
+ created.connected ? "It is connected with you both ways." : "",
9693
+ "Brief it with send_message to that id."
9694
+ ].filter(Boolean).join(" ");
9695
+ }
9696
+ };
9697
+ }
9698
+
9374
9699
  // ../daemon/src/runtime/tools/user-md.ts
9375
9700
  function userMdTools(host3, teamId) {
9376
9701
  return [
@@ -9554,8 +9879,8 @@ async function readBodyCapped(res, maxBytes) {
9554
9879
  if (done) break;
9555
9880
  if (!value) continue;
9556
9881
  if (total + value.byteLength > maxBytes) {
9557
- const keep = maxBytes - total;
9558
- if (keep > 0) chunks.push(value.subarray(0, keep));
9882
+ const keep2 = maxBytes - total;
9883
+ if (keep2 > 0) chunks.push(value.subarray(0, keep2));
9559
9884
  truncated = true;
9560
9885
  try {
9561
9886
  await reader.cancel();
@@ -9614,23 +9939,23 @@ async function firecrawlScrape(url, mode2, env, fetchFn, timeoutMs) {
9614
9939
  clearTimeout(t);
9615
9940
  }
9616
9941
  }
9617
- function cacheGet(cache, key2) {
9618
- const entry = cache.get(key2);
9942
+ function cacheGet(cache2, key2) {
9943
+ const entry = cache2.get(key2);
9619
9944
  if (!entry) return null;
9620
9945
  if (entry.expiresAt < Date.now()) {
9621
- cache.delete(key2);
9946
+ cache2.delete(key2);
9622
9947
  return null;
9623
9948
  }
9624
- cache.delete(key2);
9625
- cache.set(key2, entry);
9949
+ cache2.delete(key2);
9950
+ cache2.set(key2, entry);
9626
9951
  return entry.value;
9627
9952
  }
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;
9953
+ function cacheSet(cache2, key2, value, ttlMs, maxEntries) {
9954
+ cache2.set(key2, { value, expiresAt: Date.now() + ttlMs });
9955
+ while (cache2.size > maxEntries) {
9956
+ const oldest = cache2.keys().next().value;
9632
9957
  if (!oldest) break;
9633
- cache.delete(oldest);
9958
+ cache2.delete(oldest);
9634
9959
  }
9635
9960
  }
9636
9961
  function webSearchTool(host3) {
@@ -9671,7 +9996,7 @@ function webFetchTool(opts) {
9671
9996
  const cacheMax = opts?.cacheMax ?? DEFAULT_CACHE_MAX;
9672
9997
  const timeoutMs = opts?.timeoutMs ?? DEFAULT_TIMEOUT_MS2;
9673
9998
  const maxBodyBytes = opts?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
9674
- const cache = /* @__PURE__ */ new Map();
9999
+ const cache2 = /* @__PURE__ */ new Map();
9675
10000
  return {
9676
10001
  def: {
9677
10002
  name: "web_fetch",
@@ -9699,7 +10024,7 @@ function webFetchTool(opts) {
9699
10024
  const maxLen = typeof args.max_length === "number" ? args.max_length : DEFAULT_MAX_LENGTH;
9700
10025
  const mode2 = args.extract_mode === "text" ? "text" : "markdown";
9701
10026
  const cacheKey = `${mode2}|${url}`;
9702
- const cached = cacheGet(cache, cacheKey);
10027
+ const cached = cacheGet(cache2, cacheKey);
9703
10028
  if (cached) return formatOutput(cached, maxLen);
9704
10029
  let result = null;
9705
10030
  try {
@@ -9758,7 +10083,7 @@ function webFetchTool(opts) {
9758
10083
  extracted = { ...extracted, text: `[final URL: ${result.finalUrl}]
9759
10084
 
9760
10085
  ${extracted.text}` };
9761
- cacheSet(cache, cacheKey, extracted, cacheTtlMs, cacheMax);
10086
+ cacheSet(cache2, cacheKey, extracted, cacheTtlMs, cacheMax);
9762
10087
  return formatOutput(extracted, maxLen);
9763
10088
  } catch (err) {
9764
10089
  if (err instanceof SsrFBlockedError) throw new Error(`web_fetch: ${err.message}`);
@@ -9820,6 +10145,7 @@ function createBazilionCustomTools(opts) {
9820
10145
  if (opts.fileSink) handlers.push(deliverFileTool(opts.agent.team.path, opts.fileSink));
9821
10146
  if (opts.imageGenerationHost) handlers.push(imageGenerateTool(opts.imageGenerationHost));
9822
10147
  if (opts.askUser) handlers.push(askUserTool(opts.askUser));
10148
+ if (opts.teamHost) handlers.push(agentCreateTool(opts.teamHost));
9823
10149
  return handlers.map(ourToolToPiTool);
9824
10150
  }
9825
10151
 
@@ -9904,6 +10230,7 @@ function turnSurface(opts) {
9904
10230
  imageGenerationHost: opts.imageGenerationHost,
9905
10231
  webSearchHost: opts.webSearchHost,
9906
10232
  askUser: opts.askUser,
10233
+ teamHost: opts.teamHost,
9907
10234
  env
9908
10235
  });
9909
10236
  const promptOptions = {
@@ -9911,7 +10238,10 @@ function turnSurface(opts) {
9911
10238
  sandboxMode: shellTools.config.sandboxMode,
9912
10239
  // The guides ride along exactly when their tools are admitted.
9913
10240
  ...opts.browserHost ? { browserGuide: resolveBrowserConfig(env).attach ? "attached" : true } : {},
9914
- ...opts.webSearchHost ? { searchGuide: true } : {}
10241
+ ...opts.webSearchHost ? { searchGuide: true } : {},
10242
+ contacts: opts.contacts ?? [],
10243
+ canCreateAgents: opts.teamHost !== void 0,
10244
+ withOperator: opts.withOperator ?? true
9915
10245
  };
9916
10246
  return {
9917
10247
  cwd,
@@ -10301,7 +10631,6 @@ var RPC_HANDLERS = {
10301
10631
  publishResult: (args, { hosts }) => host(hosts.resultHost, "result").publish(args),
10302
10632
  generateImages: (args, { hosts }) => host(hosts.imageGenerationHost, "image generation").generate(args),
10303
10633
  webSearch: (args, { hosts }) => host(hosts.webSearchHost, "web search").search(args),
10304
- agentExists: ({ agentId }, { hosts }) => host(hosts.messagingHost, "messaging").agentExists(agentId),
10305
10634
  sendMessage: (args, { hosts }) => host(hosts.messagingHost, "messaging").sendMessage(args),
10306
10635
  listInbox: ({ agentId, unreadOnly }, { hosts }) => host(hosts.messagingHost, "messaging").listInbox(agentId, { unreadOnly }),
10307
10636
  markRead: async ({ messageId }, { hosts }) => {
@@ -10313,6 +10642,7 @@ var RPC_HANDLERS = {
10313
10642
  userMdWrite: ({ teamId, content, ifMatch }, { hosts }) => host(hosts.userMdHost, "USER.md").write(teamId, content, ifMatch),
10314
10643
  browserInvoke: ({ agentId, action, args }, { hosts }) => host(hosts.browserHost, "browser").invoke(agentId, action, args),
10315
10644
  mcpInvoke: ({ serverId, toolName, args }, { hosts }) => host(hosts.mcpHost, "MCP").invoke(serverId, toolName, args),
10645
+ createAgent: (args, { hosts }) => host(hosts.teamHost, "team").createAgent(args),
10316
10646
  refreshApiKey: async ({ providerName }, ctx) => {
10317
10647
  const token = await refreshApiKeyForTurn(
10318
10648
  providerName,
@@ -10943,13 +11273,30 @@ function sendAgentMessage(db, input) {
10943
11273
  }
10944
11274
 
10945
11275
  // ../daemon/src/lib/messaging-host.ts
11276
+ function recipientOf(db, from, ref) {
11277
+ const wanted = ref.trim();
11278
+ const exact = db.raw.query("SELECT id FROM agents WHERE id = ?").get(wanted);
11279
+ if (exact) return exact.id;
11280
+ const sender = agents_exports.get(db, from);
11281
+ if (sender) {
11282
+ const teammates = db.raw.query(
11283
+ "SELECT id FROM agents WHERE team_id = ? AND lower(name) = lower(?) AND status != 'archived' LIMIT 2"
11284
+ ).all(sender.teamId, wanted);
11285
+ if (teammates.length === 1 && teammates[0]) return teammates[0].id;
11286
+ if (teammates.length > 1) {
11287
+ throw new Error(`send_message: more than one teammate is named "${wanted}"; use the id`);
11288
+ }
11289
+ }
11290
+ const found = agents_exports.get(db, wanted);
11291
+ if (found) return found.id;
11292
+ throw new Error(
11293
+ `send_message: no Agent "${wanted}". Use an id or an exact name from your teammates list.`
11294
+ );
11295
+ }
10946
11296
  function createDbMessagingHost(db, opts = {}) {
10947
11297
  return {
10948
- agentExists(agentId) {
10949
- return agents_exports.get(db, agentId) !== null;
10950
- },
10951
11298
  sendMessage(input) {
10952
- const to = agents_exports.get(db, input.to)?.id ?? input.to;
11299
+ const to = recipientOf(db, input.from, input.to);
10953
11300
  const m = sendAgentMessage(db, {
10954
11301
  ...input,
10955
11302
  to,
@@ -10991,94 +11338,383 @@ function createResultHost(db, agent, conversationId, signal) {
10991
11338
  };
10992
11339
  }
10993
11340
 
10994
- // ../daemon/src/lib/telegram/mirror.ts
10995
- import { InputFile } from "grammy";
11341
+ // ../daemon/src/lib/team-host.ts
11342
+ import { existsSync as existsSync16, readFileSync as readFileSync10, rmSync as rmSync12, writeFileSync as writeFileSync8 } from "node:fs";
11343
+ import { join as join23 } from "node:path";
10996
11344
 
10997
- // ../daemon/src/lib/telegram/live.ts
10998
- var current = null;
10999
- function telegramLive() {
11000
- return current;
11345
+ // ../daemon/src/lib/telegram/config.ts
11346
+ var BOT_TOKEN_KEY = "TELEGRAM_BOT_TOKEN";
11347
+ var CHAT_ID_KEY = "TELEGRAM_CHAT_ID";
11348
+ var LAST_UPDATE_KEY = "TELEGRAM_LAST_UPDATE_ID";
11349
+ var SERVICE_TOPIC_KEY = "TELEGRAM_SERVICE_TOPIC_ID";
11350
+ var DIRECTORY_MESSAGE_KEY = "TELEGRAM_DIRECTORY_MESSAGE_ID";
11351
+ var MIGRATED_CHAT_KEY = "TELEGRAM_MIGRATED_CHAT_ID";
11352
+ function readConfigNumber(db, key2) {
11353
+ const raw = openConfig(db).get(key2) ?? "";
11354
+ if (!raw) return null;
11355
+ const value = Number(raw);
11356
+ return Number.isFinite(value) ? value : null;
11001
11357
  }
11002
- function setTelegramLive(live) {
11003
- current = live;
11358
+ function readServiceTopicId(db) {
11359
+ return readConfigNumber(db, SERVICE_TOPIC_KEY);
11360
+ }
11361
+ function readCreds(db, authToken) {
11362
+ const botToken = openSecrets(db, authToken).get(BOT_TOKEN_KEY) ?? "";
11363
+ const chatId2 = readConfigNumber(db, CHAT_ID_KEY);
11364
+ return botToken && chatId2 !== null ? { botToken, chatId: chatId2 } : null;
11365
+ }
11366
+ function redactToken(text4, botToken) {
11367
+ return (botToken ? text4.replaceAll(botToken, "[redacted]") : text4).replace(
11368
+ /bot\d+:[A-Za-z0-9_-]+/g,
11369
+ "bot[redacted]"
11370
+ );
11004
11371
  }
11005
-
11006
- // ../daemon/src/lib/telegram/markdown.ts
11007
- import { marked } from "marked";
11008
11372
 
11009
11373
  // ../daemon/src/lib/telegram/html.ts
11010
11374
  function htmlEscape(s) {
11011
11375
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
11012
11376
  }
11013
11377
 
11014
- // ../daemon/src/lib/telegram/markdown.ts
11015
- var TELEGRAM_SAFE_BUDGET = 3900;
11016
- function clip2(text4, limit) {
11017
- return text4.length <= limit ? text4 : `${text4.slice(0, limit - 1)}\u2026`;
11378
+ // ../daemon/src/lib/telegram/live.ts
11379
+ var current = null;
11380
+ function telegramLive() {
11381
+ return current;
11018
11382
  }
11019
- function headingPrefix(depth) {
11020
- return depth <= 1 ? "\u258E " : depth === 2 ? "\u25B8 " : "\xB7 ";
11383
+ function setTelegramLive(live) {
11384
+ current = live;
11021
11385
  }
11022
- function safeHref(href) {
11023
- if (!href) return null;
11024
- if (!/^(https?:|tg:|mailto:)/i.test(href.trim())) return null;
11025
- return htmlEscape(href).replaceAll('"', "%22");
11386
+
11387
+ // ../daemon/src/lib/telegram/naming.ts
11388
+ var TEAM_COLORS = [
11389
+ 7322096,
11390
+ // light blue / cyan
11391
+ 16766590,
11392
+ // orange
11393
+ 13338331,
11394
+ // purple / lavender
11395
+ 9367192,
11396
+ // green
11397
+ 16749490
11398
+ // pink / rose
11399
+ ];
11400
+ var TOPIC_NAME_TOKENS = ["{agent.name}", "{team.name}", "{team.slug}"];
11401
+ function topicNameFor(agent, team) {
11402
+ const fmt = team.telegramTopicNameFormat ?? null;
11403
+ if (fmt) {
11404
+ return renderTopicNameFormat(fmt, {
11405
+ agentName: agent.name,
11406
+ teamName: team.name ?? team.id,
11407
+ teamSlug: team.id
11408
+ });
11409
+ }
11410
+ if (team.id === DEFAULT_TEAM_ID) return agent.name;
11411
+ return `${team.id} \u203A ${agent.name}`;
11026
11412
  }
11027
- function renderInline(tokens) {
11028
- if (!tokens) return "";
11029
- let out = "";
11030
- for (const t of tokens) {
11031
- switch (t.type) {
11032
- case "text": {
11033
- const tok = t;
11034
- out += tok.tokens ? renderInline(tok.tokens) : htmlEscape(tok.text);
11035
- break;
11036
- }
11037
- case "escape":
11038
- out += htmlEscape(t.text);
11039
- break;
11040
- case "strong":
11041
- out += `<b>${renderInline(t.tokens)}</b>`;
11042
- break;
11043
- case "em":
11044
- out += `<i>${renderInline(t.tokens)}</i>`;
11045
- break;
11046
- case "del":
11047
- out += `<s>${renderInline(t.tokens)}</s>`;
11048
- break;
11049
- case "codespan":
11050
- out += `<code>${htmlEscape(t.text)}</code>`;
11051
- break;
11052
- case "br":
11053
- out += "\n";
11054
- break;
11055
- case "link": {
11056
- const tok = t;
11057
- const href = safeHref(tok.href);
11058
- const inner = renderInline(tok.tokens);
11059
- out += href ? `<a href="${href}">${inner}</a>` : inner;
11060
- break;
11061
- }
11062
- case "image": {
11063
- const tok = t;
11064
- const href = safeHref(tok.href);
11065
- const label = htmlEscape(tok.text || tok.href || "");
11066
- out += href ? `<a href="${href}">${label}</a>` : label;
11067
- break;
11068
- }
11069
- case "html":
11070
- out += htmlEscape(t.text);
11071
- break;
11072
- default: {
11073
- const raw = t.raw;
11074
- out += raw ? htmlEscape(raw) : "";
11075
- }
11413
+ function renderTopicNameFormat(fmt, vals) {
11414
+ return fmt.replaceAll("{agent.name}", vals.agentName).replaceAll("{team.name}", vals.teamName).replaceAll("{team.slug}", vals.teamSlug);
11415
+ }
11416
+ function validateTopicNameFormat(fmt) {
11417
+ if (fmt.trim().length === 0) return "Format cannot be empty.";
11418
+ const used = fmt.match(/\{[^}]*\}/g) ?? [];
11419
+ for (const token of used) {
11420
+ if (!TOPIC_NAME_TOKENS.includes(token)) {
11421
+ return `Unknown token ${token}. Allowed tokens: ${TOPIC_NAME_TOKENS.join(", ")}.`;
11076
11422
  }
11077
11423
  }
11078
- return out;
11424
+ if (!fmt.includes("{agent.name}")) {
11425
+ return "Format must include {agent.name} so each agent gets a distinct topic name.";
11426
+ }
11427
+ return null;
11079
11428
  }
11080
- function plainInline(tokens) {
11081
- if (!tokens) return "";
11429
+ function allocateTeamColor(db, teamId) {
11430
+ const existing = teams_exports.getTelegramIconColor(db, teamId);
11431
+ if (existing !== null) return existing;
11432
+ const idx = teams_exports.countAllocatedColors(db) % TEAM_COLORS.length;
11433
+ const color = TEAM_COLORS[idx] ?? 7322096;
11434
+ teams_exports.setTelegramIconColor(db, teamId, color);
11435
+ return color;
11436
+ }
11437
+ function topicDeepLink(chatId2, topicId) {
11438
+ const absStr = String(Math.abs(chatId2));
11439
+ const shortId = absStr.startsWith("100") ? absStr.slice(3) : absStr;
11440
+ return `https://t.me/c/${shortId}/${topicId}`;
11441
+ }
11442
+
11443
+ // ../daemon/src/lib/telegram/directory.ts
11444
+ function agentListLines(db, paths, chatId2) {
11445
+ const agents = agents_exports.list(db);
11446
+ const lines = [];
11447
+ for (const team of teams_exports.list(db, paths)) {
11448
+ const members = agents.filter((agent) => agent.teamId === team.id);
11449
+ if (members.length === 0) continue;
11450
+ lines.push("", `<b>${htmlEscape(team.id)}</b>`);
11451
+ for (const agent of members) {
11452
+ const label = ` \u2022 <code>${htmlEscape(agent.name)}</code>`;
11453
+ lines.push(
11454
+ agent.telegramTopicId === null ? `${label} <i>(unbound)</i>` : `${label} \u2192 <a href="${topicDeepLink(chatId2, agent.telegramTopicId)}">open</a>`
11455
+ );
11456
+ }
11457
+ }
11458
+ return lines;
11459
+ }
11460
+ function buildDirectoryBody(db, paths, chatId2) {
11461
+ if (agents_exports.list(db).length === 0) {
11462
+ return [
11463
+ "\u{1F44B} <b>bazilion is online</b>",
11464
+ "",
11465
+ "No agents yet \u2014 run /spawn in this topic to create one.",
11466
+ "See /help for the command list."
11467
+ ].join("\n");
11468
+ }
11469
+ return [
11470
+ "\u{1F6DF} <b>Available agents</b>",
11471
+ ...agentListLines(db, paths, chatId2),
11472
+ "",
11473
+ "Run /help for commands."
11474
+ ].join("\n");
11475
+ }
11476
+ async function refreshDirectoryMessage(deps) {
11477
+ const serviceTopicId = readServiceTopicId(deps.db);
11478
+ if (serviceTopicId === null) return;
11479
+ const body = buildDirectoryBody(deps.db, deps.paths, deps.chatId);
11480
+ const messageId = readConfigNumber(deps.db, DIRECTORY_MESSAGE_KEY);
11481
+ if (messageId !== null) {
11482
+ try {
11483
+ await deps.api.editMessageText(deps.chatId, messageId, body, {
11484
+ parse_mode: "HTML",
11485
+ disable_web_page_preview: true
11486
+ });
11487
+ return;
11488
+ } catch (e) {
11489
+ if (isNotModifiedError(e)) return;
11490
+ if (!isMessageGoneError(e)) throw e;
11491
+ console.warn(
11492
+ "telegram directory: pinned message gone, recreating \u2014",
11493
+ e instanceof Error ? e.message : String(e)
11494
+ );
11495
+ }
11496
+ }
11497
+ const sent = await deps.api.sendMessage(deps.chatId, body, {
11498
+ message_thread_id: serviceTopicId,
11499
+ parse_mode: "HTML",
11500
+ disable_web_page_preview: true
11501
+ });
11502
+ openConfig(deps.db).set(DIRECTORY_MESSAGE_KEY, String(sent.message_id));
11503
+ try {
11504
+ await deps.api.pinChatMessage(deps.chatId, sent.message_id, { disable_notification: true });
11505
+ } catch (e) {
11506
+ console.warn(
11507
+ "telegram directory: pin failed (continuing):",
11508
+ e instanceof Error ? e.message : String(e)
11509
+ );
11510
+ }
11511
+ }
11512
+ function isMessageGoneError(e) {
11513
+ if (!(e instanceof Error)) return false;
11514
+ const msg = e.message.toLowerCase();
11515
+ return msg.includes("message to edit not found") || msg.includes("message_id_invalid") || msg.includes("message can");
11516
+ }
11517
+ function isNotModifiedError(e) {
11518
+ if (!(e instanceof Error)) return false;
11519
+ return e.message.toLowerCase().includes("message is not modified");
11520
+ }
11521
+ var refreshScheduled = false;
11522
+ function notifyDirectoryDirty() {
11523
+ if (refreshScheduled) return;
11524
+ refreshScheduled = true;
11525
+ setImmediate(() => {
11526
+ refreshScheduled = false;
11527
+ const live = telegramLive();
11528
+ if (!live) return;
11529
+ refreshDirectoryMessage({ ...live, api: live.api }).catch(
11530
+ (e) => console.warn(
11531
+ "telegram directory: scheduled refresh failed \u2014",
11532
+ e instanceof Error ? e.message : String(e)
11533
+ )
11534
+ );
11535
+ });
11536
+ }
11537
+
11538
+ // ../daemon/src/lib/team-host.ts
11539
+ var MAX_CREATED_PER_TURN = 6;
11540
+ var MAX_ROLE = 4e3;
11541
+ function agentContacts(db, agentId) {
11542
+ const self = agents_exports.get(db, agentId);
11543
+ if (!self) return [];
11544
+ const teams = new Map(
11545
+ db.raw.query("SELECT id, name FROM teams").all().map((team) => [team.id, team.name])
11546
+ );
11547
+ const templates = new Map(profiles_exports.list(db).map((profile) => [profile.id, profile.name]));
11548
+ const contacts = agents_exports.list(db).filter((agent) => agent.id !== self.id).map((agent) => ({
11549
+ id: agent.id,
11550
+ name: agent.name,
11551
+ teamId: agent.teamId,
11552
+ teamName: teams.get(agent.teamId) ?? agent.teamId,
11553
+ template: templates.get(agent.profileId) ?? agent.profileId,
11554
+ canMessage: mayMessage(db, self.id, agent.id).allowed
11555
+ }));
11556
+ const own = contacts.filter((contact) => contact.teamId === self.teamId);
11557
+ const others = contacts.filter((contact) => contact.teamId !== self.teamId && contact.canMessage).sort((a, b) => a.teamName.localeCompare(b.teamName));
11558
+ return [...own, ...others];
11559
+ }
11560
+ function roleNote(role, creator, teamName) {
11561
+ return [
11562
+ "# Your role",
11563
+ "",
11564
+ role,
11565
+ "",
11566
+ `${creator.name} (Agent id ${creator.id}) added you to the Team ${teamName} on ${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}, when the operator asked. Report back to ${creator.name} unless the operator says otherwise.`
11567
+ ].join("\n");
11568
+ }
11569
+ function createDbTeamHost(db, paths, creatorId) {
11570
+ let created = 0;
11571
+ return {
11572
+ createAgent(input) {
11573
+ const creator = agents_exports.get(db, creatorId);
11574
+ if (!creator) throw new Error("agent_create: your own Agent record is gone");
11575
+ const name = String(input.name ?? "").trim();
11576
+ const role = String(input.role ?? "").trim();
11577
+ if (!name) throw new Error('agent_create: "name" is required');
11578
+ const nameProblem = agentNameProblem(name);
11579
+ if (nameProblem) throw new Error(`agent_create: ${nameProblem}`);
11580
+ if (!role) throw new Error('agent_create: "role" is required: say what the Agent is for');
11581
+ if (role.length > MAX_ROLE) {
11582
+ throw new Error(`agent_create: a role is at most ${MAX_ROLE} characters`);
11583
+ }
11584
+ if (created >= MAX_CREATED_PER_TURN) {
11585
+ throw new Error(
11586
+ `agent_create: at most ${MAX_CREATED_PER_TURN} Agents per turn; ask the operator before adding more`
11587
+ );
11588
+ }
11589
+ const taken = agents_exports.list(db).some(
11590
+ (agent2) => agent2.teamId === creator.teamId && agent2.name.toLowerCase() === name.toLowerCase()
11591
+ );
11592
+ if (taken) {
11593
+ throw new Error(`agent_create: this Team already has an Agent named "${name}"`);
11594
+ }
11595
+ const templateId = input.template?.trim() || creator.profileId;
11596
+ const template = profiles_exports.get(db, templateId);
11597
+ if (!template) {
11598
+ const known = profiles_exports.list(db).map((profile) => `${profile.id} (${profile.name})`).join(", ");
11599
+ throw new Error(`agent_create: no Agent template "${templateId}". Templates: ${known}`);
11600
+ }
11601
+ const creatorTemplate = profiles_exports.get(db, creator.profileId);
11602
+ const model = input.model?.trim() || creator.modelOverride || creatorTemplate?.defaultModel || "";
11603
+ if (model) parseModelString(model);
11604
+ const agent = spawnAgent(db, paths, {
11605
+ profileId: template.id,
11606
+ name,
11607
+ ...model && model !== template.defaultModel ? { modelOverride: model } : {},
11608
+ teamId: creator.teamId
11609
+ });
11610
+ created++;
11611
+ const agentsFile = join23(agent.dir, "AGENTS.md");
11612
+ const teamName = db.raw.query("SELECT name FROM teams WHERE id = ?").get(creator.teamId)?.name ?? creator.teamId;
11613
+ const rest = existsSync16(agentsFile) ? readFileSync10(agentsFile, "utf8").trim() : "";
11614
+ writeFileSync8(
11615
+ agentsFile,
11616
+ `${roleNote(role, creator, teamName)}
11617
+ ${rest ? `
11618
+ ---
11619
+
11620
+ ${rest}
11621
+ ` : ""}`
11622
+ );
11623
+ rmSync12(join23(agent.dir, "BOOTSTRAP.md"), { force: true });
11624
+ const restricted = teamPolicies_exports.mode(db, creator.teamId) === "restricted";
11625
+ if (restricted) {
11626
+ teamPolicies_exports.insertEdges(db, creator.teamId, [
11627
+ { from: creator.id, to: agent.id },
11628
+ { from: agent.id, to: creator.id }
11629
+ ]);
11630
+ }
11631
+ notifyDirectoryDirty();
11632
+ signalLiveChange();
11633
+ return {
11634
+ id: agent.id,
11635
+ name: agent.name,
11636
+ teamId: creator.teamId,
11637
+ teamName,
11638
+ template: template.name,
11639
+ model: model || template.defaultModel,
11640
+ connected: restricted
11641
+ };
11642
+ }
11643
+ };
11644
+ }
11645
+
11646
+ // ../daemon/src/lib/telegram/mirror.ts
11647
+ import { InputFile } from "grammy";
11648
+
11649
+ // ../daemon/src/lib/telegram/markdown.ts
11650
+ import { marked } from "marked";
11651
+ var TELEGRAM_SAFE_BUDGET = 3900;
11652
+ function clip2(text4, limit) {
11653
+ return text4.length <= limit ? text4 : `${text4.slice(0, limit - 1)}\u2026`;
11654
+ }
11655
+ function headingPrefix(depth) {
11656
+ return depth <= 1 ? "\u258E " : depth === 2 ? "\u25B8 " : "\xB7 ";
11657
+ }
11658
+ function safeHref(href) {
11659
+ if (!href) return null;
11660
+ if (!/^(https?:|tg:|mailto:)/i.test(href.trim())) return null;
11661
+ return htmlEscape(href).replaceAll('"', "%22");
11662
+ }
11663
+ function renderInline(tokens) {
11664
+ if (!tokens) return "";
11665
+ let out = "";
11666
+ for (const t of tokens) {
11667
+ switch (t.type) {
11668
+ case "text": {
11669
+ const tok = t;
11670
+ out += tok.tokens ? renderInline(tok.tokens) : htmlEscape(tok.text);
11671
+ break;
11672
+ }
11673
+ case "escape":
11674
+ out += htmlEscape(t.text);
11675
+ break;
11676
+ case "strong":
11677
+ out += `<b>${renderInline(t.tokens)}</b>`;
11678
+ break;
11679
+ case "em":
11680
+ out += `<i>${renderInline(t.tokens)}</i>`;
11681
+ break;
11682
+ case "del":
11683
+ out += `<s>${renderInline(t.tokens)}</s>`;
11684
+ break;
11685
+ case "codespan":
11686
+ out += `<code>${htmlEscape(t.text)}</code>`;
11687
+ break;
11688
+ case "br":
11689
+ out += "\n";
11690
+ break;
11691
+ case "link": {
11692
+ const tok = t;
11693
+ const href = safeHref(tok.href);
11694
+ const inner = renderInline(tok.tokens);
11695
+ out += href ? `<a href="${href}">${inner}</a>` : inner;
11696
+ break;
11697
+ }
11698
+ case "image": {
11699
+ const tok = t;
11700
+ const href = safeHref(tok.href);
11701
+ const label = htmlEscape(tok.text || tok.href || "");
11702
+ out += href ? `<a href="${href}">${label}</a>` : label;
11703
+ break;
11704
+ }
11705
+ case "html":
11706
+ out += htmlEscape(t.text);
11707
+ break;
11708
+ default: {
11709
+ const raw = t.raw;
11710
+ out += raw ? htmlEscape(raw) : "";
11711
+ }
11712
+ }
11713
+ }
11714
+ return out;
11715
+ }
11716
+ function plainInline(tokens) {
11717
+ if (!tokens) return "";
11082
11718
  let out = "";
11083
11719
  for (const t of tokens) {
11084
11720
  const tok = t;
@@ -11695,8 +12331,8 @@ function mirrorTypingStop(agentId) {
11695
12331
 
11696
12332
  // ../daemon/src/lib/attachments.ts
11697
12333
  import { randomUUID as randomUUID17 } from "node:crypto";
11698
- import { closeSync as closeSync5, constants as constants6, fstatSync as fstatSync5, openSync as openSync5, writeFileSync as writeFileSync8 } from "node:fs";
11699
- import { join as join23, posix as posix2 } from "node:path";
12334
+ import { closeSync as closeSync5, constants as constants6, fstatSync as fstatSync5, openSync as openSync5, writeFileSync as writeFileSync9 } from "node:fs";
12335
+ import { join as join24, posix as posix2 } from "node:path";
11700
12336
  var MAX_FILE_BYTES = 25 * 1024 * 1024;
11701
12337
  function safeName(name) {
11702
12338
  const base = name.split(/[\\/]/).pop() ?? "file";
@@ -11708,7 +12344,7 @@ function fmtBytes(n) {
11708
12344
  return `${(n / (1024 * 1024)).toFixed(1)} MB`;
11709
12345
  }
11710
12346
  function prepareInputFilesDirectory(agentDir2) {
11711
- return ensureContainedRealDirectory(join23(agentDir2, "uploads"), agentDir2, { create: true });
12347
+ return ensureContainedRealDirectory(join24(agentDir2, "uploads"), agentDir2, { create: true });
11712
12348
  }
11713
12349
  function saveInputFiles(agentDir2, files, options = {}) {
11714
12350
  if (!files || files.length === 0) return "";
@@ -11722,7 +12358,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
11722
12358
  continue;
11723
12359
  }
11724
12360
  const filename = `${randomUUID17().slice(0, 8)}-${safeName(label)}`;
11725
- const path = join23(dir, filename);
12361
+ const path = join24(dir, filename);
11726
12362
  let fd;
11727
12363
  try {
11728
12364
  fd = openSync5(
@@ -11731,7 +12367,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
11731
12367
  384
11732
12368
  );
11733
12369
  if (!fstatSync5(fd).isFile()) throw new Error("attachment target is not a regular file");
11734
- writeFileSync8(fd, buf);
12370
+ writeFileSync9(fd, buf);
11735
12371
  } finally {
11736
12372
  if (fd !== void 0) closeSync5(fd);
11737
12373
  }
@@ -11745,7 +12381,7 @@ function saveInputFiles(agentDir2, files, options = {}) {
11745
12381
 
11746
12382
  // ../daemon/src/lib/coding-environment.ts
11747
12383
  import { lstatSync as lstatSync5 } from "node:fs";
11748
- import { join as join24 } from "node:path";
12384
+ import { join as join25 } from "node:path";
11749
12385
 
11750
12386
  // ../daemon/src/core/coding-environment/config.ts
11751
12387
  var CodingEnvironmentValidationError = class extends DomainError {
@@ -11802,7 +12438,7 @@ function setTeamCodingEnvironment(db, team, input, env = process.env) {
11802
12438
  const environment = validateCodingEnvironment(input);
11803
12439
  let path = team.path;
11804
12440
  for (const part of environment.cwd === "." ? [] : environment.cwd.split("/")) {
11805
- path = join24(path, part);
12441
+ path = join25(path, part);
11806
12442
  if (!lstatSync5(path, { throwIfNoEntry: false })?.isDirectory())
11807
12443
  throw new CodingEnvironmentValidationError(
11808
12444
  "The directory must be an existing directory inside the Team"
@@ -11822,18 +12458,18 @@ function dockerTurn(db, paths, agent, env) {
11822
12458
 
11823
12459
  // ../daemon/src/lib/conversation-target.ts
11824
12460
  import { randomUUID as randomUUID18 } from "node:crypto";
11825
- import { writeFileSync as writeFileSync9 } from "node:fs";
11826
- import { join as join25 } from "node:path";
12461
+ import { writeFileSync as writeFileSync10 } from "node:fs";
12462
+ import { join as join26 } from "node:path";
11827
12463
  import { SessionManager as SessionManager2 } from "@earendil-works/pi-coding-agent";
11828
12464
  function sessionsDir(paths, agentId) {
11829
- return join25(paths.agentDir(agentId), "sessions");
12465
+ return join26(paths.agentDir(agentId), "sessions");
11830
12466
  }
11831
12467
  function startConversation(db, paths, agentId, title) {
11832
12468
  const agent = resolveAgent(db, paths, agentId);
11833
12469
  if (title !== void 0) validTitle(title);
11834
12470
  const id = randomUUID18();
11835
12471
  const header = SessionManager2.inMemory(agent.team.path, { id }).getHeader();
11836
- writeFileSync9(join25(sessionsDir(paths, agentId), `${id}.jsonl`), `${JSON.stringify(header)}
12472
+ writeFileSync10(join26(sessionsDir(paths, agentId), `${id}.jsonl`), `${JSON.stringify(header)}
11837
12473
  `, {
11838
12474
  flag: "wx",
11839
12475
  mode: 384
@@ -11881,7 +12517,7 @@ function selectedConversationTarget(db, agentId) {
11881
12517
 
11882
12518
  // ../daemon/src/lib/repository-instructions.ts
11883
12519
  import { realpathSync as realpathSync6 } from "node:fs";
11884
- import { join as join26 } from "node:path";
12520
+ import { join as join27 } from "node:path";
11885
12521
  var MAX_FILE_BYTES2 = 128 * 1024;
11886
12522
  var SKIPPED = {
11887
12523
  outside: "it resolves outside the Team workspace",
@@ -11901,7 +12537,7 @@ function loadRepositoryInstructions(root, cwd = ".") {
11901
12537
  for (let depth = 0; depth <= parts.length; depth++) {
11902
12538
  const path = [...parts.slice(0, depth), "AGENTS.md"].join("/");
11903
12539
  try {
11904
- const content = readContainedFile(join26(realRoot, path), realRoot, MAX_FILE_BYTES2);
12540
+ const content = readContainedFile(join27(realRoot, path), realRoot, MAX_FILE_BYTES2);
11905
12541
  instructions.push({ path, content: content.toString("utf8") });
11906
12542
  } catch (error) {
11907
12543
  if (error instanceof ContainedFileError) {
@@ -11969,10 +12605,10 @@ function releasePreparedAgentTurn(turn) {
11969
12605
  }
11970
12606
 
11971
12607
  // ../daemon/src/lib/user-md-host.ts
11972
- import { createHash as createHash5 } from "node:crypto";
12608
+ import { createHash as createHash7 } from "node:crypto";
11973
12609
  var USER_MD_MAX_BYTES = 12e3;
11974
12610
  function computeEtag(content) {
11975
- return createHash5("sha256").update(content, "utf8").digest("hex").slice(0, 16);
12611
+ return createHash7("sha256").update(content, "utf8").digest("hex").slice(0, 16);
11976
12612
  }
11977
12613
  function createDbUserMdHost(db, paths) {
11978
12614
  return {
@@ -12050,13 +12686,13 @@ function createWebSearchHost(opts) {
12050
12686
  const query = typeof args?.query === "string" ? args.query.trim() : "";
12051
12687
  if (!query || query.length > 512)
12052
12688
  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;
12689
+ const count2 = Number.isInteger(args.count) && args.count >= 1 ? Math.min(args.count, 10) : 5;
12054
12690
  const signal = AbortSignal.any([opts.signal, AbortSignal.timeout(DEADLINE_MS2)]);
12055
12691
  const env = opts.env();
12056
12692
  try {
12057
12693
  if (opts.backend === "brave") {
12058
12694
  const body = await getJson(
12059
- `https://api.search.brave.com/res/v1/web/search?${new URLSearchParams({ q: query, count: String(count) })}`,
12695
+ `https://api.search.brave.com/res/v1/web/search?${new URLSearchParams({ q: query, count: String(count2) })}`,
12060
12696
  { "x-subscription-token": env.BRAVE_API_KEY ?? "" },
12061
12697
  signal,
12062
12698
  fetchImpl
@@ -12064,7 +12700,7 @@ function createWebSearchHost(opts) {
12064
12700
  const rows = body.web?.results;
12065
12701
  return {
12066
12702
  backend: "brave",
12067
- results: (Array.isArray(rows) ? rows : []).slice(0, count).map((row) => ({
12703
+ results: (Array.isArray(rows) ? rows : []).slice(0, count2).map((row) => ({
12068
12704
  title: text3(row?.title, 200),
12069
12705
  url: text3(row?.url, 2048),
12070
12706
  snippet: text3(row?.description, 300)
@@ -12081,14 +12717,14 @@ function createWebSearchHost(opts) {
12081
12717
  );
12082
12718
  return {
12083
12719
  backend: "searxng",
12084
- results: (Array.isArray(body.results) ? body.results : []).slice(0, count).map((row) => ({
12720
+ results: (Array.isArray(body.results) ? body.results : []).slice(0, count2).map((row) => ({
12085
12721
  title: text3(row?.title, 200),
12086
12722
  url: text3(row?.url, 2048),
12087
12723
  snippet: text3(row?.content, 300)
12088
12724
  }))
12089
12725
  };
12090
12726
  }
12091
- return await hostedSearch(opts, query, count, signal, fetchImpl, env);
12727
+ return await hostedSearch(opts, query, count2, signal, fetchImpl, env);
12092
12728
  } catch (error) {
12093
12729
  if (opts.signal.aborted) throw new Error("web_search: cancelled");
12094
12730
  if (signal.aborted) throw new Error("web_search: no answer within 30 seconds");
@@ -12097,14 +12733,14 @@ function createWebSearchHost(opts) {
12097
12733
  }
12098
12734
  };
12099
12735
  }
12100
- async function hostedSearch(opts, query, count, signal, fetchImpl, env) {
12736
+ async function hostedSearch(opts, query, count2, signal, fetchImpl, env) {
12101
12737
  const codex = opts.backend === "openai-codex";
12102
12738
  const output = await responsesStream(
12103
12739
  codex ? CODEX_RESPONSES_URL : OPENAI_RESPONSES_URL,
12104
12740
  codex ? codexHeaders(await opts.codexToken()) : { authorization: `Bearer ${env.OPENAI_API_KEY ?? ""}` },
12105
12741
  {
12106
12742
  model: parseModelString(opts.model).modelId,
12107
- instructions: `Search the web for the query and answer concisely, citing up to ${count} sources.`,
12743
+ instructions: `Search the web for the query and answer concisely, citing up to ${count2} sources.`,
12108
12744
  input: [{ role: "user", content: [{ type: "input_text", text: query }] }],
12109
12745
  tools: [{ type: "web_search" }],
12110
12746
  tool_choice: { type: "web_search" }
@@ -12130,7 +12766,7 @@ async function hostedSearch(opts, query, count, signal, fetchImpl, env) {
12130
12766
  return {
12131
12767
  backend: opts.backend,
12132
12768
  answer: answer.join("\n").trim(),
12133
- results: results.slice(0, count)
12769
+ results: results.slice(0, count2)
12134
12770
  };
12135
12771
  }
12136
12772
 
@@ -12154,7 +12790,9 @@ async function* runAgentTurn(turn) {
12154
12790
  repositoryInstructions: turn.repositoryInstructions,
12155
12791
  mcpTools: mcp?.tools,
12156
12792
  turnId: turn.request.attemptId,
12157
- bashApprovalMode: turn.bashApprovalMode
12793
+ bashApprovalMode: turn.bashApprovalMode,
12794
+ contacts: agentContacts(db, agentId),
12795
+ withOperator: withOperator(turn)
12158
12796
  },
12159
12797
  {
12160
12798
  env,
@@ -12193,6 +12831,9 @@ async function* runAgentTurn(turn) {
12193
12831
  releasePreparedAgentTurn(turn);
12194
12832
  }
12195
12833
  }
12834
+ function withOperator(turn) {
12835
+ return turn.request.origin === "http" || turn.request.origin === "telegram";
12836
+ }
12196
12837
  function turnHosts(turn, env) {
12197
12838
  const { db, paths, authToken } = getCtx();
12198
12839
  const { agent, conversation } = turn;
@@ -12234,6 +12875,8 @@ function turnHosts(turn, env) {
12234
12875
  codexToken: () => loadAccessToken(db, authToken),
12235
12876
  signal
12236
12877
  }) : void 0,
12878
+ // Agents add teammates when the operator asks, never from a schedule or a teammate's message.
12879
+ teamHost: withOperator(turn) ? createDbTeamHost(db, paths, agent.agent.id) : void 0,
12237
12880
  // Bound to this turn's Agent: the worker cannot drive another Agent's browser.
12238
12881
  browserHost: isBrowserEnabled(env) ? createBrowserHost(resolveBrowserConfig(env), { paths, agentId: agent.agent.id, signal }) : void 0
12239
12882
  };
@@ -12536,7 +13179,7 @@ agentChatRouter.post("/:id/chat/compact", async (c) => {
12536
13179
  const { db, paths, authToken } = getCtx();
12537
13180
  const resolved = resolveAgent(db, paths, id);
12538
13181
  assertProviderReady(db, authToken, resolved.model);
12539
- const memory = qmdBackend(join27(resolved.team.path, "memory"));
13182
+ const memory = qmdBackend(join28(resolved.team.path, "memory"));
12540
13183
  await memory.init();
12541
13184
  const handle12 = await createBazilionSession({
12542
13185
  agent: resolved,
@@ -12594,9 +13237,9 @@ agentChatRouter.get(
12594
13237
  const env = mergeSecretsIntoEnv(db, authToken);
12595
13238
  const files = [];
12596
13239
  for (const file of CONTEXT_FILE_ORDER2) {
12597
- const path = join27(resolved.agent.dir, file);
12598
- if (!existsSync16(path)) continue;
12599
- const content = readFileSync10(path, "utf8").trimEnd();
13240
+ const path = join28(resolved.agent.dir, file);
13241
+ if (!existsSync17(path)) continue;
13242
+ const content = readFileSync11(path, "utf8").trimEnd();
12600
13243
  if (!content) continue;
12601
13244
  const chars = content.length + file.length + 6;
12602
13245
  files.push({ name: file, chars, tokens: estimateTokens2(chars) });
@@ -12609,9 +13252,12 @@ agentChatRouter.get(
12609
13252
  agent: resolved,
12610
13253
  paths,
12611
13254
  env,
12612
- memory: qmdBackend(join27(resolved.team.path, "memory")),
13255
+ memory: qmdBackend(join28(resolved.team.path, "memory")),
12613
13256
  messagingHost: createDbMessagingHost(db),
12614
13257
  userMdHost: createDbUserMdHost(db, paths),
13258
+ // As in a chat turn: the operator is there.
13259
+ teamHost: { createAgent: reportOnly },
13260
+ contacts: agentContacts(db, resolved.agent.id),
12615
13261
  fileSink: reportOnly,
12616
13262
  ...isBrowserEnabled(env) ? { browserHost: { invoke: reportOnly } } : {},
12617
13263
  ...searchRoute(env, resolved.model, codexConnected).backend ? { webSearchHost: { search: reportOnly } } : {},
@@ -12639,7 +13285,7 @@ agentChatRouter.get(
12639
13285
  let blockChars = name.length + 2;
12640
13286
  if (match) {
12641
13287
  try {
12642
- blockChars = readFileSync10(match.skillFile, "utf8").length;
13288
+ blockChars = readFileSync11(match.skillFile, "utf8").length;
12643
13289
  } catch {
12644
13290
  }
12645
13291
  }
@@ -12690,8 +13336,8 @@ agentChatRouter.get(
12690
13336
  agentChatRouter.post("/:id/chat/truncate", async (c) => {
12691
13337
  const body = await jsonBody(c);
12692
13338
  if (!body) return c.json({ error: "invalid JSON body" }, 400);
12693
- const keep = Number(body.keepCount);
12694
- if (!Number.isInteger(keep) || keep < 0) {
13339
+ const keep2 = Number(body.keepCount);
13340
+ if (!Number.isInteger(keep2) || keep2 < 0) {
12695
13341
  return c.json({ error: "keepCount must be a non-negative integer" }, 400);
12696
13342
  }
12697
13343
  return withSelectedConversation(c, (id, target) => {
@@ -12702,7 +13348,7 @@ agentChatRouter.post("/:id/chat/truncate", async (c) => {
12702
13348
  const conversation = openConversation(resolveAgent(db, paths, id), paths, target);
12703
13349
  const messageEntries = conversation.getBranch().filter((e) => e.type === "message" && e.message.role !== "system");
12704
13350
  const before = messageEntries.length;
12705
- const after = Math.max(0, Math.min(keep, before));
13351
+ const after = Math.max(0, Math.min(keep2, before));
12706
13352
  if (after === before) return c.json({ before, after });
12707
13353
  const lastKept = messageEntries[after - 1];
12708
13354
  if (lastKept) conversation.branch(lastKept.id);
@@ -12713,7 +13359,7 @@ agentChatRouter.post("/:id/chat/truncate", async (c) => {
12713
13359
  });
12714
13360
 
12715
13361
  // ../daemon/src/routes/agent-learning.ts
12716
- import { join as join28 } from "node:path";
13362
+ import { join as join29 } from "node:path";
12717
13363
 
12718
13364
  // ../daemon/src/lib/lesson-decisions.ts
12719
13365
  var LessonProposalConflictError = class extends DomainError {
@@ -12912,7 +13558,7 @@ for (const decision of ["approve", "reject", "revoke"]) {
12912
13558
  const team = teams_exports.get(db, agent.teamId, paths);
12913
13559
  if (!team) return c.json({ error: `team not found: ${agent.teamId}` }, 404);
12914
13560
  const proposal = await runAgentLifecycleMutation(agent.id, async () => {
12915
- const memory = qmdBackend(join28(team.path, "memory"));
13561
+ const memory = qmdBackend(join29(team.path, "memory"));
12916
13562
  if (decision === "approve") return approveLessonProposal(db, memory, current2.id, version);
12917
13563
  if (decision === "reject") return rejectLessonProposal(db, current2.id, version);
12918
13564
  return revokeLessonProposal(db, memory, current2.id, version);
@@ -12940,210 +13586,31 @@ function withEvidenceExcerpts(proposals, agent, paths) {
12940
13586
  }
12941
13587
 
12942
13588
  // ../daemon/src/routes/agents.ts
12943
- import { join as join29 } from "node:path";
13589
+ import { join as join30 } from "node:path";
12944
13590
  init_pool2();
12945
13591
 
12946
- // ../daemon/src/lib/telegram/config.ts
12947
- var BOT_TOKEN_KEY = "TELEGRAM_BOT_TOKEN";
12948
- var CHAT_ID_KEY = "TELEGRAM_CHAT_ID";
12949
- var LAST_UPDATE_KEY = "TELEGRAM_LAST_UPDATE_ID";
12950
- var SERVICE_TOPIC_KEY = "TELEGRAM_SERVICE_TOPIC_ID";
12951
- var DIRECTORY_MESSAGE_KEY = "TELEGRAM_DIRECTORY_MESSAGE_ID";
12952
- var MIGRATED_CHAT_KEY = "TELEGRAM_MIGRATED_CHAT_ID";
12953
- function readConfigNumber(db, key2) {
12954
- const raw = openConfig(db).get(key2) ?? "";
12955
- if (!raw) return null;
12956
- const value = Number(raw);
12957
- return Number.isFinite(value) ? value : null;
13592
+ // ../daemon/src/lib/telegram/profile-emojis.ts
13593
+ var BUILTIN_PROFILE_EMOJI = {
13594
+ researcher: "\u{1F4DA}",
13595
+ coder: "\u{1F4BB}",
13596
+ developer: "\u{1F4BB}",
13597
+ engineer: "\u{1F4BB}",
13598
+ "notes-archivist": "\u{1F4DD}",
13599
+ archivist: "\u{1F4DD}",
13600
+ writer: "\u{1F4DD}",
13601
+ analyst: "\u{1F4CA}",
13602
+ analytics: "\u{1F4CA}"
13603
+ };
13604
+ var _stickerMap = null;
13605
+ var _testApi = null;
13606
+ function emojiForAgent(agent, profileName) {
13607
+ if (agent.telegramIconEmoji) return agent.telegramIconEmoji;
13608
+ return BUILTIN_PROFILE_EMOJI[profileName.toLowerCase()] ?? null;
12958
13609
  }
12959
- function readServiceTopicId(db) {
12960
- return readConfigNumber(db, SERVICE_TOPIC_KEY);
12961
- }
12962
- function readCreds(db, authToken) {
12963
- const botToken = openSecrets(db, authToken).get(BOT_TOKEN_KEY) ?? "";
12964
- const chatId2 = readConfigNumber(db, CHAT_ID_KEY);
12965
- return botToken && chatId2 !== null ? { botToken, chatId: chatId2 } : null;
12966
- }
12967
- function redactToken(text4, botToken) {
12968
- return (botToken ? text4.replaceAll(botToken, "[redacted]") : text4).replace(
12969
- /bot\d+:[A-Za-z0-9_-]+/g,
12970
- "bot[redacted]"
12971
- );
12972
- }
12973
-
12974
- // ../daemon/src/lib/telegram/naming.ts
12975
- var TEAM_COLORS = [
12976
- 7322096,
12977
- // light blue / cyan
12978
- 16766590,
12979
- // orange
12980
- 13338331,
12981
- // purple / lavender
12982
- 9367192,
12983
- // green
12984
- 16749490
12985
- // pink / rose
12986
- ];
12987
- var TOPIC_NAME_TOKENS = ["{agent.name}", "{team.name}", "{team.slug}"];
12988
- function topicNameFor(agent, team) {
12989
- const fmt = team.telegramTopicNameFormat ?? null;
12990
- if (fmt) {
12991
- return renderTopicNameFormat(fmt, {
12992
- agentName: agent.name,
12993
- teamName: team.name ?? team.id,
12994
- teamSlug: team.id
12995
- });
12996
- }
12997
- if (team.id === DEFAULT_TEAM_ID) return agent.name;
12998
- return `${team.id} \u203A ${agent.name}`;
12999
- }
13000
- function renderTopicNameFormat(fmt, vals) {
13001
- return fmt.replaceAll("{agent.name}", vals.agentName).replaceAll("{team.name}", vals.teamName).replaceAll("{team.slug}", vals.teamSlug);
13002
- }
13003
- function validateTopicNameFormat(fmt) {
13004
- if (fmt.trim().length === 0) return "Format cannot be empty.";
13005
- const used = fmt.match(/\{[^}]*\}/g) ?? [];
13006
- for (const token of used) {
13007
- if (!TOPIC_NAME_TOKENS.includes(token)) {
13008
- return `Unknown token ${token}. Allowed tokens: ${TOPIC_NAME_TOKENS.join(", ")}.`;
13009
- }
13010
- }
13011
- if (!fmt.includes("{agent.name}")) {
13012
- return "Format must include {agent.name} so each agent gets a distinct topic name.";
13013
- }
13014
- return null;
13015
- }
13016
- function allocateTeamColor(db, teamId) {
13017
- const existing = teams_exports.getTelegramIconColor(db, teamId);
13018
- if (existing !== null) return existing;
13019
- const idx = teams_exports.countAllocatedColors(db) % TEAM_COLORS.length;
13020
- const color = TEAM_COLORS[idx] ?? 7322096;
13021
- teams_exports.setTelegramIconColor(db, teamId, color);
13022
- return color;
13023
- }
13024
- function topicDeepLink(chatId2, topicId) {
13025
- const absStr = String(Math.abs(chatId2));
13026
- const shortId = absStr.startsWith("100") ? absStr.slice(3) : absStr;
13027
- return `https://t.me/c/${shortId}/${topicId}`;
13028
- }
13029
-
13030
- // ../daemon/src/lib/telegram/directory.ts
13031
- function agentListLines(db, paths, chatId2) {
13032
- const agents = agents_exports.list(db);
13033
- const lines = [];
13034
- for (const team of teams_exports.list(db, paths)) {
13035
- const members = agents.filter((agent) => agent.teamId === team.id);
13036
- if (members.length === 0) continue;
13037
- lines.push("", `<b>${htmlEscape(team.id)}</b>`);
13038
- for (const agent of members) {
13039
- const label = ` \u2022 <code>${htmlEscape(agent.name)}</code>`;
13040
- lines.push(
13041
- agent.telegramTopicId === null ? `${label} <i>(unbound)</i>` : `${label} \u2192 <a href="${topicDeepLink(chatId2, agent.telegramTopicId)}">open</a>`
13042
- );
13043
- }
13044
- }
13045
- return lines;
13046
- }
13047
- function buildDirectoryBody(db, paths, chatId2) {
13048
- if (agents_exports.list(db).length === 0) {
13049
- return [
13050
- "\u{1F44B} <b>bazilion is online</b>",
13051
- "",
13052
- "No agents yet \u2014 run /spawn in this topic to create one.",
13053
- "See /help for the command list."
13054
- ].join("\n");
13055
- }
13056
- return [
13057
- "\u{1F6DF} <b>Available agents</b>",
13058
- ...agentListLines(db, paths, chatId2),
13059
- "",
13060
- "Run /help for commands."
13061
- ].join("\n");
13062
- }
13063
- async function refreshDirectoryMessage(deps) {
13064
- const serviceTopicId = readServiceTopicId(deps.db);
13065
- if (serviceTopicId === null) return;
13066
- const body = buildDirectoryBody(deps.db, deps.paths, deps.chatId);
13067
- const messageId = readConfigNumber(deps.db, DIRECTORY_MESSAGE_KEY);
13068
- if (messageId !== null) {
13069
- try {
13070
- await deps.api.editMessageText(deps.chatId, messageId, body, {
13071
- parse_mode: "HTML",
13072
- disable_web_page_preview: true
13073
- });
13074
- return;
13075
- } catch (e) {
13076
- if (isNotModifiedError(e)) return;
13077
- if (!isMessageGoneError(e)) throw e;
13078
- console.warn(
13079
- "telegram directory: pinned message gone, recreating \u2014",
13080
- e instanceof Error ? e.message : String(e)
13081
- );
13082
- }
13083
- }
13084
- const sent = await deps.api.sendMessage(deps.chatId, body, {
13085
- message_thread_id: serviceTopicId,
13086
- parse_mode: "HTML",
13087
- disable_web_page_preview: true
13088
- });
13089
- openConfig(deps.db).set(DIRECTORY_MESSAGE_KEY, String(sent.message_id));
13090
- try {
13091
- await deps.api.pinChatMessage(deps.chatId, sent.message_id, { disable_notification: true });
13092
- } catch (e) {
13093
- console.warn(
13094
- "telegram directory: pin failed (continuing):",
13095
- e instanceof Error ? e.message : String(e)
13096
- );
13097
- }
13098
- }
13099
- function isMessageGoneError(e) {
13100
- if (!(e instanceof Error)) return false;
13101
- const msg = e.message.toLowerCase();
13102
- return msg.includes("message to edit not found") || msg.includes("message_id_invalid") || msg.includes("message can");
13103
- }
13104
- function isNotModifiedError(e) {
13105
- if (!(e instanceof Error)) return false;
13106
- return e.message.toLowerCase().includes("message is not modified");
13107
- }
13108
- var refreshScheduled = false;
13109
- function notifyDirectoryDirty() {
13110
- if (refreshScheduled) return;
13111
- refreshScheduled = true;
13112
- setImmediate(() => {
13113
- refreshScheduled = false;
13114
- const live = telegramLive();
13115
- if (!live) return;
13116
- refreshDirectoryMessage({ ...live, api: live.api }).catch(
13117
- (e) => console.warn(
13118
- "telegram directory: scheduled refresh failed \u2014",
13119
- e instanceof Error ? e.message : String(e)
13120
- )
13121
- );
13122
- });
13123
- }
13124
-
13125
- // ../daemon/src/lib/telegram/profile-emojis.ts
13126
- var BUILTIN_PROFILE_EMOJI = {
13127
- researcher: "\u{1F4DA}",
13128
- coder: "\u{1F4BB}",
13129
- developer: "\u{1F4BB}",
13130
- engineer: "\u{1F4BB}",
13131
- "notes-archivist": "\u{1F4DD}",
13132
- archivist: "\u{1F4DD}",
13133
- writer: "\u{1F4DD}",
13134
- analyst: "\u{1F4CA}",
13135
- analytics: "\u{1F4CA}"
13136
- };
13137
- var _stickerMap = null;
13138
- var _testApi = null;
13139
- function emojiForAgent(agent, profileName) {
13140
- if (agent.telegramIconEmoji) return agent.telegramIconEmoji;
13141
- return BUILTIN_PROFILE_EMOJI[profileName.toLowerCase()] ?? null;
13142
- }
13143
- async function resolveStickerId(emojiChar) {
13144
- if (!emojiChar) return null;
13145
- const map = await ensureStickerMap();
13146
- return map?.get(emojiChar) ?? null;
13610
+ async function resolveStickerId(emojiChar) {
13611
+ if (!emojiChar) return null;
13612
+ const map = await ensureStickerMap();
13613
+ return map?.get(emojiChar) ?? null;
13147
13614
  }
13148
13615
  async function ensureStickerMap() {
13149
13616
  if (_stickerMap) return _stickerMap;
@@ -13215,7 +13682,7 @@ agentsRouter.get("/", (c) => {
13215
13682
  const includeArchived = c.req.query("includeArchived") === "true";
13216
13683
  const agents = agents_exports.list(getCtx().db, { includeArchived }).map((agent) => ({
13217
13684
  ...agent,
13218
- identity: loadIdentityFromFile(join29(agent.dir, "IDENTITY.md"))
13685
+ identity: loadIdentityFromFile(join30(agent.dir, "IDENTITY.md"))
13219
13686
  }));
13220
13687
  return c.json(agents);
13221
13688
  });
@@ -13254,6 +13721,8 @@ agentsRouter.patch("/:id", async (c) => {
13254
13721
  400
13255
13722
  );
13256
13723
  }
13724
+ const nameProblem = typeof name === "string" ? agentNameProblem(name.trim()) : null;
13725
+ if (nameProblem) return c.json({ error: nameProblem }, 400);
13257
13726
  if (telegramMirrorMode !== void 0 && telegramMirrorMode !== "minimal" && telegramMirrorMode !== "verbose") {
13258
13727
  return c.json({ error: `invalid telegramMirrorMode: ${String(telegramMirrorMode)}` }, 400);
13259
13728
  }
@@ -13523,26 +13992,12 @@ function writeProviderCheck(db, providerId, check) {
13523
13992
  if (check) checks[providerId] = check;
13524
13993
  else if (providerId in checks) delete checks[providerId];
13525
13994
  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));
13995
+ const store2 = openConfig(db);
13996
+ if (Object.keys(checks).length === 0) store2.remove(PROVIDER_CHECKS_KEY);
13997
+ else store2.set(PROVIDER_CHECKS_KEY, JSON.stringify(checks));
13529
13998
  }
13530
13999
 
13531
14000
  // ../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
14001
  function redactDetail(message, secrets) {
13547
14002
  let detail = message;
13548
14003
  for (const secret of secrets) {
@@ -13776,9 +14231,9 @@ function fieldStates(fields2, stored, env = process.env) {
13776
14231
  });
13777
14232
  }
13778
14233
  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);
14234
+ const store2 = field.kind === "config" ? openConfig(db) : openSecrets(db, authToken);
14235
+ if (value === "") store2.remove(field.envVar);
14236
+ else store2.set(field.envVar, value);
13782
14237
  }
13783
14238
 
13784
14239
  // ../daemon/src/lib/provider-setup.ts
@@ -14658,48 +15113,504 @@ configRouter.delete("/fields/:envVar", (c) => {
14658
15113
  return c.body(null, 204);
14659
15114
  });
14660
15115
 
14661
- // ../daemon/src/routes/conversations.ts
14662
- var conversationsRouter = newRouter();
14663
- conversationsRouter.use("/:agentId/conversations/*", async (c, next) => {
14664
- c.set("agentId", routeAgent(c, "agentId").id);
14665
- await next();
14666
- });
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
- );
14678
- conversationsRouter.post("/:agentId/conversations", async (c) => {
14679
- const input = await jsonBody(c);
14680
- const agentId = c.get("agentId");
14681
- const { db, paths } = getCtx();
14682
- return c.json(
14683
- await runAgentLifecycleMutation(
14684
- agentId,
14685
- () => startConversation(db, paths, agentId, input?.title)
14686
- )
15116
+ // ../daemon/src/lib/conversation-search.ts
15117
+ import { join as join31 } from "node:path";
15118
+ import { buildSessionContext as buildSessionContext2 } from "@earendil-works/pi-coding-agent";
15119
+ var INBOX_WAKE_PREFIX = "[[bazilion:inbox-wake]]\n";
15120
+ var MAX_WORDS = 8;
15121
+ var MAX_SEARCH_HITS = 50;
15122
+ var BEFORE = 24;
15123
+ var AFTER = 140;
15124
+ function searchWords(query) {
15125
+ const words = [...new Set(query.toLowerCase().split(/\s+/).filter(Boolean))];
15126
+ if (words.join("").length < 2) throw new DomainError(400, "Search for at least two characters");
15127
+ if (words.length > MAX_WORDS) throw new DomainError(400, `Search for at most ${MAX_WORDS} words`);
15128
+ return words;
15129
+ }
15130
+ function plainText(markdown) {
15131
+ 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");
15132
+ }
15133
+ function snippetOf(text4, words) {
15134
+ const flat = plainText(text4).replace(/\s+/g, " ").trim();
15135
+ const lower = flat.toLowerCase();
15136
+ const at = Math.min(
15137
+ ...words.map((word) => lower.indexOf(word)).filter((index) => index >= 0),
15138
+ flat.length
14687
15139
  );
14688
- });
14689
- conversationsRouter.get("/:agentId/conversations/:id", (c) => {
14690
- const { db, paths, authToken } = getCtx();
14691
- const agentId = c.get("agentId");
14692
- const id = c.req.param("id");
14693
- const conversation = get16(db, agentId, id);
14694
- if (!conversation) return c.json({ error: "Conversation not found" }, 404);
15140
+ const start2 = Math.max(0, at - BEFORE);
15141
+ const end = Math.min(flat.length, at + AFTER);
15142
+ return `${start2 > 0 ? "\u2026" : ""}${flat.slice(start2, end).trim()}${end < flat.length ? "\u2026" : ""}`;
15143
+ }
15144
+ async function searchConversations(db, paths, options) {
15145
+ const words = searchWords(options.query);
15146
+ const limit = Math.min(Math.max(options.limit ?? 20, 1), MAX_SEARCH_HITS);
15147
+ const raw = words.map((word) => JSON.stringify(word).slice(1, -1));
15148
+ const rows = db.raw.query(
15149
+ `SELECT c.id, c.agent_id agentId, c.title, a.name agentName, a.status = 'archived' archived,
15150
+ a.team_id teamId, t.name teamName, s.conversation_id selected
15151
+ FROM agent_conversations c JOIN agents a ON a.id = c.agent_id JOIN teams t ON t.id = a.team_id
15152
+ LEFT JOIN agent_conversation_selection s ON s.agent_id = c.agent_id
15153
+ WHERE (? IS NULL OR c.agent_id = ?)
15154
+ ORDER BY c.updated_at DESC`
15155
+ ).all(options.agentId ?? null, options.agentId ?? null);
15156
+ const hits = [];
15157
+ let unreadable = 0;
15158
+ for (const row of rows) {
15159
+ await new Promise((resolve9) => setImmediate(resolve9));
15160
+ if (options.signal?.aborted) break;
15161
+ const directory = join31(paths.agentDir(row.agentId), "sessions");
15162
+ let text4;
15163
+ try {
15164
+ text4 = readSessionText(directory, row.id);
15165
+ } catch {
15166
+ unreadable++;
15167
+ continue;
15168
+ }
15169
+ const lower = text4.toLowerCase();
15170
+ if (!raw.every((word) => lower.includes(word))) continue;
15171
+ let messages;
15172
+ try {
15173
+ const entries = parseSessionText(text4, row.id);
15174
+ messages = buildSessionContext2(entries.filter((entry) => entry.type !== "session")).messages;
15175
+ } catch {
15176
+ unreadable++;
15177
+ continue;
15178
+ }
15179
+ let nth = 0;
15180
+ for (const message of messages) {
15181
+ if (message.role !== "user" && message.role !== "assistant") continue;
15182
+ const [shown] = piMessagesToProviderView([message], options.secrets ?? []);
15183
+ if (!shown) continue;
15184
+ const content = redactExactValues(
15185
+ shown.content.startsWith(INBOX_WAKE_PREFIX) ? shown.content.slice(INBOX_WAKE_PREFIX.length) : shown.content,
15186
+ options.secrets ?? []
15187
+ );
15188
+ const found = plainText(content).toLowerCase();
15189
+ if (!words.every((word) => found.includes(word))) continue;
15190
+ const at = message.timestamp;
15191
+ hits.push({
15192
+ agentId: row.agentId,
15193
+ agentName: row.agentName,
15194
+ teamId: row.teamId,
15195
+ teamName: row.teamName,
15196
+ archived: Boolean(row.archived),
15197
+ conversationId: row.id,
15198
+ conversationTitle: row.title,
15199
+ active: row.selected === row.id,
15200
+ role: message.role,
15201
+ at: typeof at === "number" && Number.isFinite(at) ? at : null,
15202
+ snippet: snippetOf(content, words),
15203
+ nth: nth++
15204
+ });
15205
+ }
15206
+ }
15207
+ hits.sort((a, b) => (b.at ?? 0) - (a.at ?? 0));
15208
+ return { words, hits: hits.slice(0, limit), truncated: hits.length > limit, unreadable };
15209
+ }
15210
+
15211
+ // ../daemon/src/lib/usage.ts
15212
+ import { closeSync as closeSync6, constants as constants7, fstatSync as fstatSync6, openSync as openSync6, readdirSync as readdirSync7, readSync as readSync3 } from "node:fs";
15213
+ import { join as join32 } from "node:path";
15214
+ var CONVERSATION_FILE = /^([0-9a-f-]{36})\.jsonl$/i;
15215
+ var READ_CHUNK = 1024 * 1024;
15216
+ var CACHE_KEY = /* @__PURE__ */ Symbol.for("bazilion.usage.files");
15217
+ function cache() {
15218
+ const holder = globalThis;
15219
+ holder[CACHE_KEY] ??= /* @__PURE__ */ new Map();
15220
+ return holder[CACHE_KEY];
15221
+ }
15222
+ var count = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
15223
+ function toRecord(usage, at, provider, model) {
15224
+ if (!usage || typeof usage !== "object") return null;
15225
+ const input = count(usage.input);
15226
+ const output = count(usage.output);
15227
+ const cacheRead = count(usage.cacheRead);
15228
+ const cacheWrite = count(usage.cacheWrite);
15229
+ const total = count(usage.totalTokens) || input + output + cacheRead + cacheWrite;
15230
+ const cost = count(usage.cost?.total);
15231
+ if (total === 0 && cost === 0) return null;
15232
+ return {
15233
+ at,
15234
+ calls: 1,
15235
+ provider,
15236
+ model,
15237
+ input,
15238
+ output,
15239
+ cacheRead,
15240
+ cacheWrite,
15241
+ total,
15242
+ cost,
15243
+ billed: usage.cost?.totalFromProvider === true
15244
+ };
15245
+ }
15246
+ function usageOfLine(line, file) {
15247
+ let entry;
14695
15248
  try {
14696
- const messages = piMessagesToProviderView(
14697
- loadInitialMessages(resolveAgent(db, paths, agentId), paths, { id }),
14698
- envSecretValues(mergeSecretsIntoEnv(db, authToken))
14699
- );
14700
- return c.json({ conversation, messages });
15249
+ entry = JSON.parse(line);
14701
15250
  } catch {
14702
- return c.json(
15251
+ return null;
15252
+ }
15253
+ if (!entry || typeof entry !== "object") return null;
15254
+ const at = (typeof entry.timestamp === "string" ? Date.parse(entry.timestamp) : Number.NaN) || (typeof entry.message?.timestamp === "number" ? entry.message.timestamp : 0);
15255
+ if (!Number.isFinite(at) || at <= 0) return null;
15256
+ if (entry.type === "message" && entry.message?.role === "assistant") {
15257
+ const provider = typeof entry.message.provider === "string" ? entry.message.provider : "";
15258
+ const model = typeof entry.message.model === "string" ? entry.message.model : "";
15259
+ if (provider && model) file.lastModel = { provider, model };
15260
+ return toRecord(entry.message.usage, at, provider || "unknown", model || "unknown");
15261
+ }
15262
+ if (entry.type === "usage") {
15263
+ const provider = typeof entry.provider === "string" ? entry.provider : "unknown";
15264
+ const model = typeof entry.model === "string" ? entry.model : "unknown";
15265
+ return toRecord(entry.usage, at, provider, model);
15266
+ }
15267
+ if (entry.type === "compaction" || entry.type === "branch_summary") {
15268
+ const last = file.lastModel ?? { provider: "unknown", model: "unknown" };
15269
+ return toRecord(entry.usage, at, last.provider, last.model);
15270
+ }
15271
+ return null;
15272
+ }
15273
+ var QUARTER_HOUR = 15 * 6e4;
15274
+ function keep(file, record) {
15275
+ const at = Math.floor(record.at / QUARTER_HOUR) * QUARTER_HOUR;
15276
+ const key2 = `${at}|${record.provider}|${record.model}|${record.billed}`;
15277
+ const kept = file.totals.get(key2);
15278
+ if (!kept) {
15279
+ file.totals.set(key2, { ...record, at });
15280
+ return;
15281
+ }
15282
+ kept.calls += record.calls;
15283
+ kept.input += record.input;
15284
+ kept.output += record.output;
15285
+ kept.cacheRead += record.cacheRead;
15286
+ kept.cacheWrite += record.cacheWrite;
15287
+ kept.total += record.total;
15288
+ kept.cost += record.cost;
15289
+ }
15290
+ function scanFile(path) {
15291
+ const files = cache();
15292
+ const fd = openSync6(path, constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK);
15293
+ try {
15294
+ const stat = fstatSync6(fd);
15295
+ if (!stat.isFile()) throw new Error("not a regular file");
15296
+ let file = files.get(path);
15297
+ if (!file || file.dev !== stat.dev || file.ino !== stat.ino || stat.size < file.offset) {
15298
+ file = { dev: stat.dev, ino: stat.ino, offset: 0, totals: /* @__PURE__ */ new Map(), lastModel: null };
15299
+ files.set(path, file);
15300
+ }
15301
+ let pending = Buffer.alloc(0);
15302
+ let position = file.offset;
15303
+ const chunk = Buffer.alloc(READ_CHUNK);
15304
+ while (position < stat.size) {
15305
+ const n = readSync3(fd, chunk, 0, Math.min(READ_CHUNK, stat.size - position), position);
15306
+ if (n === 0) break;
15307
+ position += n;
15308
+ const bytes = pending.length ? Buffer.concat([pending, chunk.subarray(0, n)]) : chunk;
15309
+ const length = pending.length ? bytes.length : n;
15310
+ const end = bytes.lastIndexOf(10, length - 1);
15311
+ if (end < 0) {
15312
+ pending = Buffer.from(bytes.subarray(0, length));
15313
+ continue;
15314
+ }
15315
+ for (const line of bytes.subarray(0, end).toString("utf8").split("\n")) {
15316
+ if (!line.trim()) continue;
15317
+ const record = usageOfLine(line, file);
15318
+ if (record) keep(file, record);
15319
+ }
15320
+ pending = Buffer.from(bytes.subarray(end + 1, length));
15321
+ file.offset = position - pending.length;
15322
+ }
15323
+ return file;
15324
+ } finally {
15325
+ closeSync6(fd);
15326
+ }
15327
+ }
15328
+ function scanUsage(paths, agentIds, options = {}) {
15329
+ const conversations = [];
15330
+ let unreadable = 0;
15331
+ const seen = /* @__PURE__ */ new Set();
15332
+ for (const agentId of agentIds) {
15333
+ const directory = join32(paths.agentDir(agentId), "sessions");
15334
+ let names;
15335
+ try {
15336
+ names = readdirSync7(directory);
15337
+ } catch {
15338
+ continue;
15339
+ }
15340
+ for (const name of names) {
15341
+ const id = CONVERSATION_FILE.exec(name)?.[1];
15342
+ if (!id) continue;
15343
+ const path = join32(directory, name);
15344
+ seen.add(path);
15345
+ try {
15346
+ const totals = scanFile(path).totals;
15347
+ conversations.push({ agentId, conversationId: id, records: [...totals.values()] });
15348
+ } catch {
15349
+ unreadable++;
15350
+ }
15351
+ }
15352
+ }
15353
+ const listed = agentIds.map((id) => `${join32(paths.agentDir(id), "sessions")}/`);
15354
+ for (const path of cache().keys()) {
15355
+ if (seen.has(path)) continue;
15356
+ if (options.everyAgent || listed.some((prefix) => path.startsWith(prefix))) cache().delete(path);
15357
+ }
15358
+ return { conversations, unreadable };
15359
+ }
15360
+ var BY_PI_NAME = new Map(
15361
+ PROVIDERS.map((provider) => [provider.piName ?? provider.id, provider])
15362
+ );
15363
+ function planProviders(env) {
15364
+ return new Set(
15365
+ PROVIDERS.filter(
15366
+ (provider) => provider.plan || provider.planEnv && env[provider.planEnv]
15367
+ ).map((provider) => provider.piName ?? provider.id)
15368
+ );
15369
+ }
15370
+ var ALWAYS_PLANS = planProviders({});
15371
+ function billingOf(provider, plans = ALWAYS_PLANS) {
15372
+ if (BY_PI_NAME.get(provider)?.local) return "local";
15373
+ if (plans.has(provider)) return "plan";
15374
+ return "paid";
15375
+ }
15376
+ var emptyTotals = () => ({
15377
+ calls: 0,
15378
+ inputTokens: 0,
15379
+ outputTokens: 0,
15380
+ cacheReadTokens: 0,
15381
+ cacheWriteTokens: 0,
15382
+ totalTokens: 0,
15383
+ cost: 0,
15384
+ estimated: false,
15385
+ planTokens: 0,
15386
+ localTokens: 0,
15387
+ unpricedTokens: 0
15388
+ });
15389
+ function addRecord(totals, record, plans = ALWAYS_PLANS) {
15390
+ const billing = billingOf(record.provider, plans);
15391
+ totals.calls += record.calls;
15392
+ totals.inputTokens += record.input;
15393
+ totals.outputTokens += record.output;
15394
+ totals.cacheReadTokens += record.cacheRead;
15395
+ totals.cacheWriteTokens += record.cacheWrite;
15396
+ totals.totalTokens += record.total;
15397
+ if (billing === "plan") totals.planTokens += record.total;
15398
+ else if (billing === "local") totals.localTokens += record.total;
15399
+ else if (record.cost > 0) {
15400
+ totals.cost += record.cost;
15401
+ if (!record.billed) totals.estimated = true;
15402
+ } else totals.unpricedTokens += record.total;
15403
+ }
15404
+ var formatters = /* @__PURE__ */ new Map();
15405
+ function validTimeZone(value) {
15406
+ if (!value) return null;
15407
+ try {
15408
+ return new Intl.DateTimeFormat("en-CA", { timeZone: value }).resolvedOptions().timeZone;
15409
+ } catch {
15410
+ return null;
15411
+ }
15412
+ }
15413
+ function dayOf(at, timeZone) {
15414
+ let formatter = formatters.get(timeZone);
15415
+ if (!formatter) {
15416
+ formatter = new Intl.DateTimeFormat("en-CA", {
15417
+ timeZone,
15418
+ year: "numeric",
15419
+ month: "2-digit",
15420
+ day: "2-digit"
15421
+ });
15422
+ formatters.set(timeZone, formatter);
15423
+ }
15424
+ return formatter.format(at);
15425
+ }
15426
+ function shiftDay(day, offset) {
15427
+ const date = /* @__PURE__ */ new Date(`${day}T00:00:00Z`);
15428
+ date.setUTCDate(date.getUTCDate() + offset);
15429
+ return date.toISOString().slice(0, 10);
15430
+ }
15431
+ function agentRows(db) {
15432
+ return db.raw.query(
15433
+ `SELECT a.id, a.name, a.status, a.team_id, t.name team_name
15434
+ FROM agents a JOIN teams t ON t.id = a.team_id`
15435
+ ).all();
15436
+ }
15437
+ var bySpend = (a, b) => b.cost - a.cost || b.totalTokens - a.totalTokens;
15438
+ function usageReport(db, paths, query) {
15439
+ const plans = query.plans ?? ALWAYS_PLANS;
15440
+ const agents = agentRows(db);
15441
+ const shown = agents.filter(
15442
+ (agent) => (!query.agentId || agent.id === query.agentId) && (!query.teamId || agent.team_id === query.teamId)
15443
+ );
15444
+ const { conversations, unreadable } = scanUsage(
15445
+ paths,
15446
+ shown.map((agent) => agent.id),
15447
+ { everyAgent: shown.length === agents.length }
15448
+ );
15449
+ const to = dayOf(query.now ?? Date.now(), query.timeZone);
15450
+ const from = query.days === null ? null : shiftDay(to, -(query.days - 1));
15451
+ const totals = emptyTotals();
15452
+ const days = /* @__PURE__ */ new Map();
15453
+ const byAgent = /* @__PURE__ */ new Map();
15454
+ const byTeam = /* @__PURE__ */ new Map();
15455
+ const byModel = /* @__PURE__ */ new Map();
15456
+ if (from !== null) {
15457
+ for (let day = from; day <= to; day = shiftDay(day, 1)) days.set(day, { day, ...emptyTotals() });
15458
+ }
15459
+ const agentById = new Map(agents.map((agent) => [agent.id, agent]));
15460
+ for (const conversation of conversations) {
15461
+ const agent = agentById.get(conversation.agentId);
15462
+ if (!agent) continue;
15463
+ for (const record of conversation.records) {
15464
+ const day = dayOf(record.at, query.timeZone);
15465
+ if (from !== null && day < from || day > to) continue;
15466
+ addRecord(totals, record, plans);
15467
+ let dayTotals = days.get(day);
15468
+ if (!dayTotals) {
15469
+ dayTotals = { day, ...emptyTotals() };
15470
+ days.set(day, dayTotals);
15471
+ }
15472
+ addRecord(dayTotals, record, plans);
15473
+ let agentTotals = byAgent.get(agent.id);
15474
+ if (!agentTotals) {
15475
+ agentTotals = {
15476
+ agentId: agent.id,
15477
+ agentName: agent.name,
15478
+ teamId: agent.team_id,
15479
+ teamName: agent.team_name,
15480
+ archived: agent.status === "archived",
15481
+ ...emptyTotals()
15482
+ };
15483
+ byAgent.set(agent.id, agentTotals);
15484
+ }
15485
+ addRecord(agentTotals, record, plans);
15486
+ let teamTotals = byTeam.get(agent.team_id);
15487
+ if (!teamTotals) {
15488
+ teamTotals = { teamId: agent.team_id, teamName: agent.team_name, ...emptyTotals() };
15489
+ byTeam.set(agent.team_id, teamTotals);
15490
+ }
15491
+ addRecord(teamTotals, record, plans);
15492
+ const modelKey = `${record.provider}\0${record.model}`;
15493
+ let modelTotals = byModel.get(modelKey);
15494
+ if (!modelTotals) {
15495
+ modelTotals = {
15496
+ provider: record.provider,
15497
+ providerName: BY_PI_NAME.get(record.provider)?.displayName ?? record.provider,
15498
+ model: record.model,
15499
+ billing: billingOf(record.provider, plans),
15500
+ ...emptyTotals()
15501
+ };
15502
+ byModel.set(modelKey, modelTotals);
15503
+ }
15504
+ addRecord(modelTotals, record, plans);
15505
+ }
15506
+ }
15507
+ return {
15508
+ days: query.days,
15509
+ timeZone: query.timeZone,
15510
+ from,
15511
+ to,
15512
+ totals,
15513
+ byDay: [...days.values()].sort((a, b) => a.day.localeCompare(b.day)),
15514
+ byAgent: [...byAgent.values()].sort(bySpend),
15515
+ byTeam: [...byTeam.values()].sort(bySpend),
15516
+ byModel: [...byModel.values()].sort(bySpend),
15517
+ unreadable,
15518
+ scope: query.agentId ? {
15519
+ kind: "agent",
15520
+ id: query.agentId,
15521
+ name: agentById.get(query.agentId)?.name ?? query.agentId
15522
+ } : query.teamId ? {
15523
+ kind: "team",
15524
+ id: query.teamId,
15525
+ name: db.raw.query("SELECT name FROM teams WHERE id = ?").get(query.teamId)?.name ?? query.teamId
15526
+ } : null
15527
+ };
15528
+ }
15529
+ function conversationUsage2(paths, agentId, plans = ALWAYS_PLANS) {
15530
+ const usage = /* @__PURE__ */ new Map();
15531
+ for (const conversation of scanUsage(paths, [agentId]).conversations) {
15532
+ const totals = emptyTotals();
15533
+ for (const record of conversation.records) addRecord(totals, record, plans);
15534
+ usage.set(conversation.conversationId, {
15535
+ calls: totals.calls,
15536
+ totalTokens: totals.totalTokens,
15537
+ cost: totals.cost,
15538
+ estimated: totals.estimated,
15539
+ planTokens: totals.planTokens,
15540
+ localTokens: totals.localTokens
15541
+ });
15542
+ }
15543
+ return usage;
15544
+ }
15545
+
15546
+ // ../daemon/src/routes/conversations.ts
15547
+ var conversationsRouter = newRouter();
15548
+ var conversationSearchRouter = newRouter();
15549
+ conversationSearchRouter.get("/search", async (c) => {
15550
+ const { db, paths, authToken } = getCtx();
15551
+ const agent = c.req.query("agent");
15552
+ return c.json(
15553
+ await searchConversations(db, paths, {
15554
+ signal: c.req.raw.signal,
15555
+ query: c.req.query("q") ?? "",
15556
+ ...agent ? { agentId: routeAgentRef(agent).id } : {},
15557
+ limit: Number(c.req.query("limit") ?? 20) || 20,
15558
+ secrets: envSecretValues(mergeSecretsIntoEnv(db, authToken))
15559
+ })
15560
+ );
15561
+ });
15562
+ conversationsRouter.use("/:agentId/conversations/*", async (c, next) => {
15563
+ c.set("agentId", routeAgent(c, "agentId").id);
15564
+ await next();
15565
+ });
15566
+ conversationsRouter.get("/:agentId/conversations", (c) => {
15567
+ const { db, paths } = getCtx();
15568
+ const list13 = list11(
15569
+ db,
15570
+ c.get("agentId"),
15571
+ Number(c.req.query("limit") ?? 20),
15572
+ Number(c.req.query("offset") ?? 0)
15573
+ );
15574
+ const used = conversationUsage2(
15575
+ paths,
15576
+ c.get("agentId"),
15577
+ planProviders(mergeSecretsIntoEnv(db, getCtx().authToken))
15578
+ );
15579
+ const usage = {};
15580
+ for (const conversation of list13.conversations) {
15581
+ const found = used.get(conversation.id);
15582
+ if (found) usage[conversation.id] = found;
15583
+ }
15584
+ return c.json({ ...list13, usage });
15585
+ });
15586
+ conversationsRouter.post("/:agentId/conversations", async (c) => {
15587
+ const input = await jsonBody(c);
15588
+ const agentId = c.get("agentId");
15589
+ const { db, paths } = getCtx();
15590
+ return c.json(
15591
+ await runAgentLifecycleMutation(
15592
+ agentId,
15593
+ () => startConversation(db, paths, agentId, input?.title)
15594
+ )
15595
+ );
15596
+ });
15597
+ conversationsRouter.get("/:agentId/conversations/:id", (c) => {
15598
+ const { db, paths, authToken } = getCtx();
15599
+ const agentId = c.get("agentId");
15600
+ const id = c.req.param("id");
15601
+ const conversation = get16(db, agentId, id);
15602
+ if (!conversation) return c.json({ error: "Conversation not found" }, 404);
15603
+ try {
15604
+ const messages = piMessagesToProviderView(
15605
+ loadInitialMessages(resolveAgent(db, paths, agentId), paths, { id }),
15606
+ envSecretValues(mergeSecretsIntoEnv(db, authToken))
15607
+ );
15608
+ const usage = conversationUsage2(paths, agentId, planProviders(mergeSecretsIntoEnv(db, authToken))).get(
15609
+ id
15610
+ ) ?? null;
15611
+ return c.json({ conversation, messages, usage });
15612
+ } catch {
15613
+ return c.json(
14703
15614
  {
14704
15615
  error: "Conversation history is missing, corrupt or unavailable",
14705
15616
  conversation
@@ -14735,19 +15646,19 @@ conversationsRouter.patch("/:agentId/conversations/:id", async (c) => {
14735
15646
  import { streamSSE } from "hono/streaming";
14736
15647
 
14737
15648
  // ../daemon/src/lib/live.ts
14738
- import { createHash as createHash6 } from "node:crypto";
15649
+ import { createHash as createHash8 } from "node:crypto";
14739
15650
  var CHECK_MS = 1e3;
14740
15651
  var ATTENTION_EVERY = 5;
14741
15652
  var SETTLE_MS = 25;
14742
15653
  function readLiveActivity() {
14743
15654
  const { db, paths } = getCtx();
14744
- return { type: "activity", agents: readActivity(db, paths) };
15655
+ return { type: "activity", agents: readActivity(db, paths), roster: rosterRevision(db) };
14745
15656
  }
14746
15657
  function readLiveAttention() {
14747
15658
  const { db } = getCtx();
14748
15659
  const waiting = waitingAttention(db);
14749
15660
  const all = projectAttention(db, { state: "all", limit: 1e5 }, waiting);
14750
- const revision = createHash6("sha256").update(
15661
+ const revision = createHash8("sha256").update(
14751
15662
  all.items.map((item) => `${item.key}|${item.updatedAt}|${item.acknowledgedAt ?? ""}`).join("\n")
14752
15663
  ).update(JSON.stringify(all.degraded)).digest("hex").slice(0, 16);
14753
15664
  return {
@@ -15043,25 +15954,25 @@ agentMessagesRouter.post("/:id/messages", async (c) => {
15043
15954
  });
15044
15955
 
15045
15956
  // ../daemon/src/routes/misc.ts
15046
- import { existsSync as existsSync17 } from "node:fs";
15957
+ import { existsSync as existsSync18 } from "node:fs";
15047
15958
  import { homedir as homedir4 } from "node:os";
15048
- import { join as join32 } from "node:path";
15959
+ import { join as join35 } from "node:path";
15049
15960
 
15050
15961
  // ../daemon/src/lib/backup.ts
15051
- import { mkdtempSync as mkdtempSync3, rmSync as rmSync13 } from "node:fs";
15962
+ import { mkdtempSync as mkdtempSync3, rmSync as rmSync14 } from "node:fs";
15052
15963
  import { tmpdir as tmpdir3 } from "node:os";
15053
- import { join as join31, resolve as resolve7 } from "node:path";
15964
+ import { join as join34, resolve as resolve7 } from "node:path";
15054
15965
  import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
15055
15966
  import { create as create6 } from "tar";
15056
15967
 
15057
15968
  // ../daemon/src/lib/daemon-liveness.ts
15058
- import { mkdirSync as mkdirSync11, readFileSync as readFileSync11, rmSync as rmSync12, writeFileSync as writeFileSync10 } from "node:fs";
15059
- import { join as join30 } from "node:path";
15969
+ import { mkdirSync as mkdirSync11, readFileSync as readFileSync12, rmSync as rmSync13, writeFileSync as writeFileSync11 } from "node:fs";
15970
+ import { join as join33 } from "node:path";
15060
15971
  var DAEMON_PID_FILE = "daemon.pid";
15061
15972
  function runningDaemonPid(home) {
15062
15973
  let pid;
15063
15974
  try {
15064
- pid = Number.parseInt(readFileSync11(join30(home, DAEMON_PID_FILE), "utf8"), 10);
15975
+ pid = Number.parseInt(readFileSync12(join33(home, DAEMON_PID_FILE), "utf8"), 10);
15065
15976
  } catch (error) {
15066
15977
  if (error.code === "ENOENT") return null;
15067
15978
  throw error;
@@ -15078,26 +15989,26 @@ function assertDaemonStopped(home) {
15078
15989
  const pid = runningDaemonPid(home);
15079
15990
  if (pid !== null) {
15080
15991
  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)})`
15992
+ `a bazilion daemon (pid ${pid}) is running on ${home}; stop it first (if none is running, delete ${join33(home, DAEMON_PID_FILE)})`
15082
15993
  );
15083
15994
  }
15084
15995
  }
15085
15996
  function claimDaemonPidFile(home) {
15086
- const path = join30(home, DAEMON_PID_FILE);
15997
+ const path = join33(home, DAEMON_PID_FILE);
15087
15998
  const content = `${process.pid}
15088
15999
  `;
15089
16000
  mkdirSync11(home, { recursive: true });
15090
16001
  try {
15091
- writeFileSync10(path, content, { flag: "wx", mode: 384 });
16002
+ writeFileSync11(path, content, { flag: "wx", mode: 384 });
15092
16003
  } catch (error) {
15093
16004
  if (error.code !== "EEXIST") throw error;
15094
16005
  assertDaemonStopped(home);
15095
- rmSync12(path, { force: true });
15096
- writeFileSync10(path, content, { flag: "wx", mode: 384 });
16006
+ rmSync13(path, { force: true });
16007
+ writeFileSync11(path, content, { flag: "wx", mode: 384 });
15097
16008
  }
15098
16009
  return () => {
15099
16010
  try {
15100
- if (readFileSync11(path, "utf8") === content) rmSync12(path);
16011
+ if (readFileSync12(path, "utf8") === content) rmSync13(path);
15101
16012
  } catch {
15102
16013
  }
15103
16014
  };
@@ -15112,10 +16023,10 @@ function createBackupSnapshot(db) {
15112
16023
  return snapshot3;
15113
16024
  }
15114
16025
  async function takeSnapshot(db) {
15115
- const directory = mkdtempSync3(join31(tmpdir3(), "bazilion-backup-"));
15116
- const cleanup = () => rmSync13(directory, { recursive: true, force: true });
16026
+ const directory = mkdtempSync3(join34(tmpdir3(), "bazilion-backup-"));
16027
+ const cleanup = () => rmSync14(directory, { recursive: true, force: true });
15117
16028
  try {
15118
- const database = join31(directory, "bazilion.snapshot");
16029
+ const database = join34(directory, "bazilion.snapshot");
15119
16030
  await db.backupTo(database);
15120
16031
  const snapshot3 = new DatabaseSync2(database, { readOnly: true });
15121
16032
  try {
@@ -15163,12 +16074,12 @@ miscRouter.get("/health", (c) => {
15163
16074
  miscRouter.get("/health/details", async (c) => {
15164
16075
  const { paths } = getCtx();
15165
16076
  const pathChecks = {
15166
- home: existsSync17(paths.home),
15167
- db: existsSync17(paths.db),
15168
- auth: existsSync17(paths.authFile),
15169
- profiles: existsSync17(paths.profilesDir),
15170
- agents: existsSync17(paths.agentsDir),
15171
- skills: existsSync17(paths.skillsDir)
16077
+ home: existsSync18(paths.home),
16078
+ db: existsSync18(paths.db),
16079
+ auth: existsSync18(paths.authFile),
16080
+ profiles: existsSync18(paths.profilesDir),
16081
+ agents: existsSync18(paths.agentsDir),
16082
+ skills: existsSync18(paths.skillsDir)
15172
16083
  };
15173
16084
  let database = null;
15174
16085
  const triggersSection = { active: 0, disabled: 0 };
@@ -15214,7 +16125,7 @@ miscRouter.get("/health/details", async (c) => {
15214
16125
  } catch {
15215
16126
  }
15216
16127
  }
15217
- const openclawSkillsDir = join32(homedir4(), ".openclaw", "skills");
16128
+ const openclawSkillsDir = join35(homedir4(), ".openclaw", "skills");
15218
16129
  const providerSection = {
15219
16130
  // Hosted providers with credentials; local servers are reported below.
15220
16131
  configured: PROVIDERS.filter(
@@ -15264,7 +16175,7 @@ miscRouter.get("/health/details", async (c) => {
15264
16175
  },
15265
16176
  openclaw: {
15266
16177
  path: openclawSkillsDir,
15267
- exists: existsSync17(openclawSkillsDir)
16178
+ exists: existsSync18(openclawSkillsDir)
15268
16179
  },
15269
16180
  triggers: triggersSection,
15270
16181
  tokens: tokensSection,
@@ -15291,7 +16202,7 @@ function publicShellSecurityError(error) {
15291
16202
  }
15292
16203
  miscRouter.get("/backup", async (c) => {
15293
16204
  const { db, paths } = getCtx();
15294
- if (!existsSync17(paths.home)) {
16205
+ if (!existsSync18(paths.home)) {
15295
16206
  return c.json({ error: `bazilion home not found at ${paths.home}` }, 404);
15296
16207
  }
15297
16208
  let snapshot3;
@@ -15622,8 +16533,8 @@ notificationsRouter.put("/", async (c) => {
15622
16533
  });
15623
16534
 
15624
16535
  // ../daemon/src/routes/profiles.ts
15625
- import { existsSync as existsSync18, readFileSync as readFileSync12, writeFileSync as writeFileSync11 } from "node:fs";
15626
- import { join as join33 } from "node:path";
16536
+ import { existsSync as existsSync19, readFileSync as readFileSync13, writeFileSync as writeFileSync12 } from "node:fs";
16537
+ import { join as join36 } from "node:path";
15627
16538
  var profilesRouter = newRouter();
15628
16539
  profilesRouter.get("/", (c) => {
15629
16540
  const { db } = getCtx();
@@ -15705,20 +16616,20 @@ function profileFile(c) {
15705
16616
  if (!PROFILE_FILES.includes(file)) {
15706
16617
  return c.json({ error: `unsupported file: ${file}` }, 400);
15707
16618
  }
15708
- return join33(paths.profilesDir, id, file);
16619
+ return join36(paths.profilesDir, id, file);
15709
16620
  }
15710
16621
  profilesRouter.get("/:id/files/:file", (c) => {
15711
16622
  const path = profileFile(c);
15712
16623
  if (typeof path !== "string") return path;
15713
- if (!existsSync18(path)) return c.json({ error: `file not present: ${c.req.param("file")}` }, 404);
15714
- return c.json({ content: readFileSync12(path, "utf8") });
16624
+ if (!existsSync19(path)) return c.json({ error: `file not present: ${c.req.param("file")}` }, 404);
16625
+ return c.json({ content: readFileSync13(path, "utf8") });
15715
16626
  });
15716
16627
  profilesRouter.put("/:id/files/:file", async (c) => {
15717
16628
  const body = await jsonBody(c);
15718
16629
  if (typeof body?.content !== "string") return c.json({ error: "content is required" }, 400);
15719
16630
  const path = profileFile(c);
15720
16631
  if (typeof path !== "string") return path;
15721
- writeFileSync11(path, body.content);
16632
+ writeFileSync12(path, body.content);
15722
16633
  return c.body(null, 204);
15723
16634
  });
15724
16635
 
@@ -15759,11 +16670,11 @@ function dosDateTime(epochMs) {
15759
16670
  function uniqueNames(names) {
15760
16671
  const seen = /* @__PURE__ */ new Map();
15761
16672
  return names.map((name) => {
15762
- const count = (seen.get(name) ?? 0) + 1;
15763
- seen.set(name, count);
15764
- if (count === 1) return name;
16673
+ const count2 = (seen.get(name) ?? 0) + 1;
16674
+ seen.set(name, count2);
16675
+ if (count2 === 1) return name;
15765
16676
  const dot = name.lastIndexOf(".");
15766
- return dot > 0 ? `${name.slice(0, dot)} (${count})${name.slice(dot)}` : `${name} (${count})`;
16677
+ return dot > 0 ? `${name.slice(0, dot)} (${count2})${name.slice(dot)}` : `${name} (${count2})`;
15767
16678
  });
15768
16679
  }
15769
16680
  function localHeader(name, bytes, crc, epochMs) {
@@ -15926,13 +16837,33 @@ resultsRouter.get("/:id/preview", (c) => {
15926
16837
  const db = getCtx().db;
15927
16838
  const result = get17(db, c.req.param("id"));
15928
16839
  if (!result) return c.json({ error: "Result not found" }, 404);
15929
- const text4 = ["text/plain", "text/markdown"].includes(result.mimeType);
16840
+ const text4 = isTextPreview(result);
15930
16841
  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)) {
16842
+ if (!text4 && (!image || result.byteLength > 10 * 1024 * 1024)) {
15932
16843
  return c.json({ error: "Preview is unavailable for this file. Use Download." }, 415);
15933
16844
  }
16845
+ const bytesParam = Number(c.req.query("bytes"));
16846
+ const cut = text4 && Number.isInteger(bytesParam) && bytesParam > 0 ? bytesParam : null;
15934
16847
  try {
15935
16848
  const bytes = read(db, result.id);
16849
+ if (text4) {
16850
+ let shown;
16851
+ try {
16852
+ shown = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
16853
+ } catch {
16854
+ return c.json({ error: "This file is not text. Use Download." }, 415);
16855
+ }
16856
+ if (shown.includes("\0"))
16857
+ return c.json({ error: "This file is not text. Use Download." }, 415);
16858
+ if (cut !== null && Buffer.byteLength(shown) > cut) {
16859
+ shown = Buffer.from(shown).subarray(0, cut).toString("utf8").replace(/\uFFFD$/, "");
16860
+ }
16861
+ c.header("Content-Type", "text/plain; charset=utf-8");
16862
+ c.header("X-Content-Type-Options", "nosniff");
16863
+ c.header("Content-Security-Policy", "default-src 'none'; sandbox");
16864
+ c.header("Cache-Control", "private, max-age=3600");
16865
+ return c.body(shown);
16866
+ }
15936
16867
  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
16868
  if (image && !magic)
15938
16869
  return c.json({ error: "File content does not match its image type. Use Download." }, 415);
@@ -15968,9 +16899,9 @@ shellApprovalsRouter.post("/:id", async (c) => {
15968
16899
  });
15969
16900
 
15970
16901
  // ../daemon/src/routes/skills.ts
15971
- import { mkdtempSync as mkdtempSync4, rmSync as rmSync14, writeFileSync as writeFileSync12 } from "node:fs";
16902
+ import { mkdtempSync as mkdtempSync4, rmSync as rmSync15, writeFileSync as writeFileSync13 } from "node:fs";
15972
16903
  import { homedir as homedir5, tmpdir as tmpdir4 } from "node:os";
15973
- import { join as join34 } from "node:path";
16904
+ import { join as join37 } from "node:path";
15974
16905
  var MAX_ZIP_BYTES = 50 * 1024 * 1024;
15975
16906
  var skillsRouter = newRouter();
15976
16907
  skillsRouter.get("/", (c) => {
@@ -16000,7 +16931,7 @@ skillsRouter.delete("/:name", (c) => {
16000
16931
  const name = c.req.param("name");
16001
16932
  const skill = discoverSkills(paths).find((s) => s.name === name);
16002
16933
  if (!skill) return c.json({ error: `skill not found: ${name}` }, 404);
16003
- rmSync14(skill.dir, { recursive: true, force: true });
16934
+ rmSync15(skill.dir, { recursive: true, force: true });
16004
16935
  skillMeta_exports.remove(db, name);
16005
16936
  return c.body(null, 204);
16006
16937
  });
@@ -16037,7 +16968,7 @@ skillsRouter.post("/import", async (c) => {
16037
16968
  }
16038
16969
  return c.json({ error: err.message }, 400);
16039
16970
  } finally {
16040
- if (input.tempZipPath) rmSync14(input.tempZipPath, { recursive: true, force: true });
16971
+ if (input.tempZipPath) rmSync15(input.tempZipPath, { recursive: true, force: true });
16041
16972
  }
16042
16973
  });
16043
16974
  function flattenFindings(findings) {
@@ -16063,10 +16994,10 @@ async function parseImportInput(request) {
16063
16994
  if (!filename.toLowerCase().endsWith(".zip")) {
16064
16995
  throw new Error("uploaded file must be a .zip archive");
16065
16996
  }
16066
- const tmpDir = mkdtempSync4(join34(tmpdir4(), "bazilion-skill-upload-"));
16067
- const zipPath = join34(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
16997
+ const tmpDir = mkdtempSync4(join37(tmpdir4(), "bazilion-skill-upload-"));
16998
+ const zipPath = join37(tmpDir, filename.replace(/[^\w.-]+/g, "_"));
16068
16999
  const buf = Buffer.from(await file.arrayBuffer());
16069
- writeFileSync12(zipPath, buf);
17000
+ writeFileSync13(zipPath, buf);
16070
17001
  const forceField = form.get("force");
16071
17002
  return {
16072
17003
  source: zipPath,
@@ -16080,7 +17011,7 @@ async function parseImportInput(request) {
16080
17011
  const { source } = body;
16081
17012
  if (typeof source !== "string" || !source) throw new Error("source is required");
16082
17013
  return {
16083
- source: source === "openclaw" ? join34(homedir5(), ".openclaw", "skills") : source,
17014
+ source: source === "openclaw" ? join37(homedir5(), ".openclaw", "skills") : source,
16084
17015
  force: Boolean(body.force),
16085
17016
  tempZipPath: null,
16086
17017
  sourceLabel: source
@@ -16150,7 +17081,7 @@ teamCodingEnvironmentRouter.put("/:id/coding-environment", async (c) => {
16150
17081
  });
16151
17082
 
16152
17083
  // ../daemon/src/routes/team-memory.ts
16153
- import { join as join35 } from "node:path";
17084
+ import { join as join38 } from "node:path";
16154
17085
  var teamMemoryRouter = newRouter();
16155
17086
  teamMemoryRouter.onError((error, c) => {
16156
17087
  const safe = sanitizeNativeModuleError(error, { subject: "Bazilion memory" });
@@ -16158,7 +17089,7 @@ teamMemoryRouter.onError((error, c) => {
16158
17089
  return onRouteError(safe, c);
16159
17090
  });
16160
17091
  async function openMemory(c) {
16161
- const mem = qmdBackend(join35(routeTeam(c).path, "memory"));
17092
+ const mem = qmdBackend(join38(routeTeam(c).path, "memory"));
16162
17093
  await mem.init();
16163
17094
  return mem;
16164
17095
  }
@@ -16213,19 +17144,19 @@ teamPolicyRouter.post("/:id/policy/save-as-template", async (c) => {
16213
17144
  });
16214
17145
 
16215
17146
  // ../daemon/src/lib/git/context-directory.ts
16216
- import { createHash as createHash7 } from "node:crypto";
17147
+ import { createHash as createHash9 } from "node:crypto";
16217
17148
  import {
16218
- closeSync as closeSync6,
16219
- constants as constants7,
16220
- fstatSync as fstatSync6,
17149
+ closeSync as closeSync7,
17150
+ constants as constants8,
17151
+ fstatSync as fstatSync7,
16221
17152
  lstatSync as lstatSync6,
16222
17153
  opendirSync,
16223
- openSync as openSync6,
16224
- readSync as readSync3,
17154
+ openSync as openSync7,
17155
+ readSync as readSync4,
16225
17156
  realpathSync as realpathSync7
16226
17157
  } from "node:fs";
16227
- import { join as join36 } from "node:path";
16228
- var hash = (value) => createHash7("sha256").update(value).digest("hex");
17158
+ import { join as join39 } from "node:path";
17159
+ var hash = (value) => createHash9("sha256").update(value).digest("hex");
16229
17160
  var ContextReadError = class extends Error {
16230
17161
  code;
16231
17162
  constructor(code) {
@@ -16262,22 +17193,22 @@ var ContextDirectory = class _ContextDirectory {
16262
17193
  this.parent = parent;
16263
17194
  if (parent) component(registeredPath);
16264
17195
  parent?.assertOpen();
16265
- const canonicalPath = parent ? join36(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
17196
+ const canonicalPath = parent ? join39(parent.canonicalPath, registeredPath) : realpathSync7(registeredPath);
16266
17197
  this.canonicalPath = canonicalPath;
16267
17198
  let fd;
16268
17199
  try {
16269
- fd = openSync6(
16270
- parent ? join36(parent.path, registeredPath) : canonicalPath,
16271
- constants7.O_RDONLY | constants7.O_DIRECTORY | constants7.O_NOFOLLOW
17200
+ fd = openSync7(
17201
+ parent ? join39(parent.path, registeredPath) : canonicalPath,
17202
+ constants8.O_RDONLY | constants8.O_DIRECTORY | constants8.O_NOFOLLOW
16272
17203
  );
16273
- const stat = fstatSync6(fd, { bigint: true });
17204
+ const stat = fstatSync7(fd, { bigint: true });
16274
17205
  if (!stat.isDirectory() || stat.ino <= 0n) throw new ContextReadError("root_changed");
16275
17206
  this.fd = fd;
16276
17207
  this.originalIdentity = { dev: stat.dev, ino: stat.ino };
16277
17208
  this.identity = hash(identity(stat));
16278
17209
  fd = void 0;
16279
17210
  } finally {
16280
- if (fd !== void 0) closeSync6(fd);
17211
+ if (fd !== void 0) closeSync7(fd);
16281
17212
  }
16282
17213
  }
16283
17214
  get path() {
@@ -16316,7 +17247,7 @@ var ContextDirectory = class _ContextDirectory {
16316
17247
  entry(name) {
16317
17248
  component(name);
16318
17249
  this.assertOpen();
16319
- const path = join36(this.path, name);
17250
+ const path = join39(this.path, name);
16320
17251
  try {
16321
17252
  return lstatSync6(path);
16322
17253
  } catch (error) {
@@ -16325,7 +17256,7 @@ var ContextDirectory = class _ContextDirectory {
16325
17256
  }
16326
17257
  }
16327
17258
  observe(name) {
16328
- const path = join36(this.path, name);
17259
+ const path = join39(this.path, name);
16329
17260
  try {
16330
17261
  return lstatSync6(path, { bigint: true });
16331
17262
  } catch (error) {
@@ -16367,21 +17298,21 @@ var ContextDirectory = class _ContextDirectory {
16367
17298
  if (entry.size > maxBytes) throw new ContextReadError("byte_limit");
16368
17299
  let fd;
16369
17300
  try {
16370
- fd = openSync6(
16371
- join36(this.path, name),
16372
- constants7.O_RDONLY | constants7.O_NOFOLLOW | constants7.O_NONBLOCK
17301
+ fd = openSync7(
17302
+ join39(this.path, name),
17303
+ constants8.O_RDONLY | constants8.O_NOFOLLOW | constants8.O_NONBLOCK
16373
17304
  );
16374
- const before = fstatSync6(fd, { bigint: true });
17305
+ const before = fstatSync7(fd, { bigint: true });
16375
17306
  if (!before.isFile() || stamp(entry) !== stamp(before))
16376
17307
  throw new ContextReadError("source_changed");
16377
17308
  const buffer = Buffer.alloc(Math.min(maxBytes, Number(before.size)) + 1);
16378
17309
  let size = 0;
16379
17310
  while (size < buffer.length) {
16380
- const count = readSync3(fd, buffer, size, buffer.length - size, null);
16381
- if (!count) break;
16382
- size += count;
17311
+ const count2 = readSync4(fd, buffer, size, buffer.length - size, null);
17312
+ if (!count2) break;
17313
+ size += count2;
16383
17314
  }
16384
- if (size > maxBytes || BigInt(size) !== before.size || stamp(fstatSync6(fd, { bigint: true })) !== stamp(before))
17315
+ if (size > maxBytes || BigInt(size) !== before.size || stamp(fstatSync7(fd, { bigint: true })) !== stamp(before))
16385
17316
  throw new ContextReadError("source_changed");
16386
17317
  if (!FD_PATHS) this.checkedPath();
16387
17318
  this.observedFiles.set(name, stamp(before));
@@ -16390,16 +17321,16 @@ var ContextDirectory = class _ContextDirectory {
16390
17321
  if (error instanceof ContextReadError) throw error;
16391
17322
  throw new ContextReadError("unreadable");
16392
17323
  } finally {
16393
- if (fd !== void 0) closeSync6(fd);
17324
+ if (fd !== void 0) closeSync7(fd);
16394
17325
  }
16395
17326
  }
16396
17327
  validate(skipGit = false, names) {
16397
17328
  this.assertOpen();
16398
- const currentPath = this.parent ? join36(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
17329
+ const currentPath = this.parent ? join39(this.parent.path, this.registeredPath) : realpathSync7(this.registeredPath);
16399
17330
  const stat = lstatSync6(currentPath, { bigint: true });
16400
17331
  if (!stat.isDirectory() || identity(stat) !== identity(this.originalIdentity))
16401
17332
  throw new ContextReadError("root_changed");
16402
- const retained = fstatSync6(this.fd, { bigint: true });
17333
+ const retained = fstatSync7(this.fd, { bigint: true });
16403
17334
  if (!retained.isDirectory() || identity(retained) !== identity(this.originalIdentity))
16404
17335
  throw new ContextReadError("root_changed");
16405
17336
  if (this.listing !== void 0 && JSON.stringify(this.listNames()) !== this.listing)
@@ -16426,7 +17357,7 @@ var ContextDirectory = class _ContextDirectory {
16426
17357
  }
16427
17358
  }
16428
17359
  try {
16429
- closeSync6(this.fd);
17360
+ closeSync7(this.fd);
16430
17361
  } catch (error) {
16431
17362
  failure ??= error;
16432
17363
  }
@@ -16503,18 +17434,18 @@ async function listChanges(captured, base, identity2, limits = REVIEW_LIMITS) {
16503
17434
  for (const header of parseRaw(raw)) {
16504
17435
  const scoped = reviewScope(header.path);
16505
17436
  if (!scoped.included) excludedTracked++;
16506
- const count = counts.get(header.path) ?? null;
17437
+ const count2 = counts.get(header.path) ?? null;
16507
17438
  entries.push({
16508
17439
  path: header.path,
16509
17440
  previousPath: header.previousPath,
16510
17441
  status: header.status,
16511
- binary: count?.binary ?? false,
16512
- addedLines: count?.added ?? null,
16513
- deletedLines: count?.deleted ?? null,
17442
+ binary: count2?.binary ?? false,
17443
+ addedLines: count2?.added ?? null,
17444
+ deletedLines: count2?.deleted ?? null,
16514
17445
  patch: null,
16515
17446
  patchTruncated: false,
16516
17447
  // A credential-shaped or Bazilion-owned tracked file may be listed, but never captured.
16517
- contentOmitted: scoped.included ? count?.binary ? "binary" : null : "excluded",
17448
+ contentOmitted: scoped.included ? count2?.binary ? "binary" : null : "excluded",
16518
17449
  excludedReason: scoped.included ? null : scoped.reason
16519
17450
  });
16520
17451
  }
@@ -16821,9 +17752,9 @@ async function readOrNull(captured, args) {
16821
17752
 
16822
17753
  // ../daemon/src/lib/git/capture.ts
16823
17754
  import { execFile } from "node:child_process";
16824
- import { mkdirSync as mkdirSync12, mkdtempSync as mkdtempSync5, rmSync as rmSync15, utimesSync, writeFileSync as writeFileSync13 } from "node:fs";
17755
+ import { mkdirSync as mkdirSync12, mkdtempSync as mkdtempSync5, rmSync as rmSync16, utimesSync, writeFileSync as writeFileSync14 } from "node:fs";
16825
17756
  import { tmpdir as tmpdir5 } from "node:os";
16826
- import { join as join37 } from "node:path";
17757
+ import { join as join40 } from "node:path";
16827
17758
  var INSPECTION_BUDGET_MS = 5e3;
16828
17759
  var METADATA_BUDGET_MS = 2500;
16829
17760
  var METADATA_BYTES = 64 * 1024 * 1024;
@@ -16839,7 +17770,7 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16839
17770
  const worktree = root.gitWorktreePath;
16840
17771
  const start2 = Date.now();
16841
17772
  let bytes = 0;
16842
- let count = 0;
17773
+ let count2 = 0;
16843
17774
  const marker = root.entry(".git");
16844
17775
  if (!marker?.isDirectory() || marker.isSymbolicLink())
16845
17776
  throw new ContextReadError("unsupported_git_metadata");
@@ -16852,12 +17783,12 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16852
17783
  const dir = git.directory("info");
16853
17784
  if (dir.entry("sparse-checkout")) throw new ContextReadError("unsupported_git_metadata");
16854
17785
  }
16855
- const scratch = mkdtempSync5(join37(tmpdir5(), "bazilion-context-git-"));
17786
+ const scratch = mkdtempSync5(join40(tmpdir5(), "bazilion-context-git-"));
16856
17787
  let cleaned = false;
16857
17788
  const cleanup = () => {
16858
17789
  if (cleaned) return;
16859
17790
  cleaned = true;
16860
- rmSync15(scratch, { recursive: true, force: true });
17791
+ rmSync16(scratch, { recursive: true, force: true });
16861
17792
  };
16862
17793
  const checkBudget = () => {
16863
17794
  if (Date.now() - start2 >= budgetMs) throw new ContextReadError("git_timeout");
@@ -16912,9 +17843,9 @@ async function captureRepositoryGit(root, budgetMs = INSPECTION_BUDGET_MS) {
16912
17843
  const configLines = ["[core]", "repositoryformatversion = 0", "bare = false", "filemode = true"];
16913
17844
  if (capturedConfig) {
16914
17845
  bytes += capturedConfig.length;
16915
- count++;
16916
- const configPath = join37(scratch, "captured-config");
16917
- writeFileSync13(configPath, capturedConfig, { mode: 384 });
17846
+ count2++;
17847
+ const configPath = join40(scratch, "captured-config");
17848
+ writeFileSync14(configPath, capturedConfig, { mode: 384 });
16918
17849
  const config = await rawGit([
16919
17850
  "config",
16920
17851
  "--no-includes",
@@ -16966,27 +17897,27 @@ objectformat = ${value}`
16966
17897
  const exclude = git.directory("info").read("exclude", METADATA_READ);
16967
17898
  if (exclude) {
16968
17899
  bytes += exclude.length;
16969
- mkdirSync12(join37(scratch, "info"), { mode: 448 });
16970
- writeFileSync13(join37(scratch, "info", "exclude"), exclude, { mode: 384 });
17900
+ mkdirSync12(join40(scratch, "info"), { mode: 448 });
17901
+ writeFileSync14(join40(scratch, "info", "exclude"), exclude, { mode: 384 });
16971
17902
  }
16972
17903
  }
16973
17904
  const copy = (source, destination, depth) => {
16974
17905
  if (depth > METADATA_DEPTH) throw new ContextReadError("git_metadata_limit");
16975
17906
  for (const name of source.list()) {
16976
- if (++count > METADATA_ENTRIES || Date.now() - start2 > METADATA_BUDGET_MS)
17907
+ if (++count2 > METADATA_ENTRIES || Date.now() - start2 > METADATA_BUDGET_MS)
16977
17908
  throw new ContextReadError("git_metadata_limit");
16978
17909
  const entry = source.entry(name);
16979
17910
  if (!entry || entry.isSymbolicLink()) throw new ContextReadError("unsupported_git_metadata");
16980
17911
  if (name === "alternates" || name === "http-alternates")
16981
17912
  throw new ContextReadError("unsupported_git_metadata");
16982
17913
  if (entry.isDirectory()) {
16983
- mkdirSync12(join37(destination, name), { mode: 448 });
16984
- copy(source.directory(name), join37(destination, name), depth + 1);
17914
+ mkdirSync12(join40(destination, name), { mode: 448 });
17915
+ copy(source.directory(name), join40(destination, name), depth + 1);
16985
17916
  } else {
16986
17917
  const content = source.read(name, METADATA_BYTES - bytes);
16987
17918
  if (!content) throw new ContextReadError("source_changed");
16988
17919
  bytes += content.length;
16989
- writeFileSync13(join37(destination, name), content, { mode: 384 });
17920
+ writeFileSync14(join40(destination, name), content, { mode: 384 });
16990
17921
  }
16991
17922
  }
16992
17923
  };
@@ -16994,22 +17925,22 @@ objectformat = ${value}`
16994
17925
  const written = name === "index" ? git.entry(name) : null;
16995
17926
  const content = git.read(name, Math.min(METADATA_READ_LARGE, METADATA_BYTES - bytes));
16996
17927
  if (content) {
16997
- count++;
17928
+ count2++;
16998
17929
  bytes += content.length;
16999
- writeFileSync13(join37(scratch, name), content, { mode: 384 });
17930
+ writeFileSync14(join40(scratch, name), content, { mode: 384 });
17000
17931
  if (written) {
17001
17932
  const seconds = Math.floor(written.mtimeMs / 1e3);
17002
- utimesSync(join37(scratch, name), seconds, seconds);
17933
+ utimesSync(join40(scratch, name), seconds, seconds);
17003
17934
  }
17004
17935
  }
17005
17936
  }
17006
17937
  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);
17938
+ mkdirSync12(join40(scratch, name), { mode: 448 });
17939
+ if (git.entry(name)) copy(git.directory(name), join40(scratch, name), 0);
17009
17940
  }
17010
17941
  if (git.list().some((name) => name.startsWith("sharedindex.")))
17011
17942
  throw new ContextReadError("unsupported_git_metadata");
17012
- writeFileSync13(join37(scratch, "config"), `${configLines.join("\n")}
17943
+ writeFileSync14(join40(scratch, "config"), `${configLines.join("\n")}
17013
17944
  `, { mode: 384 });
17014
17945
  const validate2 = () => git.validate();
17015
17946
  validate2();
@@ -17022,7 +17953,7 @@ objectformat = ${value}`
17022
17953
 
17023
17954
  // ../daemon/src/lib/git-review/authors.ts
17024
17955
  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";
17956
+ import { isAbsolute as isAbsolute8, join as join41, relative as relative5, resolve as resolve8, sep as sep6 } from "node:path";
17026
17957
  var FILE_TOOLS = /* @__PURE__ */ new Set(["write", "edit"]);
17027
17958
  var CONVERSATIONS_PER_AGENT = 5;
17028
17959
  var SANDBOX_ROOT = "/workspace";
@@ -17047,7 +17978,7 @@ function readChangeAuthors(db, paths, team, changedPaths) {
17047
17978
  }
17048
17979
  const members = list(db, { includeArchived: true }).filter((agent) => agent.teamId === team.id);
17049
17980
  for (const agent of members) {
17050
- const directory = join38(paths.agentDir(agent.id), "sessions");
17981
+ const directory = join41(paths.agentDir(agent.id), "sessions");
17051
17982
  const recent = list11(db, agent.id, CONVERSATIONS_PER_AGENT, 0).conversations;
17052
17983
  for (const conversation of recent) {
17053
17984
  let lines;
@@ -17093,8 +18024,10 @@ function readChangeAuthors(db, paths, team, changedPaths) {
17093
18024
 
17094
18025
  // ../daemon/src/lib/git-review/service.ts
17095
18026
  var ReviewUnavailableError = class extends DomainError {
17096
- constructor(code, message) {
17097
- super(409, message, code);
18027
+ reason;
18028
+ constructor(reason, message) {
18029
+ super(409, message, reason);
18030
+ this.reason = reason;
17098
18031
  }
17099
18032
  };
17100
18033
  function requireTeam(db, paths, teamId) {
@@ -17137,12 +18070,18 @@ async function withRepository(teamDir, fn) {
17137
18070
  }
17138
18071
  async function readTeamReview(db, paths, teamId, input = {}) {
17139
18072
  const team = requireTeam(db, paths, teamId);
17140
- const changes = await withRepository(team.path, async (captured) => {
17141
- const base = await resolveComparisonBase(captured, input.base ?? "HEAD");
17142
- const identity2 = await readRepositoryIdentity(captured);
17143
- const listed = await listChanges(captured, base, identity2, input.limits);
17144
- return input.patches ? attachPatches(captured, listed, input.limits, input.patchPath) : listed;
17145
- });
18073
+ let changes;
18074
+ try {
18075
+ changes = await withRepository(team.path, async (captured) => {
18076
+ const base = await resolveComparisonBase(captured, input.base ?? "HEAD");
18077
+ const identity2 = await readRepositoryIdentity(captured);
18078
+ const listed = await listChanges(captured, base, identity2, input.limits);
18079
+ return input.patches ? attachPatches(captured, listed, input.limits, input.patchPath) : listed;
18080
+ });
18081
+ } catch (error) {
18082
+ if (!(error instanceof ReviewUnavailableError)) throw error;
18083
+ return { teamId: team.id, unavailable: { code: error.reason, message: error.message } };
18084
+ }
17146
18085
  if (!input.authors) return { teamId: team.id, changes };
17147
18086
  const changedPaths = changes.changes.map((change) => change.path);
17148
18087
  return {
@@ -17188,8 +18127,8 @@ function hunkForLine(patch, line) {
17188
18127
  const header = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(lines[start2] ?? "");
17189
18128
  if (!header) continue;
17190
18129
  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;
18130
+ const count2 = header[2] === void 0 ? 1 : Number(header[2]);
18131
+ if (line < first || line >= first + Math.max(count2, 1)) continue;
17193
18132
  return lines.slice(start2, starts[position + 1] ?? lines.length).join("\n");
17194
18133
  }
17195
18134
  return null;
@@ -17847,8 +18786,8 @@ Run <code>/talk ${htmlEscape(agent.name)}</code> after fixing the underlying iss
17847
18786
  };
17848
18787
  }
17849
18788
  function autoName(ctx, profile) {
17850
- const count = agents_exports.countByProfile(ctx.db, profile.id);
17851
- return `${profile.id}-${count + 1}`;
18789
+ const count2 = agents_exports.countByProfile(ctx.db, profile.id);
18790
+ return `${profile.id}-${count2 + 1}`;
17852
18791
  }
17853
18792
 
17854
18793
  // ../daemon/src/lib/telegram/commands/spawn-team.ts
@@ -17968,9 +18907,9 @@ var handle9 = async (ctx) => {
17968
18907
  }
17969
18908
  const lines = ["<b>bazilion teams</b>", ""];
17970
18909
  for (const g of teams) {
17971
- const count = agents_exports.countByTeam(ctx.db, g.id);
18910
+ const count2 = agents_exports.countByTeam(ctx.db, g.id);
17972
18911
  const label = `<code>${htmlEscape(g.id)}</code> \xB7 ${htmlEscape(g.name)}`;
17973
- lines.push(`${label} \u2014 ${count} agent${count === 1 ? "" : "s"}`);
18912
+ lines.push(`${label} \u2014 ${count2} agent${count2 === 1 ? "" : "s"}`);
17974
18913
  }
17975
18914
  return { text: lines.join("\n"), parseMode: "HTML" };
17976
18915
  };
@@ -19170,10 +20109,7 @@ function parseCron(expr) {
19170
20109
  };
19171
20110
  return parsed;
19172
20111
  }
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;
20112
+ function dayMatches(parsed, date) {
19177
20113
  const domMatch = parsed.dom.has(date.getDate());
19178
20114
  const dowMatch = parsed.dow.has(date.getDay());
19179
20115
  if (parsed.domRestricted && parsed.dowRestricted) {
@@ -19183,218 +20119,66 @@ function matchesCron(parsed, date) {
19183
20119
  if (parsed.dowRestricted) return dowMatch;
19184
20120
  return true;
19185
20121
  }
20122
+ function matchesCron(parsed, date) {
20123
+ if (!parsed.minute.has(date.getMinutes())) return false;
20124
+ if (!parsed.hour.has(date.getHours())) return false;
20125
+ if (!parsed.month.has(date.getMonth() + 1)) return false;
20126
+ return dayMatches(parsed, date);
20127
+ }
20128
+ var LOOKAHEAD_YEARS = 5;
20129
+ function nextCronMatch(parsed, from) {
20130
+ const date = new Date(Math.ceil(from / 6e4) * 6e4);
20131
+ const limit = new Date(date);
20132
+ limit.setFullYear(limit.getFullYear() + LOOKAHEAD_YEARS);
20133
+ while (date <= limit) {
20134
+ if (!parsed.month.has(date.getMonth() + 1)) {
20135
+ date.setMonth(date.getMonth() + 1, 1);
20136
+ date.setHours(0, 0, 0, 0);
20137
+ } else if (!dayMatches(parsed, date)) {
20138
+ date.setDate(date.getDate() + 1);
20139
+ date.setHours(0, 0, 0, 0);
20140
+ } else if (!parsed.hour.has(date.getHours())) {
20141
+ date.setHours(date.getHours() + 1, 0, 0, 0);
20142
+ } else if (!parsed.minute.has(date.getMinutes())) {
20143
+ date.setTime(date.getTime() + 6e4);
20144
+ } else {
20145
+ return date.getTime();
20146
+ }
20147
+ }
20148
+ return null;
20149
+ }
19186
20150
  function validateCron(expr) {
19187
20151
  parseCron(expr);
19188
20152
  }
19189
20153
 
19190
- // ../daemon/src/routes/triggers.ts
19191
- var triggersRouter = newRouter();
19192
- function triggerExists(id) {
19193
- return triggers_exports.get(getCtx().db, id) !== null;
19194
- }
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);
20154
+ // ../daemon/src/lib/review-provider.ts
20155
+ function reviewEndpoint(providerName, env) {
20156
+ const raw = providerEndpoint(providerName, env);
20157
+ if (!raw) return void 0;
20158
+ let url;
20159
+ try {
20160
+ url = new URL(raw);
20161
+ } catch {
20162
+ throw new ExecutionUnavailableError("Provider endpoint is invalid.");
19201
20163
  }
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);
20164
+ if (url.username || url.password || url.hash) {
20165
+ throw new ExecutionUnavailableError("Provider endpoint contains unsafe URL fields.");
19238
20166
  }
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);
20167
+ if (!findProvider(providerName)?.local && url.protocol !== "https:") {
20168
+ throw new ExecutionUnavailableError("Credential-bearing provider endpoints require HTTPS.");
19255
20169
  }
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
- );
20170
+ return url.toString().replace(/\/$/, "");
20171
+ }
20172
+ function explicitCredentialEnv(providerName, env) {
20173
+ const values = providerCredentialEnv(providerName, env) ?? {};
20174
+ if (providerName === "bedrock") {
20175
+ delete values.AWS_PROFILE;
20176
+ const bearer = values.AWS_BEARER_TOKEN_BEDROCK;
20177
+ const staticPair = values.AWS_ACCESS_KEY_ID && values.AWS_SECRET_ACCESS_KEY;
20178
+ if (!bearer && !staticPair) {
20179
+ throw new ExecutionUnavailableError(
20180
+ "Bedrock learning reviews require an explicit bearer token or static key pair; AWS profiles are not read by the reviewer."
20181
+ );
19398
20182
  }
19399
20183
  }
19400
20184
  if (providerName === "google-vertex") {
@@ -19647,6 +20431,23 @@ function isDue(t, now, cronCache) {
19647
20431
  }
19648
20432
  return false;
19649
20433
  }
20434
+ function nextRunAt(t, now = Date.now()) {
20435
+ if (!t.enabled) return null;
20436
+ if (t.kind === "interval") {
20437
+ const every = (t.intervalSec ?? 0) * 1e3;
20438
+ if (every <= 0) return null;
20439
+ return Math.max((t.lastFiredAt ?? t.createdAt) + every, now);
20440
+ }
20441
+ if (!t.cronExpr) return null;
20442
+ let parsed;
20443
+ try {
20444
+ parsed = parseCron(t.cronExpr);
20445
+ } catch {
20446
+ return null;
20447
+ }
20448
+ const from = t.lastFiredAt && floorToMinute(t.lastFiredAt) === floorToMinute(now) ? floorToMinute(now) + 6e4 : floorToMinute(now);
20449
+ return nextCronMatch(parsed, from);
20450
+ }
19650
20451
  function scheduledOccurrence(t, now) {
19651
20452
  if (t.kind === "cron") return floorToMinute(now);
19652
20453
  const baseline = t.lastFiredAt ?? t.createdAt;
@@ -19729,9 +20530,9 @@ function decodeText2(payload) {
19729
20530
  }
19730
20531
  return payload;
19731
20532
  }
19732
- var INBOX_WAKE_PREFIX = "[[bazilion:inbox-wake]]\n";
20533
+ var INBOX_WAKE_PREFIX2 = "[[bazilion:inbox-wake]]\n";
19733
20534
  function buildInboxPrompt(agentId, messages, fromNames) {
19734
- const lines = [INBOX_WAKE_PREFIX.trimEnd()];
20535
+ const lines = [INBOX_WAKE_PREFIX2.trimEnd()];
19735
20536
  lines.push(
19736
20537
  `You have ${messages.length} new message${messages.length === 1 ? "" : "s"} in your inbox:`
19737
20538
  );
@@ -19817,12 +20618,26 @@ async function fireInboxWake(agentId) {
19817
20618
  }
19818
20619
  turnStarted = true;
19819
20620
  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
- );
20621
+ if (forgetTurnFailure(`inbox-start:${agentId}`)) signalLiveChange();
20622
+ let failure = null;
20623
+ try {
20624
+ for await (const frame of runAgentTurn(preparedTurn)) {
20625
+ const frameFailure = turnFrameFailure(frame);
20626
+ if (frameFailure) failure ??= turnFailureReason(frameFailure);
19825
20627
  }
20628
+ } catch (error) {
20629
+ failure ??= turnFailureReason(error);
20630
+ }
20631
+ if (failure && !controller.signal.aborted) {
20632
+ console.warn(JSON.stringify({ event: "inbox_wake_failed", agentId, failure: "turn_failed" }));
20633
+ rememberTurnFailure({
20634
+ id: attemptId,
20635
+ agentId,
20636
+ origin: "inbox",
20637
+ at: Date.now(),
20638
+ reason: failure
20639
+ });
20640
+ signalLiveChange();
19826
20641
  }
19827
20642
  } catch (err) {
19828
20643
  if (!handoffStarted && registered) unregisterAgent(agentId);
@@ -19830,6 +20645,14 @@ async function fireInboxWake(agentId) {
19830
20645
  if (!turnStarted) {
19831
20646
  retryInMs = backoff ? Math.min(backoff.delayMs * 2, INBOX_RETRY_MAX_MS) : INBOX_RETRY_BASE_MS;
19832
20647
  s.inboxBackoff.set(agentId, { delayMs: retryInMs, nextAttemptAt: Date.now() + retryInMs });
20648
+ rememberTurnFailure({
20649
+ id: `inbox-start:${agentId}`,
20650
+ agentId,
20651
+ origin: "inbox",
20652
+ at: Date.now(),
20653
+ reason: turnFailureReason(err)
20654
+ });
20655
+ signalLiveChange();
19833
20656
  }
19834
20657
  console.warn(
19835
20658
  JSON.stringify({
@@ -19930,7 +20753,217 @@ function stopScheduler() {
19930
20753
  return s.stopPromise;
19931
20754
  }
19932
20755
 
20756
+ // ../daemon/src/routes/triggers.ts
20757
+ var triggersRouter = newRouter();
20758
+ function triggerExists(id) {
20759
+ return triggers_exports.get(getCtx().db, id) !== null;
20760
+ }
20761
+ triggersRouter.get("/:id/dispatches", (c) => {
20762
+ const id = c.req.param("id");
20763
+ if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
20764
+ const requestedLimit = Number(c.req.query("limit") ?? 20);
20765
+ if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
20766
+ return c.json({ error: "limit must be a positive integer" }, 400);
20767
+ }
20768
+ const limit = Math.min(100, requestedLimit);
20769
+ return c.json({
20770
+ dispatches: triggerDispatches_exports.listForTrigger(getCtx().db, id, limit)
20771
+ });
20772
+ });
20773
+ triggersRouter.delete("/:id", (c) => {
20774
+ const id = c.req.param("id");
20775
+ if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
20776
+ triggers_exports.remove(getCtx().db, id);
20777
+ return c.body(null, 204);
20778
+ });
20779
+ triggersRouter.patch("/:id", async (c) => {
20780
+ const id = c.req.param("id");
20781
+ const body = await jsonBody(c);
20782
+ if (!body) return c.json({ error: "invalid JSON body" }, 400);
20783
+ if (!triggerExists(id)) return c.json({ error: `trigger not found: ${id}` }, 404);
20784
+ const { db } = getCtx();
20785
+ if (typeof body.enabled === "boolean") triggers_exports.setEnabled(db, id, body.enabled);
20786
+ return c.json({ trigger: triggers_exports.get(db, id) });
20787
+ });
20788
+ var agentTriggersRouter = newRouter();
20789
+ agentTriggersRouter.get("/:id/triggers", (c) => {
20790
+ const { db } = getCtx();
20791
+ const triggers = triggers_exports.listForAgent(db, routeAgent(c).id);
20792
+ const schedulerOff = process.env.BAZILION_SCHEDULER === "off";
20793
+ const now = Date.now();
20794
+ return c.json({
20795
+ triggers,
20796
+ dispatches: triggers.flatMap(
20797
+ (trigger) => triggerDispatches_exports.listForTrigger(db, trigger.id, 10)
20798
+ ),
20799
+ nextRuns: Object.fromEntries(
20800
+ triggers.map((trigger) => [trigger.id, schedulerOff ? null : nextRunAt(trigger, now)])
20801
+ ),
20802
+ schedulerOff
20803
+ });
20804
+ });
20805
+ agentTriggersRouter.post("/:id/triggers", async (c) => {
20806
+ const body = await jsonBody(c);
20807
+ if (!body) return c.json({ error: "invalid JSON body" }, 400);
20808
+ if (typeof body.message !== "string" || !body.message.trim()) {
20809
+ return c.json({ error: "message is required" }, 400);
20810
+ }
20811
+ const agentId = routeAgent(c).id;
20812
+ const { db } = getCtx();
20813
+ if (body.kind === "interval") {
20814
+ const intervalSec = body.intervalSec;
20815
+ if (typeof intervalSec !== "number" || !Number.isInteger(intervalSec) || intervalSec < 1) {
20816
+ return c.json({ error: "intervalSec must be a whole number of seconds, at least 1" }, 400);
20817
+ }
20818
+ const trigger = triggers_exports.insert(db, {
20819
+ agentId,
20820
+ kind: "interval",
20821
+ intervalSec,
20822
+ cronExpr: null,
20823
+ message: body.message,
20824
+ enabled: body.enabled
20825
+ });
20826
+ return c.json({ trigger }, 201);
20827
+ }
20828
+ if (body.kind === "cron") {
20829
+ if (typeof body.cronExpr !== "string" || !body.cronExpr.trim()) {
20830
+ return c.json({ error: "cronExpr is required for kind=cron" }, 400);
20831
+ }
20832
+ try {
20833
+ validateCron(body.cronExpr);
20834
+ } catch (err) {
20835
+ return c.json({ error: `invalid cron: ${err.message}` }, 400);
20836
+ }
20837
+ const trigger = triggers_exports.insert(db, {
20838
+ agentId,
20839
+ kind: "cron",
20840
+ intervalSec: null,
20841
+ cronExpr: body.cronExpr.trim(),
20842
+ message: body.message,
20843
+ enabled: body.enabled
20844
+ });
20845
+ return c.json({ trigger }, 201);
20846
+ }
20847
+ return c.json({ error: `invalid kind: ${body.kind}` }, 400);
20848
+ });
20849
+
20850
+ // ../daemon/src/routes/usage.ts
20851
+ var usageRouter = newRouter();
20852
+ var MAX_USAGE_DAYS = 3660;
20853
+ usageRouter.get("/", (c) => {
20854
+ const { db, paths } = getCtx();
20855
+ const rawDays = c.req.query("days") ?? "30";
20856
+ let days = null;
20857
+ if (rawDays !== "all") {
20858
+ days = Number(rawDays);
20859
+ if (!Number.isInteger(days) || days < 1 || days > MAX_USAGE_DAYS)
20860
+ throw new DomainError(400, `days must be a whole number from 1 to ${MAX_USAGE_DAYS}, or all`);
20861
+ }
20862
+ const rawZone = c.req.query("tz");
20863
+ const timeZone = rawZone ? validTimeZone(rawZone) : Intl.DateTimeFormat().resolvedOptions().timeZone;
20864
+ if (!timeZone) throw new DomainError(400, `unknown time zone: ${rawZone}`);
20865
+ const agentRef = c.req.query("agent");
20866
+ const agentId = agentRef ? routeAgentRef(agentRef).id : void 0;
20867
+ const teamRef = c.req.query("team");
20868
+ const teamId = teamRef ? get3(db, teamRef, paths)?.id : void 0;
20869
+ if (teamRef && !teamId) throw new DomainError(404, `team not found: ${teamRef}`);
20870
+ const plans = planProviders(mergeSecretsIntoEnv(db, getCtx().authToken));
20871
+ return c.json(usageReport(db, paths, { days, timeZone, agentId, teamId, plans }));
20872
+ });
20873
+
20874
+ // ../daemon/src/routes/user-queue.ts
20875
+ import { bodyLimit as bodyLimit3 } from "hono/body-limit";
20876
+ var userQueueRouter = newRouter();
20877
+ userQueueRouter.use("/:agentId/queue/*", bodyLimit3({ maxSize: 36 * 1024 * 1024 }));
20878
+ userQueueRouter.use("/:agentId/queue/*", async (c, next) => {
20879
+ c.set("agentId", routeAgent(c, "agentId").id);
20880
+ await next();
20881
+ });
20882
+ userQueueRouter.get(
20883
+ "/:agentId/queue",
20884
+ (c) => c.json({
20885
+ ...list4(getCtx().db, c.get("agentId")),
20886
+ turnActive: isActiveAgent(c.get("agentId"))
20887
+ })
20888
+ );
20889
+ userQueueRouter.post("/:agentId/queue", async (c) => {
20890
+ const input = await jsonBody(c);
20891
+ return c.json(
20892
+ await enqueueUserInput(c.get("agentId"), {
20893
+ message: input?.message,
20894
+ attachments: input?.attachments ?? []
20895
+ }),
20896
+ 202
20897
+ );
20898
+ });
20899
+ userQueueRouter.patch("/:agentId/queue/:id", async (c) => {
20900
+ const input = await jsonBody(c);
20901
+ return c.json(
20902
+ edit(getCtx().db, c.get("agentId"), c.req.param("id"), input?.message)
20903
+ );
20904
+ });
20905
+ userQueueRouter.delete("/:agentId/queue/:id", async (c) => {
20906
+ const { item, origin } = remove4(getCtx().db, c.get("agentId"), c.req.param("id"));
20907
+ if (item.status === "pending") await notifyTelegramQueueOutcome(item, origin, "removed");
20908
+ return c.json(item);
20909
+ });
20910
+ userQueueRouter.post("/:agentId/queue/control", async (c) => {
20911
+ const input = await jsonBody(c);
20912
+ if (typeof input?.paused !== "boolean") return c.json({ error: "paused must be a boolean" }, 400);
20913
+ setPaused(getCtx().db, c.get("agentId"), input.paused);
20914
+ return c.json({ paused: input.paused });
20915
+ });
20916
+
20917
+ // ../daemon/src/app.ts
20918
+ function createApp() {
20919
+ const app2 = new Hono2();
20920
+ app2.use("*", authMiddleware);
20921
+ app2.use("/api/*", async (c, next) => {
20922
+ await next();
20923
+ if (!c.res.headers.has("cache-control")) c.res.headers.set("cache-control", "no-store");
20924
+ });
20925
+ app2.route("/api/agents", agentsRouter);
20926
+ app2.route("/api/agents", agentChatRouter);
20927
+ app2.route("/api/agents", agentBrowserRouter);
20928
+ app2.route("/api/agents", agentLearningRouter);
20929
+ app2.route("/api/agents", agentMessagesRouter);
20930
+ app2.route("/api/agents", agentSkillsRouter);
20931
+ app2.route("/api/agents", agentTelegramRouter);
20932
+ app2.route("/api/agents", agentTriggersRouter);
20933
+ app2.route("/api/agents", conversationsRouter);
20934
+ app2.route("/api/agents", userQueueRouter);
20935
+ app2.route("/api/agents", questionsRouter);
20936
+ app2.route("/api/teams", teamsRouter);
20937
+ app2.route("/api/teams", teamMemoryRouter);
20938
+ app2.route("/api/teams", teamPolicyRouter);
20939
+ app2.route("/api/teams", teamReviewRouter);
20940
+ app2.route("/api/teams", teamMessagesRouter);
20941
+ app2.route("/api/teams", teamCodingEnvironmentRouter);
20942
+ app2.route("/api/teams", teamTelegramRouter);
20943
+ app2.route("/api/team-templates", teamTemplatesRouter);
20944
+ app2.route("/api/results", resultsRouter);
20945
+ app2.route("/api/attention", attentionRouter);
20946
+ app2.route("/api/activity", activityRouter);
20947
+ app2.route("/api/usage", usageRouter);
20948
+ app2.route("/api/conversations", conversationSearchRouter);
20949
+ app2.route("/api/events", eventsRouter);
20950
+ app2.route("/api/notifications", notificationsRouter);
20951
+ app2.route("/api/shell-approvals", shellApprovalsRouter);
20952
+ app2.route("/api/profiles", profilesRouter);
20953
+ app2.route("/api/skills", skillsRouter);
20954
+ app2.route("/api/triggers", triggersRouter);
20955
+ app2.route("/api/messages", messagesRouter);
20956
+ app2.route("/api/mcp-servers", mcpRouter);
20957
+ app2.route("/api/config/telegram", telegramRouter);
20958
+ app2.route("/api/config", configRouter);
20959
+ app2.route("/api", miscRouter);
20960
+ app2.route("/api", authRouter);
20961
+ return app2;
20962
+ }
20963
+
19933
20964
  // ../daemon/src/index.ts
20965
+ init_install();
20966
+ init_resources();
19934
20967
  var host2 = process.env.HOST ?? "127.0.0.1";
19935
20968
  var port = Number.parseInt(process.env.PORT ?? "4321", 10);
19936
20969
  var publicOrigin2 = publicOriginConfig(process.env.BAZILION_PUBLIC_ORIGIN);