@pixelzx/genesis 2026.5.5-2 → 2026.5.5-3

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 (1017) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/dist/.buildstamp +1 -1
  3. package/dist/abort-Yw60gQ-C.js +201 -0
  4. package/dist/abort.runtime-DYQuut_O.js +2 -0
  5. package/dist/abort.runtime.js +1 -1
  6. package/dist/accounts-BSCHGPHp.js +107 -0
  7. package/dist/accounts-Bb0FqxV2.js +104 -0
  8. package/dist/accounts-BjGgx8lz.js +2 -0
  9. package/dist/acp-cli-emMnOaiO.js +2193 -0
  10. package/dist/acp-spawn-BmyUZuJX.js +1093 -0
  11. package/dist/acp-spawn-DPF5zmnN.js +2 -0
  12. package/dist/acp-stateful-target-driver-CJ4JyIHf.js +89 -0
  13. package/dist/action-agents-D1tXt8Kj.js +67 -0
  14. package/dist/action-focus-Bk6AJsNH.js +132 -0
  15. package/dist/action-help-4nFSAuVo.js +7 -0
  16. package/dist/action-info-D-byoefn.js +101 -0
  17. package/dist/action-kill-Bo-NwBVR.js +33 -0
  18. package/dist/action-list-lAa4rlzN.js +21 -0
  19. package/dist/action-log-BasoUC3L.js +30 -0
  20. package/dist/action-send-DwLkiz4x.js +39 -0
  21. package/dist/action-spawn-C70_iR8d.js +47 -0
  22. package/dist/action-unfocus-dUVMx5Fh.js +29 -0
  23. package/dist/actions.runtime-BdSo6rN8.js +18 -0
  24. package/dist/actions.runtime-BvY67XKu.js +5 -0
  25. package/dist/actions.runtime.js +1 -1
  26. package/dist/agent-DDBv3Vgl.js +2 -0
  27. package/dist/agent-command-DC7I_88W.js +874 -0
  28. package/dist/agent-harness-runtime-TA6YH7Ud.js +144 -0
  29. package/dist/agent-runner-utils-CMe-JIDq.js +239 -0
  30. package/dist/agent-runner.runtime-le6AmJRw.js +3455 -0
  31. package/dist/agent-runner.runtime.js +1 -1
  32. package/dist/agent-runtime-CONy4fDD.js +18 -0
  33. package/dist/agents-BlbOM4XW.js +953 -0
  34. package/dist/agents-Byj8CDAP.js +5 -0
  35. package/dist/aliases-C3Ks5x38.js +2 -0
  36. package/dist/aliases-CxBcx9gF.js +96 -0
  37. package/dist/api-CLoj7nYH.js +3 -0
  38. package/dist/api-DZiRkVPk.js +5 -0
  39. package/dist/api-_Y4nIHNo.js +139 -0
  40. package/dist/approval-gateway-resolver-Ba_2kb3B.js +29 -0
  41. package/dist/approval-gateway-runtime-7VMivk0A.js +2 -0
  42. package/dist/approval-handler-runtime-Bh0onoHD.js +439 -0
  43. package/dist/approval-native-runtime-IYFyT8Hf.js +729 -0
  44. package/dist/attempt-execution.runtime-CpL2tsYd.js +509 -0
  45. package/dist/attempt-execution.runtime.js +1 -1
  46. package/dist/attempt.prompt-helpers-Gx9nGKbW.js +221 -0
  47. package/dist/attempt.tool-run-context-BmuljBMs.js +933 -0
  48. package/dist/audit-CsjqOEVE.js +939 -0
  49. package/dist/audit.runtime-BybEaYH4.js +7 -0
  50. package/dist/audit.runtime.js +1 -1
  51. package/dist/auth-BFbLz2gx.js +383 -0
  52. package/dist/auth-DdoNShRm.js +2 -0
  53. package/dist/auth-order-CtO2WQTH.js +2 -0
  54. package/dist/auth-order-zXIiW-Cn.js +96 -0
  55. package/dist/bash-tools-CnDYSbnX.js +2824 -0
  56. package/dist/bash-tools-DiOcKaak.js +3 -0
  57. package/dist/binding-routing-E9Gh_NqO.js +85 -0
  58. package/dist/binding-targets-C5PbBaZ6.js +121 -0
  59. package/dist/bridge-server-DragdaQD.js +113 -0
  60. package/dist/browser-control-auth-D_M31xJ1.js +2 -0
  61. package/dist/browser-node-runtime-Bgu82luB.js +12 -0
  62. package/dist/browser-profiles-C3ffkgOt.js +2 -0
  63. package/dist/browser-runtime-D84IBo4A.js +387 -0
  64. package/dist/browser-setup-tools-VC7rGCyn.js +13 -0
  65. package/dist/build-DeGDX_pJ.js +550 -0
  66. package/dist/build-info.json +3 -3
  67. package/dist/bundled/boot-md/handler.js +2 -2
  68. package/dist/bundled/session-memory/handler.js +1 -1
  69. package/dist/call-CbvF41H8.js +3 -0
  70. package/dist/call-DuDGOVT1.js +331 -0
  71. package/dist/call.runtime-DztWXjMr.js +2 -0
  72. package/dist/call.runtime.js +1 -1
  73. package/dist/capability-cli-DoJLi3eS.js +1401 -0
  74. package/dist/catchup-Dk-5hIwm.js +300 -0
  75. package/dist/channel-BJ9iEC4Y.js +595 -0
  76. package/dist/channel-BdvsbgZE.js +453 -0
  77. package/dist/channel-Bu-7KaIx.js +1802 -0
  78. package/dist/channel-C9vQNMK1.js +350 -0
  79. package/dist/channel-CZoVAZyW.js +491 -0
  80. package/dist/channel-Cr2KTwyo.js +840 -0
  81. package/dist/channel-DCeC6AEQ.js +297 -0
  82. package/dist/channel-DOGp2TfT.js +1320 -0
  83. package/dist/channel-Dfq1lxxI.js +226 -0
  84. package/dist/channel-core-DiltAzdr.js +5 -0
  85. package/dist/channel-hZDaTBpm.js +1100 -0
  86. package/dist/channel-inbound-DvOS-Z1s.js +31 -0
  87. package/dist/channel-plugin-runtime-PFRHQ61T.js +771 -0
  88. package/dist/channel-runtime-BAjxIEfQ.js +425 -0
  89. package/dist/channel-szBwbQZB.js +1174 -0
  90. package/dist/channel.runtime-B1Ry35gt.js +89 -0
  91. package/dist/channel.runtime-BNp6GxaQ.js +34702 -0
  92. package/dist/channel.runtime-BfjvNvbj.js +2364 -0
  93. package/dist/channel.runtime-BlGn4QYV.js +4 -0
  94. package/dist/channel.runtime-D7bv5rJl.js +576 -0
  95. package/dist/channel.runtime-DQ5gSgeW.js +109 -0
  96. package/dist/channel.runtime-IxClQMdT.js +430 -0
  97. package/dist/channel.setup-BsfyGPgV.js +10 -0
  98. package/dist/channels-Dn2VHRmZ.js +733 -0
  99. package/dist/channels-cli-l4xjPvDv.js +268 -0
  100. package/dist/chat-zUeX8mQw.js +2758 -0
  101. package/dist/clawbot-cli-C3BFdHJB.js +9 -0
  102. package/dist/cli/daemon-cli.js +4 -4
  103. package/dist/cli-BTnpFsj1.js +2 -0
  104. package/dist/cli-CAFQ6Cwy.js +72 -0
  105. package/dist/cli-CiqIbwtg.js +219 -0
  106. package/dist/cli-DL1ppK38.js +2 -0
  107. package/dist/cli-runner-DO6lEPJr.js +286 -0
  108. package/dist/cli-runner.runtime-B-Ic4DyC.js +3 -0
  109. package/dist/cli-runner.runtime-C4cAORcg.js +4 -0
  110. package/dist/cli-runner.runtime.js +1 -1
  111. package/dist/cli-startup-metadata.json +2 -2
  112. package/dist/cli.runtime-CYHctHVS.js +1261 -0
  113. package/dist/cli.runtime.js +1 -1
  114. package/dist/client-Bb_miREU.js +138 -0
  115. package/dist/client-CrPccv7a.js +713 -0
  116. package/dist/command-auth-B7P-1IeA.js +76 -0
  117. package/dist/command-config-resolution-BB-SsCob.js +23 -0
  118. package/dist/command-config-resolution-DMKYb0Kh.js +2 -0
  119. package/dist/command-config-resolution.runtime-Coeaa9lz.js +2 -0
  120. package/dist/command-config-resolution.runtime.js +1 -1
  121. package/dist/command-registry-B2JzWHqy.js +9 -0
  122. package/dist/command-registry-CNUpJUp8.js +4 -0
  123. package/dist/command-registry-core-BLap9aka.js +101 -0
  124. package/dist/command-secret-gateway-ChRXthnT.js +528 -0
  125. package/dist/command-status.runtime-D8VWyC3v.js +87 -0
  126. package/dist/command-status.runtime.js +1 -1
  127. package/dist/commands-acp-QLk1cU5f.js +77 -0
  128. package/dist/commands-compact.runtime-BIHG2RSY.js +10 -0
  129. package/dist/commands-compact.runtime.js +1 -1
  130. package/dist/commands-handlers.runtime-DjimbxSJ.js +4597 -0
  131. package/dist/commands-handlers.runtime.js +1 -1
  132. package/dist/commands-status-DiIQSYSt.js +16 -0
  133. package/dist/commands-status.runtime-DBRxICN6.js +3 -0
  134. package/dist/commands-status.runtime.js +1 -1
  135. package/dist/commands-subagents-control.runtime-BmqXiKHu.js +3 -0
  136. package/dist/commands-subagents-control.runtime-CVQSOd8H.js +2 -0
  137. package/dist/commands-subagents-control.runtime.js +1 -1
  138. package/dist/commands-system-prompt-2qwZc3xL.js +158 -0
  139. package/dist/commands-system-prompt-Clnn_Gct.js +2 -0
  140. package/dist/commands.runtime-DAqpiDPr.js +166 -0
  141. package/dist/commands.runtime.js +1 -1
  142. package/dist/compact-DqOkQZYr.js +1118 -0
  143. package/dist/compact.runtime-CC_l29j4.js +12 -0
  144. package/dist/compact.runtime.js +1 -1
  145. package/dist/completion-cli-DZFJPSiF.js +328 -0
  146. package/dist/config-D9XEe0Cd.js +251 -0
  147. package/dist/config-cli-DVDwIjKr.js +1078 -0
  148. package/dist/configure-39oQUHuK.js +1245 -0
  149. package/dist/configure-BGD8tViZ.js +2 -0
  150. package/dist/connect-options-Fpky6zuL.js +699 -0
  151. package/dist/control-auth-BlqH4IVx.js +125 -0
  152. package/dist/control-service-CaqDohiY.js +156 -0
  153. package/dist/conversation-id-BH9GFVB2.js +235 -0
  154. package/dist/conversation-id-UdIegcf4.js +38 -0
  155. package/dist/conversation-runtime-Bao0kIPf.js +31 -0
  156. package/dist/core-DXUh5Xbm.js +275 -0
  157. package/dist/cron-cli-B1mxHnGP.js +713 -0
  158. package/dist/daemon-cli-CaHBNwMy.js +12 -0
  159. package/dist/daemon-install-BBwOxf1q.js +64 -0
  160. package/dist/delegate-7G7R4C-C.js +64 -0
  161. package/dist/detached-task-runtime-BMdSrcuz.js +73 -0
  162. package/dist/devices-cli-DnEQH3R2.js +496 -0
  163. package/dist/diagnostics-C8VwSDtU.js +154 -0
  164. package/dist/direct-dm-BSEkIiOe.js +64 -0
  165. package/dist/dispatch-1gv6It-6.js +1131 -0
  166. package/dist/dispatch-acp-hbhR9aHr.js +981 -0
  167. package/dist/dispatch-acp-manager.runtime-BXQbK1cO.js +3 -0
  168. package/dist/dispatch-acp-manager.runtime.js +1 -1
  169. package/dist/dispatch-acp.runtime-Dhx090J2.js +19 -0
  170. package/dist/dispatch-acp.runtime.js +1 -1
  171. package/dist/doctor-device-pairing-1gf3tk3g.js +307 -0
  172. package/dist/doctor-gateway-daemon-flow-LEnN6pL-.js +250 -0
  173. package/dist/doctor-gateway-health-DwxLkTV4.js +60 -0
  174. package/dist/doctor-gateway-services-BhqUOY_e.js +316 -0
  175. package/dist/doctor-health-CdJkaUYf.js +59 -0
  176. package/dist/doctor-health-contributions-BaTnIzCT.js +486 -0
  177. package/dist/doctor-prompter-BZTb5rOn.js +56 -0
  178. package/dist/doctor-workspace-status-DnBARoPa.js +75 -0
  179. package/dist/dreaming-BAGFdUxh.js +1574 -0
  180. package/dist/dreaming-narrative-XoOfVb0x.js +595 -0
  181. package/dist/embedded-gateway-stub.runtime-xwZ-M7Ei.js +9 -0
  182. package/dist/embedded-gateway-stub.runtime.js +1 -1
  183. package/dist/entry.js +2 -2
  184. package/dist/exec-approvals-cli-CWVWSMk-.js +498 -0
  185. package/dist/extensionAPI.js +1 -1
  186. package/dist/extensions/active-memory/index.js +1 -1
  187. package/dist/extensions/bluebubbles/api.js +3 -3
  188. package/dist/extensions/bluebubbles/channel-plugin-api.js +1 -1
  189. package/dist/extensions/browser/browser-bridge.js +1 -1
  190. package/dist/extensions/browser/browser-config.js +4 -4
  191. package/dist/extensions/browser/browser-control-auth.js +2 -2
  192. package/dist/extensions/browser/browser-doctor.js +2 -2
  193. package/dist/extensions/browser/browser-maintenance.js +2 -2
  194. package/dist/extensions/browser/browser-profiles.js +2 -2
  195. package/dist/extensions/browser/browser-runtime-api.js +10 -10
  196. package/dist/extensions/browser/index.js +1 -1
  197. package/dist/extensions/browser/plugin-registration.js +1 -1
  198. package/dist/extensions/browser/register.runtime.js +3 -3
  199. package/dist/extensions/browser/runtime-api.js +11 -11
  200. package/dist/extensions/browser/test-support.js +1 -1
  201. package/dist/extensions/device-pair/api.js +1 -1
  202. package/dist/extensions/device-pair/index.js +3 -3
  203. package/dist/extensions/device-pair/notify.js +1 -1
  204. package/dist/extensions/device-pair/pair-command-approve.js +1 -1
  205. package/dist/extensions/google-meet/index.js +2 -2
  206. package/dist/extensions/imessage/api.js +3 -3
  207. package/dist/extensions/imessage/channel-plugin-api.js +1 -1
  208. package/dist/extensions/imessage/runtime-api.js +3 -3
  209. package/dist/extensions/irc/api.js +2 -2
  210. package/dist/extensions/irc/channel-plugin-api.js +1 -1
  211. package/dist/extensions/line/api.js +2 -2
  212. package/dist/extensions/line/channel-plugin-api.js +1 -1
  213. package/dist/extensions/line/contract-api.js +1 -1
  214. package/dist/extensions/line/runtime-api.js +4 -4
  215. package/dist/extensions/line/setup-api.js +1 -1
  216. package/dist/extensions/llm-task/index.js +2 -2
  217. package/dist/extensions/lobster/index.js +3 -3
  218. package/dist/extensions/lobster/runtime-api.js +1 -1
  219. package/dist/extensions/mattermost/api.js +1 -1
  220. package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
  221. package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
  222. package/dist/extensions/mattermost/policy-api.js +1 -1
  223. package/dist/extensions/mattermost/runtime-api.js +4 -4
  224. package/dist/extensions/mattermost/slash-route-api.js +1 -1
  225. package/dist/extensions/memory-core/api.js +1 -1
  226. package/dist/extensions/memory-core/cli-metadata.js +2 -2
  227. package/dist/extensions/memory-core/index.js +3 -3
  228. package/dist/extensions/memory-lancedb/cli-metadata.js +1 -1
  229. package/dist/extensions/msteams/api.js +1 -1
  230. package/dist/extensions/msteams/channel-plugin-api.js +1 -1
  231. package/dist/extensions/msteams/runtime-api.js +3 -3
  232. package/dist/extensions/msteams/test-api.js +1 -1
  233. package/dist/extensions/nextcloud-talk/api.js +1 -1
  234. package/dist/extensions/nextcloud-talk/channel-plugin-api.js +1 -1
  235. package/dist/extensions/nextcloud-talk/runtime-api.js +2 -2
  236. package/dist/extensions/openshell/index.js +2 -2
  237. package/dist/extensions/signal/api.js +6 -6
  238. package/dist/extensions/signal/channel-plugin-api.js +1 -1
  239. package/dist/extensions/signal/reaction-runtime-api.js +1 -1
  240. package/dist/extensions/signal/runtime-api.js +7 -7
  241. package/dist/extensions/skill-workshop/api.js +1 -1
  242. package/dist/extensions/skill-workshop/index.js +1 -1
  243. package/dist/extensions/synology-chat/api.js +1 -1
  244. package/dist/extensions/synology-chat/channel-plugin-api.js +1 -1
  245. package/dist/extensions/tlon/api.js +2 -2
  246. package/dist/extensions/tlon/channel-plugin-api.js +1 -1
  247. package/dist/extensions/tlon/runtime-api.js +1 -1
  248. package/dist/extensions/tlon/test-api.js +1 -1
  249. package/dist/extensions/twitch/api.js +1 -1
  250. package/dist/extensions/twitch/channel-plugin-api.js +1 -1
  251. package/dist/extensions/twitch/setup-plugin-api.js +1 -1
  252. package/dist/extensions/zalo/api.js +3 -3
  253. package/dist/extensions/zalo/channel-plugin-api.js +1 -1
  254. package/dist/extensions/zalo/runtime-api.js +2 -2
  255. package/dist/extensions/zalo/setup-api.js +2 -2
  256. package/dist/extensions/zalouser/api.js +3 -3
  257. package/dist/extensions/zalouser/channel-plugin-api.js +1 -1
  258. package/dist/extensions/zalouser/runtime-api.js +6 -6
  259. package/dist/extensions/zalouser/setup-plugin-api.js +1 -1
  260. package/dist/extensions/zalouser/test-api.js +1 -1
  261. package/dist/fallbacks-BKA5XrxA.js +31 -0
  262. package/dist/fallbacks-QvezaDAr.js +2 -0
  263. package/dist/fallbacks-shared-DS-qTOLR.js +111 -0
  264. package/dist/gateway-C0YHaLXO.js +115 -0
  265. package/dist/gateway-cli-DJBCD8J5.js +1325 -0
  266. package/dist/gateway-rpc-CmJXd4SU.js +14 -0
  267. package/dist/gateway-rpc.runtime-C9Fs2mSx.js +23 -0
  268. package/dist/gateway-rpc.runtime.js +1 -1
  269. package/dist/gateway-runtime-Bm2_MhFn.js +15 -0
  270. package/dist/gateway-status-DXKMKFtB.js +584 -0
  271. package/dist/genesis-tools-AolFZ-0I.js +8999 -0
  272. package/dist/genesis-tools.runtime-CBWXJqzw.js +2 -0
  273. package/dist/genesis-tools.runtime.js +1 -1
  274. package/dist/get-reply-BpxjHQBp.js +3879 -0
  275. package/dist/get-reply-from-config.runtime-DJKEqLSi.js +2 -0
  276. package/dist/get-reply-from-config.runtime.js +1 -1
  277. package/dist/graph-users-D2Q5UTGQ.js +1337 -0
  278. package/dist/health-BNKpuAPB.js +469 -0
  279. package/dist/health-BkxZfKx8.js +3 -0
  280. package/dist/heartbeat-runner-Bdu2q6k3.js +5 -0
  281. package/dist/heartbeat-runner-C0B-c-fv.js +1292 -0
  282. package/dist/heartbeat-runner.runtime-Cic23eNy.js +4 -0
  283. package/dist/heartbeat-runner.runtime.js +1 -1
  284. package/dist/hooks-cli-BfCr2In5.js +433 -0
  285. package/dist/image-fallbacks-Dgy-LmDo.js +2 -0
  286. package/dist/image-fallbacks-RlfTqOne.js +31 -0
  287. package/dist/inbound-reply-dispatch-D4KJHWLG.js +73 -0
  288. package/dist/index.js +2 -2
  289. package/dist/infra-runtime-BTJv3KK8.js +39 -0
  290. package/dist/init-q4INH9uv.js +59 -0
  291. package/dist/install-BT4BNeMX.js +190 -0
  292. package/dist/install.runtime-BnqPyIyn.js +2 -0
  293. package/dist/launchd-BM_37PLv.js +698 -0
  294. package/dist/library-DGd4UZKC.js +45 -0
  295. package/dist/lifecycle-B_RLw4uY.js +229 -0
  296. package/dist/lifecycle-Bw01evSl.js +571 -0
  297. package/dist/lifecycle-core-CTjCo-k0.js +422 -0
  298. package/dist/lifecycle.runtime-BxpD2Ol7.js +2 -0
  299. package/dist/lifecycle.runtime.js +1 -1
  300. package/dist/list-BXa4zUF-.js +2 -0
  301. package/dist/list-BugTSXmQ.js +131 -0
  302. package/dist/list-CgC_rsta.js +1201 -0
  303. package/dist/list-D2sk1YPs.js +2 -0
  304. package/dist/list.probe-C6zfgLdG.js +419 -0
  305. package/dist/llm-slug-generator-DsWJvqNx.js +79 -0
  306. package/dist/llm-slug-generator.js +1 -1
  307. package/dist/load-config-D6ZKPY7I.js +35 -0
  308. package/dist/local-dispatch.runtime-MWMxyZKj.js +8 -0
  309. package/dist/local-dispatch.runtime.js +1 -1
  310. package/dist/logs-cli-Dn-8jl3z.js +265 -0
  311. package/dist/logs-cli.runtime-DwsccWUJ.js +2 -0
  312. package/dist/logs-cli.runtime.js +1 -1
  313. package/dist/main-session-restart-recovery-6Uh4W8ZJ.js +206 -0
  314. package/dist/managed-image-attachments-DHawPS1-.js +2 -0
  315. package/dist/managed-image-attachments-DjtxwZ9o.js +635 -0
  316. package/dist/manager-D0tkR46e.js +2057 -0
  317. package/dist/manager-g_P1RDky.js +2 -0
  318. package/dist/markdown-to-line-7AxR7QFo.js +790 -0
  319. package/dist/mcp/plugin-tools-serve.js +1 -1
  320. package/dist/mcp-cli-Cw2XQMOA.js +725 -0
  321. package/dist/mcp-http-DFKqya8U.js +529 -0
  322. package/dist/memory-core-host-runtime-cli-DaAsOXiU.js +9 -0
  323. package/dist/message-BDCG7eWj.js +232 -0
  324. package/dist/message-action-runner-6C7kXcC9.js +2 -0
  325. package/dist/message-action-runner-C2P3efhU.js +1407 -0
  326. package/dist/message-actions-BWQWt5gT.js +143 -0
  327. package/dist/message.gateway.runtime-BXChuYAf.js +2 -0
  328. package/dist/message.gateway.runtime.js +1 -1
  329. package/dist/models-auth-status-B8lnM1PS.js +201 -0
  330. package/dist/models-cli-DbUA18AN.js +219 -0
  331. package/dist/monitor-BEJe2ceJ.js +1237 -0
  332. package/dist/monitor-BO9i6U5R.js +1459 -0
  333. package/dist/monitor-BZLrxL_x.js +1661 -0
  334. package/dist/monitor-CDDxHGlD.js +788 -0
  335. package/dist/monitor-D779kLc0.js +671 -0
  336. package/dist/monitor-V5ZNCrQL.js +2 -0
  337. package/dist/monitor-auth-D2rCHNgr.js +207 -0
  338. package/dist/monitor-processing-BLbsNFVv.js +1974 -0
  339. package/dist/monitor.runtime-RrusGXVO.js +2 -0
  340. package/dist/monitor.runtime.js +1 -1
  341. package/dist/monitor.webhook-B0DuBNWa.js +180 -0
  342. package/dist/msteams-hh9nwLlZ.js +35 -0
  343. package/dist/native-hook-relay-BygYZoeR.js +519 -0
  344. package/dist/nextcloud-talk-AadRCqXn.js +17 -0
  345. package/dist/node-cli-FF1zz0JU.js +2506 -0
  346. package/dist/node-service-f8mmgM5L.js +68 -0
  347. package/dist/nodes-cli-tQ5dpecZ.js +1046 -0
  348. package/dist/nodes-utils-BfpGcUca.js +84 -0
  349. package/dist/nodes.helpers-CMXxavTs.js +34 -0
  350. package/dist/notify-DaNP5Zyh.js +315 -0
  351. package/dist/onboard-B9hx80Dm.js +632 -0
  352. package/dist/onboard-helpers-BlPrFJHK.js +204 -0
  353. package/dist/onboard-helpers-kL8mgUkl.js +6 -0
  354. package/dist/onboard-remote-ByHuQd1m.js +193 -0
  355. package/dist/onboard-remote-CRPXcrWy.js +2 -0
  356. package/dist/onboard-skills-ChtyNRCd.js +2 -0
  357. package/dist/onboard-skills-DROlYXya.js +134 -0
  358. package/dist/openai-http-2An5HAJU.js +500 -0
  359. package/dist/openresponses-http-DpbJXZP4.js +1128 -0
  360. package/dist/operator-approvals-client-BoN_VmkB.js +68 -0
  361. package/dist/outbound.runtime-D_aebUn6.js +2 -0
  362. package/dist/outbound.runtime.js +1 -1
  363. package/dist/pair-command-approve-i-1VECJx.js +44 -0
  364. package/dist/persistent-bindings.lifecycle-eZyKQ1D8.js +85 -0
  365. package/dist/persistent-bindings.lifecycle-mxY73TJR.js +2 -0
  366. package/dist/pi-embedded-0fErjTQ7.js +2905 -0
  367. package/dist/pi-embedded-Bc1jC2x0.js +4 -0
  368. package/dist/pi-embedded.runtime-Bn_RZ5z8.js +4 -0
  369. package/dist/pi-embedded.runtime.js +1 -1
  370. package/dist/pi-tool-definition-adapter-thh7LO1t.js +217 -0
  371. package/dist/pi-tools-BtlLDovQ.js +1057 -0
  372. package/dist/pi-tools.before-tool-call-BJ_X8Dq3.js +2 -0
  373. package/dist/pi-tools.before-tool-call-DdPCGWCs.js +433 -0
  374. package/dist/plugin-CdHHk4Xn.js +12195 -0
  375. package/dist/plugin-enabled-DybhbjKQ.js +140 -0
  376. package/dist/plugin-registration-Bgwpsokw.js +23 -0
  377. package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
  378. package/dist/plugin-sdk/acp-binding-runtime.js +1 -1
  379. package/dist/plugin-sdk/acp-runtime.js +2 -2
  380. package/dist/plugin-sdk/agent-harness-runtime.js +5 -5
  381. package/dist/plugin-sdk/agent-harness.js +6 -6
  382. package/dist/plugin-sdk/agent-runtime.js +2 -2
  383. package/dist/plugin-sdk/approval-gateway-runtime.js +2 -2
  384. package/dist/plugin-sdk/approval-handler-runtime.js +3 -3
  385. package/dist/plugin-sdk/approval-runtime.js +1 -1
  386. package/dist/plugin-sdk/browser-node-runtime.js +4 -4
  387. package/dist/plugin-sdk/browser-setup-tools.js +3 -3
  388. package/dist/plugin-sdk/browser-support.js +7 -7
  389. package/dist/plugin-sdk/channel-core.js +2 -2
  390. package/dist/plugin-sdk/channel-inbound.js +2 -2
  391. package/dist/plugin-sdk/command-auth.js +1 -1
  392. package/dist/plugin-sdk/command-status-runtime.js +1 -1
  393. package/dist/plugin-sdk/compat.js +1 -1
  394. package/dist/plugin-sdk/conversation-binding-runtime.js +1 -1
  395. package/dist/plugin-sdk/conversation-runtime.js +3 -3
  396. package/dist/plugin-sdk/core.js +2 -2
  397. package/dist/plugin-sdk/direct-dm.js +1 -1
  398. package/dist/plugin-sdk/gateway-runtime.js +3 -3
  399. package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
  400. package/dist/plugin-sdk/index.js +1 -1
  401. package/dist/plugin-sdk/infra-runtime.js +2 -2
  402. package/dist/plugin-sdk/irc.js +2 -2
  403. package/dist/plugin-sdk/matrix.js +1 -1
  404. package/dist/plugin-sdk/memory-core-host-runtime-cli.js +2 -2
  405. package/dist/plugin-sdk/memory-core.js +2 -2
  406. package/dist/plugin-sdk/msteams.js +2 -2
  407. package/dist/plugin-sdk/nextcloud-talk.js +2 -2
  408. package/dist/plugin-sdk/nostr.js +1 -1
  409. package/dist/plugin-sdk/reply-dispatch-runtime.js +1 -1
  410. package/dist/plugin-sdk/reply-runtime.js +4 -4
  411. package/dist/plugin-sdk/runtime-secret-resolution.js +1 -1
  412. package/dist/plugin-sdk/runtime.js +2 -2
  413. package/dist/plugin-sdk/session-visibility.js +1 -1
  414. package/dist/plugin-sdk/testing.js +4 -4
  415. package/dist/plugin-sdk/tlon.js +1 -1
  416. package/dist/plugin-sdk/zalo.js +1 -1
  417. package/dist/plugin-sdk/zalouser.js +1 -1
  418. package/dist/plugin-service-ClhrJfT3.js +2890 -0
  419. package/dist/plugins/runtime/index.js +1 -1
  420. package/dist/policy-CoqHgREn.js +328 -0
  421. package/dist/postinstall-inventory.json +418 -418
  422. package/dist/prepare.runtime-CawO_32K.js +815 -0
  423. package/dist/prepare.runtime.js +1 -1
  424. package/dist/probe-BP3QS65i.js +74 -0
  425. package/dist/probe-BdCXAH_u.js +2 -0
  426. package/dist/probe-Cv5tXOMP.js +2205 -0
  427. package/dist/probe-D-D_1oc4.js +241 -0
  428. package/dist/probe-DO-gll0g.js +2 -0
  429. package/dist/probe-T6c0F73q.js +45 -0
  430. package/dist/probe-dxji7IxZ.js +1443 -0
  431. package/dist/program-GMPfHt5E.js +111 -0
  432. package/dist/prompt-select-styled-BvuJNEJG.js +20 -0
  433. package/dist/protocol-Batc2DmY.js +2234 -0
  434. package/dist/provider-dispatcher-CGYoOdKf.js +2 -0
  435. package/dist/provider-dispatcher-iTEDM88F.js +22 -0
  436. package/dist/qr-cli-6IxenO1C.js +349 -0
  437. package/dist/qr-cli-D63piSog.js +2 -0
  438. package/dist/reaction-runtime-api-DgwRXTz2.js +116 -0
  439. package/dist/reactions-Dnh7t4Zl.js +998 -0
  440. package/dist/register-service-commands-D7w01SKL.js +71 -0
  441. package/dist/register.agent-j1Eno4xr.js +248 -0
  442. package/dist/register.configure-ubwxTkGt.js +15 -0
  443. package/dist/register.maintenance-B7FuM_ZW.js +438 -0
  444. package/dist/register.message-QR3u9rBl.js +329 -0
  445. package/dist/register.onboard-Bdcf_lH0.js +81 -0
  446. package/dist/register.runtime-QDduc4yj.js +81 -0
  447. package/dist/register.runtime.js +1 -1
  448. package/dist/register.setup-DzVV6tdQ.js +150 -0
  449. package/dist/register.status-health-sessions-Brw3VcxG.js +1215 -0
  450. package/dist/register.subclis-B8qDbqPl.js +29 -0
  451. package/dist/register.subclis-DdoN3nZi.js +3 -0
  452. package/dist/register.subclis-core-CWHmnIoe.js +249 -0
  453. package/dist/reply-dispatch-runtime-BVLvCeJ0.js +13 -0
  454. package/dist/reply-runtime-BXkvfLv_.js +11 -0
  455. package/dist/reply.runtime-BTkpxI5R.js +2 -0
  456. package/dist/reply.runtime.js +1 -1
  457. package/dist/restart-health-6cjrRBpF.js +202 -0
  458. package/dist/restart-health-b6Qw43Tj.js +2 -0
  459. package/dist/root-help-DDa1oEtT.js +44 -0
  460. package/dist/routes-CoCMty69.js +2 -0
  461. package/dist/routes-D9uC_Zdy.js +3341 -0
  462. package/dist/rpc-DpLGM3FH.js +61 -0
  463. package/dist/rpc.runtime-B27EA5A0.js +21 -0
  464. package/dist/rpc.runtime.js +1 -1
  465. package/dist/run-delivery.runtime-OmILefLX.js +530 -0
  466. package/dist/run-delivery.runtime.js +1 -1
  467. package/dist/run-embedded.runtime-Dc43u_Z7.js +4 -0
  468. package/dist/run-embedded.runtime.js +1 -1
  469. package/dist/run-execution-cli.runtime-DL5w7Ac8.js +4 -0
  470. package/dist/run-execution-cli.runtime.js +1 -1
  471. package/dist/run-executor.runtime-Bzwt0zP-.js +277 -0
  472. package/dist/run-executor.runtime.js +1 -1
  473. package/dist/run-main-BLD1wTLU.js +516 -0
  474. package/dist/run-subagent-registry.runtime-CddCeg6W.js +2 -0
  475. package/dist/run-subagent-registry.runtime.js +1 -1
  476. package/dist/run-wait-D4Gxuyru.js +135 -0
  477. package/dist/runtime-8BuIPrSY.js +973 -0
  478. package/dist/runtime-Co8r21pw.js +9 -0
  479. package/dist/runtime-api-BG0XWkir.js +4 -0
  480. package/dist/runtime-api-BjBzlgns.js +9 -0
  481. package/dist/runtime-api-DlYbbA-n.js +14 -0
  482. package/dist/runtime-api-faT33SE2.js +9 -0
  483. package/dist/runtime-embedded-pi.runtime-QdJ7K4t0.js +2 -0
  484. package/dist/runtime-embedded-pi.runtime.js +1 -1
  485. package/dist/runtime-internal-C0xc_Zhf.js +2 -0
  486. package/dist/runtime-options-DLv7ygkO.js +275 -0
  487. package/dist/runtime-schema-CQK5R5Pl.js +27780 -0
  488. package/dist/scan-Yz6DoQn5.js +523 -0
  489. package/dist/scan-k38hL_6o.js +2 -0
  490. package/dist/secrets-cli-Bjvr0bOw.js +2101 -0
  491. package/dist/security-cli-C2gkMFcB.js +486 -0
  492. package/dist/selection-DC8EXnRg.js +7736 -0
  493. package/dist/selection-DmSFI5k4.js +2 -0
  494. package/dist/send-CT6EfHrc.js +102 -0
  495. package/dist/send-_ANvjE_C.js +156 -0
  496. package/dist/send.runtime-COIjG4BV.js +2 -0
  497. package/dist/send.runtime.js +1 -1
  498. package/dist/server-COkv9Si4.js +13 -0
  499. package/dist/server-DHLQZJL8.js +77 -0
  500. package/dist/server-context-6jnr-aAw.js +2 -0
  501. package/dist/server-context-DK1QsdLh.js +847 -0
  502. package/dist/server-node-events-q8H0odkq.js +481 -0
  503. package/dist/server-plugin-bootstrap-Bw4a88yA.js +2 -0
  504. package/dist/server-plugin-bootstrap-By_w9ngt.js +11333 -0
  505. package/dist/server-restart-sentinel-CGLYF3mk.js +697 -0
  506. package/dist/server.impl-8j4SImks.js +12735 -0
  507. package/dist/service-CNjb_qXC.js +2 -0
  508. package/dist/service-CyR3mZIU.js +120 -0
  509. package/dist/service-audit-DIL0OiMa.js +260 -0
  510. package/dist/service-audit-pwloDggS.js +2 -0
  511. package/dist/session-kill-http-Dek5w0Ee.js +110 -0
  512. package/dist/session-reset-service-B_9Ps0kr.js +471 -0
  513. package/dist/session-route-Cr6vOd9_.js +93 -0
  514. package/dist/session-status.runtime-C_x1MHH5.js +2 -0
  515. package/dist/session-status.runtime.js +1 -1
  516. package/dist/session-subagent-reactivation.runtime-BKWuNild.js +2 -0
  517. package/dist/session-subagent-reactivation.runtime.js +1 -1
  518. package/dist/session-tab-registry-C08V5jx6.js +491 -0
  519. package/dist/session-visibility-D4j8hN_B.js +147 -0
  520. package/dist/sessions-helpers-DmUVRk16.js +304 -0
  521. package/dist/sessions-history-http-DN3KzEnX.js +383 -0
  522. package/dist/sessions-patch-BPtlF0Lu.js +309 -0
  523. package/dist/sessions-resolve-D6KPfG_4.js +174 -0
  524. package/dist/sessions.runtime-DGL1-G20.js +2 -0
  525. package/dist/sessions.runtime.js +1 -1
  526. package/dist/setup-CkYiQoP0.js +495 -0
  527. package/dist/setup-api-CUGYqGNT.js +29 -0
  528. package/dist/setup-core-BmplfubJ.js +171 -0
  529. package/dist/setup-core-C5ddWpfy.js +176 -0
  530. package/dist/setup-surface-2JmEfowI.js +219 -0
  531. package/dist/setup-surface-BzHQx_GD.js +403 -0
  532. package/dist/setup-surface-DOH6kc6w.js +286 -0
  533. package/dist/setup.finalize-Ci2HBkDq.js +539 -0
  534. package/dist/setup.gateway-config-CyG_Fzaa.js +250 -0
  535. package/dist/shared-BItUH43s.js +121 -0
  536. package/dist/shared-D7diJkX6.js +198 -0
  537. package/dist/shared-DJU_HCJ1.js +76 -0
  538. package/dist/slash-state-C4YD-tLz.js +1911 -0
  539. package/dist/src-8HdytGc7.js +3974 -0
  540. package/dist/startup-context-CfcCyUU0.js +312 -0
  541. package/dist/status-B94yciC9.js +397 -0
  542. package/dist/status-BUkUYtFm.js +190 -0
  543. package/dist/status-BsHC-0MV.js +2 -0
  544. package/dist/status-D4jNATg0.js +209 -0
  545. package/dist/status-U8ut-X2Q.js +2 -0
  546. package/dist/status-all-CIzsXQnV.js +498 -0
  547. package/dist/status-json-alPkfWTd.js +14 -0
  548. package/dist/status-json-command-CAkzWzw7.js +84 -0
  549. package/dist/status-jxNdVQVZ.js +3 -0
  550. package/dist/status-runtime-shared-BSsA48i9.js +257 -0
  551. package/dist/status-subagents.runtime-hIKg6PXV.js +18 -0
  552. package/dist/status-subagents.runtime.js +1 -1
  553. package/dist/status-text-BmLJrLth.js +237 -0
  554. package/dist/status.gateway-connection.runtime-Dr7HJ1wZ.js +2 -0
  555. package/dist/status.gateway-connection.runtime.js +1 -1
  556. package/dist/status.gather-DFY0T97g.js +2 -0
  557. package/dist/status.gather-e6sfNh8I.js +292 -0
  558. package/dist/status.runtime-DBvapXQS.js +2 -0
  559. package/dist/status.runtime.js +1 -1
  560. package/dist/status.scan-DSpkE-Q-.js +65 -0
  561. package/dist/status.scan-overview-Dr72bkbi.js +379 -0
  562. package/dist/status.scan.fast-json-C7k_m46S.js +2 -0
  563. package/dist/status.scan.fast-json-KHh7R3wX.js +132 -0
  564. package/dist/status.summary-C4r9lkCH.js +214 -0
  565. package/dist/status.summary-D0EJwkmX.js +2 -0
  566. package/dist/subagent-announce-Bu5-8O3P.js +351 -0
  567. package/dist/subagent-announce-delivery-4hk9P48s.js +726 -0
  568. package/dist/subagent-announce-output-Csyi1-Kz.js +364 -0
  569. package/dist/subagent-control-DAeNsV_G.js +506 -0
  570. package/dist/subagent-followup.runtime-Bch92LIq.js +68 -0
  571. package/dist/subagent-followup.runtime.js +1 -1
  572. package/dist/subagent-orphan-recovery-mNzyr1b-.js +305 -0
  573. package/dist/subagent-registry-BMjQxBxi.js +3 -0
  574. package/dist/subagent-registry-D4DFKQCL.js +1753 -0
  575. package/dist/subagent-registry.runtime.js +1 -1
  576. package/dist/subagent-spawn-C13uUm47.js +1005 -0
  577. package/dist/system-cli-BU6GhJxG.js +59 -0
  578. package/dist/targets-eYkepVzz.js +67 -0
  579. package/dist/task-executor-DzJLcm4D.js +360 -0
  580. package/dist/task-owner-access-DW9EbhjP.js +74 -0
  581. package/dist/task-registry-DBJkAtFF.js +2366 -0
  582. package/dist/task-registry-delivery-runtime-BdkPeGC1.js +2 -0
  583. package/dist/task-registry-delivery-runtime-Ov88LGnv.js +3 -0
  584. package/dist/task-registry.maintenance-BU6Z4V_9.js +416 -0
  585. package/dist/task-registry.maintenance-sEo6eYdx.js +2 -0
  586. package/dist/telegram/token.js +1 -1
  587. package/dist/testing-B2jHeQft.js +575 -0
  588. package/dist/text-report-HYrgZP8-.js +587 -0
  589. package/dist/tool-resolution-BZxaDOKg.js +90 -0
  590. package/dist/tools-effective-inventory-BCvCprpD.js +152 -0
  591. package/dist/tools-invoke-http-Dt1rsx4a.js +206 -0
  592. package/dist/trash-F4tvjrKS.js +24 -0
  593. package/dist/tui-cli-DlQ1oejy.js +4575 -0
  594. package/dist/update-cli-DHMdwQWA.js +1759 -0
  595. package/dist/upgrade-UR-EI5pO.js +1226 -0
  596. package/dist/video-generation-task-status-qtHrIZLt.js +163 -0
  597. package/dist/wait-for-idle-before-flush-CYB_61O0.js +5986 -0
  598. package/dist/wizard-models-BKqMCaCm.js +161 -0
  599. package/package.json +1 -1
  600. package/dist/abort-BHSttDhY.js +0 -201
  601. package/dist/abort.runtime-VJ9lFsZS.js +0 -2
  602. package/dist/accounts-BNvagEOQ.js +0 -104
  603. package/dist/accounts-CPIuzenz.js +0 -107
  604. package/dist/accounts-r08DQWhZ.js +0 -2
  605. package/dist/acp-cli-i0L-eRs9.js +0 -2193
  606. package/dist/acp-spawn-CHzVLe9q.js +0 -1093
  607. package/dist/acp-spawn-CqvxDuBq.js +0 -2
  608. package/dist/acp-stateful-target-driver-CWRLc_NP.js +0 -89
  609. package/dist/action-agents-SNCscX_-.js +0 -67
  610. package/dist/action-focus-B2s0PF2E.js +0 -132
  611. package/dist/action-help-CXKbyaZ7.js +0 -7
  612. package/dist/action-info-B3IDKxWu.js +0 -101
  613. package/dist/action-kill-idGvCNhT.js +0 -33
  614. package/dist/action-list-Di7gO3qL.js +0 -21
  615. package/dist/action-log-BCsz-gFi.js +0 -30
  616. package/dist/action-send-DLsdZnVc.js +0 -39
  617. package/dist/action-spawn-DhKEOdL0.js +0 -47
  618. package/dist/action-unfocus-Dh7ti5UP.js +0 -29
  619. package/dist/actions.runtime-BPf03SN3.js +0 -18
  620. package/dist/actions.runtime-CJg_lweh.js +0 -5
  621. package/dist/agent-C3PLvvws.js +0 -2
  622. package/dist/agent-command-UroeNrV4.js +0 -874
  623. package/dist/agent-harness-runtime-MXvI9FlJ.js +0 -144
  624. package/dist/agent-runner-utils-CaVgLZrf.js +0 -239
  625. package/dist/agent-runner.runtime-Csqm3m09.js +0 -3455
  626. package/dist/agent-runtime-B9nUYDUz.js +0 -18
  627. package/dist/agents-BP4p-1q2.js +0 -5
  628. package/dist/agents-CDiXfrfc.js +0 -953
  629. package/dist/aliases-BBCtCq2A.js +0 -96
  630. package/dist/aliases-DrFtFq1p.js +0 -2
  631. package/dist/api-BH0oEwR1.js +0 -5
  632. package/dist/api-D-4gHdrl.js +0 -139
  633. package/dist/api-DE6RYTxv.js +0 -3
  634. package/dist/approval-gateway-resolver-URpDQMld.js +0 -29
  635. package/dist/approval-gateway-runtime-B087BMms.js +0 -2
  636. package/dist/approval-handler-runtime-BEl3ua8-.js +0 -439
  637. package/dist/approval-native-runtime-ghjYGufu.js +0 -729
  638. package/dist/attempt-execution.runtime-PCTFYqLh.js +0 -509
  639. package/dist/attempt.prompt-helpers-CkWEozQ2.js +0 -221
  640. package/dist/attempt.tool-run-context-DbqVgXFk.js +0 -933
  641. package/dist/audit-Lb1yNEwg.js +0 -939
  642. package/dist/audit.runtime-DOnixKE_.js +0 -7
  643. package/dist/auth-BrlJ7NM9.js +0 -2
  644. package/dist/auth-CJoP7Yst.js +0 -383
  645. package/dist/auth-order-D0KFgBib.js +0 -96
  646. package/dist/auth-order-_xlUHzCg.js +0 -2
  647. package/dist/bash-tools-BEVEHCl9.js +0 -2824
  648. package/dist/bash-tools-DJ0D8Wr5.js +0 -3
  649. package/dist/binding-routing-IfKqPcfO.js +0 -85
  650. package/dist/binding-targets-2huR0hTX.js +0 -121
  651. package/dist/bridge-server-D8Y8Fzdz.js +0 -113
  652. package/dist/browser-control-auth-Q6UpVLEj.js +0 -2
  653. package/dist/browser-node-runtime-C9KvsOyx.js +0 -12
  654. package/dist/browser-profiles-DFcwiMEf.js +0 -2
  655. package/dist/browser-runtime-sbZ3hKg6.js +0 -387
  656. package/dist/browser-setup-tools-CP4BkZ9z.js +0 -13
  657. package/dist/build-DzHX2LrH.js +0 -550
  658. package/dist/call-ORivR4Db.js +0 -331
  659. package/dist/call-qzfm6lro.js +0 -3
  660. package/dist/call.runtime-BkzJe07B.js +0 -2
  661. package/dist/capability-cli-BDCvm93o.js +0 -1401
  662. package/dist/catchup-CjZa2PrP.js +0 -300
  663. package/dist/channel-B3UAL9Pk.js +0 -840
  664. package/dist/channel-B5L9LJBF.js +0 -453
  665. package/dist/channel-BGXl6A-E.js +0 -297
  666. package/dist/channel-BNUblayu.js +0 -1320
  667. package/dist/channel-Bej-TN7f.js +0 -491
  668. package/dist/channel-BzOKSC4e.js +0 -350
  669. package/dist/channel-CY2xEOzR.js +0 -1802
  670. package/dist/channel-D2kKLWUA.js +0 -226
  671. package/dist/channel-DcjCe46M.js +0 -1100
  672. package/dist/channel-GqA96nmt.js +0 -595
  673. package/dist/channel-YI2aIJFQ.js +0 -1174
  674. package/dist/channel-core-DqPUhmTt.js +0 -5
  675. package/dist/channel-inbound-CzgMd2Xi.js +0 -31
  676. package/dist/channel-plugin-runtime-DI5uUbxx.js +0 -771
  677. package/dist/channel-runtime-BJqKQitD.js +0 -425
  678. package/dist/channel.runtime-BBn9mgbB.js +0 -89
  679. package/dist/channel.runtime-Bhj1b9gQ.js +0 -34702
  680. package/dist/channel.runtime-BzOVx90Z.js +0 -576
  681. package/dist/channel.runtime-CQkLKWlq.js +0 -109
  682. package/dist/channel.runtime-D8qT4A1x.js +0 -4
  683. package/dist/channel.runtime-DjK9Re1w.js +0 -2364
  684. package/dist/channel.runtime-tWwM8hFw.js +0 -430
  685. package/dist/channel.setup-gaiRZ-r8.js +0 -10
  686. package/dist/channels-BXIl3hBo.js +0 -733
  687. package/dist/channels-cli-CrmBqaul.js +0 -268
  688. package/dist/chat-C42usv-F.js +0 -2758
  689. package/dist/clawbot-cli-BGYO_ymZ.js +0 -9
  690. package/dist/cli-BbD25CFK.js +0 -2
  691. package/dist/cli-CYD4Wfcq.js +0 -219
  692. package/dist/cli-D-6ycHAw.js +0 -72
  693. package/dist/cli-DX4CK-bw.js +0 -2
  694. package/dist/cli-runner-C5_PBTxm.js +0 -286
  695. package/dist/cli-runner.runtime-DE7RpQ27.js +0 -3
  696. package/dist/cli-runner.runtime-ueVMICzY.js +0 -4
  697. package/dist/cli.runtime-DSO8Vfrh.js +0 -1261
  698. package/dist/client-BKro32pr.js +0 -138
  699. package/dist/client-Vx7pseEY.js +0 -713
  700. package/dist/command-auth-CvFUTCCJ.js +0 -76
  701. package/dist/command-config-resolution-BnW1XGnW.js +0 -23
  702. package/dist/command-config-resolution-BrlfYyiN.js +0 -2
  703. package/dist/command-config-resolution.runtime-DYMr8J0t.js +0 -2
  704. package/dist/command-registry-Bi9thw1b.js +0 -9
  705. package/dist/command-registry-D__zH4Fg.js +0 -4
  706. package/dist/command-registry-core-DQoNFQZT.js +0 -101
  707. package/dist/command-secret-gateway-B27Zpgo9.js +0 -528
  708. package/dist/command-status.runtime-fERQMzeI.js +0 -87
  709. package/dist/commands-acp-BmORmf3-.js +0 -77
  710. package/dist/commands-compact.runtime-BUaXIw-I.js +0 -10
  711. package/dist/commands-handlers.runtime-BxbkeuTc.js +0 -4597
  712. package/dist/commands-status-4OW5sqmg.js +0 -16
  713. package/dist/commands-status.runtime-Cl7nJp_7.js +0 -3
  714. package/dist/commands-subagents-control.runtime-BR4qBGkk.js +0 -2
  715. package/dist/commands-subagents-control.runtime-C8ufgKPI.js +0 -3
  716. package/dist/commands-system-prompt-BsimvjJt.js +0 -158
  717. package/dist/commands-system-prompt-CKrY0h7P.js +0 -2
  718. package/dist/commands.runtime-BHsDdaEU.js +0 -166
  719. package/dist/compact-BHYLQst3.js +0 -1118
  720. package/dist/compact.runtime-7-tZRdgw.js +0 -12
  721. package/dist/completion-cli-1sAiSIYc.js +0 -328
  722. package/dist/config-BZ3FuFjH.js +0 -251
  723. package/dist/config-cli-B_dNq5hD.js +0 -1078
  724. package/dist/configure-BOvmX2NJ.js +0 -2
  725. package/dist/configure-DR9NYN9e.js +0 -1245
  726. package/dist/connect-options-DlmPTyhG.js +0 -699
  727. package/dist/control-auth-C_zNiV10.js +0 -125
  728. package/dist/control-service-B1TL51jf.js +0 -156
  729. package/dist/conversation-id-B3lLiTfF.js +0 -235
  730. package/dist/conversation-id-DORmTZm_.js +0 -38
  731. package/dist/conversation-runtime-DDxZZZXE.js +0 -31
  732. package/dist/core-DbPzffGG.js +0 -275
  733. package/dist/cron-cli-AoH4jhFt.js +0 -713
  734. package/dist/daemon-cli-BOJdM3wT.js +0 -12
  735. package/dist/daemon-install-D8HPES4u.js +0 -64
  736. package/dist/delegate-Dmdda3kT.js +0 -64
  737. package/dist/detached-task-runtime-BB5az34R.js +0 -73
  738. package/dist/devices-cli-Cy9DF-DP.js +0 -496
  739. package/dist/diagnostics-CTE0TWR1.js +0 -154
  740. package/dist/direct-dm-9jzadx9u.js +0 -64
  741. package/dist/dispatch-DU7cqfv6.js +0 -1131
  742. package/dist/dispatch-acp-Cu_nUtKg.js +0 -981
  743. package/dist/dispatch-acp-manager.runtime-8MOQ5BRn.js +0 -3
  744. package/dist/dispatch-acp.runtime-DatcHNJq.js +0 -19
  745. package/dist/doctor-device-pairing-Qm-r7mwu.js +0 -307
  746. package/dist/doctor-gateway-daemon-flow-BN2uGhFJ.js +0 -250
  747. package/dist/doctor-gateway-health-CD7Vzth9.js +0 -60
  748. package/dist/doctor-gateway-services-CIypZgv_.js +0 -316
  749. package/dist/doctor-health-ByjG3620.js +0 -59
  750. package/dist/doctor-health-contributions-CxNByg_i.js +0 -486
  751. package/dist/doctor-prompter-BYIoKiZ8.js +0 -56
  752. package/dist/doctor-workspace-status-DL2fRPoT.js +0 -75
  753. package/dist/dreaming-CCctNgkQ.js +0 -1574
  754. package/dist/dreaming-narrative-BPtXKc2-.js +0 -595
  755. package/dist/embedded-gateway-stub.runtime-Hi36BeCq.js +0 -9
  756. package/dist/exec-approvals-cli-DyslUWtQ.js +0 -498
  757. package/dist/fallbacks-B3xZC-ms.js +0 -2
  758. package/dist/fallbacks-CWDz-tSa.js +0 -31
  759. package/dist/fallbacks-shared-BlZBjxHL.js +0 -111
  760. package/dist/gateway-NYBkUx5r.js +0 -115
  761. package/dist/gateway-cli-E5gYA0U1.js +0 -1325
  762. package/dist/gateway-rpc-BrG5Lkfm.js +0 -14
  763. package/dist/gateway-rpc.runtime-BrTGchr9.js +0 -23
  764. package/dist/gateway-runtime-DctMRv_p.js +0 -15
  765. package/dist/gateway-status-B6ol1agz.js +0 -584
  766. package/dist/genesis-tools-D_ah3Zek.js +0 -8999
  767. package/dist/genesis-tools.runtime-Cy7aTWEN.js +0 -2
  768. package/dist/get-reply-BvVkxYum.js +0 -3879
  769. package/dist/get-reply-from-config.runtime-DR3yiK1R.js +0 -2
  770. package/dist/graph-users-yBNugoFz.js +0 -1337
  771. package/dist/health-D_wk2s7j.js +0 -3
  772. package/dist/health-MRnjOx-_.js +0 -469
  773. package/dist/heartbeat-runner-NuhhYnxs.js +0 -5
  774. package/dist/heartbeat-runner-Y4NeUV3L.js +0 -1292
  775. package/dist/heartbeat-runner.runtime-eGfKtcpP.js +0 -4
  776. package/dist/hooks-cli-CtfN2vc-.js +0 -433
  777. package/dist/image-fallbacks-CgeDMYZo.js +0 -2
  778. package/dist/image-fallbacks-CzQ85Eo8.js +0 -31
  779. package/dist/inbound-reply-dispatch-jVlLaSqn.js +0 -73
  780. package/dist/infra-runtime-D2Pqjk-r.js +0 -39
  781. package/dist/init-D_MTYqrw.js +0 -59
  782. package/dist/install-X7wgrwQ1.js +0 -190
  783. package/dist/install.runtime-C4wO4Nr9.js +0 -2
  784. package/dist/launchd-lFgfiDrN.js +0 -688
  785. package/dist/library-DIykYIWD.js +0 -45
  786. package/dist/lifecycle-BNuFzffC.js +0 -571
  787. package/dist/lifecycle-IWN9qlwo.js +0 -229
  788. package/dist/lifecycle-core-CFv5qkS8.js +0 -422
  789. package/dist/lifecycle.runtime-9oo2JCI2.js +0 -2
  790. package/dist/list-BZ3mMSpA.js +0 -2
  791. package/dist/list-CzQs_k0U.js +0 -131
  792. package/dist/list-CzTJTFOH.js +0 -1201
  793. package/dist/list-qDXsgKhB.js +0 -2
  794. package/dist/list.probe-EOZR6ueo.js +0 -419
  795. package/dist/llm-slug-generator-DzWIx0nh.js +0 -79
  796. package/dist/load-config-C_8uUnXU.js +0 -35
  797. package/dist/local-dispatch.runtime-DLd10Xb1.js +0 -8
  798. package/dist/logs-cli-mnOTmC9R.js +0 -265
  799. package/dist/logs-cli.runtime-BvP3aise.js +0 -2
  800. package/dist/main-session-restart-recovery-D7Vxmu7e.js +0 -206
  801. package/dist/managed-image-attachments-BB5u0Zq8.js +0 -2
  802. package/dist/managed-image-attachments-BeRGNdL9.js +0 -635
  803. package/dist/manager-BhNWV4EC.js +0 -2
  804. package/dist/manager-CbZ9ncZs.js +0 -2057
  805. package/dist/markdown-to-line-DyB8w7ef.js +0 -790
  806. package/dist/mcp-cli-CWzLBrDF.js +0 -725
  807. package/dist/mcp-http-1jD7LE0a.js +0 -529
  808. package/dist/memory-core-host-runtime-cli-P80xoEfr.js +0 -9
  809. package/dist/message-BAhd_1ud.js +0 -232
  810. package/dist/message-action-runner-CH2jjT21.js +0 -1407
  811. package/dist/message-action-runner-DW7z_bMx.js +0 -2
  812. package/dist/message-actions-BjBGSsJB.js +0 -143
  813. package/dist/message.gateway.runtime-sUc85g7X.js +0 -2
  814. package/dist/models-auth-status-D6lrM56M.js +0 -201
  815. package/dist/models-cli-CmnbAk2M.js +0 -219
  816. package/dist/monitor-AyGe8vyk.js +0 -1237
  817. package/dist/monitor-DQuy2kx-.js +0 -671
  818. package/dist/monitor-DmtJiX5o.js +0 -788
  819. package/dist/monitor-GB8lcnal.js +0 -1459
  820. package/dist/monitor-IuVjATac.js +0 -1661
  821. package/dist/monitor-auth-rF7mr3Cm.js +0 -207
  822. package/dist/monitor-bnOvJyLN.js +0 -2
  823. package/dist/monitor-processing-B1ewr2qF.js +0 -1974
  824. package/dist/monitor.runtime-BrUD5_VN.js +0 -2
  825. package/dist/monitor.webhook-BvJG6Xbh.js +0 -180
  826. package/dist/msteams-DUDRy3xt.js +0 -35
  827. package/dist/native-hook-relay-CTpTLgCA.js +0 -519
  828. package/dist/nextcloud-talk-BH2uWRZ2.js +0 -17
  829. package/dist/node-cli-AWE1ZFfV.js +0 -2506
  830. package/dist/node-service-DCI-s3Mm.js +0 -68
  831. package/dist/nodes-cli-B7IWCrYq.js +0 -1046
  832. package/dist/nodes-utils-Dg2hrC3z.js +0 -84
  833. package/dist/nodes.helpers-CkJO5i0d.js +0 -34
  834. package/dist/notify-bsxfkOWp.js +0 -315
  835. package/dist/onboard-BQaZtwIU.js +0 -632
  836. package/dist/onboard-helpers-Cc2AnoIU.js +0 -6
  837. package/dist/onboard-helpers-DIxfEXNM.js +0 -204
  838. package/dist/onboard-remote-CYhQbOXH.js +0 -2
  839. package/dist/onboard-remote-DrH3yVxE.js +0 -193
  840. package/dist/onboard-skills-DCI3hVXa.js +0 -134
  841. package/dist/onboard-skills-i4KuFzS4.js +0 -2
  842. package/dist/openai-http-D_7Nk3iN.js +0 -500
  843. package/dist/openresponses-http-BITxvD4V.js +0 -1128
  844. package/dist/operator-approvals-client-C0t_-2xC.js +0 -68
  845. package/dist/outbound.runtime-C8_lBQcx.js +0 -2
  846. package/dist/pair-command-approve-D3s1W5go.js +0 -44
  847. package/dist/persistent-bindings.lifecycle-CCR6khHJ.js +0 -85
  848. package/dist/persistent-bindings.lifecycle-Dgoo5bpE.js +0 -2
  849. package/dist/pi-embedded-C2l80M7j.js +0 -4
  850. package/dist/pi-embedded-DMHGJgoQ.js +0 -2905
  851. package/dist/pi-embedded.runtime-fA0EsIue.js +0 -4
  852. package/dist/pi-tool-definition-adapter-B4hSYdYX.js +0 -217
  853. package/dist/pi-tools-YCHBvJG0.js +0 -1057
  854. package/dist/pi-tools.before-tool-call-BsyruRs4.js +0 -433
  855. package/dist/pi-tools.before-tool-call-D1maRTbl.js +0 -2
  856. package/dist/plugin-DmBZwzWQ.js +0 -12195
  857. package/dist/plugin-enabled-rr_Y1Kwh.js +0 -140
  858. package/dist/plugin-registration-J1JWqMZg.js +0 -23
  859. package/dist/plugin-service-CPY8FSW2.js +0 -2890
  860. package/dist/policy-DDUw681i.js +0 -328
  861. package/dist/prepare.runtime-BfnpyhHB.js +0 -815
  862. package/dist/probe-CCdD6_vN.js +0 -1443
  863. package/dist/probe-CakOsrSu.js +0 -241
  864. package/dist/probe-Ctrcd_Q7.js +0 -2205
  865. package/dist/probe-D9IFIte1.js +0 -2
  866. package/dist/probe-DXMI0QlZ.js +0 -74
  867. package/dist/probe-KtX2HjXM.js +0 -45
  868. package/dist/probe-OcOYm1bj.js +0 -2
  869. package/dist/program-DxZA1yAX.js +0 -111
  870. package/dist/prompt-select-styled-CATG4Xp5.js +0 -20
  871. package/dist/protocol-C40iRm9c.js +0 -2234
  872. package/dist/provider-dispatcher-BZp3Stzr.js +0 -2
  873. package/dist/provider-dispatcher-JJxN7BDL.js +0 -22
  874. package/dist/qr-cli-IMKzycXh.js +0 -349
  875. package/dist/qr-cli-W8X3Ha5T.js +0 -2
  876. package/dist/reaction-runtime-api-D7i4oMn9.js +0 -116
  877. package/dist/reactions-D9eRHeXM.js +0 -998
  878. package/dist/register-service-commands-D37K4_BJ.js +0 -71
  879. package/dist/register.agent-p1q6ZWSs.js +0 -248
  880. package/dist/register.configure-tgXCoIHv.js +0 -15
  881. package/dist/register.maintenance-BtBgu8zC.js +0 -438
  882. package/dist/register.message-B5msOUKt.js +0 -329
  883. package/dist/register.onboard-BO11PDUs.js +0 -81
  884. package/dist/register.runtime-D8XvwfoZ.js +0 -81
  885. package/dist/register.setup-Ba19XSJi.js +0 -150
  886. package/dist/register.status-health-sessions-Bne0mmgw.js +0 -1215
  887. package/dist/register.subclis--mdYCZZM.js +0 -3
  888. package/dist/register.subclis-_kuyreQm.js +0 -29
  889. package/dist/register.subclis-core-UkVTqwB1.js +0 -249
  890. package/dist/reply-dispatch-runtime-DcxOLr7n.js +0 -13
  891. package/dist/reply-runtime-B4VQJnqi.js +0 -11
  892. package/dist/reply.runtime-B990ty9C.js +0 -2
  893. package/dist/restart-health-BWUPc4R-.js +0 -202
  894. package/dist/restart-health-CWvsjHVN.js +0 -2
  895. package/dist/root-help-D9aeVXNr.js +0 -44
  896. package/dist/routes-BSmEgP46.js +0 -2
  897. package/dist/routes-Z67chkN5.js +0 -3341
  898. package/dist/rpc-CBQZvJME.js +0 -61
  899. package/dist/rpc.runtime-ClhNVRer.js +0 -21
  900. package/dist/run-delivery.runtime-Bj566BTH.js +0 -530
  901. package/dist/run-embedded.runtime-DuB-mQh2.js +0 -4
  902. package/dist/run-execution-cli.runtime-Oy4FGfj5.js +0 -4
  903. package/dist/run-executor.runtime-B7-lfFh3.js +0 -277
  904. package/dist/run-main-1Fvwazhp.js +0 -516
  905. package/dist/run-subagent-registry.runtime-Bx9Wga3d.js +0 -2
  906. package/dist/run-wait-C-VgbefQ.js +0 -135
  907. package/dist/runtime-BV7JmOaE.js +0 -9
  908. package/dist/runtime-D7npxl4G.js +0 -973
  909. package/dist/runtime-api-BkVIoPU9.js +0 -4
  910. package/dist/runtime-api-CdhgyHMB.js +0 -9
  911. package/dist/runtime-api-CmlBBCCY.js +0 -9
  912. package/dist/runtime-api-DnhXPE_z.js +0 -14
  913. package/dist/runtime-embedded-pi.runtime-DpKqDUrl.js +0 -2
  914. package/dist/runtime-internal-Bu1n9i4P.js +0 -2
  915. package/dist/runtime-options-CN4g8VJE.js +0 -275
  916. package/dist/runtime-schema-Jjsquqvq.js +0 -27780
  917. package/dist/scan-C8jthyct.js +0 -523
  918. package/dist/scan-DEd4q4aN.js +0 -2
  919. package/dist/secrets-cli-iBL8NBAq.js +0 -2101
  920. package/dist/security-cli-CzYBRa4n.js +0 -486
  921. package/dist/selection-BOalx5uy.js +0 -2
  922. package/dist/selection-BZFVKdFz.js +0 -7736
  923. package/dist/send-C4mKkkWW.js +0 -156
  924. package/dist/send-C_36w3lb.js +0 -102
  925. package/dist/send.runtime-vJT5TzDj.js +0 -2
  926. package/dist/server-BTmWWR_9.js +0 -13
  927. package/dist/server-CBQVrNY0.js +0 -77
  928. package/dist/server-context-Dq2VA7I4.js +0 -2
  929. package/dist/server-context-O_WUP8OV.js +0 -847
  930. package/dist/server-node-events-B8PLg0eQ.js +0 -481
  931. package/dist/server-plugin-bootstrap-ChIvqLMw.js +0 -2
  932. package/dist/server-plugin-bootstrap-Rbxd2g6a.js +0 -11333
  933. package/dist/server-restart-sentinel-BCd6AqrQ.js +0 -697
  934. package/dist/server.impl-CEOWGKN5.js +0 -12735
  935. package/dist/service-ChLFBF7Q.js +0 -120
  936. package/dist/service-XI052xiT.js +0 -2
  937. package/dist/service-audit-BFxGImYM.js +0 -254
  938. package/dist/service-audit-cqHyD5gB.js +0 -2
  939. package/dist/session-kill-http-ChCr5CQ3.js +0 -110
  940. package/dist/session-reset-service-DsYIDYdh.js +0 -471
  941. package/dist/session-route-rem428sJ.js +0 -93
  942. package/dist/session-status.runtime-CFmGwoCm.js +0 -2
  943. package/dist/session-subagent-reactivation.runtime-DLkpnURC.js +0 -2
  944. package/dist/session-tab-registry-DWyzIez5.js +0 -491
  945. package/dist/session-visibility-CJocpWP0.js +0 -147
  946. package/dist/sessions-helpers-CMf9gVTZ.js +0 -304
  947. package/dist/sessions-history-http-C5iZkW8x.js +0 -383
  948. package/dist/sessions-patch-2sBcHc9a.js +0 -309
  949. package/dist/sessions-resolve-D1hmolC-.js +0 -174
  950. package/dist/sessions.runtime-DMPmzLE0.js +0 -2
  951. package/dist/setup-D1ekkhVk.js +0 -495
  952. package/dist/setup-api-DilgjV01.js +0 -29
  953. package/dist/setup-core-CFAiauCt.js +0 -171
  954. package/dist/setup-core-RgJfQc-C.js +0 -176
  955. package/dist/setup-surface-C0l9bHY3.js +0 -286
  956. package/dist/setup-surface-CfcFHZln.js +0 -403
  957. package/dist/setup-surface-CyDRXq_1.js +0 -219
  958. package/dist/setup.finalize-JPqhcPh5.js +0 -539
  959. package/dist/setup.gateway-config-Df6Jm4vX.js +0 -250
  960. package/dist/shared-3gP_6DZV.js +0 -76
  961. package/dist/shared-C9fN-WCy.js +0 -198
  962. package/dist/shared-Cz9c46Aj.js +0 -121
  963. package/dist/slash-state-C7nXXf23.js +0 -1911
  964. package/dist/src-LnF0REtW.js +0 -3974
  965. package/dist/startup-context-CxTy7OzN.js +0 -312
  966. package/dist/status-4n9xL7HY.js +0 -2
  967. package/dist/status-B4kD5cCF.js +0 -2
  968. package/dist/status-CARBoVql.js +0 -209
  969. package/dist/status-COK71LP_.js +0 -3
  970. package/dist/status-DxcqzXtf.js +0 -397
  971. package/dist/status-all-r7zyk41X.js +0 -498
  972. package/dist/status-f2DLmjOF.js +0 -190
  973. package/dist/status-json-C_wESP21.js +0 -14
  974. package/dist/status-json-command-C6w9ZAHp.js +0 -84
  975. package/dist/status-runtime-shared-Bq_SUJpC.js +0 -257
  976. package/dist/status-subagents.runtime-03fp3eBE.js +0 -18
  977. package/dist/status-text-CNvz374U.js +0 -237
  978. package/dist/status.gateway-connection.runtime-zjQmormq.js +0 -2
  979. package/dist/status.gather-BhjoJVEs.js +0 -2
  980. package/dist/status.gather-zdywRvBb.js +0 -292
  981. package/dist/status.runtime-DB31ZRnK.js +0 -2
  982. package/dist/status.scan-DjhdTOWP.js +0 -65
  983. package/dist/status.scan-overview-BYxTBsOw.js +0 -379
  984. package/dist/status.scan.fast-json-Dz0JcORG.js +0 -2
  985. package/dist/status.scan.fast-json-FroEIZ9d.js +0 -132
  986. package/dist/status.summary-3UVa_X5B.js +0 -214
  987. package/dist/status.summary-BGzGsyZB.js +0 -2
  988. package/dist/subagent-announce-BvRFZ87M.js +0 -351
  989. package/dist/subagent-announce-delivery-QvuOM46S.js +0 -726
  990. package/dist/subagent-announce-output-fOtzkOiP.js +0 -364
  991. package/dist/subagent-control-DwnzmG6T.js +0 -506
  992. package/dist/subagent-followup.runtime-DxR1eP_x.js +0 -68
  993. package/dist/subagent-orphan-recovery-CiBbDxX3.js +0 -305
  994. package/dist/subagent-registry-D5FrT_tn.js +0 -3
  995. package/dist/subagent-registry-DbPekx8d.js +0 -1753
  996. package/dist/subagent-spawn-W-bTaU9l.js +0 -1005
  997. package/dist/system-cli-B443uVHG.js +0 -59
  998. package/dist/targets-3Lcm8HoL.js +0 -67
  999. package/dist/task-executor-B5e9_Hmt.js +0 -360
  1000. package/dist/task-owner-access-CIEssJ78.js +0 -74
  1001. package/dist/task-registry-M1bHrFvP.js +0 -2366
  1002. package/dist/task-registry-delivery-runtime-CiHBC7sJ.js +0 -3
  1003. package/dist/task-registry-delivery-runtime-M4O7ffju.js +0 -2
  1004. package/dist/task-registry.maintenance-BURvMU0r.js +0 -2
  1005. package/dist/task-registry.maintenance-CgrLoBqi.js +0 -416
  1006. package/dist/testing-CRy_6-wt.js +0 -575
  1007. package/dist/text-report-B3-4Dvfb.js +0 -587
  1008. package/dist/tool-resolution-C52y5Qtc.js +0 -90
  1009. package/dist/tools-effective-inventory-WlIlqM7G.js +0 -152
  1010. package/dist/tools-invoke-http-B04Rc8tG.js +0 -206
  1011. package/dist/trash-BV5Gcx3a.js +0 -24
  1012. package/dist/tui-cli-DMZ07qRK.js +0 -4575
  1013. package/dist/update-cli-DeBm7b4g.js +0 -1759
  1014. package/dist/upgrade-C9ke1SCc.js +0 -1226
  1015. package/dist/video-generation-task-status-I3jvAjUL.js +0 -163
  1016. package/dist/wait-for-idle-before-flush-BZhF2ejZ.js +0 -5986
  1017. package/dist/wizard-models-CMKeAr_M.js +0 -161
@@ -1,4597 +0,0 @@
1
- import { i as formatErrorMessage } from "./errors-Jbvi20TW.js";
2
- import { a as normalizeLowercaseStringOrEmpty, c as normalizeOptionalString, i as normalizeFastMode, s as normalizeOptionalLowercaseString } from "./string-coerce-C1IzJjqi.js";
3
- import { m as resolveUserPath, r as clampInt } from "./utils-DaGfogP-.js";
4
- import { _ as resolveStateDir } from "./paths-DmR9mjUX.js";
5
- import { r as logVerbose } from "./globals-C5IxqXPj.js";
6
- import { s as normalizeStringEntries } from "./string-normalization-Bvcn03I9.js";
7
- import { a as clearPluginManifestRegistryCache } from "./manifest-registry-DQR_-Eq8.js";
8
- import { F as unsetConfigOverride, M as getConfigOverrides, N as resetConfigOverrides, P as setConfigOverride, T as validateConfigObjectWithPlugins, u as readConfigFileSnapshot, y as writeConfigFile } from "./io-DNd8mbjy.js";
9
- import { r as normalizeOptionalAccountId } from "./account-id-C3j_3_su.js";
10
- import { u as resolveAgentIdFromSessionKey } from "./session-key-EpIbK3Oz.js";
11
- import { o as normalizeChannelId } from "./registry-CXnn3dzM.js";
12
- import { i as normalizeChannelId$1, t as getChannelPlugin } from "./registry-DXDC8Wqv.js";
13
- import { i as unsetConfigValueAtPath, n as parseConfigPath, r as setConfigValueAtPath, t as getConfigValueAtPath } from "./config-paths-DaElECOW.js";
14
- import { b as resolveAgentWorkspaceDir, p as resolveSessionAgentId, y as resolveAgentDir } from "./agent-scope-CDjZLqNk.js";
15
- import { t as parseDurationMs } from "./parse-duration-DH3x5y_9.js";
16
- import { n as isRestartEnabled, t as isCommandFlagEnabled } from "./commands.flags-CR-1vURU.js";
17
- import "./config-3He3LWHw.js";
18
- import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-CfESmEX1.js";
19
- import { r as isInternalMessageChannel, u as normalizeMessageChannel } from "./message-channel-BbI8d0sw.js";
20
- import { n as resolveChannelApprovalCapability } from "./plugins-DNe6i7Rv.js";
21
- import { m as triggerInternalHook, n as createInternalHookEvent } from "./internal-hooks-aB3cCCPc.js";
22
- import { x as prepareProviderRuntimeAuth } from "./provider-runtime-CE8zqYv8.js";
23
- import { t as ensureGenesisModelsJson } from "./models-config-DnicdxyQ.js";
24
- import { g as resolveResponseUsageMode, m as normalizeUsageDisplay } from "./thinking-CM0wvLlr.js";
25
- import { t as requireApiKey } from "./model-auth-runtime-shared-7w03qzdi.js";
26
- import { i as discoverModels, r as discoverAuthStorage } from "./pi-model-discovery-k8VUE5Tp.js";
27
- import { a as resolveSessionFilePathOptions, i as resolveSessionFilePath, r as resolveDefaultSessionStorePath } from "./paths-DD6L4IvS.js";
28
- import { t as loadSessionStore } from "./store-load-CUqchamJ.js";
29
- import { o as resolveFreshSessionTotalTokens } from "./types-Bx9yhV03.js";
30
- import { o as updateSessionStore } from "./store-CUSu4-Qr.js";
31
- import { t as extractDeliveryInfo } from "./sessions--xDkaJeX.js";
32
- import { i as formatUsd, r as formatTokenCount } from "./usage-format-CeDc5if9.js";
33
- import { n as stripInboundMetadata } from "./strip-inbound-meta-BpubGgAq.js";
34
- import { t as diagnosticLogger } from "./diagnostic-runtime-BvLyIIwP.js";
35
- import { n as redactSupportString } from "./diagnostic-support-redaction-DZPXhPOk.js";
36
- import { C as safeJsonStringify, S as safeTrajectorySessionFileName, b as resolveTrajectoryFilePath, w as sanitizeDiagnosticPayload, x as resolveTrajectoryPointerFilePath, y as TRAJECTORY_RUNTIME_FILE_MAX_BYTES } from "./selection-BZFVKdFz.js";
37
- import { S as setTtsProvider, _ as setLastTtsAttempt, a as getTtsMaxLength, b as setTtsEnabled, c as isTtsEnabled, h as resolveTtsPrefsPath, i as getResolvedSpeechProviderConfig, l as isTtsProviderConfigured, m as resolveTtsConfig, o as getTtsProvider, r as getLastTtsAttempt, s as isSummarizationEnabled, v as setSummarizationEnabled, w as textToSpeech, x as setTtsMaxLength } from "./tts-Dp_lVFqh.js";
38
- import { t as analyzeBootstrapBudget } from "./bootstrap-budget-CpN-YN0m.js";
39
- import { h as resolveBootstrapTotalMaxChars, p as resolveBootstrapMaxChars } from "./pi-embedded-helpers-BhsTiD6Y.js";
40
- import { n as resolveSandboxRuntimeStatus } from "./runtime-status-W0lHxRqX.js";
41
- import { i as resolveImageSanitizationLimits, n as sanitizeImageBlocks } from "./tool-images-1Y5MwBpT.js";
42
- import { r as getApiKeyForModel } from "./model-auth-CDl8OFEJ.js";
43
- import { t as registerProviderStreamForModel } from "./provider-stream-DQRHM0a1.js";
44
- import { m as stripToolResultDetails } from "./transport-stream-shared-B3e6W1dy.js";
45
- import { i as unsetConfiguredMcpServer, r as setConfiguredMcpServer, t as listConfiguredMcpServers } from "./mcp-config-CDKA6_LY.js";
46
- import { t as EmbeddedBlockChunker } from "./pi-embedded-block-chunker-D1H99cJT.js";
47
- import { r as callGateway } from "./call-ORivR4Db.js";
48
- import { d as writeRestartSentinel, n as buildRestartSuccessContinuation, r as formatDoctorNonInteractiveHint, s as removeRestartSentinelFile } from "./restart-sentinel-D0qfIlId.js";
49
- import { l as triggerGenesisRestart, o as scheduleGatewaySigusr1Restart } from "./restart-C-4J0cf2.js";
50
- import { i as resolveReplyToMode } from "./reply-threading-CSNWvu2g.js";
51
- import { _ as authorizeConfigWriteShared, b as resolveConfigWriteTargetFromPathShared, v as canBypassConfigWritePolicyShared, y as formatConfigWriteDeniedMessageShared } from "./channel-config-helpers-Bn_khg_r.js";
52
- import { n as formatTaskStatusDetail, r as formatTaskStatusTitle, t as buildTaskStatusSnapshot } from "./task-status-LIWTrTqj.js";
53
- import { a as clearSessionQueues } from "./queue-Rq1mceUG.js";
54
- import { r as getSessionBindingService } from "./session-binding-service-DoeFMDT5.js";
55
- import { h as replyRunRegistry, i as getActiveEmbeddedRunSnapshot } from "./runs-DUTtPgDm.js";
56
- import "./diagnostic-CC9CPVio.js";
57
- import { t as formatDurationCompact } from "./format-duration-D7ua_Cv_.js";
58
- import "./sandbox-DAnx9TYc.js";
59
- import { t as buildSystemPromptReport } from "./system-prompt-report-DUc7GJ-N.js";
60
- import { n as estimateTokensFromChars } from "./cjk-chars-DwPGabQx.js";
61
- import { i as streamWithPayloadPatch } from "./moonshot-thinking-stream-wrappers-C6ChjovN.js";
62
- import { r as resolveModelWithRegistry } from "./model-Dox-u3UD.js";
63
- import { i as matchPluginCommand, n as executePluginCommand } from "./commands-BZ3Hrsgn.js";
64
- import { t as isApprovalNotFoundError } from "./approval-errors-Cp6xrD42.js";
65
- import { r as normalizeCommandBody } from "./commands-registry-normalize-ZSb2LkjJ.js";
66
- import { i as setAbortMemory, r as isAbortTrigger } from "./abort-primitives-B2NIccgr.js";
67
- import "./commands-registry-BUxuRHG0.js";
68
- import { n as formatTimeAgo } from "./format-relative-uQtNNoGl.js";
69
- import { o as stripMentions, s as stripStructuralPrefixes } from "./mentions-Dm5IQz51.js";
70
- import { n as setChannelConversationBindingMaxAgeBySessionKey, t as setChannelConversationBindingIdleTimeoutBySessionKey } from "./conversation-bindings-CgNVPGwn.js";
71
- import { a as readChannelAllowFromStore, l as removeChannelAllowFromStoreEntry, t as addChannelAllowFromStoreEntry } from "./pairing-store-DI7znxyK.js";
72
- import { i as installPluginFromPath, r as installPluginFromNpmSpec } from "./install-BmYV_Qz0.js";
73
- import { l as resolveArchiveKind } from "./archive-Cm1nQqez.js";
74
- import { n as isImplicitSameChatApprovalAuthorization } from "./approval-auth-helpers-BUQDSYGo.js";
75
- import { n as parseActivationCommand } from "./group-activation-C_gTAl_1.js";
76
- import { t as resolveFastModeState } from "./fast-mode-Cw7-WKiu.js";
77
- import { n as resolveSessionAuthProfileOverride } from "./session-override-Cra7WfkP.js";
78
- import { n as extractExplicitGroupId, t as formatElevatedUnavailableMessage } from "./elevated-unavailable-Dl1vpi7z.js";
79
- import { t as resolveRuntimePolicySessionKey } from "./runtime-policy-session-key-ClUJDeX7.js";
80
- import { a as shouldPersistAbortCutoff, i as resolveAbortCutoffFromContext, t as applyAbortCutoffToSessionEntry } from "./abort-cutoff-ICh6JSMK.js";
81
- import { t as resolveEffectiveToolInventory } from "./tools-effective-inventory-WlIlqM7G.js";
82
- import { r as resolveConversationBindingContextFromAcpCommand } from "./conversation-binding-input-4r2gq_KQ.js";
83
- import { n as resolveSessionEntryForKey, r as stopSubagentsForRequester, t as formatAbortReplyText } from "./abort-BHSttDhY.js";
84
- import { t as extractBtwQuestion } from "./btw-command-DGuvquyH.js";
85
- import { t as formatThreadBindingDurationLabel } from "./thread-bindings-messages-BbXbfHuh.js";
86
- import { n as getSpeechProvider, r as listSpeechProviders, t as canonicalizeSpeechProviderId } from "./provider-registry-ChCcnRHr.js";
87
- import { a as requireGatewayClientScopeForInternalChannel, i as requireCommandFlagEnabled, n as rejectNonOwnerCommand, r as rejectUnauthorizedCommand, t as buildDisabledCommandReply } from "./command-gates-BZ2Ly1tg.js";
88
- import { t as handleAcpCommand } from "./commands-acp-BmORmf3-.js";
89
- import { n as buildCommandsMessagePaginated, r as buildHelpMessage, t as buildCommandsMessage } from "./command-status-builders-gbO0smso.js";
90
- import { _ as getFinishedSession, v as getSession } from "./bash-tools.exec-runtime-nmZEc38u.js";
91
- import { t as listSkillCommandsForAgents } from "./skill-commands-Cjewv1mD.js";
92
- import { r as handleModelsCommand } from "./commands-models-BAneNjrI.js";
93
- import { n as setPluginEnabledInConfig } from "./enable--YQu1m7B.js";
94
- import { r as createExecTool } from "./bash-tools-BEVEHCl9.js";
95
- import { n as listTasksForAgentIdForStatus, r as listTasksForSessionKeyForStatus } from "./status-text-CNvz374U.js";
96
- import { n as buildThreadingToolContext } from "./agent-runner-utils-CaVgLZrf.js";
97
- import { d as resolveChannelAccountId, f as resolveCommandSurfaceChannel, l as resolveSubagentsAction, o as resolveHandledPrefix, s as resolveRequesterSessionKey, u as stopWithText } from "./shared-C9fN-WCy.js";
98
- import { t as buildToolsMessage } from "./status-ChOxNWSb.js";
99
- import { t as parseConfigValue } from "./config-value-sfbZgEb6.js";
100
- import { t as resolveCommandsSystemPromptBundle } from "./commands-system-prompt-BsimvjJt.js";
101
- import { a as writeSupportBundleDirectory, i as textSupportBundleFile, n as jsonlSupportBundleFile, r as supportBundleContents, t as jsonSupportBundleFile } from "./diagnostic-support-bundle-CZhX-X2W.js";
102
- import { t as buildStatusReply } from "./commands-status-4OW5sqmg.js";
103
- import { i as buildNpmInstallRecordFields, n as persistPluginInstall } from "./plugins-install-persist-Ccyj_thC.js";
104
- import { h as parseClawHubPluginSpec } from "./clawhub-LPw6cLUe.js";
105
- import { r as installPluginFromClawHub } from "./clawhub-Dz5KDje-.js";
106
- import { a as buildPluginDiagnosticsReport, c as formatPluginCompatibilityNotice, o as buildPluginInspectReport, s as buildPluginSnapshotReport, t as buildAllPluginInspectReports } from "./status-DagNCfVv.js";
107
- import { a as decidePreferredClawHubFallback, i as createPluginInstallLogger, n as buildPreferredClawHubSpec, u as resolveFileNpmSpecToLocalPath } from "./plugins-command-helpers-oZG-T69i.js";
108
- import { n as loadCostUsageSummary, r as loadSessionCostSummary } from "./session-cost-usage-CbaKFiYP.js";
109
- import { fileURLToPath } from "node:url";
110
- import fs from "node:fs";
111
- import path from "node:path";
112
- import { SessionManager } from "@mariozechner/pi-coding-agent";
113
- import { streamSimple } from "@mariozechner/pi-ai";
114
- //#region src/channels/plugins/config-writes.ts
115
- function isInternalConfigWriteMessageChannel(channel) {
116
- return normalizeLowercaseStringOrEmpty(channel) === "webchat";
117
- }
118
- function authorizeConfigWrite(params) {
119
- return authorizeConfigWriteShared(params);
120
- }
121
- function resolveConfigWriteTargetFromPath(path) {
122
- return resolveConfigWriteTargetFromPathShared({
123
- path,
124
- normalizeChannelId: (raw) => normalizeLowercaseStringOrEmpty(raw)
125
- });
126
- }
127
- function canBypassConfigWritePolicy(params) {
128
- return canBypassConfigWritePolicyShared({
129
- ...params,
130
- isInternalMessageChannel: isInternalConfigWriteMessageChannel
131
- });
132
- }
133
- function formatConfigWriteDeniedMessage(params) {
134
- return formatConfigWriteDeniedMessageShared(params);
135
- }
136
- //#endregion
137
- //#region src/auto-reply/reply/config-write-authorization.ts
138
- function resolveConfigWriteDeniedText(params) {
139
- const writeAuth = authorizeConfigWrite({
140
- cfg: params.cfg,
141
- origin: {
142
- channelId: params.channelId,
143
- accountId: params.accountId
144
- },
145
- target: params.target,
146
- allowBypass: canBypassConfigWritePolicy({
147
- channel: params.channel ?? "",
148
- gatewayClientScopes: params.gatewayClientScopes
149
- })
150
- });
151
- if (writeAuth.allowed) return null;
152
- return formatConfigWriteDeniedMessage({
153
- result: writeAuth,
154
- fallbackChannelId: params.channelId
155
- });
156
- }
157
- //#endregion
158
- //#region src/auto-reply/reply/commands-allowlist.ts
159
- const ACTIONS = new Set([
160
- "list",
161
- "add",
162
- "remove"
163
- ]);
164
- const SCOPES = new Set([
165
- "dm",
166
- "group",
167
- "all"
168
- ]);
169
- function resolveAllowlistAccountId(params) {
170
- const explicitAccountId = normalizeOptionalAccountId(params.parsedAccount);
171
- if (explicitAccountId) return explicitAccountId;
172
- const configuredDefaultAccountId = normalizeOptionalString(getChannelPlugin(params.channelId)?.config.defaultAccountId?.(params.cfg));
173
- const ctxAccountId = normalizeOptionalAccountId(params.ctxAccountId);
174
- return configuredDefaultAccountId || ctxAccountId || "default";
175
- }
176
- function parseAllowlistCommand(raw) {
177
- const trimmed = raw.trim();
178
- if (!(normalizeOptionalLowercaseString(trimmed) ?? "").startsWith("/allowlist")) return null;
179
- const rest = trimmed.slice(10).trim();
180
- if (!rest) return {
181
- action: "list",
182
- scope: "dm"
183
- };
184
- const tokens = rest.split(/\s+/);
185
- let action = "list";
186
- let scope = "dm";
187
- let resolve = false;
188
- let target = "both";
189
- let channel;
190
- let account;
191
- const entryTokens = [];
192
- let i = 0;
193
- const firstAction = normalizeOptionalLowercaseString(tokens[i]);
194
- if (firstAction && ACTIONS.has(firstAction)) {
195
- action = firstAction;
196
- i += 1;
197
- }
198
- const firstScope = normalizeOptionalLowercaseString(tokens[i]);
199
- if (firstScope && SCOPES.has(firstScope)) {
200
- scope = firstScope;
201
- i += 1;
202
- }
203
- for (; i < tokens.length; i += 1) {
204
- const token = tokens[i];
205
- const lowered = normalizeOptionalLowercaseString(token) ?? "";
206
- if (lowered === "--resolve" || lowered === "resolve") {
207
- resolve = true;
208
- continue;
209
- }
210
- if (lowered === "--config" || lowered === "config") {
211
- target = "config";
212
- continue;
213
- }
214
- if (lowered === "--store" || lowered === "store") {
215
- target = "store";
216
- continue;
217
- }
218
- if (lowered === "--channel" && tokens[i + 1]) {
219
- channel = tokens[i + 1];
220
- i += 1;
221
- continue;
222
- }
223
- if (lowered === "--account" && tokens[i + 1]) {
224
- account = tokens[i + 1];
225
- i += 1;
226
- continue;
227
- }
228
- const kv = token.split("=");
229
- if (kv.length === 2) {
230
- const key = normalizeOptionalLowercaseString(kv[0]);
231
- const value = normalizeOptionalString(kv[1]);
232
- if (key === "channel") {
233
- if (value) channel = value;
234
- continue;
235
- }
236
- if (key === "account") {
237
- if (value) account = value;
238
- continue;
239
- }
240
- const normalizedValue = normalizeOptionalLowercaseString(value);
241
- if (key === "scope" && normalizedValue && SCOPES.has(normalizedValue)) {
242
- scope = normalizedValue;
243
- continue;
244
- }
245
- }
246
- entryTokens.push(token);
247
- }
248
- if (action === "add" || action === "remove") {
249
- const entry = entryTokens.join(" ").trim();
250
- if (!entry) return {
251
- action: "error",
252
- message: "Usage: /allowlist add|remove <entry>"
253
- };
254
- return {
255
- action,
256
- scope,
257
- entry,
258
- channel,
259
- account,
260
- resolve,
261
- target
262
- };
263
- }
264
- return {
265
- action: "list",
266
- scope,
267
- channel,
268
- account,
269
- resolve
270
- };
271
- }
272
- function normalizeAllowFrom(params) {
273
- const plugin = getChannelPlugin(params.channelId);
274
- if (plugin?.config.formatAllowFrom) return plugin.config.formatAllowFrom({
275
- cfg: params.cfg,
276
- accountId: params.accountId,
277
- allowFrom: params.values
278
- });
279
- return normalizeStringEntries(params.values);
280
- }
281
- function formatEntryList(entries, resolved) {
282
- if (entries.length === 0) return "(none)";
283
- return entries.map((entry) => {
284
- const name = resolved?.get(entry);
285
- return name ? `${entry} (${name})` : entry;
286
- }).join(", ");
287
- }
288
- async function updatePairingStoreAllowlist(params) {
289
- const storeEntry = {
290
- channel: params.channelId,
291
- entry: params.entry,
292
- accountId: params.accountId
293
- };
294
- if (params.action === "add") {
295
- await addChannelAllowFromStoreEntry(storeEntry);
296
- return;
297
- }
298
- await removeChannelAllowFromStoreEntry(storeEntry);
299
- if (params.accountId === "default") await removeChannelAllowFromStoreEntry({
300
- channel: params.channelId,
301
- entry: params.entry
302
- });
303
- }
304
- function mapResolvedAllowlistNames(entries) {
305
- const map = /* @__PURE__ */ new Map();
306
- for (const entry of entries) if (entry.resolved && entry.name) map.set(entry.input, entry.name);
307
- return map;
308
- }
309
- async function resolveAllowlistNames(params) {
310
- return mapResolvedAllowlistNames(await getChannelPlugin(params.channelId)?.allowlist?.resolveNames?.({
311
- cfg: params.cfg,
312
- accountId: params.accountId,
313
- scope: params.scope,
314
- entries: params.entries
315
- }) ?? []);
316
- }
317
- async function readAllowlistConfig(params) {
318
- return await getChannelPlugin(params.channelId)?.allowlist?.readConfig?.({
319
- cfg: params.cfg,
320
- accountId: params.accountId
321
- }) ?? {};
322
- }
323
- const handleAllowlistCommand = async (params, allowTextCommands) => {
324
- if (!allowTextCommands) return null;
325
- const parsed = parseAllowlistCommand(params.command.commandBodyNormalized);
326
- if (!parsed) return null;
327
- if (parsed.action === "error") return {
328
- shouldContinue: false,
329
- reply: { text: `āš ļø ${parsed.message}` }
330
- };
331
- const unauthorized = rejectUnauthorizedCommand(params, "/allowlist");
332
- if (unauthorized) return unauthorized;
333
- if (parsed.action !== "list") {
334
- const nonOwner = rejectNonOwnerCommand(params, "/allowlist");
335
- if (nonOwner) return nonOwner;
336
- }
337
- const channelId = normalizeChannelId(parsed.channel) ?? params.command.channelId ?? normalizeChannelId(params.command.channel);
338
- if (!channelId) return {
339
- shouldContinue: false,
340
- reply: { text: "āš ļø Unknown channel. Add channel=<id> to the command." }
341
- };
342
- if (normalizeOptionalString(parsed.account) && !normalizeOptionalAccountId(parsed.account)) return {
343
- shouldContinue: false,
344
- reply: { text: "āš ļø Invalid account id. Reserved keys (__proto__, constructor, prototype) are blocked." }
345
- };
346
- const accountId = resolveAllowlistAccountId({
347
- cfg: params.cfg,
348
- channelId,
349
- parsedAccount: parsed.account,
350
- ctxAccountId: params.ctx.AccountId
351
- });
352
- const plugin = getChannelPlugin(channelId);
353
- if (parsed.action === "list") {
354
- const supportsStore = Boolean(plugin?.pairing);
355
- if (!plugin?.allowlist?.readConfig && !supportsStore) return {
356
- shouldContinue: false,
357
- reply: { text: `āš ļø ${channelId} does not expose allowlist configuration.` }
358
- };
359
- const storeAllowFrom = supportsStore ? await readChannelAllowFromStore(channelId, process.env, accountId).catch(() => []) : [];
360
- const configState = await readAllowlistConfig({
361
- cfg: params.cfg,
362
- channelId,
363
- accountId
364
- });
365
- const dmAllowFrom = (configState.dmAllowFrom ?? []).map(String);
366
- const groupAllowFrom = (configState.groupAllowFrom ?? []).map(String);
367
- const groupOverrides = (configState.groupOverrides ?? []).map((entry) => ({
368
- label: entry.label,
369
- entries: entry.entries.map(String).filter(Boolean)
370
- }));
371
- const dmDisplay = normalizeAllowFrom({
372
- cfg: params.cfg,
373
- channelId,
374
- accountId,
375
- values: dmAllowFrom
376
- });
377
- const groupDisplay = normalizeAllowFrom({
378
- cfg: params.cfg,
379
- channelId,
380
- accountId,
381
- values: groupAllowFrom
382
- });
383
- const groupOverrideEntries = groupOverrides.flatMap((entry) => entry.entries);
384
- const groupOverrideDisplay = normalizeAllowFrom({
385
- cfg: params.cfg,
386
- channelId,
387
- accountId,
388
- values: groupOverrideEntries
389
- });
390
- const resolvedDm = parsed.resolve && dmDisplay.length > 0 ? await resolveAllowlistNames({
391
- cfg: params.cfg,
392
- channelId,
393
- accountId,
394
- scope: "dm",
395
- entries: dmDisplay
396
- }) : void 0;
397
- const resolvedGroup = parsed.resolve && groupOverrideDisplay.length > 0 ? await resolveAllowlistNames({
398
- cfg: params.cfg,
399
- channelId,
400
- accountId,
401
- scope: "group",
402
- entries: groupOverrideDisplay
403
- }) : void 0;
404
- const lines = ["🧾 Allowlist"];
405
- lines.push(`Channel: ${channelId}${accountId ? ` (account ${accountId})` : ""}`);
406
- if (configState.dmPolicy) lines.push(`DM policy: ${configState.dmPolicy}`);
407
- if (configState.groupPolicy) lines.push(`Group policy: ${configState.groupPolicy}`);
408
- const showDm = parsed.scope === "dm" || parsed.scope === "all";
409
- const showGroup = parsed.scope === "group" || parsed.scope === "all";
410
- if (showDm) lines.push(`DM allowFrom (config): ${formatEntryList(dmDisplay, resolvedDm)}`);
411
- if (supportsStore && storeAllowFrom.length > 0) {
412
- const storeLabel = normalizeAllowFrom({
413
- cfg: params.cfg,
414
- channelId,
415
- accountId,
416
- values: storeAllowFrom
417
- });
418
- lines.push(`Paired allowFrom (store): ${formatEntryList(storeLabel)}`);
419
- }
420
- if (showGroup) {
421
- if (groupAllowFrom.length > 0) lines.push(`Group allowFrom (config): ${formatEntryList(groupDisplay, resolvedGroup)}`);
422
- if (groupOverrides.length > 0) {
423
- lines.push("Group overrides:");
424
- for (const entry of groupOverrides) {
425
- const normalized = normalizeAllowFrom({
426
- cfg: params.cfg,
427
- channelId,
428
- accountId,
429
- values: entry.entries
430
- });
431
- lines.push(`- ${entry.label}: ${formatEntryList(normalized, resolvedGroup)}`);
432
- }
433
- }
434
- }
435
- return {
436
- shouldContinue: false,
437
- reply: { text: lines.join("\n") }
438
- };
439
- }
440
- const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
441
- label: "/allowlist write",
442
- allowedScopes: ["operator.admin"],
443
- missingText: "āŒ /allowlist add|remove requires operator.admin for gateway clients."
444
- });
445
- if (missingAdminScope) return missingAdminScope;
446
- const disabled = requireCommandFlagEnabled(params.cfg, {
447
- label: "/allowlist edits",
448
- configKey: "config",
449
- disabledVerb: "are"
450
- });
451
- if (disabled) return disabled;
452
- const shouldUpdateConfig = parsed.target !== "store";
453
- const shouldTouchStore = parsed.target !== "config" && Boolean(plugin?.pairing);
454
- if (shouldUpdateConfig) {
455
- if (parsed.scope === "all") return {
456
- shouldContinue: false,
457
- reply: { text: "āš ļø /allowlist add|remove requires scope dm or group." }
458
- };
459
- if (!plugin?.allowlist?.applyConfigEdit) return {
460
- shouldContinue: false,
461
- reply: { text: `āš ļø ${channelId} does not support ${parsed.scope} allowlist edits via /allowlist.` }
462
- };
463
- const snapshot = await readConfigFileSnapshot();
464
- if (!snapshot.valid || !snapshot.parsed || typeof snapshot.parsed !== "object") return {
465
- shouldContinue: false,
466
- reply: { text: "āš ļø Config file is invalid; fix it before using /allowlist." }
467
- };
468
- const parsedConfig = structuredClone(snapshot.parsed);
469
- const editResult = await plugin.allowlist.applyConfigEdit({
470
- cfg: params.cfg,
471
- parsedConfig,
472
- accountId,
473
- scope: parsed.scope,
474
- action: parsed.action,
475
- entry: parsed.entry
476
- });
477
- if (!editResult) return {
478
- shouldContinue: false,
479
- reply: { text: `āš ļø ${channelId} does not support ${parsed.scope} allowlist edits via /allowlist.` }
480
- };
481
- if (editResult.kind === "invalid-entry") return {
482
- shouldContinue: false,
483
- reply: { text: "āš ļø Invalid allowlist entry." }
484
- };
485
- const deniedText = resolveConfigWriteDeniedText({
486
- cfg: params.cfg,
487
- channel: params.command.channel,
488
- channelId,
489
- accountId,
490
- gatewayClientScopes: params.ctx.GatewayClientScopes,
491
- target: editResult.writeTarget
492
- });
493
- if (deniedText) return {
494
- shouldContinue: false,
495
- reply: { text: deniedText }
496
- };
497
- const configChanged = editResult.changed;
498
- if (configChanged) {
499
- const validated = validateConfigObjectWithPlugins(parsedConfig);
500
- if (!validated.ok) {
501
- const issue = validated.issues[0];
502
- return {
503
- shouldContinue: false,
504
- reply: { text: `āš ļø Config invalid after update (${issue.path}: ${issue.message}).` }
505
- };
506
- }
507
- await writeConfigFile(validated.config);
508
- }
509
- if (!configChanged && !shouldTouchStore) return {
510
- shouldContinue: false,
511
- reply: { text: parsed.action === "add" ? "āœ… Already allowlisted." : "āš ļø Entry not found." }
512
- };
513
- if (shouldTouchStore) await updatePairingStoreAllowlist({
514
- action: parsed.action,
515
- channelId,
516
- accountId,
517
- entry: parsed.entry
518
- });
519
- const actionLabel = parsed.action === "add" ? "added" : "removed";
520
- const scopeLabel = parsed.scope === "dm" ? "DM" : "group";
521
- const locations = [];
522
- if (configChanged) locations.push(editResult.pathLabel);
523
- if (shouldTouchStore) locations.push("pairing store");
524
- return {
525
- shouldContinue: false,
526
- reply: { text: `āœ… ${scopeLabel} allowlist ${actionLabel}: ${locations.length > 0 ? locations.join(" + ") : "no-op"}.` }
527
- };
528
- }
529
- if (!shouldTouchStore) return {
530
- shouldContinue: false,
531
- reply: { text: "āš ļø This channel does not support allowlist storage." }
532
- };
533
- await updatePairingStoreAllowlist({
534
- action: parsed.action,
535
- channelId,
536
- accountId,
537
- entry: parsed.entry
538
- });
539
- const actionLabel = parsed.action === "add" ? "added" : "removed";
540
- return {
541
- shouldContinue: false,
542
- reply: { text: `āœ… ${parsed.scope === "dm" ? "DM" : "group"} allowlist ${actionLabel} in pairing store.` }
543
- };
544
- };
545
- //#endregion
546
- //#region src/infra/channel-approval-auth.ts
547
- function resolveApprovalCommandAuthorization(params) {
548
- const channel = normalizeMessageChannel(params.channel);
549
- if (!channel) return {
550
- authorized: true,
551
- explicit: false
552
- };
553
- const approvalCapability = resolveChannelApprovalCapability(getChannelPlugin(channel));
554
- const resolved = approvalCapability?.authorizeActorAction?.({
555
- cfg: params.cfg,
556
- accountId: params.accountId,
557
- senderId: params.senderId,
558
- action: "approve",
559
- approvalKind: params.kind
560
- });
561
- if (!resolved) return {
562
- authorized: true,
563
- explicit: false
564
- };
565
- const implicitSameChatAuthorization = isImplicitSameChatApprovalAuthorization(resolved);
566
- const availability = approvalCapability?.getActionAvailabilityState?.({
567
- cfg: params.cfg,
568
- accountId: params.accountId,
569
- action: "approve",
570
- approvalKind: params.kind
571
- });
572
- return {
573
- authorized: resolved.authorized,
574
- reason: resolved.reason,
575
- explicit: resolved.authorized ? !implicitSameChatAuthorization && availability?.kind !== "disabled" : true
576
- };
577
- }
578
- //#endregion
579
- //#region src/auto-reply/reply/commands-approve.ts
580
- const COMMAND_REGEX = /^\/?approve(?:\s|$)/i;
581
- const FOREIGN_COMMAND_MENTION_REGEX = /^\/approve@([^\s]+)(?:\s|$)/i;
582
- const DECISION_ALIASES = {
583
- allow: "allow-once",
584
- once: "allow-once",
585
- "allow-once": "allow-once",
586
- allowonce: "allow-once",
587
- always: "allow-always",
588
- "allow-always": "allow-always",
589
- allowalways: "allow-always",
590
- deny: "deny",
591
- reject: "deny",
592
- block: "deny"
593
- };
594
- const APPROVE_USAGE_TEXT = "Usage: /approve <id> <decision> (see the pending approval message for available decisions)";
595
- function parseApproveCommand(raw) {
596
- const trimmed = raw.trim();
597
- if (FOREIGN_COMMAND_MENTION_REGEX.test(trimmed)) return {
598
- ok: false,
599
- error: "āŒ This /approve command targets a different Telegram bot."
600
- };
601
- const commandMatch = trimmed.match(COMMAND_REGEX);
602
- if (!commandMatch) return null;
603
- const rest = trimmed.slice(commandMatch[0].length).trim();
604
- if (!rest) return {
605
- ok: false,
606
- error: APPROVE_USAGE_TEXT
607
- };
608
- const tokens = rest.split(/\s+/).filter(Boolean);
609
- if (tokens.length < 2) return {
610
- ok: false,
611
- error: APPROVE_USAGE_TEXT
612
- };
613
- const first = normalizeLowercaseStringOrEmpty(tokens[0]);
614
- const second = normalizeLowercaseStringOrEmpty(tokens[1]);
615
- if (DECISION_ALIASES[first]) return {
616
- ok: true,
617
- decision: DECISION_ALIASES[first],
618
- id: tokens.slice(1).join(" ").trim()
619
- };
620
- if (DECISION_ALIASES[second]) return {
621
- ok: true,
622
- decision: DECISION_ALIASES[second],
623
- id: tokens[0]
624
- };
625
- return {
626
- ok: false,
627
- error: APPROVE_USAGE_TEXT
628
- };
629
- }
630
- function buildResolvedByLabel(params) {
631
- return `${params.command.channel}:${params.command.senderId ?? "unknown"}`;
632
- }
633
- function formatApprovalSubmitError(error) {
634
- return formatErrorMessage(error);
635
- }
636
- function resolveApprovalMethods(params) {
637
- if (params.approvalId.startsWith("plugin:")) return params.pluginAuthorization.authorized ? ["plugin.approval.resolve"] : [];
638
- if (params.execAuthorization.authorized && params.pluginAuthorization.authorized) return ["exec.approval.resolve", "plugin.approval.resolve"];
639
- if (params.execAuthorization.authorized) return ["exec.approval.resolve"];
640
- if (params.pluginAuthorization.authorized) return ["plugin.approval.resolve"];
641
- return [];
642
- }
643
- function resolveApprovalAuthorizationError(params) {
644
- if (params.approvalId.startsWith("plugin:")) return params.pluginAuthorization.reason ?? "āŒ You are not authorized to approve this request.";
645
- return params.execAuthorization.reason ?? params.pluginAuthorization.reason ?? "āŒ You are not authorized to approve this request.";
646
- }
647
- const handleApproveCommand = async (params, allowTextCommands) => {
648
- if (!allowTextCommands) return null;
649
- const normalized = params.command.commandBodyNormalized;
650
- const parsed = parseApproveCommand(normalized);
651
- if (!parsed) return null;
652
- if (!parsed.ok) return {
653
- shouldContinue: false,
654
- reply: { text: parsed.error }
655
- };
656
- const isPluginId = parsed.id.startsWith("plugin:");
657
- const effectiveAccountId = resolveChannelAccountId({
658
- cfg: params.cfg,
659
- ctx: params.ctx,
660
- command: params.command
661
- });
662
- const approveCommandBehavior = resolveChannelApprovalCapability(getChannelPlugin(params.command.channel))?.resolveApproveCommandBehavior?.({
663
- cfg: params.cfg,
664
- accountId: effectiveAccountId,
665
- senderId: params.command.senderId,
666
- approvalKind: isPluginId ? "plugin" : "exec"
667
- });
668
- if (approveCommandBehavior?.kind === "ignore") return { shouldContinue: false };
669
- if (approveCommandBehavior?.kind === "reply") return {
670
- shouldContinue: false,
671
- reply: { text: approveCommandBehavior.text }
672
- };
673
- const execApprovalAuthorization = resolveApprovalCommandAuthorization({
674
- cfg: params.cfg,
675
- channel: params.command.channel,
676
- accountId: effectiveAccountId,
677
- senderId: params.command.senderId,
678
- kind: "exec"
679
- });
680
- const pluginApprovalAuthorization = resolveApprovalCommandAuthorization({
681
- cfg: params.cfg,
682
- channel: params.command.channel,
683
- accountId: effectiveAccountId,
684
- senderId: params.command.senderId,
685
- kind: "plugin"
686
- });
687
- const hasExplicitApprovalAuthorization = execApprovalAuthorization.explicit && execApprovalAuthorization.authorized || pluginApprovalAuthorization.explicit && pluginApprovalAuthorization.authorized;
688
- if (!params.command.isAuthorizedSender && !hasExplicitApprovalAuthorization) {
689
- logVerbose(`Ignoring /approve from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
690
- return { shouldContinue: false };
691
- }
692
- const missingScope = requireGatewayClientScopeForInternalChannel(params, {
693
- label: "/approve",
694
- allowedScopes: ["operator.approvals", "operator.admin"],
695
- missingText: "āŒ /approve requires operator.approvals for gateway clients."
696
- });
697
- if (missingScope) return missingScope;
698
- const resolvedBy = buildResolvedByLabel(params);
699
- const callApprovalMethod = async (method) => {
700
- await callGateway({
701
- method,
702
- params: {
703
- id: parsed.id,
704
- decision: parsed.decision
705
- },
706
- clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
707
- clientDisplayName: `Chat approval (${resolvedBy})`,
708
- mode: GATEWAY_CLIENT_MODES.BACKEND
709
- });
710
- };
711
- const methods = resolveApprovalMethods({
712
- approvalId: parsed.id,
713
- execAuthorization: execApprovalAuthorization,
714
- pluginAuthorization: pluginApprovalAuthorization
715
- });
716
- if (methods.length === 0) return {
717
- shouldContinue: false,
718
- reply: { text: resolveApprovalAuthorizationError({
719
- approvalId: parsed.id,
720
- execAuthorization: execApprovalAuthorization,
721
- pluginAuthorization: pluginApprovalAuthorization
722
- }) }
723
- };
724
- let lastError = null;
725
- for (const [index, method] of methods.entries()) try {
726
- await callApprovalMethod(method);
727
- lastError = null;
728
- break;
729
- } catch (error) {
730
- lastError = error;
731
- const isLastMethod = index === methods.length - 1;
732
- if (!isApprovalNotFoundError(error) || isLastMethod) return {
733
- shouldContinue: false,
734
- reply: { text: `āŒ Failed to submit approval: ${formatApprovalSubmitError(error)}` }
735
- };
736
- }
737
- if (lastError) return {
738
- shouldContinue: false,
739
- reply: { text: `āŒ Failed to submit approval: ${formatApprovalSubmitError(lastError)}` }
740
- };
741
- return {
742
- shouldContinue: false,
743
- reply: { text: `āœ… Approval ${parsed.decision} submitted for ${parsed.id}.` }
744
- };
745
- };
746
- //#endregion
747
- //#region src/auto-reply/reply/bash-command.ts
748
- const CHAT_BASH_SCOPE_KEY = "chat:bash";
749
- const DEFAULT_FOREGROUND_MS = 2e3;
750
- const MAX_FOREGROUND_MS = 3e4;
751
- let activeJob = null;
752
- function resolveForegroundMs(cfg) {
753
- const raw = cfg.commands?.bashForegroundMs;
754
- if (typeof raw !== "number" || Number.isNaN(raw)) return DEFAULT_FOREGROUND_MS;
755
- return clampInt(raw, 0, MAX_FOREGROUND_MS);
756
- }
757
- function formatSessionSnippet(sessionId) {
758
- const trimmed = sessionId.trim();
759
- if (trimmed.length <= 12) return trimmed;
760
- return `${trimmed.slice(0, 8)}…`;
761
- }
762
- function formatOutputBlock(text) {
763
- const trimmed = text.trim();
764
- if (!trimmed) return "(no output)";
765
- return `\`\`\`txt\n${trimmed}\n\`\`\``;
766
- }
767
- function parseBashRequest(raw) {
768
- const trimmed = raw.trimStart();
769
- let restSource = "";
770
- if (normalizeLowercaseStringOrEmpty(trimmed).startsWith("/bash")) {
771
- const match = trimmed.match(/^\/bash(?:\s*:\s*|\s+|$)([\s\S]*)$/i);
772
- if (!match) return null;
773
- restSource = match[1] ?? "";
774
- } else if (trimmed.startsWith("!")) {
775
- restSource = trimmed.slice(1);
776
- if (restSource.trimStart().startsWith(":")) restSource = restSource.trimStart().slice(1);
777
- } else return null;
778
- const rest = restSource.trimStart();
779
- if (!rest) return { action: "help" };
780
- const tokenMatch = rest.match(/^(\S+)(?:\s+([\s\S]+))?$/);
781
- const token = normalizeOptionalString(tokenMatch?.[1]) ?? "";
782
- const remainder = normalizeOptionalString(tokenMatch?.[2]) ?? "";
783
- const lowered = normalizeLowercaseStringOrEmpty(token);
784
- if (lowered === "poll") return {
785
- action: "poll",
786
- sessionId: remainder || void 0
787
- };
788
- if (lowered === "stop") return {
789
- action: "stop",
790
- sessionId: remainder || void 0
791
- };
792
- if (lowered === "help") return { action: "help" };
793
- return {
794
- action: "run",
795
- command: rest
796
- };
797
- }
798
- function resolveRawCommandBody(params) {
799
- const stripped = stripStructuralPrefixes(params.ctx.CommandBody ?? params.ctx.RawBody ?? params.ctx.Body ?? "");
800
- return params.isGroup ? stripMentions(stripped, params.ctx, params.cfg, params.agentId) : stripped;
801
- }
802
- function getScopedSession(sessionId) {
803
- const running = getSession(sessionId);
804
- if (running && running.scopeKey === CHAT_BASH_SCOPE_KEY) return { running };
805
- const finished = getFinishedSession(sessionId);
806
- if (finished && finished.scopeKey === CHAT_BASH_SCOPE_KEY) return { finished };
807
- return {};
808
- }
809
- function ensureActiveJobState() {
810
- if (!activeJob) return null;
811
- if (activeJob.state === "starting") return activeJob;
812
- const { running, finished } = getScopedSession(activeJob.sessionId);
813
- if (running) return activeJob;
814
- if (finished) {
815
- activeJob = null;
816
- return null;
817
- }
818
- activeJob = null;
819
- return null;
820
- }
821
- function attachActiveWatcher(sessionId) {
822
- if (!activeJob || activeJob.state !== "running") return;
823
- if (activeJob.sessionId !== sessionId) return;
824
- if (activeJob.watcherAttached) return;
825
- const { running } = getScopedSession(sessionId);
826
- const child = running?.child;
827
- if (!child) return;
828
- activeJob.watcherAttached = true;
829
- child.once("close", () => {
830
- if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
831
- });
832
- }
833
- function buildUsageReply() {
834
- return { text: [
835
- "āš™ļø Usage:",
836
- "- ! <command>",
837
- "- !poll | ! poll",
838
- "- !stop | ! stop",
839
- "- /bash ... (alias; same subcommands as !)"
840
- ].join("\n") };
841
- }
842
- async function handleBashChatCommand(params) {
843
- if (!isCommandFlagEnabled(params.cfg, "bash")) return buildDisabledCommandReply({
844
- label: "bash",
845
- configKey: "bash",
846
- docsUrl: "https://docs.genesis.ai/tools/slash-commands#config"
847
- });
848
- const agentId = params.agentId ?? resolveSessionAgentId({
849
- sessionKey: params.sessionKey,
850
- config: params.cfg
851
- });
852
- if (!params.elevated.enabled || !params.elevated.allowed) {
853
- const runtimeSandboxed = resolveSandboxRuntimeStatus({
854
- cfg: params.cfg,
855
- sessionKey: resolveRuntimePolicySessionKey({
856
- cfg: params.cfg,
857
- ctx: params.ctx,
858
- sessionKey: params.sessionKey
859
- })
860
- }).sandboxed;
861
- return { text: formatElevatedUnavailableMessage({
862
- runtimeSandboxed,
863
- failures: params.elevated.failures,
864
- sessionKey: params.sessionKey
865
- }) };
866
- }
867
- const request = parseBashRequest(resolveRawCommandBody({
868
- ctx: params.ctx,
869
- cfg: params.cfg,
870
- agentId,
871
- isGroup: params.isGroup
872
- }).trim());
873
- if (!request) return { text: "āš ļø Unrecognized bash request." };
874
- const liveJob = ensureActiveJobState();
875
- if (request.action === "help") return buildUsageReply();
876
- if (request.action === "poll") {
877
- const sessionId = normalizeOptionalString(request.sessionId) || (liveJob?.state === "running" ? liveJob.sessionId : "");
878
- if (!sessionId) return { text: "āš™ļø No active bash job." };
879
- const { running, finished } = getScopedSession(sessionId);
880
- if (running) {
881
- attachActiveWatcher(sessionId);
882
- const runtimeSec = Math.max(0, Math.floor((Date.now() - running.startedAt) / 1e3));
883
- const tail = running.tail || "(no output yet)";
884
- return { text: [
885
- `āš™ļø bash still running (session ${formatSessionSnippet(sessionId)}, ${runtimeSec}s).`,
886
- formatOutputBlock(tail),
887
- "Hint: !stop (or /bash stop)"
888
- ].join("\n") };
889
- }
890
- if (finished) {
891
- if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
892
- const exitLabel = finished.exitSignal ? `signal ${String(finished.exitSignal)}` : `code ${String(finished.exitCode ?? 0)}`;
893
- return { text: [
894
- `${finished.status === "completed" ? "āš™ļø" : "āš ļø"} bash finished (session ${formatSessionSnippet(sessionId)}).`,
895
- `Exit: ${exitLabel}`,
896
- formatOutputBlock(finished.aggregated || finished.tail)
897
- ].join("\n") };
898
- }
899
- if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
900
- return { text: `āš™ļø No bash session found for ${formatSessionSnippet(sessionId)}.` };
901
- }
902
- if (request.action === "stop") {
903
- const sessionId = normalizeOptionalString(request.sessionId) || (liveJob?.state === "running" ? liveJob.sessionId : "");
904
- if (!sessionId) return { text: "āš™ļø No active bash job." };
905
- const { running } = getScopedSession(sessionId);
906
- if (!running) {
907
- if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
908
- return { text: `āš™ļø No running bash job found for ${formatSessionSnippet(sessionId)}.` };
909
- }
910
- if (!running.backgrounded) return { text: `āš ļø Session ${formatSessionSnippet(sessionId)} is not backgrounded.` };
911
- const pid = running.pid ?? running.child?.pid;
912
- if (!pid) return { text: `āš ļø Unable to stop bash session ${formatSessionSnippet(sessionId)} because no process ID is available. Use !poll ${sessionId} to check whether it exits on its own.` };
913
- const { killProcessTree } = await import("./kill-tree-Be-ZU6Ay.js");
914
- killProcessTree(pid);
915
- return { text: `āš™ļø bash stopping (session ${formatSessionSnippet(sessionId)}). Use !poll ${sessionId} to confirm exit.` };
916
- }
917
- if (liveJob) return { text: `āš ļø A bash job is already running (${liveJob.state === "running" ? formatSessionSnippet(liveJob.sessionId) : "starting"}). Use !poll / !stop (or /bash poll / /bash stop).` };
918
- const commandText = request.command.trim();
919
- if (!commandText) return buildUsageReply();
920
- activeJob = {
921
- state: "starting",
922
- startedAt: Date.now(),
923
- command: commandText
924
- };
925
- try {
926
- const foregroundMs = resolveForegroundMs(params.cfg);
927
- const shouldBackgroundImmediately = foregroundMs <= 0;
928
- const timeoutSec = params.cfg.tools?.exec?.timeoutSec;
929
- const notifyOnExit = params.cfg.tools?.exec?.notifyOnExit;
930
- const notifyOnExitEmptySuccess = params.cfg.tools?.exec?.notifyOnExitEmptySuccess;
931
- const result = await createExecTool({
932
- scopeKey: CHAT_BASH_SCOPE_KEY,
933
- allowBackground: true,
934
- timeoutSec,
935
- sessionKey: params.sessionKey,
936
- notifyOnExit,
937
- notifyOnExitEmptySuccess,
938
- elevated: {
939
- enabled: params.elevated.enabled,
940
- allowed: params.elevated.allowed,
941
- defaultLevel: "on"
942
- }
943
- }).execute("chat-bash", {
944
- command: commandText,
945
- background: shouldBackgroundImmediately,
946
- yieldMs: shouldBackgroundImmediately ? void 0 : foregroundMs,
947
- timeout: timeoutSec,
948
- elevated: true
949
- });
950
- if (result.details?.status === "running") {
951
- const sessionId = result.details.sessionId;
952
- activeJob = {
953
- state: "running",
954
- sessionId,
955
- startedAt: result.details.startedAt,
956
- command: commandText,
957
- watcherAttached: false
958
- };
959
- attachActiveWatcher(sessionId);
960
- logVerbose(`Started bash session ${formatSessionSnippet(sessionId)}: ${commandText}`);
961
- return { text: `āš™ļø bash started (session ${sessionId}). Still running; use !poll / !stop (or /bash poll / /bash stop).` };
962
- }
963
- activeJob = null;
964
- const exitCode = result.details?.status === "completed" ? result.details.exitCode : 0;
965
- const output = result.details?.status === "completed" ? result.details.aggregated : result.content.map((chunk) => chunk.type === "text" ? chunk.text : "").join("\n");
966
- return { text: [
967
- `āš™ļø bash: ${commandText}`,
968
- `Exit: ${exitCode}`,
969
- formatOutputBlock(output || "(no output)")
970
- ].join("\n") };
971
- } catch (err) {
972
- activeJob = null;
973
- const message = formatErrorMessage(err);
974
- return { text: [`āš ļø bash failed: ${commandText}`, formatOutputBlock(message)].join("\n") };
975
- }
976
- }
977
- //#endregion
978
- //#region src/auto-reply/reply/commands-bash.ts
979
- const handleBashCommand = async (params, allowTextCommands) => {
980
- if (!allowTextCommands) return null;
981
- const { command } = params;
982
- const bashSlashRequested = command.commandBodyNormalized === "/bash" || command.commandBodyNormalized.startsWith("/bash ");
983
- const bashBangRequested = command.commandBodyNormalized.startsWith("!");
984
- if (!bashSlashRequested && !(bashBangRequested && command.isAuthorizedSender)) return null;
985
- const unauthorized = rejectUnauthorizedCommand(params, "/bash");
986
- if (unauthorized) return unauthorized;
987
- const agentId = params.sessionKey ? resolveSessionAgentId({
988
- sessionKey: params.sessionKey,
989
- config: params.cfg
990
- }) : params.agentId;
991
- return {
992
- shouldContinue: false,
993
- reply: await handleBashChatCommand({
994
- ctx: params.ctx,
995
- cfg: params.cfg,
996
- agentId,
997
- sessionKey: params.sessionKey,
998
- isGroup: params.isGroup,
999
- elevated: params.elevated
1000
- })
1001
- };
1002
- };
1003
- //#endregion
1004
- //#region src/agents/btw.ts
1005
- function collectTextContent(content) {
1006
- return content.filter((part) => part.type === "text").map((part) => part.text).join("");
1007
- }
1008
- function collectThinkingContent(content) {
1009
- return content.filter((part) => part.type === "thinking").map((part) => part.thinking).join("");
1010
- }
1011
- function buildBtwSystemPrompt() {
1012
- return [
1013
- "You are answering an ephemeral /btw side question about the current conversation.",
1014
- "Use the conversation only as background context.",
1015
- "Answer only the side question in the last user message.",
1016
- "Do not continue, resume, or complete any unfinished task from the conversation.",
1017
- "Do not emit tool calls, pseudo-tool calls, shell commands, file writes, patches, or code unless the side question explicitly asks for them.",
1018
- "Do not say you will continue the main task after answering.",
1019
- "If the question can be answered briefly, answer briefly."
1020
- ].join("\n");
1021
- }
1022
- function buildBtwQuestionPrompt(question, inFlightPrompt) {
1023
- const lines = ["Answer this side question only.", "Ignore any unfinished task in the conversation while answering it."];
1024
- const trimmedPrompt = inFlightPrompt?.trim();
1025
- if (trimmedPrompt) lines.push("", "Current in-flight main task request for background context only:", "<in_flight_main_task>", trimmedPrompt, "</in_flight_main_task>", "Do not continue or complete that task while answering the side question.");
1026
- lines.push("", "<btw_side_question>", question.trim(), "</btw_side_question>");
1027
- return lines.join("\n");
1028
- }
1029
- function normalizeBtwContentBlocks(content) {
1030
- if (Array.isArray(content)) return content;
1031
- if (content && typeof content === "object") return [content];
1032
- }
1033
- function isBtwTextBlock(block) {
1034
- if (!block || typeof block !== "object") return false;
1035
- const record = block;
1036
- return normalizeLowercaseStringOrEmpty(record.type) === "text" && typeof record.text === "string";
1037
- }
1038
- function isBtwImageBlock(block) {
1039
- if (!block || typeof block !== "object") return false;
1040
- const record = block;
1041
- return normalizeLowercaseStringOrEmpty(record.type) === "image" && typeof record.data === "string" && typeof record.mimeType === "string";
1042
- }
1043
- async function sanitizeBtwUserMessage(params) {
1044
- if (typeof params.message.content === "string") return params.message;
1045
- const blocks = normalizeBtwContentBlocks(params.message.content);
1046
- if (!blocks) return;
1047
- const content = [];
1048
- for (const block of blocks) {
1049
- if (isBtwTextBlock(block)) {
1050
- content.push({
1051
- type: "text",
1052
- text: block.text
1053
- });
1054
- continue;
1055
- }
1056
- if (!isBtwImageBlock(block)) continue;
1057
- const { images } = await sanitizeImageBlocks([block], "btw:context", params.imageLimits);
1058
- const image = images[0];
1059
- if (image) content.push(image);
1060
- }
1061
- if (content.length === 0) return;
1062
- return {
1063
- ...params.message,
1064
- content
1065
- };
1066
- }
1067
- function sanitizeBtwAssistantMessage(message) {
1068
- const rawContent = message.content;
1069
- if (typeof rawContent === "string") {
1070
- const trimmed = rawContent.trim();
1071
- return trimmed.length > 0 ? {
1072
- ...message,
1073
- content: [{
1074
- type: "text",
1075
- text: trimmed
1076
- }]
1077
- } : void 0;
1078
- }
1079
- const blocks = normalizeBtwContentBlocks(rawContent);
1080
- if (!blocks) return;
1081
- const content = blocks.flatMap((block) => isBtwTextBlock(block) ? [{
1082
- type: "text",
1083
- text: block.text
1084
- }] : []);
1085
- if (content.length === 0) return;
1086
- return {
1087
- ...message,
1088
- content
1089
- };
1090
- }
1091
- async function toSimpleContextMessages(params) {
1092
- const contextMessages = [];
1093
- for (const message of params.messages) {
1094
- if (!message || typeof message !== "object") continue;
1095
- const role = message.role;
1096
- if (role === "user") {
1097
- const sanitizedMessage = await sanitizeBtwUserMessage({
1098
- message,
1099
- imageLimits: params.imageLimits
1100
- });
1101
- if (sanitizedMessage) contextMessages.push(sanitizedMessage);
1102
- continue;
1103
- }
1104
- if (role !== "assistant") continue;
1105
- const sanitizedMessage = sanitizeBtwAssistantMessage(message);
1106
- if (sanitizedMessage) contextMessages.push(sanitizedMessage);
1107
- }
1108
- return stripToolResultDetails(contextMessages);
1109
- }
1110
- function resolveSessionTranscriptPath(params) {
1111
- try {
1112
- const agentId = params.sessionKey?.split(":")[1];
1113
- const pathOpts = resolveSessionFilePathOptions({
1114
- agentId,
1115
- storePath: params.storePath
1116
- });
1117
- return resolveSessionFilePath(params.sessionId, params.sessionEntry, pathOpts);
1118
- } catch (error) {
1119
- diagnosticLogger.debug(`resolveSessionTranscriptPath failed: sessionId=${params.sessionId} err=${String(error)}`);
1120
- return;
1121
- }
1122
- }
1123
- async function resolveRuntimeModel(params) {
1124
- await ensureGenesisModelsJson(params.cfg, params.agentDir);
1125
- const modelRegistry = discoverModels(discoverAuthStorage(params.agentDir), params.agentDir);
1126
- const model = resolveModelWithRegistry({
1127
- provider: params.provider,
1128
- modelId: params.model,
1129
- modelRegistry,
1130
- cfg: params.cfg
1131
- });
1132
- if (!model) throw new Error(`Unknown model: ${params.provider}/${params.model}`);
1133
- return {
1134
- model,
1135
- authProfileId: await resolveSessionAuthProfileOverride({
1136
- cfg: params.cfg,
1137
- provider: params.provider,
1138
- agentDir: params.agentDir,
1139
- sessionEntry: params.sessionEntry,
1140
- sessionStore: params.sessionStore,
1141
- sessionKey: params.sessionKey,
1142
- storePath: params.storePath,
1143
- isNewSession: params.isNewSession
1144
- }),
1145
- authProfileIdSource: params.sessionEntry?.authProfileOverrideSource
1146
- };
1147
- }
1148
- async function runBtwSideQuestion(params) {
1149
- const sessionId = params.sessionEntry.sessionId?.trim();
1150
- if (!sessionId) throw new Error("No active session context.");
1151
- const sessionFile = resolveSessionTranscriptPath({
1152
- sessionId,
1153
- sessionEntry: params.sessionEntry,
1154
- sessionKey: params.sessionKey,
1155
- storePath: params.storePath
1156
- });
1157
- if (!sessionFile) throw new Error("No active session transcript.");
1158
- const sessionManager = SessionManager.open(sessionFile);
1159
- const activeRunSnapshot = getActiveEmbeddedRunSnapshot(sessionId);
1160
- const imageLimits = resolveImageSanitizationLimits(params.cfg);
1161
- let messages = [];
1162
- let inFlightPrompt;
1163
- if (Array.isArray(activeRunSnapshot?.messages) && activeRunSnapshot.messages.length > 0) {
1164
- messages = await toSimpleContextMessages({
1165
- messages: activeRunSnapshot.messages,
1166
- imageLimits
1167
- });
1168
- inFlightPrompt = activeRunSnapshot.inFlightPrompt;
1169
- } else if (activeRunSnapshot) {
1170
- inFlightPrompt = activeRunSnapshot.inFlightPrompt;
1171
- if (activeRunSnapshot.transcriptLeafId && sessionManager.branch) try {
1172
- sessionManager.branch(activeRunSnapshot.transcriptLeafId);
1173
- } catch (error) {
1174
- diagnosticLogger.debug(`btw snapshot leaf unavailable: sessionId=${sessionId} leaf=${activeRunSnapshot.transcriptLeafId} err=${String(error)}`);
1175
- sessionManager.resetLeaf?.();
1176
- }
1177
- else sessionManager.resetLeaf?.();
1178
- } else {
1179
- const leafEntry = sessionManager.getLeafEntry?.();
1180
- if (leafEntry?.type === "message" && leafEntry.message?.role === "user") if (leafEntry.parentId && sessionManager.branch) sessionManager.branch(leafEntry.parentId);
1181
- else sessionManager.resetLeaf?.();
1182
- }
1183
- if (messages.length === 0) {
1184
- const sessionContext = sessionManager.buildSessionContext();
1185
- messages = await toSimpleContextMessages({
1186
- messages: Array.isArray(sessionContext.messages) ? sessionContext.messages : [],
1187
- imageLimits
1188
- });
1189
- }
1190
- if (messages.length === 0 && !inFlightPrompt?.trim()) throw new Error("No active session context.");
1191
- const { model, authProfileId } = await resolveRuntimeModel({
1192
- cfg: params.cfg,
1193
- provider: params.provider,
1194
- model: params.model,
1195
- agentDir: params.agentDir,
1196
- sessionEntry: params.sessionEntry,
1197
- sessionStore: params.sessionStore,
1198
- sessionKey: params.sessionKey,
1199
- storePath: params.storePath,
1200
- isNewSession: params.isNewSession
1201
- });
1202
- const apiKeyInfo = await getApiKeyForModel({
1203
- model,
1204
- cfg: params.cfg,
1205
- profileId: authProfileId,
1206
- agentDir: params.agentDir
1207
- });
1208
- let runtimeModel = model;
1209
- let apiKey = apiKeyInfo.mode === "aws-sdk" && !apiKeyInfo.apiKey ? void 0 : requireApiKey(apiKeyInfo, model.provider);
1210
- const sessionAgentId = resolveSessionAgentId({
1211
- sessionKey: params.sessionKey,
1212
- config: params.cfg
1213
- });
1214
- const workspaceDir = resolveAgentWorkspaceDir(params.cfg, sessionAgentId);
1215
- if (apiKey) {
1216
- const preparedAuth = await prepareProviderRuntimeAuth({
1217
- provider: model.provider,
1218
- config: params.cfg,
1219
- workspaceDir,
1220
- env: process.env,
1221
- context: {
1222
- config: params.cfg,
1223
- agentDir: params.agentDir,
1224
- workspaceDir,
1225
- env: process.env,
1226
- provider: model.provider,
1227
- modelId: model.id,
1228
- model,
1229
- apiKey,
1230
- authMode: apiKeyInfo.mode,
1231
- profileId: authProfileId
1232
- }
1233
- });
1234
- if (preparedAuth?.baseUrl) runtimeModel = {
1235
- ...runtimeModel,
1236
- baseUrl: preparedAuth.baseUrl
1237
- };
1238
- if (preparedAuth?.apiKey) apiKey = preparedAuth.apiKey;
1239
- }
1240
- const providerStreamFn = registerProviderStreamForModel({
1241
- model: runtimeModel,
1242
- cfg: params.cfg,
1243
- agentDir: params.agentDir,
1244
- workspaceDir,
1245
- env: process.env
1246
- });
1247
- const chunker = params.opts?.onBlockReply && params.blockReplyChunking ? new EmbeddedBlockChunker(params.blockReplyChunking) : void 0;
1248
- let emittedBlocks = 0;
1249
- let blockEmitChain = Promise.resolve();
1250
- let answerText = "";
1251
- let reasoningText = "";
1252
- let assistantStarted = false;
1253
- let sawTextEvent = false;
1254
- const emitBlockChunk = async (text) => {
1255
- if (!text.trim() || !params.opts?.onBlockReply) return;
1256
- emittedBlocks += 1;
1257
- blockEmitChain = blockEmitChain.then(async () => {
1258
- await params.opts?.onBlockReply?.({
1259
- text,
1260
- btw: { question: params.question }
1261
- });
1262
- });
1263
- await blockEmitChain;
1264
- };
1265
- const stream = await streamWithPayloadPatch(providerStreamFn ?? streamSimple, runtimeModel, {
1266
- systemPrompt: buildBtwSystemPrompt(),
1267
- messages: [...messages, {
1268
- role: "user",
1269
- content: [{
1270
- type: "text",
1271
- text: buildBtwQuestionPrompt(params.question, inFlightPrompt)
1272
- }],
1273
- timestamp: Date.now()
1274
- }]
1275
- }, {
1276
- apiKey,
1277
- reasoning: void 0,
1278
- signal: params.opts?.abortSignal
1279
- }, (payloadObj) => {
1280
- if (Array.isArray(payloadObj.tools) && payloadObj.tools.length === 0) delete payloadObj.tools;
1281
- });
1282
- let finalEvent;
1283
- for await (const event of stream) {
1284
- finalEvent = event.type === "done" || event.type === "error" ? event : finalEvent;
1285
- if (!assistantStarted && (event.type === "text_start" || event.type === "start")) {
1286
- assistantStarted = true;
1287
- await params.opts?.onAssistantMessageStart?.();
1288
- }
1289
- if (event.type === "text_delta") {
1290
- sawTextEvent = true;
1291
- answerText += event.delta;
1292
- chunker?.append(event.delta);
1293
- if (chunker && params.resolvedBlockStreamingBreak === "text_end") chunker.drain({
1294
- force: false,
1295
- emit: (chunk) => void emitBlockChunk(chunk)
1296
- });
1297
- continue;
1298
- }
1299
- if (event.type === "text_end" && chunker && params.resolvedBlockStreamingBreak === "text_end") {
1300
- chunker.drain({
1301
- force: true,
1302
- emit: (chunk) => void emitBlockChunk(chunk)
1303
- });
1304
- continue;
1305
- }
1306
- if (event.type === "thinking_delta") {
1307
- reasoningText += event.delta;
1308
- if (params.resolvedReasoningLevel !== "off") await params.opts?.onReasoningStream?.({
1309
- text: reasoningText,
1310
- isReasoning: true
1311
- });
1312
- continue;
1313
- }
1314
- if (event.type === "thinking_end" && params.resolvedReasoningLevel !== "off") await params.opts?.onReasoningEnd?.();
1315
- }
1316
- if (chunker && params.resolvedBlockStreamingBreak !== "text_end" && chunker.hasBuffered()) chunker.drain({
1317
- force: true,
1318
- emit: (chunk) => void emitBlockChunk(chunk)
1319
- });
1320
- await blockEmitChain;
1321
- if (finalEvent?.type === "error") {
1322
- const message = collectTextContent(finalEvent.error.content);
1323
- throw new Error(message || finalEvent.error.errorMessage || "BTW failed.");
1324
- }
1325
- const finalMessage = finalEvent?.type === "done" ? finalEvent.message : void 0;
1326
- if (finalMessage) {
1327
- if (!sawTextEvent) answerText = collectTextContent(finalMessage.content);
1328
- if (!reasoningText) reasoningText = collectThinkingContent(finalMessage.content);
1329
- }
1330
- const answer = answerText.trim();
1331
- if (!answer) throw new Error("No BTW response generated.");
1332
- if (emittedBlocks > 0) return;
1333
- return { text: answer };
1334
- }
1335
- //#endregion
1336
- //#region src/auto-reply/reply/commands-btw.ts
1337
- const BTW_USAGE = "Usage: /btw <side question>";
1338
- const handleBtwCommand = async (params, allowTextCommands) => {
1339
- if (!allowTextCommands) return null;
1340
- const question = extractBtwQuestion(params.command.commandBodyNormalized);
1341
- if (question === null) return null;
1342
- const unauthorized = rejectUnauthorizedCommand(params, "/btw");
1343
- if (unauthorized) return unauthorized;
1344
- if (!question) return {
1345
- shouldContinue: false,
1346
- reply: { text: BTW_USAGE }
1347
- };
1348
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
1349
- if (!targetSessionEntry?.sessionId) return {
1350
- shouldContinue: false,
1351
- reply: { text: "āš ļø /btw requires an active session with existing context." }
1352
- };
1353
- const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
1354
- sessionKey: params.sessionKey,
1355
- config: params.cfg
1356
- }) : params.agentId;
1357
- const agentDir = (sessionAgentId ? resolveAgentDir(params.cfg, sessionAgentId) : void 0) ?? params.agentDir;
1358
- if (!agentDir) return {
1359
- shouldContinue: false,
1360
- reply: { text: "āš ļø /btw is unavailable because the active agent directory could not be resolved." }
1361
- };
1362
- try {
1363
- await params.typing?.startTypingLoop();
1364
- const reply = await runBtwSideQuestion({
1365
- cfg: params.cfg,
1366
- agentDir,
1367
- provider: params.provider,
1368
- model: params.model,
1369
- question,
1370
- sessionEntry: targetSessionEntry,
1371
- sessionStore: params.sessionStore,
1372
- sessionKey: params.sessionKey,
1373
- storePath: params.storePath,
1374
- resolvedThinkLevel: "off",
1375
- resolvedReasoningLevel: "off",
1376
- blockReplyChunking: params.blockReplyChunking,
1377
- resolvedBlockStreamingBreak: params.resolvedBlockStreamingBreak,
1378
- opts: params.opts,
1379
- isNewSession: false
1380
- });
1381
- return {
1382
- shouldContinue: false,
1383
- reply: reply ? {
1384
- ...reply,
1385
- btw: { question }
1386
- } : reply
1387
- };
1388
- } catch (error) {
1389
- const message = error instanceof Error ? error.message.trim() : "";
1390
- return {
1391
- shouldContinue: false,
1392
- reply: {
1393
- text: `āš ļø /btw failed${message ? `: ${message}` : "."}`,
1394
- btw: { question },
1395
- isError: true
1396
- }
1397
- };
1398
- }
1399
- };
1400
- //#endregion
1401
- //#region src/auto-reply/reply/commands-compact.ts
1402
- let compactRuntimePromise = null;
1403
- function loadCompactRuntime() {
1404
- compactRuntimePromise ??= import("./commands-compact.runtime-BUaXIw-I.js");
1405
- return compactRuntimePromise;
1406
- }
1407
- function extractCompactInstructions(params) {
1408
- const raw = stripStructuralPrefixes(params.rawBody ?? "");
1409
- const trimmed = (params.isGroup ? stripMentions(raw, params.ctx, params.cfg, params.agentId) : raw).trim();
1410
- if (!trimmed) return;
1411
- const prefix = normalizeLowercaseStringOrEmpty(trimmed).startsWith("/compact") ? "/compact" : null;
1412
- if (!prefix) return;
1413
- let rest = trimmed.slice(prefix.length).trimStart();
1414
- if (rest.startsWith(":")) rest = rest.slice(1).trimStart();
1415
- return rest.length ? rest : void 0;
1416
- }
1417
- function isCompactionSkipReason(reason) {
1418
- const text = normalizeOptionalLowercaseString(reason) ?? "";
1419
- return text.includes("nothing to compact") || text.includes("below threshold") || text.includes("already compacted") || text.includes("no real conversation messages");
1420
- }
1421
- function formatCompactionReason(reason) {
1422
- const text = normalizeOptionalString(reason);
1423
- if (!text) return;
1424
- const lower = normalizeLowercaseStringOrEmpty(text);
1425
- if (lower.includes("nothing to compact")) return "nothing compactable in this session yet";
1426
- if (lower.includes("below threshold")) return "context is below the compaction threshold";
1427
- if (lower.includes("already compacted")) return "session was already compacted recently";
1428
- if (lower.includes("no real conversation messages")) return "no real conversation messages yet";
1429
- return text;
1430
- }
1431
- const handleCompactCommand = async (params) => {
1432
- if (!(params.command.commandBodyNormalized === "/compact" || params.command.commandBodyNormalized.startsWith("/compact "))) return null;
1433
- if (!params.command.isAuthorizedSender) {
1434
- logVerbose(`Ignoring /compact from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
1435
- return { shouldContinue: false };
1436
- }
1437
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
1438
- if (!targetSessionEntry?.sessionId) return {
1439
- shouldContinue: false,
1440
- reply: { text: "āš™ļø Compaction unavailable (missing session id)." }
1441
- };
1442
- const runtime = await loadCompactRuntime();
1443
- const sessionId = targetSessionEntry.sessionId;
1444
- if (runtime.isEmbeddedPiRunActive(sessionId)) {
1445
- runtime.abortEmbeddedPiRun(sessionId);
1446
- await runtime.waitForEmbeddedPiRunEnd(sessionId, 15e3);
1447
- }
1448
- const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
1449
- sessionKey: params.sessionKey,
1450
- config: params.cfg
1451
- }) : params.agentId ?? "main";
1452
- const sessionAgentDir = sessionAgentId === (params.agentId ?? "main") && params.agentDir ? params.agentDir : resolveAgentDir(params.cfg, sessionAgentId);
1453
- const customInstructions = extractCompactInstructions({
1454
- rawBody: params.ctx.CommandBody ?? params.ctx.RawBody ?? params.ctx.Body,
1455
- ctx: params.ctx,
1456
- cfg: params.cfg,
1457
- agentId: sessionAgentId,
1458
- isGroup: params.isGroup
1459
- });
1460
- const result = await runtime.compactEmbeddedPiSession({
1461
- sessionId,
1462
- sessionKey: params.sessionKey,
1463
- allowGatewaySubagentBinding: true,
1464
- messageChannel: params.command.channel,
1465
- groupId: targetSessionEntry.groupId,
1466
- groupChannel: targetSessionEntry.groupChannel,
1467
- groupSpace: targetSessionEntry.space,
1468
- spawnedBy: targetSessionEntry.spawnedBy,
1469
- senderId: params.command.senderId,
1470
- senderName: params.ctx.SenderName,
1471
- senderUsername: params.ctx.SenderUsername,
1472
- senderE164: params.ctx.SenderE164,
1473
- sessionFile: runtime.resolveSessionFilePath(sessionId, targetSessionEntry, runtime.resolveSessionFilePathOptions({
1474
- agentId: sessionAgentId,
1475
- storePath: params.storePath
1476
- })),
1477
- workspaceDir: params.workspaceDir,
1478
- agentDir: sessionAgentDir,
1479
- config: params.cfg,
1480
- skillsSnapshot: targetSessionEntry.skillsSnapshot,
1481
- provider: params.provider,
1482
- model: params.model,
1483
- agentHarnessId: targetSessionEntry.sessionId === sessionId ? targetSessionEntry.agentHarnessId : void 0,
1484
- thinkLevel: params.resolvedThinkLevel ?? await params.resolveDefaultThinkingLevel(),
1485
- bashElevated: {
1486
- enabled: false,
1487
- allowed: false,
1488
- defaultLevel: "off"
1489
- },
1490
- customInstructions,
1491
- trigger: "manual",
1492
- senderIsOwner: params.command.senderIsOwner,
1493
- ownerNumbers: params.command.ownerList.length > 0 ? params.command.ownerList : void 0
1494
- });
1495
- const compactLabel = result.ok || isCompactionSkipReason(result.reason) ? result.compacted ? result.result?.tokensBefore != null && result.result?.tokensAfter != null ? `Compacted (${runtime.formatTokenCount(result.result.tokensBefore)} → ${runtime.formatTokenCount(result.result.tokensAfter)})` : result.result?.tokensBefore ? `Compacted (${runtime.formatTokenCount(result.result.tokensBefore)} before)` : "Compacted" : "Compaction skipped" : "Compaction failed";
1496
- if (result.ok && result.compacted) await runtime.incrementCompactionCount({
1497
- cfg: params.cfg,
1498
- sessionEntry: targetSessionEntry,
1499
- sessionStore: params.sessionStore,
1500
- sessionKey: params.sessionKey,
1501
- storePath: params.storePath,
1502
- tokensAfter: result.result?.tokensAfter
1503
- });
1504
- const totalTokens = result.result?.tokensAfter ?? runtime.resolveFreshSessionTotalTokens(targetSessionEntry);
1505
- const contextSummary = runtime.formatContextUsageShort(typeof totalTokens === "number" && totalTokens > 0 ? totalTokens : null, params.contextTokens ?? targetSessionEntry.contextTokens ?? null);
1506
- const reason = formatCompactionReason(result.reason);
1507
- const line = reason ? `${compactLabel}: ${reason} • ${contextSummary}` : `${compactLabel} • ${contextSummary}`;
1508
- runtime.enqueueSystemEvent(line, { sessionKey: params.sessionKey });
1509
- return {
1510
- shouldContinue: false,
1511
- reply: { text: `āš™ļø ${line}` }
1512
- };
1513
- };
1514
- //#endregion
1515
- //#region src/auto-reply/reply/commands-slash-parse.ts
1516
- function parseSlashCommandActionArgs(raw, slash) {
1517
- const trimmed = raw.trim();
1518
- const slashLower = normalizeLowercaseStringOrEmpty(slash);
1519
- if (!normalizeLowercaseStringOrEmpty(trimmed).startsWith(slashLower)) return { kind: "no-match" };
1520
- const rest = trimmed.slice(slash.length).trim();
1521
- if (!rest) return { kind: "empty" };
1522
- const match = rest.match(/^(\S+)(?:\s+([\s\S]+))?$/);
1523
- if (!match) return { kind: "invalid" };
1524
- return {
1525
- kind: "parsed",
1526
- action: normalizeLowercaseStringOrEmpty(match[1]),
1527
- args: (match[2] ?? "").trim()
1528
- };
1529
- }
1530
- function parseSlashCommandOrNull(raw, slash, opts) {
1531
- const parsed = parseSlashCommandActionArgs(raw, slash);
1532
- if (parsed.kind === "no-match") return null;
1533
- if (parsed.kind === "invalid") return {
1534
- ok: false,
1535
- message: opts.invalidMessage
1536
- };
1537
- if (parsed.kind === "empty") return {
1538
- ok: true,
1539
- action: opts.defaultAction ?? "show",
1540
- args: ""
1541
- };
1542
- return {
1543
- ok: true,
1544
- action: parsed.action,
1545
- args: parsed.args
1546
- };
1547
- }
1548
- //#endregion
1549
- //#region src/auto-reply/reply/commands-setunset.ts
1550
- function parseSetUnsetCommand(params) {
1551
- const action = params.action;
1552
- const args = params.args.trim();
1553
- if (action === "unset") {
1554
- if (!args) return {
1555
- kind: "error",
1556
- message: `Usage: ${params.slash} unset path`
1557
- };
1558
- return {
1559
- kind: "unset",
1560
- path: args
1561
- };
1562
- }
1563
- if (!args) return {
1564
- kind: "error",
1565
- message: `Usage: ${params.slash} set path=value`
1566
- };
1567
- const eqIndex = args.indexOf("=");
1568
- if (eqIndex <= 0) return {
1569
- kind: "error",
1570
- message: `Usage: ${params.slash} set path=value`
1571
- };
1572
- const path = args.slice(0, eqIndex).trim();
1573
- const rawValue = args.slice(eqIndex + 1);
1574
- if (!path) return {
1575
- kind: "error",
1576
- message: `Usage: ${params.slash} set path=value`
1577
- };
1578
- const parsed = parseConfigValue(rawValue);
1579
- if (parsed.error) return {
1580
- kind: "error",
1581
- message: parsed.error
1582
- };
1583
- return {
1584
- kind: "set",
1585
- path,
1586
- value: parsed.value
1587
- };
1588
- }
1589
- function parseSetUnsetCommandAction(params) {
1590
- if (params.action !== "set" && params.action !== "unset") return null;
1591
- const parsed = parseSetUnsetCommand({
1592
- slash: params.slash,
1593
- action: params.action,
1594
- args: params.args
1595
- });
1596
- if (parsed.kind === "error") return params.onError(parsed.message);
1597
- return parsed.kind === "set" ? params.onSet(parsed.path, parsed.value) : params.onUnset(parsed.path);
1598
- }
1599
- function parseSlashCommandWithSetUnset(params) {
1600
- const parsed = parseSlashCommandOrNull(params.raw, params.slash, { invalidMessage: params.invalidMessage });
1601
- if (!parsed) return null;
1602
- if (!parsed.ok) return params.onError(parsed.message);
1603
- const { action, args } = parsed;
1604
- const setUnset = parseSetUnsetCommandAction({
1605
- slash: params.slash,
1606
- action,
1607
- args,
1608
- onSet: params.onSet,
1609
- onUnset: params.onUnset,
1610
- onError: params.onError
1611
- });
1612
- if (setUnset) return setUnset;
1613
- const knownAction = params.onKnownAction(action, args);
1614
- if (knownAction) return knownAction;
1615
- return params.onError(params.usageMessage);
1616
- }
1617
- //#endregion
1618
- //#region src/auto-reply/reply/commands-setunset-standard.ts
1619
- function parseStandardSetUnsetSlashCommand(params) {
1620
- return parseSlashCommandWithSetUnset({
1621
- raw: params.raw,
1622
- slash: params.slash,
1623
- invalidMessage: params.invalidMessage,
1624
- usageMessage: params.usageMessage,
1625
- onKnownAction: params.onKnownAction,
1626
- onSet: params.onSet ?? ((path, value) => ({
1627
- action: "set",
1628
- path,
1629
- value
1630
- })),
1631
- onUnset: params.onUnset ?? ((path) => ({
1632
- action: "unset",
1633
- path
1634
- })),
1635
- onError: params.onError ?? ((message) => ({
1636
- action: "error",
1637
- message
1638
- }))
1639
- });
1640
- }
1641
- //#endregion
1642
- //#region src/auto-reply/reply/config-commands.ts
1643
- function parseConfigCommand(raw) {
1644
- return parseStandardSetUnsetSlashCommand({
1645
- raw,
1646
- slash: "/config",
1647
- invalidMessage: "Invalid /config syntax.",
1648
- usageMessage: "Usage: /config show|set|unset",
1649
- onKnownAction: (action, args) => {
1650
- if (action === "show" || action === "get") return {
1651
- action: "show",
1652
- path: args || void 0
1653
- };
1654
- }
1655
- });
1656
- }
1657
- //#endregion
1658
- //#region src/auto-reply/reply/debug-commands.ts
1659
- function parseDebugCommand(raw) {
1660
- return parseStandardSetUnsetSlashCommand({
1661
- raw,
1662
- slash: "/debug",
1663
- invalidMessage: "Invalid /debug syntax.",
1664
- usageMessage: "Usage: /debug show|set|unset|reset",
1665
- onKnownAction: (action) => {
1666
- if (action === "show") return { action: "show" };
1667
- if (action === "reset") return { action: "reset" };
1668
- }
1669
- });
1670
- }
1671
- //#endregion
1672
- //#region src/auto-reply/reply/commands-config.ts
1673
- const handleConfigCommand = async (params, allowTextCommands) => {
1674
- if (!allowTextCommands) return null;
1675
- const configCommand = parseConfigCommand(params.command.commandBodyNormalized);
1676
- if (!configCommand) return null;
1677
- const unauthorized = rejectUnauthorizedCommand(params, "/config");
1678
- if (unauthorized) return unauthorized;
1679
- const nonOwner = configCommand.action === "show" && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/config");
1680
- if (nonOwner) return nonOwner;
1681
- const disabled = requireCommandFlagEnabled(params.cfg, {
1682
- label: "/config",
1683
- configKey: "config"
1684
- });
1685
- if (disabled) return disabled;
1686
- if (configCommand.action === "error") return {
1687
- shouldContinue: false,
1688
- reply: { text: `āš ļø ${configCommand.message}` }
1689
- };
1690
- let parsedWritePath;
1691
- if (configCommand.action === "set" || configCommand.action === "unset") {
1692
- const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
1693
- label: "/config write",
1694
- allowedScopes: ["operator.admin"],
1695
- missingText: "āŒ /config set|unset requires operator.admin for gateway clients."
1696
- });
1697
- if (missingAdminScope) return missingAdminScope;
1698
- const parsedPath = parseConfigPath(configCommand.path);
1699
- if (!parsedPath.ok || !parsedPath.path) return {
1700
- shouldContinue: false,
1701
- reply: { text: `āš ļø ${parsedPath.error ?? "Invalid path."}` }
1702
- };
1703
- parsedWritePath = parsedPath.path;
1704
- const channelId = params.command.channelId ?? normalizeChannelId(params.command.channel);
1705
- const deniedText = resolveConfigWriteDeniedText({
1706
- cfg: params.cfg,
1707
- channel: params.command.channel,
1708
- channelId,
1709
- accountId: resolveChannelAccountId({
1710
- cfg: params.cfg,
1711
- ctx: params.ctx,
1712
- command: params.command
1713
- }),
1714
- gatewayClientScopes: params.ctx.GatewayClientScopes,
1715
- target: resolveConfigWriteTargetFromPath(parsedWritePath)
1716
- });
1717
- if (deniedText) return {
1718
- shouldContinue: false,
1719
- reply: { text: deniedText }
1720
- };
1721
- }
1722
- const snapshot = await readConfigFileSnapshot();
1723
- if (!snapshot.valid || !snapshot.parsed || typeof snapshot.parsed !== "object") return {
1724
- shouldContinue: false,
1725
- reply: { text: "āš ļø Config file is invalid; fix it before using /config." }
1726
- };
1727
- const parsedBase = structuredClone(snapshot.parsed);
1728
- if (configCommand.action === "show") {
1729
- const pathRaw = normalizeOptionalString(configCommand.path);
1730
- if (pathRaw) {
1731
- const parsedPath = parseConfigPath(pathRaw);
1732
- if (!parsedPath.ok || !parsedPath.path) return {
1733
- shouldContinue: false,
1734
- reply: { text: `āš ļø ${parsedPath.error ?? "Invalid path."}` }
1735
- };
1736
- const value = getConfigValueAtPath(parsedBase, parsedPath.path);
1737
- return {
1738
- shouldContinue: false,
1739
- reply: { text: `āš™ļø Config ${pathRaw}:\n\`\`\`json\n${JSON.stringify(value ?? null, null, 2)}\n\`\`\`` }
1740
- };
1741
- }
1742
- return {
1743
- shouldContinue: false,
1744
- reply: { text: `āš™ļø Config (raw):\n\`\`\`json\n${JSON.stringify(parsedBase, null, 2)}\n\`\`\`` }
1745
- };
1746
- }
1747
- if (configCommand.action === "unset") {
1748
- if (!unsetConfigValueAtPath(parsedBase, parsedWritePath ?? [])) return {
1749
- shouldContinue: false,
1750
- reply: { text: `āš™ļø No config value found for ${configCommand.path}.` }
1751
- };
1752
- const validated = validateConfigObjectWithPlugins(parsedBase);
1753
- if (!validated.ok) {
1754
- const issue = validated.issues[0];
1755
- return {
1756
- shouldContinue: false,
1757
- reply: { text: `āš ļø Config invalid after unset (${issue.path}: ${issue.message}).` }
1758
- };
1759
- }
1760
- await writeConfigFile(validated.config);
1761
- return {
1762
- shouldContinue: false,
1763
- reply: { text: `āš™ļø Config updated: ${configCommand.path} removed.` }
1764
- };
1765
- }
1766
- if (configCommand.action === "set") {
1767
- setConfigValueAtPath(parsedBase, parsedWritePath ?? [], configCommand.value);
1768
- const validated = validateConfigObjectWithPlugins(parsedBase);
1769
- if (!validated.ok) {
1770
- const issue = validated.issues[0];
1771
- return {
1772
- shouldContinue: false,
1773
- reply: { text: `āš ļø Config invalid after set (${issue.path}: ${issue.message}).` }
1774
- };
1775
- }
1776
- await writeConfigFile(validated.config);
1777
- const valueLabel = typeof configCommand.value === "string" ? `"${configCommand.value}"` : JSON.stringify(configCommand.value);
1778
- return {
1779
- shouldContinue: false,
1780
- reply: { text: `āš™ļø Config updated: ${configCommand.path}=${valueLabel ?? "null"}` }
1781
- };
1782
- }
1783
- return null;
1784
- };
1785
- const handleDebugCommand = async (params, allowTextCommands) => {
1786
- if (!allowTextCommands) return null;
1787
- const debugCommand = parseDebugCommand(params.command.commandBodyNormalized);
1788
- if (!debugCommand) return null;
1789
- const unauthorized = rejectUnauthorizedCommand(params, "/debug");
1790
- if (unauthorized) return unauthorized;
1791
- const nonOwner = rejectNonOwnerCommand(params, "/debug");
1792
- if (nonOwner) return nonOwner;
1793
- const disabled = requireCommandFlagEnabled(params.cfg, {
1794
- label: "/debug",
1795
- configKey: "debug"
1796
- });
1797
- if (disabled) return disabled;
1798
- if (debugCommand.action === "error") return {
1799
- shouldContinue: false,
1800
- reply: { text: `āš ļø ${debugCommand.message}` }
1801
- };
1802
- if (debugCommand.action === "show") {
1803
- const overrides = getConfigOverrides();
1804
- if (!(Object.keys(overrides).length > 0)) return {
1805
- shouldContinue: false,
1806
- reply: { text: "āš™ļø Debug overrides: (none)" }
1807
- };
1808
- return {
1809
- shouldContinue: false,
1810
- reply: { text: `āš™ļø Debug overrides (memory-only):\n\`\`\`json\n${JSON.stringify(overrides, null, 2)}\n\`\`\`` }
1811
- };
1812
- }
1813
- if (debugCommand.action === "reset") {
1814
- resetConfigOverrides();
1815
- return {
1816
- shouldContinue: false,
1817
- reply: { text: "āš™ļø Debug overrides cleared; using config on disk." }
1818
- };
1819
- }
1820
- if (debugCommand.action === "unset") {
1821
- const result = unsetConfigOverride(debugCommand.path);
1822
- if (!result.ok) return {
1823
- shouldContinue: false,
1824
- reply: { text: `āš ļø ${result.error ?? "Invalid path."}` }
1825
- };
1826
- if (!result.removed) return {
1827
- shouldContinue: false,
1828
- reply: { text: `āš™ļø No debug override found for ${debugCommand.path}.` }
1829
- };
1830
- return {
1831
- shouldContinue: false,
1832
- reply: { text: `āš™ļø Debug override removed for ${debugCommand.path}.` }
1833
- };
1834
- }
1835
- if (debugCommand.action === "set") {
1836
- const result = setConfigOverride(debugCommand.path, debugCommand.value);
1837
- if (!result.ok) return {
1838
- shouldContinue: false,
1839
- reply: { text: `āš ļø ${result.error ?? "Invalid override."}` }
1840
- };
1841
- const valueLabel = typeof debugCommand.value === "string" ? `"${debugCommand.value}"` : JSON.stringify(debugCommand.value);
1842
- return {
1843
- shouldContinue: false,
1844
- reply: { text: `āš™ļø Debug override set: ${debugCommand.path}=${valueLabel ?? "null"}` }
1845
- };
1846
- }
1847
- return null;
1848
- };
1849
- //#endregion
1850
- //#region src/auto-reply/reply/commands-context-report.ts
1851
- function formatInt(n) {
1852
- return new Intl.NumberFormat("en-US").format(n);
1853
- }
1854
- function formatCharsAndTokens(chars) {
1855
- return `${formatInt(chars)} chars (~${formatInt(estimateTokensFromChars(chars))} tok)`;
1856
- }
1857
- function parseContextArgs(commandBodyNormalized) {
1858
- if (commandBodyNormalized === "/context") return "";
1859
- if (commandBodyNormalized.startsWith("/context ")) return commandBodyNormalized.slice(8).trim();
1860
- return "";
1861
- }
1862
- function formatListTop(entries, cap) {
1863
- const sorted = [...entries].toSorted((a, b) => b.value - a.value);
1864
- const top = sorted.slice(0, cap);
1865
- const omitted = Math.max(0, sorted.length - top.length);
1866
- return {
1867
- lines: top.map((e) => `- ${e.name}: ${formatCharsAndTokens(e.value)}`),
1868
- omitted
1869
- };
1870
- }
1871
- async function resolveContextReport(params) {
1872
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
1873
- const existing = targetSessionEntry?.systemPromptReport;
1874
- if (existing && existing.source === "run") return existing;
1875
- const bootstrapMaxChars = resolveBootstrapMaxChars(params.cfg);
1876
- const bootstrapTotalMaxChars = resolveBootstrapTotalMaxChars(params.cfg);
1877
- const { resolveCommandsSystemPromptBundle } = await import("./commands-system-prompt-CKrY0h7P.js");
1878
- const { systemPrompt, tools, skillsPrompt, bootstrapFiles, injectedFiles, sandboxRuntime } = await resolveCommandsSystemPromptBundle(params);
1879
- return buildSystemPromptReport({
1880
- source: "estimate",
1881
- generatedAt: Date.now(),
1882
- sessionId: targetSessionEntry?.sessionId,
1883
- sessionKey: params.sessionKey,
1884
- provider: params.provider,
1885
- model: params.model,
1886
- workspaceDir: params.workspaceDir,
1887
- bootstrapMaxChars,
1888
- bootstrapTotalMaxChars,
1889
- sandbox: {
1890
- mode: sandboxRuntime.mode,
1891
- sandboxed: sandboxRuntime.sandboxed
1892
- },
1893
- systemPrompt,
1894
- bootstrapFiles,
1895
- injectedFiles,
1896
- skillsPrompt,
1897
- tools
1898
- });
1899
- }
1900
- async function buildContextReply(params) {
1901
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
1902
- const sub = normalizeLowercaseStringOrEmpty(parseContextArgs(params.command.commandBodyNormalized).split(/\s+/).find(Boolean));
1903
- if (!sub || sub === "help") return { text: [
1904
- "🧠 /context",
1905
- "",
1906
- "What counts as context (high-level), plus a breakdown mode.",
1907
- "",
1908
- "Try:",
1909
- "- /context list (short breakdown)",
1910
- "- /context detail (per-file + per-tool + per-skill + system prompt size)",
1911
- "- /context json (same, machine-readable)",
1912
- "",
1913
- "Inline shortcut = a command token inside a normal message (e.g. ā€œhey /statusā€). It runs immediately (allowlisted senders only) and is stripped before the model sees the remaining text."
1914
- ].join("\n") };
1915
- const report = await resolveContextReport(params);
1916
- const cachedContextUsageTokens = resolveFreshSessionTotalTokens(targetSessionEntry);
1917
- const session = {
1918
- totalTokens: targetSessionEntry?.totalTokens ?? null,
1919
- totalTokensFresh: targetSessionEntry?.totalTokensFresh ?? null,
1920
- inputTokens: targetSessionEntry?.inputTokens ?? null,
1921
- outputTokens: targetSessionEntry?.outputTokens ?? null,
1922
- contextTokens: params.contextTokens ?? null
1923
- };
1924
- if (sub === "json") return { text: JSON.stringify({
1925
- report,
1926
- session
1927
- }, null, 2) };
1928
- if (sub !== "list" && sub !== "show" && sub !== "detail" && sub !== "deep") return { text: ["Unknown /context mode.", "Use: /context, /context list, /context detail, or /context json"].join("\n") };
1929
- const fileLines = report.injectedWorkspaceFiles.map((f) => {
1930
- const status = f.missing ? "MISSING" : f.truncated ? "TRUNCATED" : "OK";
1931
- const raw = f.missing ? "0" : formatCharsAndTokens(f.rawChars);
1932
- const injected = f.missing ? "0" : formatCharsAndTokens(f.injectedChars);
1933
- return `- ${f.name}: ${status} | raw ${raw} | injected ${injected}`;
1934
- });
1935
- const sandboxLine = `Sandbox: mode=${report.sandbox?.mode ?? "unknown"} sandboxed=${report.sandbox?.sandboxed ?? false}`;
1936
- const toolSchemaLine = `Tool schemas (JSON): ${formatCharsAndTokens(report.tools.schemaChars)} (counts toward context; not shown as text)`;
1937
- const toolListLine = `Tool list (system prompt text): ${formatCharsAndTokens(report.tools.listChars)}`;
1938
- const skillNameSet = new Set(report.skills.entries.map((s) => s.name));
1939
- const skillNames = Array.from(skillNameSet);
1940
- const toolNames = report.tools.entries.map((t) => t.name);
1941
- const formatNameList = (names, cap) => names.length <= cap ? names.join(", ") : `${names.slice(0, cap).join(", ")}, … (+${names.length - cap} more)`;
1942
- const skillsLine = `Skills list (system prompt text): ${formatCharsAndTokens(report.skills.promptChars)} (${skillNameSet.size} skills)`;
1943
- const skillsNamesLine = skillNameSet.size ? `Skills: ${formatNameList(skillNames, 20)}` : "Skills: (none)";
1944
- const toolsNamesLine = toolNames.length ? `Tools: ${formatNameList(toolNames, 30)}` : "Tools: (none)";
1945
- const systemPromptLine = `System prompt (${report.source}): ${formatCharsAndTokens(report.systemPrompt.chars)} (Project Context ${formatCharsAndTokens(report.systemPrompt.projectContextChars)})`;
1946
- const workspaceLabel = report.workspaceDir ?? params.workspaceDir;
1947
- const bootstrapMaxChars = typeof report.bootstrapMaxChars === "number" && Number.isFinite(report.bootstrapMaxChars) && report.bootstrapMaxChars > 0 ? report.bootstrapMaxChars : resolveBootstrapMaxChars(params.cfg);
1948
- const bootstrapTotalMaxChars = typeof report.bootstrapTotalMaxChars === "number" && Number.isFinite(report.bootstrapTotalMaxChars) && report.bootstrapTotalMaxChars > 0 ? report.bootstrapTotalMaxChars : resolveBootstrapTotalMaxChars(params.cfg);
1949
- const bootstrapMaxLabel = `${formatInt(bootstrapMaxChars)} chars`;
1950
- const bootstrapTotalLabel = `${formatInt(bootstrapTotalMaxChars)} chars`;
1951
- const bootstrapAnalysis = analyzeBootstrapBudget({
1952
- files: report.injectedWorkspaceFiles,
1953
- bootstrapMaxChars,
1954
- bootstrapTotalMaxChars
1955
- });
1956
- const truncatedBootstrapFiles = bootstrapAnalysis.truncatedFiles;
1957
- const truncationCauseCounts = truncatedBootstrapFiles.reduce((acc, file) => {
1958
- for (const cause of file.causes) if (cause === "per-file-limit") acc.perFile += 1;
1959
- else if (cause === "total-limit") acc.total += 1;
1960
- return acc;
1961
- }, {
1962
- perFile: 0,
1963
- total: 0
1964
- });
1965
- const truncationCauseParts = [truncationCauseCounts.perFile > 0 ? `${truncationCauseCounts.perFile} file(s) exceeded max/file` : null, truncationCauseCounts.total > 0 ? `${truncationCauseCounts.total} file(s) hit max/total` : null].filter(Boolean);
1966
- const bootstrapWarningLines = truncatedBootstrapFiles.length > 0 ? [
1967
- `⚠ Bootstrap context is over configured limits: ${truncatedBootstrapFiles.length} file(s) truncated (${formatInt(bootstrapAnalysis.totals.rawChars)} raw chars -> ${formatInt(bootstrapAnalysis.totals.injectedChars)} injected chars).`,
1968
- ...truncationCauseParts.length ? [`Causes: ${truncationCauseParts.join("; ")}.`] : [],
1969
- "Tip: increase `agents.defaults.bootstrapMaxChars` and/or `agents.defaults.bootstrapTotalMaxChars` if this truncation is not intentional."
1970
- ] : [];
1971
- const contextWindowLabel = session.contextTokens != null ? formatInt(session.contextTokens) : "?";
1972
- const totalsLine = cachedContextUsageTokens != null ? `Session tokens (cached): ${formatInt(cachedContextUsageTokens)} total / ctx=${contextWindowLabel}` : `Session tokens (cached): unknown / ctx=${contextWindowLabel}`;
1973
- const sharedContextLines = [
1974
- `Workspace: ${workspaceLabel}`,
1975
- `Bootstrap max/file: ${bootstrapMaxLabel}`,
1976
- `Bootstrap max/total: ${bootstrapTotalLabel}`,
1977
- sandboxLine,
1978
- systemPromptLine,
1979
- ...bootstrapWarningLines.length ? ["", ...bootstrapWarningLines] : [],
1980
- "",
1981
- "Injected workspace files:",
1982
- ...fileLines,
1983
- "",
1984
- skillsLine,
1985
- skillsNamesLine
1986
- ];
1987
- if (sub === "detail" || sub === "deep") {
1988
- const perSkill = formatListTop(report.skills.entries.map((s) => ({
1989
- name: s.name,
1990
- value: s.blockChars
1991
- })), 30);
1992
- const perToolSchema = formatListTop(report.tools.entries.map((t) => ({
1993
- name: t.name,
1994
- value: t.schemaChars
1995
- })), 30);
1996
- const perToolSummary = formatListTop(report.tools.entries.map((t) => ({
1997
- name: t.name,
1998
- value: t.summaryChars
1999
- })), 30);
2000
- const toolPropsLines = report.tools.entries.filter((t) => t.propertiesCount != null).toSorted((a, b) => (b.propertiesCount ?? 0) - (a.propertiesCount ?? 0)).slice(0, 30).map((t) => `- ${t.name}: ${t.propertiesCount} params`);
2001
- const trackedPromptChars = report.systemPrompt.chars + report.tools.schemaChars;
2002
- const trackedPromptLine = `Tracked prompt estimate: ${formatCharsAndTokens(trackedPromptChars)}`;
2003
- const actualContextLine = cachedContextUsageTokens != null ? `Actual context usage (cached): ${formatInt(cachedContextUsageTokens)} tok` : "Actual context usage (cached): unavailable";
2004
- const overheadTokens = cachedContextUsageTokens != null ? cachedContextUsageTokens - estimateTokensFromChars(trackedPromptChars) : null;
2005
- const overheadLine = overheadTokens == null ? null : overheadTokens > 0 ? `Untracked provider/runtime overhead: ~${formatInt(overheadTokens)} tok` : "Untracked provider/runtime overhead: not observed in cached usage";
2006
- return { text: [
2007
- "🧠 Context breakdown (detailed)",
2008
- ...sharedContextLines,
2009
- ...perSkill.lines.length ? ["Top skills (prompt entry size):", ...perSkill.lines] : [],
2010
- ...perSkill.omitted ? [`… (+${perSkill.omitted} more skills)`] : [],
2011
- "",
2012
- toolListLine,
2013
- toolSchemaLine,
2014
- toolsNamesLine,
2015
- "Top tools (schema size):",
2016
- ...perToolSchema.lines,
2017
- ...perToolSchema.omitted ? [`… (+${perToolSchema.omitted} more tools)`] : [],
2018
- "",
2019
- "Top tools (summary text size):",
2020
- ...perToolSummary.lines,
2021
- ...perToolSummary.omitted ? [`… (+${perToolSummary.omitted} more tools)`] : [],
2022
- ...toolPropsLines.length ? [
2023
- "",
2024
- "Tools (param count):",
2025
- ...toolPropsLines
2026
- ] : [],
2027
- "",
2028
- trackedPromptLine,
2029
- actualContextLine,
2030
- ...overheadLine ? [overheadLine] : [],
2031
- "",
2032
- totalsLine,
2033
- "",
2034
- "Inline shortcut: a command token inside normal text (e.g. ā€œhey /statusā€) that runs immediately (allowlisted senders only) and is stripped before the model sees the remaining message."
2035
- ].filter(Boolean).join("\n") };
2036
- }
2037
- return { text: [
2038
- "🧠 Context breakdown",
2039
- ...sharedContextLines,
2040
- toolListLine,
2041
- toolSchemaLine,
2042
- toolsNamesLine,
2043
- "",
2044
- totalsLine,
2045
- "",
2046
- "Inline shortcut: a command token inside normal text (e.g. ā€œhey /statusā€) that runs immediately (allowlisted senders only) and is stripped before the model sees the remaining message."
2047
- ].join("\n") };
2048
- }
2049
- //#endregion
2050
- //#region src/auto-reply/reply/commands-context-command.ts
2051
- const handleContextCommand = async (params, allowTextCommands) => {
2052
- if (!allowTextCommands) return null;
2053
- const normalized = params.command.commandBodyNormalized;
2054
- if (normalized !== "/context" && !normalized.startsWith("/context ")) return null;
2055
- if (!params.command.isAuthorizedSender) {
2056
- logVerbose(`Ignoring /context from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2057
- return { shouldContinue: false };
2058
- }
2059
- return {
2060
- shouldContinue: false,
2061
- reply: await buildContextReply(params)
2062
- };
2063
- };
2064
- //#endregion
2065
- //#region src/auto-reply/reply/commands-export-common.ts
2066
- function escapeRegExp(value) {
2067
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2068
- }
2069
- function parseExportCommandOutputPath(commandBodyNormalized, aliases) {
2070
- const normalized = commandBodyNormalized.trim();
2071
- if (aliases.some((alias) => normalized === `/${alias}`)) return {};
2072
- const aliasPattern = aliases.map(escapeRegExp).join("|");
2073
- return { outputPath: normalized.replace(new RegExp(`^/(${aliasPattern})\\s*`), "").trim().split(/\s+/).find((part) => !part.startsWith("-")) };
2074
- }
2075
- function resolveExportCommandSessionTarget(params) {
2076
- const targetAgentId = resolveAgentIdFromSessionKey(params.sessionKey) || params.agentId;
2077
- const storePath = params.storePath ?? resolveDefaultSessionStorePath(targetAgentId);
2078
- const entry = loadSessionStore(storePath, { skipCache: true })[params.sessionKey];
2079
- if (!entry?.sessionId) return { text: `āŒ Session not found: ${params.sessionKey}` };
2080
- try {
2081
- return {
2082
- entry,
2083
- sessionFile: resolveSessionFilePath(entry.sessionId, entry, resolveSessionFilePathOptions({
2084
- agentId: targetAgentId,
2085
- storePath
2086
- }))
2087
- };
2088
- } catch (err) {
2089
- return { text: `āŒ Failed to resolve session file: ${formatErrorMessage(err)}` };
2090
- }
2091
- }
2092
- function isReplyPayload(value) {
2093
- return "text" in value;
2094
- }
2095
- //#endregion
2096
- //#region src/auto-reply/reply/commands-export-session.ts
2097
- const EXPORT_HTML_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "export-html");
2098
- function loadTemplate(fileName) {
2099
- return fs.readFileSync(path.join(EXPORT_HTML_DIR, fileName), "utf-8");
2100
- }
2101
- function generateHtml(sessionData) {
2102
- const template = loadTemplate("template.html");
2103
- const templateCss = loadTemplate("template.css");
2104
- const templateJs = loadTemplate("template.js");
2105
- const markedJs = loadTemplate(path.join("vendor", "marked.min.js"));
2106
- const hljsJs = loadTemplate(path.join("vendor", "highlight.min.js"));
2107
- const themeVars = `
2108
- --cyan: #00d7ff;
2109
- --blue: #5f87ff;
2110
- --green: #b5bd68;
2111
- --red: #cc6666;
2112
- --yellow: #ffff00;
2113
- --gray: #808080;
2114
- --dimGray: #666666;
2115
- --darkGray: #505050;
2116
- --accent: #8abeb7;
2117
- --selectedBg: #3a3a4a;
2118
- --userMsgBg: #343541;
2119
- --toolPendingBg: #282832;
2120
- --toolSuccessBg: #283228;
2121
- --toolErrorBg: #3c2828;
2122
- --customMsgBg: #2d2838;
2123
- --text: #e0e0e0;
2124
- --dim: #666666;
2125
- --muted: #808080;
2126
- --border: #5f87ff;
2127
- --borderAccent: #00d7ff;
2128
- --borderMuted: #505050;
2129
- --success: #b5bd68;
2130
- --error: #cc6666;
2131
- --warning: #ffff00;
2132
- --thinkingText: #808080;
2133
- --userMessageBg: #343541;
2134
- --userMessageText: #e0e0e0;
2135
- --customMessageBg: #2d2838;
2136
- --customMessageText: #e0e0e0;
2137
- --customMessageLabel: #9575cd;
2138
- --toolTitle: #e0e0e0;
2139
- --toolOutput: #808080;
2140
- --mdHeading: #f0c674;
2141
- --mdLink: #81a2be;
2142
- --mdLinkUrl: #666666;
2143
- --mdCode: #8abeb7;
2144
- --mdCodeBlock: #b5bd68;
2145
- `;
2146
- const bodyBg = "#1e1e28";
2147
- const containerBg = "#282832";
2148
- const infoBg = "#343541";
2149
- const sessionDataBase64 = Buffer.from(JSON.stringify(sessionData)).toString("base64");
2150
- const css = templateCss.replace("/* {{THEME_VARS}} */", themeVars.trim()).replace("/* {{BODY_BG_DECL}} */", `--body-bg: ${bodyBg};`).replace("/* {{CONTAINER_BG_DECL}} */", `--container-bg: ${containerBg};`).replace("/* {{INFO_BG_DECL}} */", `--info-bg: ${infoBg};`);
2151
- return template.replace("{{CSS}}", css).replace("{{JS}}", templateJs).replace("{{SESSION_DATA}}", sessionDataBase64).replace("{{MARKED_JS}}", markedJs).replace("{{HIGHLIGHT_JS}}", hljsJs);
2152
- }
2153
- async function buildExportSessionReply(params) {
2154
- const args = parseExportCommandOutputPath(params.command.commandBodyNormalized, ["export-session", "export"]);
2155
- const sessionTarget = resolveExportCommandSessionTarget(params);
2156
- if (isReplyPayload(sessionTarget)) return sessionTarget;
2157
- const { entry, sessionFile } = sessionTarget;
2158
- if (!fs.existsSync(sessionFile)) return { text: `āŒ Session file not found: ${sessionFile}` };
2159
- const sessionManager = SessionManager.open(sessionFile);
2160
- const entries = sessionManager.getEntries();
2161
- const header = sessionManager.getHeader();
2162
- const leafId = sessionManager.getLeafId();
2163
- const { systemPrompt, tools } = await resolveCommandsSystemPromptBundle({
2164
- ...params,
2165
- sessionEntry: entry
2166
- });
2167
- const html = generateHtml({
2168
- header,
2169
- entries,
2170
- leafId,
2171
- systemPrompt,
2172
- tools: tools.map((t) => ({
2173
- name: t.name,
2174
- description: t.description,
2175
- parameters: t.parameters
2176
- }))
2177
- });
2178
- const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
2179
- const defaultFileName = `genesis-session-${entry.sessionId.slice(0, 8)}-${timestamp}.html`;
2180
- const outputPath = args.outputPath ? path.resolve(args.outputPath.startsWith("~") ? args.outputPath.replace("~", process.env.HOME ?? "") : args.outputPath) : path.join(params.workspaceDir, defaultFileName);
2181
- const outputDir = path.dirname(outputPath);
2182
- if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
2183
- fs.writeFileSync(outputPath, html, "utf-8");
2184
- const relativePath = path.relative(params.workspaceDir, outputPath);
2185
- return { text: [
2186
- "āœ… Session exported!",
2187
- "",
2188
- `šŸ“„ File: ${relativePath.startsWith("..") ? outputPath : relativePath}`,
2189
- `šŸ“Š Entries: ${entries.length}`,
2190
- `🧠 System prompt: ${systemPrompt.length.toLocaleString()} chars`,
2191
- `šŸ”§ Tools: ${tools.length}`
2192
- ].join("\n") };
2193
- }
2194
- //#endregion
2195
- //#region src/trajectory/export.ts
2196
- const MAX_TRAJECTORY_RUNTIME_EVENTS = 2e5;
2197
- const MAX_TRAJECTORY_TOTAL_EVENTS = 25e4;
2198
- const MAX_TRAJECTORY_SESSION_FILE_BYTES = 50 * 1024 * 1024;
2199
- function parseSessionEntries(content) {
2200
- return content.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean).flatMap((line) => {
2201
- try {
2202
- return [JSON.parse(line)];
2203
- } catch {
2204
- return [];
2205
- }
2206
- });
2207
- }
2208
- function migrateLegacySessionEntries(entries) {
2209
- const version = entries.find((entry) => entry.type === "session")?.version ?? 1;
2210
- if (version < 2) {
2211
- let previousId = null;
2212
- let index = 0;
2213
- for (const entry of entries) {
2214
- if (entry.type === "session") {
2215
- entry.version = 2;
2216
- continue;
2217
- }
2218
- const mutable = entry;
2219
- if (typeof mutable.id !== "string") mutable.id = `legacy-${index++}`;
2220
- mutable.parentId = previousId;
2221
- const entryId = mutable.id;
2222
- previousId = typeof entryId === "string" ? entryId : null;
2223
- if (entry.type === "compaction" && typeof mutable.firstKeptEntryIndex === "number") {
2224
- const target = entries[mutable.firstKeptEntryIndex];
2225
- if (target && target.type !== "session") mutable.firstKeptEntryId = target.id;
2226
- delete mutable.firstKeptEntryIndex;
2227
- }
2228
- }
2229
- }
2230
- if (version < 3) for (const entry of entries) {
2231
- if (entry.type === "session") {
2232
- entry.version = 3;
2233
- continue;
2234
- }
2235
- if (entry.type === "message") {
2236
- const message = entry.message;
2237
- if (message?.role === "hookMessage") message.role = "custom";
2238
- }
2239
- }
2240
- }
2241
- function readSessionBranch(filePath) {
2242
- const fileEntries = parseSessionEntries(fs.readFileSync(filePath, "utf8"));
2243
- migrateLegacySessionEntries(fileEntries);
2244
- const header = fileEntries.find((entry) => entry.type === "session") ?? null;
2245
- const entries = fileEntries.filter((entry) => entry.type !== "session" && typeof entry.id === "string" && (typeof entry.timestamp === "string" || typeof entry.timestamp === "number"));
2246
- const byId = new Map(entries.map((entry) => [entry.id, entry]));
2247
- const leafId = entries.at(-1)?.id ?? null;
2248
- const branchEntries = [];
2249
- let current = leafId ? byId.get(leafId) : void 0;
2250
- while (current) {
2251
- branchEntries.unshift(current);
2252
- current = current.parentId ? byId.get(current.parentId) : void 0;
2253
- }
2254
- return {
2255
- header,
2256
- leafId,
2257
- branchEntries
2258
- };
2259
- }
2260
- function parseJsonlFile(filePath, params) {
2261
- if (!fs.existsSync(filePath)) return [];
2262
- const stat = fs.statSync(filePath);
2263
- if (stat.size > params.maxBytes) throw new Error(`Trajectory runtime file is too large to export (${stat.size} bytes; limit ${params.maxBytes})`);
2264
- const rows = fs.readFileSync(filePath, "utf8").split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
2265
- const parsed = [];
2266
- for (const row of rows) {
2267
- if (parsed.length >= params.maxEvents) throw new Error(`Trajectory runtime file has too many events to export (limit ${params.maxEvents})`);
2268
- try {
2269
- const value = JSON.parse(row);
2270
- if (!params.validate || params.validate(value)) parsed.push(value);
2271
- } catch {}
2272
- }
2273
- return parsed;
2274
- }
2275
- function isFiniteNumber(value) {
2276
- return typeof value === "number" && Number.isFinite(value);
2277
- }
2278
- function isRecord(value) {
2279
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2280
- }
2281
- function isRuntimeTrajectoryEventForSession(value, sessionId) {
2282
- if (!isRecord(value)) return false;
2283
- return value.traceSchema === "genesis-trajectory" && value.schemaVersion === 1 && value.source === "runtime" && typeof value.type === "string" && typeof value.ts === "string" && !Number.isNaN(Date.parse(value.ts)) && isFiniteNumber(value.seq) && value.sessionId === sessionId && (!("data" in value) || value.data === void 0 || isRecord(value.data));
2284
- }
2285
- function isRegularNonSymlinkFile(filePath) {
2286
- try {
2287
- const linkStat = fs.lstatSync(filePath);
2288
- if (linkStat.isSymbolicLink() || !linkStat.isFile()) return false;
2289
- const stat = fs.statSync(filePath);
2290
- return stat.isFile() && stat.dev === linkStat.dev && stat.ino === linkStat.ino;
2291
- } catch {
2292
- return false;
2293
- }
2294
- }
2295
- function readRuntimePointerFile(sessionFile, sessionId) {
2296
- const pointerPath = resolveTrajectoryPointerFilePath(sessionFile);
2297
- if (!isRegularNonSymlinkFile(pointerPath)) return;
2298
- try {
2299
- const parsed = JSON.parse(fs.readFileSync(pointerPath, "utf8"));
2300
- if (!isRecord(parsed)) return;
2301
- if (parsed.sessionId !== sessionId || typeof parsed.runtimeFile !== "string") return;
2302
- const runtimeFile = path.resolve(parsed.runtimeFile);
2303
- const safeRuntimeFileName = `${safeTrajectorySessionFileName(sessionId)}.jsonl`;
2304
- if (runtimeFile !== path.resolve(resolveTrajectoryFilePath({
2305
- env: {},
2306
- sessionFile,
2307
- sessionId
2308
- })) && path.basename(runtimeFile) !== safeRuntimeFileName) return;
2309
- return runtimeFile;
2310
- } catch {
2311
- return;
2312
- }
2313
- }
2314
- function resolveTrajectoryRuntimeFile(params) {
2315
- if (params.runtimeFile) return params.runtimeFile;
2316
- return [
2317
- readRuntimePointerFile(params.sessionFile, params.sessionId),
2318
- resolveTrajectoryFilePath({
2319
- env: {},
2320
- sessionFile: params.sessionFile,
2321
- sessionId: params.sessionId
2322
- }),
2323
- resolveTrajectoryFilePath({
2324
- sessionFile: params.sessionFile,
2325
- sessionId: params.sessionId
2326
- })
2327
- ].filter((candidate) => Boolean(candidate)).find((candidate) => isRegularNonSymlinkFile(candidate));
2328
- }
2329
- function normalizeTimestamp(value) {
2330
- if (typeof value === "number" && Number.isFinite(value)) {
2331
- const parsed = new Date(value);
2332
- if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
2333
- }
2334
- if (typeof value === "string") {
2335
- const parsed = new Date(value);
2336
- if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
2337
- }
2338
- return (/* @__PURE__ */ new Date(0)).toISOString();
2339
- }
2340
- function resolveMessageEventType(message) {
2341
- if (message.role === "user") return "user.message";
2342
- if (message.role === "assistant") return "assistant.message";
2343
- if (message.role === "toolResult") return "tool.result";
2344
- return `message.${message.role}`;
2345
- }
2346
- function extractAssistantToolCalls(message) {
2347
- if (message.role !== "assistant" || !Array.isArray(message.content)) return [];
2348
- return message.content.flatMap((block, index) => {
2349
- if (!block || typeof block !== "object") return [];
2350
- const typedBlock = block;
2351
- const blockType = typeof typedBlock.type === "string" ? typedBlock.type.trim().toLowerCase() : "";
2352
- if (blockType !== "toolcall" && blockType !== "tooluse" && blockType !== "functioncall") return [];
2353
- return [{
2354
- id: typeof typedBlock.id === "string" ? typedBlock.id : void 0,
2355
- name: typeof typedBlock.name === "string" ? typedBlock.name : void 0,
2356
- arguments: typedBlock.arguments ?? typedBlock.input ?? typedBlock.parameters,
2357
- index
2358
- }];
2359
- });
2360
- }
2361
- function buildTranscriptEvents(params) {
2362
- const events = [];
2363
- let seq = 0;
2364
- for (const entry of params.entries) {
2365
- const push = (type, data) => {
2366
- events.push({
2367
- traceSchema: "genesis-trajectory",
2368
- schemaVersion: 1,
2369
- traceId: params.traceId,
2370
- source: "transcript",
2371
- type,
2372
- ts: normalizeTimestamp(entry.timestamp),
2373
- seq: 0,
2374
- sourceSeq: seq += 1,
2375
- sessionId: params.sessionId,
2376
- sessionKey: params.sessionKey,
2377
- workspaceDir: params.workspaceDir,
2378
- entryId: entry.id,
2379
- parentEntryId: entry.parentId,
2380
- data
2381
- });
2382
- };
2383
- switch (entry.type) {
2384
- case "message":
2385
- push(resolveMessageEventType(entry.message), { message: sanitizeDiagnosticPayload(entry.message) });
2386
- for (const toolCall of extractAssistantToolCalls(entry.message)) push("tool.call", {
2387
- toolCallId: toolCall.id,
2388
- name: toolCall.name,
2389
- arguments: sanitizeDiagnosticPayload(toolCall.arguments),
2390
- assistantEntryId: entry.id,
2391
- blockIndex: toolCall.index
2392
- });
2393
- break;
2394
- case "compaction":
2395
- push("session.compaction", {
2396
- summary: entry.summary,
2397
- firstKeptEntryId: entry.firstKeptEntryId,
2398
- tokensBefore: entry.tokensBefore,
2399
- details: sanitizeDiagnosticPayload(entry.details),
2400
- fromHook: entry.fromHook ?? false
2401
- });
2402
- break;
2403
- case "branch_summary":
2404
- push("session.branch_summary", {
2405
- fromId: entry.fromId,
2406
- summary: entry.summary,
2407
- details: sanitizeDiagnosticPayload(entry.details),
2408
- fromHook: entry.fromHook ?? false
2409
- });
2410
- break;
2411
- case "custom":
2412
- push("session.custom", {
2413
- customType: entry.customType,
2414
- data: sanitizeDiagnosticPayload(entry.data)
2415
- });
2416
- break;
2417
- case "custom_message":
2418
- push("session.custom_message", {
2419
- customType: entry.customType,
2420
- content: sanitizeDiagnosticPayload(entry.content),
2421
- details: sanitizeDiagnosticPayload(entry.details),
2422
- display: entry.display
2423
- });
2424
- break;
2425
- case "thinking_level_change":
2426
- push("session.thinking_level_change", { thinkingLevel: entry.thinkingLevel });
2427
- break;
2428
- case "model_change":
2429
- push("session.model_change", {
2430
- provider: entry.provider,
2431
- modelId: entry.modelId
2432
- });
2433
- break;
2434
- case "label":
2435
- push("session.label", {
2436
- targetId: entry.targetId,
2437
- label: entry.label
2438
- });
2439
- break;
2440
- case "session_info":
2441
- push("session.info", { name: entry.name });
2442
- break;
2443
- }
2444
- }
2445
- return events;
2446
- }
2447
- function sortTrajectoryEvents(events) {
2448
- const sourceOrder = {
2449
- runtime: 0,
2450
- transcript: 1,
2451
- export: 2
2452
- };
2453
- const sorted = events.toSorted((left, right) => {
2454
- const byTs = left.ts.localeCompare(right.ts);
2455
- if (byTs !== 0) return byTs;
2456
- const bySource = sourceOrder[left.source] - sourceOrder[right.source];
2457
- if (bySource !== 0) return bySource;
2458
- return (left.sourceSeq ?? left.seq) - (right.sourceSeq ?? right.seq);
2459
- });
2460
- for (const [index, event] of sorted.entries()) event.seq = index + 1;
2461
- return sorted;
2462
- }
2463
- function trajectoryJsonlFile(pathName, events) {
2464
- return jsonlSupportBundleFile(pathName, events.map((event) => safeJsonStringify(event)).filter((line) => Boolean(line)));
2465
- }
2466
- function buildTrajectoryExportRedaction(params) {
2467
- const env = process.env;
2468
- return {
2469
- env,
2470
- stateDir: resolveStateDir(env),
2471
- workspaceDir: path.resolve(params.workspaceDir)
2472
- };
2473
- }
2474
- function redactWorkspacePathString(value, redaction) {
2475
- const workspaceDir = redaction.workspaceDir;
2476
- if (!workspaceDir) return value;
2477
- const normalizedWorkspaceDir = workspaceDir.replaceAll("\\", "/");
2478
- let next = value;
2479
- for (const candidate of new Set([workspaceDir, normalizedWorkspaceDir])) {
2480
- if (!candidate) continue;
2481
- const escaped = candidate.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
2482
- next = next.replace(new RegExp(`${escaped}(?=$|[\\\\/])`, "gu"), "$WORKSPACE_DIR");
2483
- }
2484
- return next;
2485
- }
2486
- function maybeRedactPathString(value, redaction) {
2487
- const workspaceRedacted = redactWorkspacePathString(value, redaction);
2488
- if (workspaceRedacted !== value || path.isAbsolute(workspaceRedacted) || workspaceRedacted.includes(redaction.stateDir) || (redaction.env.HOME ? workspaceRedacted.includes(redaction.env.HOME) : false) || (redaction.env.USERPROFILE ? workspaceRedacted.includes(redaction.env.USERPROFILE) : false)) return redactSupportString(workspaceRedacted, redaction);
2489
- return workspaceRedacted;
2490
- }
2491
- function redactLocalPathValues(value, redaction) {
2492
- if (typeof value === "string") return maybeRedactPathString(value, redaction);
2493
- if (Array.isArray(value)) return value.map((entry) => redactLocalPathValues(entry, redaction));
2494
- if (!value || typeof value !== "object") return value;
2495
- const record = value;
2496
- const next = {};
2497
- for (const [key, entry] of Object.entries(record)) next[key] = redactLocalPathValues(entry, redaction);
2498
- return next;
2499
- }
2500
- function redactEventForExport(event, redaction) {
2501
- return {
2502
- ...event,
2503
- workspaceDir: event.workspaceDir ? maybeRedactPathString(event.workspaceDir, redaction) : void 0,
2504
- data: event.data ? redactLocalPathValues(event.data, redaction) : void 0
2505
- };
2506
- }
2507
- function resolveRuntimeContext(runtimeEvents) {
2508
- const runtimeData = runtimeEvents.slice().toReversed().find((event) => event.type === "context.compiled")?.data;
2509
- const toolsValue = Array.isArray(runtimeData?.tools) ? runtimeData.tools : void 0;
2510
- return {
2511
- systemPrompt: typeof runtimeData?.systemPrompt === "string" ? runtimeData.systemPrompt : void 0,
2512
- tools: toolsValue
2513
- };
2514
- }
2515
- function resolveLatestRuntimeEventData(runtimeEvents, type) {
2516
- return runtimeEvents.slice().toReversed().find((candidate) => candidate.type === type)?.data;
2517
- }
2518
- function normalizePathForMatch(value) {
2519
- return value.replaceAll("\\", "/").trim().toLowerCase();
2520
- }
2521
- function collectPotentialPathStrings(value) {
2522
- const found = /* @__PURE__ */ new Set();
2523
- const visit = (input) => {
2524
- if (!input || typeof input !== "object") return;
2525
- if (Array.isArray(input)) {
2526
- for (const entry of input) visit(entry);
2527
- return;
2528
- }
2529
- for (const [key, entry] of Object.entries(input)) if (typeof entry === "string" && (key.toLowerCase().includes("path") || entry.endsWith("SKILL.md") || entry.endsWith("skill.md"))) found.add(entry);
2530
- else visit(entry);
2531
- };
2532
- visit(value);
2533
- return [...found];
2534
- }
2535
- function markInvokedSkills(params) {
2536
- if (!params.skills || typeof params.skills !== "object") return params.skills;
2537
- const skillsRecord = params.skills;
2538
- if (!Array.isArray(skillsRecord.entries) || skillsRecord.entries.length === 0) return params.skills;
2539
- const invokedPaths = new Set(params.events.flatMap((event) => {
2540
- if (event.type !== "tool.call") return [];
2541
- return collectPotentialPathStrings(event.data?.arguments);
2542
- }));
2543
- const normalizedInvokedPaths = new Set([...invokedPaths].map((value) => normalizePathForMatch(value)));
2544
- const entries = skillsRecord.entries.map((entry) => {
2545
- const rawPath = typeof entry.filePath === "string" ? entry.filePath : void 0;
2546
- const normalizedPath = rawPath ? normalizePathForMatch(rawPath) : void 0;
2547
- const skillDirName = rawPath?.replaceAll("\\", "/").split("/").slice(-2, -1)[0]?.toLowerCase() ?? void 0;
2548
- const invoked = normalizedPath ? [...normalizedInvokedPaths].some((candidate) => candidate === normalizedPath || candidate.endsWith(normalizedPath) || (skillDirName ? candidate.endsWith(`/${skillDirName}/skill.md`) : false)) : false;
2549
- return invoked ? {
2550
- ...entry,
2551
- invoked,
2552
- invocationDetectedBy: "tool-call-file-path"
2553
- } : {
2554
- ...entry,
2555
- invoked: false
2556
- };
2557
- });
2558
- return {
2559
- ...skillsRecord,
2560
- entries
2561
- };
2562
- }
2563
- function buildMetadataCapture(params) {
2564
- const runtimeMetadata = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.metadata");
2565
- if (!runtimeMetadata) return;
2566
- const modelFallback = (() => {
2567
- const latest = params.runtimeEvents.slice().toReversed().find((event) => event.provider || event.modelId || event.modelApi);
2568
- if (!latest?.provider && !latest?.modelId && !latest?.modelApi) return;
2569
- return {
2570
- provider: latest.provider,
2571
- name: latest.modelId,
2572
- api: latest.modelApi
2573
- };
2574
- })();
2575
- return {
2576
- traceSchema: "genesis-trajectory",
2577
- schemaVersion: 1,
2578
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2579
- traceId: params.manifest.traceId,
2580
- sessionId: params.manifest.sessionId,
2581
- sessionKey: params.manifest.sessionKey,
2582
- harness: runtimeMetadata.harness,
2583
- model: runtimeMetadata.model ?? modelFallback,
2584
- config: runtimeMetadata.config,
2585
- plugins: runtimeMetadata.plugins,
2586
- skills: markInvokedSkills({
2587
- skills: runtimeMetadata.skills,
2588
- events: params.events
2589
- }),
2590
- prompting: runtimeMetadata.prompting,
2591
- redaction: runtimeMetadata.redaction,
2592
- metadata: runtimeMetadata.metadata
2593
- };
2594
- }
2595
- function buildArtifactsCapture(params) {
2596
- const runtimeArtifacts = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.artifacts");
2597
- const runtimeCompletion = resolveLatestRuntimeEventData(params.runtimeEvents, "model.completed");
2598
- const runtimeEnd = resolveLatestRuntimeEventData(params.runtimeEvents, "session.ended");
2599
- if (!runtimeArtifacts && !runtimeCompletion && !runtimeEnd) return;
2600
- return {
2601
- traceSchema: "genesis-trajectory",
2602
- schemaVersion: 1,
2603
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2604
- traceId: params.manifest.traceId,
2605
- sessionId: params.manifest.sessionId,
2606
- sessionKey: params.manifest.sessionKey,
2607
- finalStatus: runtimeArtifacts?.finalStatus ?? runtimeEnd?.status,
2608
- aborted: runtimeArtifacts?.aborted ?? runtimeEnd?.aborted,
2609
- externalAbort: runtimeArtifacts?.externalAbort ?? runtimeEnd?.externalAbort,
2610
- timedOut: runtimeArtifacts?.timedOut ?? runtimeEnd?.timedOut,
2611
- idleTimedOut: runtimeArtifacts?.idleTimedOut ?? runtimeEnd?.idleTimedOut,
2612
- timedOutDuringCompaction: runtimeArtifacts?.timedOutDuringCompaction ?? runtimeEnd?.timedOutDuringCompaction,
2613
- promptError: runtimeArtifacts?.promptError ?? runtimeEnd?.promptError ?? runtimeCompletion?.promptError,
2614
- promptErrorSource: runtimeArtifacts?.promptErrorSource ?? runtimeCompletion?.promptErrorSource,
2615
- usage: runtimeArtifacts?.usage ?? runtimeCompletion?.usage,
2616
- promptCache: runtimeArtifacts?.promptCache ?? runtimeCompletion?.promptCache,
2617
- compactionCount: runtimeArtifacts?.compactionCount ?? runtimeCompletion?.compactionCount,
2618
- assistantTexts: runtimeArtifacts?.assistantTexts ?? runtimeCompletion?.assistantTexts,
2619
- finalPromptText: runtimeArtifacts?.finalPromptText ?? runtimeCompletion?.finalPromptText,
2620
- itemLifecycle: runtimeArtifacts?.itemLifecycle,
2621
- toolMetas: runtimeArtifacts?.toolMetas,
2622
- didSendViaMessagingTool: runtimeArtifacts?.didSendViaMessagingTool,
2623
- successfulCronAdds: runtimeArtifacts?.successfulCronAdds,
2624
- messagingToolSentTexts: runtimeArtifacts?.messagingToolSentTexts,
2625
- messagingToolSentMediaUrls: runtimeArtifacts?.messagingToolSentMediaUrls,
2626
- messagingToolSentTargets: runtimeArtifacts?.messagingToolSentTargets,
2627
- lastToolError: runtimeArtifacts?.lastToolError
2628
- };
2629
- }
2630
- function buildPromptsCapture(params) {
2631
- const runtimeMetadata = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.metadata");
2632
- const latestCompiled = resolveLatestRuntimeEventData(params.runtimeEvents, "context.compiled");
2633
- const submittedPrompts = params.runtimeEvents.filter((event) => event.type === "prompt.submitted").map((event) => event.data?.prompt).filter((prompt) => typeof prompt === "string");
2634
- const systemPrompt = (typeof latestCompiled?.systemPrompt === "string" ? latestCompiled.systemPrompt : void 0) ?? params.runtimeContext.systemPrompt;
2635
- const skillsPrompt = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.skillsPrompt === "string" ? runtimeMetadata.prompting.skillsPrompt : void 0;
2636
- const userPromptPrefixText = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.userPromptPrefixText === "string" ? runtimeMetadata.prompting.userPromptPrefixText : void 0;
2637
- const promptReport = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.systemPromptReport === "object" ? runtimeMetadata.prompting.systemPromptReport : void 0;
2638
- if (!systemPrompt && submittedPrompts.length === 0 && !skillsPrompt && !userPromptPrefixText) return;
2639
- return {
2640
- traceSchema: "genesis-trajectory",
2641
- schemaVersion: 1,
2642
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2643
- traceId: params.manifest.traceId,
2644
- sessionId: params.manifest.sessionId,
2645
- sessionKey: params.manifest.sessionKey,
2646
- system: systemPrompt,
2647
- submittedPrompts,
2648
- latestSubmittedPrompt: submittedPrompts.at(-1),
2649
- skillsPrompt,
2650
- userPromptPrefixText,
2651
- systemPromptReport: promptReport
2652
- };
2653
- }
2654
- function resolveDefaultTrajectoryExportDir(params) {
2655
- const timestamp = (params.now ?? /* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
2656
- const sessionFileName = safeTrajectorySessionFileName(params.sessionId);
2657
- return path.join(params.workspaceDir, ".genesis", "trajectory-exports", `genesis-trajectory-${sessionFileName.slice(0, 8)}-${timestamp}`);
2658
- }
2659
- function exportTrajectoryBundle(params) {
2660
- const redaction = buildTrajectoryExportRedaction({ workspaceDir: params.workspaceDir });
2661
- const sessionStat = fs.statSync(params.sessionFile);
2662
- if (sessionStat.size > MAX_TRAJECTORY_SESSION_FILE_BYTES) throw new Error(`Trajectory session file is too large to export (${sessionStat.size} bytes; limit ${MAX_TRAJECTORY_SESSION_FILE_BYTES})`);
2663
- const { header, leafId, branchEntries } = readSessionBranch(params.sessionFile);
2664
- const runtimeFile = resolveTrajectoryRuntimeFile({
2665
- runtimeFile: params.runtimeFile,
2666
- sessionFile: params.sessionFile,
2667
- sessionId: params.sessionId
2668
- });
2669
- const runtimeEvents = runtimeFile ? parseJsonlFile(runtimeFile, {
2670
- maxBytes: TRAJECTORY_RUNTIME_FILE_MAX_BYTES,
2671
- maxEvents: MAX_TRAJECTORY_RUNTIME_EVENTS,
2672
- validate: (value) => isRuntimeTrajectoryEventForSession(value, params.sessionId)
2673
- }) : [];
2674
- const transcriptEvents = buildTranscriptEvents({
2675
- entries: branchEntries,
2676
- sessionId: params.sessionId,
2677
- sessionKey: params.sessionKey,
2678
- workspaceDir: params.workspaceDir,
2679
- traceId: params.sessionId
2680
- });
2681
- const maxTotalEvents = params.maxTotalEvents ?? MAX_TRAJECTORY_TOTAL_EVENTS;
2682
- const totalEventCount = runtimeEvents.length + transcriptEvents.length;
2683
- if (totalEventCount > maxTotalEvents) throw new Error(`Trajectory export has too many events (${totalEventCount}; limit ${maxTotalEvents})`);
2684
- const rawEvents = sortTrajectoryEvents([...runtimeEvents, ...transcriptEvents]);
2685
- const events = rawEvents.map((event) => redactEventForExport(event, redaction));
2686
- const manifest = {
2687
- traceSchema: "genesis-trajectory",
2688
- schemaVersion: 1,
2689
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2690
- traceId: params.sessionId,
2691
- sessionId: params.sessionId,
2692
- sessionKey: params.sessionKey,
2693
- workspaceDir: maybeRedactPathString(params.workspaceDir, redaction),
2694
- leafId,
2695
- eventCount: events.length,
2696
- runtimeEventCount: runtimeEvents.length,
2697
- transcriptEventCount: transcriptEvents.length,
2698
- sourceFiles: {
2699
- session: maybeRedactPathString(params.sessionFile, redaction),
2700
- runtime: runtimeFile && isRegularNonSymlinkFile(runtimeFile) ? maybeRedactPathString(runtimeFile, redaction) : void 0
2701
- }
2702
- };
2703
- const bundleRuntimeContext = resolveRuntimeContext(runtimeEvents);
2704
- const files = [];
2705
- const supplementalFiles = [];
2706
- const metadataCapture = buildMetadataCapture({
2707
- manifest,
2708
- runtimeEvents,
2709
- events: rawEvents
2710
- });
2711
- const artifactsCapture = buildArtifactsCapture({
2712
- manifest,
2713
- runtimeEvents
2714
- });
2715
- const promptsCapture = buildPromptsCapture({
2716
- manifest,
2717
- runtimeEvents,
2718
- runtimeContext: bundleRuntimeContext
2719
- });
2720
- if (metadataCapture) {
2721
- files.push(jsonSupportBundleFile("metadata.json", redactLocalPathValues(metadataCapture, redaction)));
2722
- supplementalFiles.push("metadata.json");
2723
- }
2724
- if (artifactsCapture) {
2725
- files.push(jsonSupportBundleFile("artifacts.json", redactLocalPathValues(artifactsCapture, redaction)));
2726
- supplementalFiles.push("artifacts.json");
2727
- }
2728
- if (promptsCapture) {
2729
- files.push(jsonSupportBundleFile("prompts.json", redactLocalPathValues(promptsCapture, redaction)));
2730
- supplementalFiles.push("prompts.json");
2731
- }
2732
- if (supplementalFiles.length > 0) manifest.supplementalFiles = supplementalFiles;
2733
- files.push(trajectoryJsonlFile("events.jsonl", events));
2734
- files.push(jsonSupportBundleFile("session-branch.json", redactLocalPathValues(sanitizeDiagnosticPayload({
2735
- header,
2736
- leafId,
2737
- entries: branchEntries
2738
- }), redaction)));
2739
- if (bundleRuntimeContext.systemPrompt) files.push(textSupportBundleFile("system-prompt.txt", redactLocalPathValues(bundleRuntimeContext.systemPrompt, redaction)));
2740
- if (bundleRuntimeContext.tools) files.push(jsonSupportBundleFile("tools.json", redactLocalPathValues(bundleRuntimeContext.tools, redaction)));
2741
- manifest.contents = [...supportBundleContents(files)];
2742
- writeSupportBundleDirectory({
2743
- outputDir: params.outputDir,
2744
- files: [jsonSupportBundleFile("manifest.json", manifest), ...files]
2745
- });
2746
- return {
2747
- manifest,
2748
- outputDir: params.outputDir,
2749
- events,
2750
- header,
2751
- runtimeFile: runtimeFile && isRegularNonSymlinkFile(runtimeFile) ? runtimeFile : void 0,
2752
- supplementalFiles
2753
- };
2754
- }
2755
- //#endregion
2756
- //#region src/auto-reply/reply/commands-export-trajectory.ts
2757
- function isPathInsideOrEqual(baseDir, candidate) {
2758
- const relative = path.relative(baseDir, candidate);
2759
- return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
2760
- }
2761
- function validateExistingExportDirectory(params) {
2762
- const linkStat = fs.lstatSync(params.dir);
2763
- if (linkStat.isSymbolicLink() || !linkStat.isDirectory()) throw new Error(`${params.label} must be a real directory inside the workspace`);
2764
- const realDir = fs.realpathSync(params.dir);
2765
- if (!isPathInsideOrEqual(params.realWorkspace, realDir)) throw new Error("Trajectory exports directory must stay inside the workspace");
2766
- return realDir;
2767
- }
2768
- function mkdirIfMissingThenValidate(params) {
2769
- if (!fs.existsSync(params.dir)) try {
2770
- fs.mkdirSync(params.dir, { mode: 448 });
2771
- } catch (error) {
2772
- if (error.code !== "EEXIST") throw error;
2773
- }
2774
- return validateExistingExportDirectory(params);
2775
- }
2776
- function resolveTrajectoryExportBaseDir(workspaceDir) {
2777
- const workspacePath = path.resolve(workspaceDir);
2778
- const realWorkspace = fs.realpathSync(workspacePath);
2779
- const stateDir = path.join(workspacePath, ".genesis");
2780
- mkdirIfMissingThenValidate({
2781
- dir: stateDir,
2782
- label: "Genesis state directory",
2783
- realWorkspace
2784
- });
2785
- const baseDir = path.join(stateDir, "trajectory-exports");
2786
- const realBase = mkdirIfMissingThenValidate({
2787
- dir: baseDir,
2788
- label: "Trajectory exports directory",
2789
- realWorkspace
2790
- });
2791
- return {
2792
- baseDir: path.resolve(baseDir),
2793
- realBase
2794
- };
2795
- }
2796
- function resolveTrajectoryCommandOutputDir(params) {
2797
- const { baseDir, realBase } = resolveTrajectoryExportBaseDir(params.workspaceDir);
2798
- const raw = params.outputPath?.trim();
2799
- if (!raw) {
2800
- const defaultDir = resolveDefaultTrajectoryExportDir({
2801
- workspaceDir: params.workspaceDir,
2802
- sessionId: params.sessionId
2803
- });
2804
- return path.join(baseDir, path.basename(defaultDir));
2805
- }
2806
- if (path.isAbsolute(raw) || raw.startsWith("~")) throw new Error("Output path must be relative to the workspace trajectory exports directory");
2807
- const resolvedBase = path.resolve(baseDir);
2808
- const outputDir = path.resolve(resolvedBase, raw);
2809
- const relative = path.relative(resolvedBase, outputDir);
2810
- if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("Output path must stay inside the workspace trajectory exports directory");
2811
- let existingParent = outputDir;
2812
- while (!fs.existsSync(existingParent)) {
2813
- const next = path.dirname(existingParent);
2814
- if (next === existingParent) break;
2815
- existingParent = next;
2816
- }
2817
- if (!isPathInsideOrEqual(realBase, fs.realpathSync(existingParent))) throw new Error("Output path must stay inside the real trajectory exports directory");
2818
- return outputDir;
2819
- }
2820
- async function buildExportTrajectoryReply(params) {
2821
- const args = parseExportCommandOutputPath(params.command.commandBodyNormalized, ["export-trajectory", "trajectory"]);
2822
- const sessionTarget = resolveExportCommandSessionTarget(params);
2823
- if (isReplyPayload(sessionTarget)) return sessionTarget;
2824
- const { entry, sessionFile } = sessionTarget;
2825
- if (!fs.existsSync(sessionFile)) return { text: "āŒ Session file not found." };
2826
- let outputDir;
2827
- try {
2828
- outputDir = resolveTrajectoryCommandOutputDir({
2829
- outputPath: args.outputPath,
2830
- workspaceDir: params.workspaceDir,
2831
- sessionId: entry.sessionId
2832
- });
2833
- } catch (err) {
2834
- return { text: `āŒ Failed to resolve output path: ${formatErrorMessage(err)}` };
2835
- }
2836
- let bundle;
2837
- try {
2838
- bundle = exportTrajectoryBundle({
2839
- outputDir,
2840
- sessionFile,
2841
- sessionId: entry.sessionId,
2842
- sessionKey: params.sessionKey,
2843
- workspaceDir: params.workspaceDir
2844
- });
2845
- } catch (err) {
2846
- return { text: `āŒ Failed to export trajectory: ${formatErrorMessage(err)}` };
2847
- }
2848
- const relativePath = path.relative(params.workspaceDir, bundle.outputDir);
2849
- const displayPath = relativePath && !relativePath.startsWith("..") && !path.isAbsolute(relativePath) ? relativePath : path.basename(bundle.outputDir);
2850
- const files = [
2851
- "manifest.json",
2852
- "events.jsonl",
2853
- "session-branch.json"
2854
- ];
2855
- if (bundle.events.some((event) => event.type === "context.compiled")) files.push("system-prompt.txt", "tools.json");
2856
- files.push(...bundle.supplementalFiles);
2857
- return { text: [
2858
- "āœ… Trajectory exported!",
2859
- "",
2860
- `šŸ“¦ Bundle: ${displayPath}`,
2861
- `🧵 Session: ${entry.sessionId}`,
2862
- `šŸ“Š Events: ${bundle.manifest.eventCount}`,
2863
- `🧪 Runtime events: ${bundle.manifest.runtimeEventCount}`,
2864
- `šŸ“ Transcript events: ${bundle.manifest.transcriptEventCount}`,
2865
- `šŸ“ Files: ${files.join(", ")}`
2866
- ].join("\n") };
2867
- }
2868
- //#endregion
2869
- //#region src/auto-reply/reply/commands-whoami.ts
2870
- const handleWhoamiCommand = async (params, allowTextCommands) => {
2871
- if (!allowTextCommands) return null;
2872
- if (params.command.commandBodyNormalized !== "/whoami") return null;
2873
- if (!params.command.isAuthorizedSender) {
2874
- logVerbose(`Ignoring /whoami from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2875
- return { shouldContinue: false };
2876
- }
2877
- const senderId = params.ctx.SenderId ?? "";
2878
- const senderUsername = params.ctx.SenderUsername ?? "";
2879
- const lines = ["🧭 Identity", `Channel: ${params.command.channel}`];
2880
- if (senderId) lines.push(`User id: ${senderId}`);
2881
- if (senderUsername) {
2882
- const handle = senderUsername.startsWith("@") ? senderUsername : `@${senderUsername}`;
2883
- lines.push(`Username: ${handle}`);
2884
- }
2885
- if (params.ctx.ChatType === "group" && params.ctx.From) lines.push(`Chat: ${params.ctx.From}`);
2886
- if (params.ctx.MessageThreadId != null) lines.push(`Thread: ${params.ctx.MessageThreadId}`);
2887
- const allowFromSender = params.command.senderId ?? "";
2888
- if (allowFromSender) lines.push(`AllowFrom: ${allowFromSender}`);
2889
- return {
2890
- shouldContinue: false,
2891
- reply: { text: lines.join("\n") }
2892
- };
2893
- };
2894
- //#endregion
2895
- //#region src/auto-reply/reply/commands-info.ts
2896
- const handleHelpCommand = async (params, allowTextCommands) => {
2897
- if (!allowTextCommands) return null;
2898
- if (params.command.commandBodyNormalized !== "/help") return null;
2899
- if (!params.command.isAuthorizedSender) {
2900
- logVerbose(`Ignoring /help from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2901
- return { shouldContinue: false };
2902
- }
2903
- return {
2904
- shouldContinue: false,
2905
- reply: { text: buildHelpMessage(params.cfg) }
2906
- };
2907
- };
2908
- const handleCommandsListCommand = async (params, allowTextCommands) => {
2909
- if (!allowTextCommands) return null;
2910
- if (params.command.commandBodyNormalized !== "/commands") return null;
2911
- if (!params.command.isAuthorizedSender) {
2912
- logVerbose(`Ignoring /commands from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2913
- return { shouldContinue: false };
2914
- }
2915
- const agentId = params.sessionKey ? resolveSessionAgentId({
2916
- sessionKey: params.sessionKey,
2917
- config: params.cfg
2918
- }) : params.agentId;
2919
- const skillCommands = params.skillCommands ?? listSkillCommandsForAgents({
2920
- cfg: params.cfg,
2921
- agentIds: agentId ? [agentId] : void 0
2922
- });
2923
- const surface = params.ctx.Surface;
2924
- const commandPlugin = surface ? getChannelPlugin(surface) : null;
2925
- const paginated = buildCommandsMessagePaginated(params.cfg, skillCommands, {
2926
- page: 1,
2927
- surface
2928
- });
2929
- const channelData = commandPlugin?.commands?.buildCommandsListChannelData?.({
2930
- currentPage: paginated.currentPage,
2931
- totalPages: paginated.totalPages,
2932
- agentId
2933
- });
2934
- if (channelData) return {
2935
- shouldContinue: false,
2936
- reply: {
2937
- text: paginated.text,
2938
- channelData
2939
- }
2940
- };
2941
- return {
2942
- shouldContinue: false,
2943
- reply: { text: buildCommandsMessage(params.cfg, skillCommands, { surface }) }
2944
- };
2945
- };
2946
- const handleToolsCommand = async (params, allowTextCommands) => {
2947
- if (!allowTextCommands) return null;
2948
- const normalized = params.command.commandBodyNormalized;
2949
- let verbose = false;
2950
- if (normalized === "/tools" || normalized === "/tools compact") verbose = false;
2951
- else if (normalized === "/tools verbose") verbose = true;
2952
- else if (normalized.startsWith("/tools ")) return {
2953
- shouldContinue: false,
2954
- reply: { text: "Usage: /tools [compact|verbose]" }
2955
- };
2956
- else return null;
2957
- if (!params.command.isAuthorizedSender) {
2958
- logVerbose(`Ignoring /tools from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2959
- return { shouldContinue: false };
2960
- }
2961
- try {
2962
- const effectiveAccountId = resolveChannelAccountId({
2963
- cfg: params.cfg,
2964
- ctx: params.ctx,
2965
- command: params.command
2966
- });
2967
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
2968
- const sessionBound = Boolean(params.sessionKey);
2969
- const agentId = sessionBound ? resolveSessionAgentId({
2970
- sessionKey: params.sessionKey,
2971
- config: params.cfg
2972
- }) : params.agentId;
2973
- const threadingContext = buildThreadingToolContext({
2974
- sessionCtx: params.ctx,
2975
- config: params.cfg,
2976
- hasRepliedRef: void 0
2977
- });
2978
- return {
2979
- shouldContinue: false,
2980
- reply: { text: buildToolsMessage(resolveEffectiveToolInventory({
2981
- cfg: params.cfg,
2982
- agentId,
2983
- sessionKey: params.sessionKey,
2984
- workspaceDir: params.workspaceDir,
2985
- agentDir: sessionBound ? void 0 : params.agentDir,
2986
- modelProvider: params.provider,
2987
- modelId: params.model,
2988
- messageProvider: params.command.channel,
2989
- senderIsOwner: params.command.senderIsOwner,
2990
- senderId: params.command.senderId,
2991
- senderName: params.ctx.SenderName,
2992
- senderUsername: params.ctx.SenderUsername,
2993
- senderE164: params.ctx.SenderE164,
2994
- accountId: effectiveAccountId,
2995
- currentChannelId: threadingContext.currentChannelId,
2996
- currentThreadTs: typeof params.ctx.MessageThreadId === "string" || typeof params.ctx.MessageThreadId === "number" ? String(params.ctx.MessageThreadId) : void 0,
2997
- currentMessageId: threadingContext.currentMessageId,
2998
- groupId: targetSessionEntry?.groupId ?? extractExplicitGroupId(params.ctx.From),
2999
- groupChannel: targetSessionEntry?.groupChannel ?? params.ctx.GroupChannel ?? params.ctx.GroupSubject,
3000
- groupSpace: targetSessionEntry?.space ?? params.ctx.GroupSpace,
3001
- replyToMode: resolveReplyToMode(params.cfg, params.ctx.OriginatingChannel ?? params.ctx.Provider, effectiveAccountId, params.ctx.ChatType)
3002
- }), { verbose }) }
3003
- };
3004
- } catch (err) {
3005
- return {
3006
- shouldContinue: false,
3007
- reply: { text: String(err).includes("missing scope:") ? "You do not have permission to view available tools." : "Couldn't load available tools right now. Try again in a moment." }
3008
- };
3009
- }
3010
- };
3011
- const handleStatusCommand = async (params, allowTextCommands) => {
3012
- if (!allowTextCommands) return null;
3013
- if (!(params.directives.hasStatusDirective || params.command.commandBodyNormalized === "/status")) return null;
3014
- if (!params.command.isAuthorizedSender) {
3015
- logVerbose(`Ignoring /status from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3016
- return { shouldContinue: false };
3017
- }
3018
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3019
- return {
3020
- shouldContinue: false,
3021
- reply: await buildStatusReply({
3022
- cfg: params.cfg,
3023
- command: params.command,
3024
- sessionEntry: targetSessionEntry,
3025
- sessionKey: params.sessionKey,
3026
- parentSessionKey: targetSessionEntry?.parentSessionKey ?? params.ctx.ParentSessionKey,
3027
- sessionScope: params.sessionScope,
3028
- storePath: params.storePath,
3029
- provider: params.provider,
3030
- model: params.model,
3031
- contextTokens: params.contextTokens,
3032
- resolvedThinkLevel: params.resolvedThinkLevel,
3033
- resolvedFastMode: params.resolvedFastMode,
3034
- resolvedVerboseLevel: params.resolvedVerboseLevel,
3035
- resolvedReasoningLevel: params.resolvedReasoningLevel,
3036
- resolvedElevatedLevel: params.resolvedElevatedLevel,
3037
- resolveDefaultThinkingLevel: params.resolveDefaultThinkingLevel,
3038
- isGroup: params.isGroup,
3039
- defaultGroupActivation: params.defaultGroupActivation,
3040
- mediaDecisions: params.ctx.MediaUnderstandingDecisions
3041
- })
3042
- };
3043
- };
3044
- const handleExportSessionCommand = async (params, allowTextCommands) => {
3045
- if (!allowTextCommands) return null;
3046
- const normalized = params.command.commandBodyNormalized;
3047
- if (normalized !== "/export-session" && !normalized.startsWith("/export-session ") && normalized !== "/export" && !normalized.startsWith("/export ")) return null;
3048
- if (!params.command.isAuthorizedSender) {
3049
- logVerbose(`Ignoring /export-session from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3050
- return { shouldContinue: false };
3051
- }
3052
- return {
3053
- shouldContinue: false,
3054
- reply: await buildExportSessionReply(params)
3055
- };
3056
- };
3057
- const handleExportTrajectoryCommand = async (params, allowTextCommands) => {
3058
- if (!allowTextCommands) return null;
3059
- const normalized = params.command.commandBodyNormalized;
3060
- if (normalized !== "/export-trajectory" && !normalized.startsWith("/export-trajectory ") && normalized !== "/trajectory" && !normalized.startsWith("/trajectory ")) return null;
3061
- const unauthorized = rejectUnauthorizedCommand(params, "/export-trajectory");
3062
- if (unauthorized) return unauthorized;
3063
- const nonOwner = rejectNonOwnerCommand(params, "/export-trajectory");
3064
- if (nonOwner) return nonOwner;
3065
- return {
3066
- shouldContinue: false,
3067
- reply: await buildExportTrajectoryReply(params)
3068
- };
3069
- };
3070
- //#endregion
3071
- //#region src/auto-reply/reply/mcp-commands.ts
3072
- function parseMcpCommand(raw) {
3073
- return parseStandardSetUnsetSlashCommand({
3074
- raw,
3075
- slash: "/mcp",
3076
- invalidMessage: "Invalid /mcp syntax.",
3077
- usageMessage: "Usage: /mcp show|set|unset",
3078
- onKnownAction: (action, args) => {
3079
- if (action === "show" || action === "get") return {
3080
- action: "show",
3081
- name: args || void 0
3082
- };
3083
- },
3084
- onSet: (name, value) => ({
3085
- action: "set",
3086
- name,
3087
- value
3088
- }),
3089
- onUnset: (name) => ({
3090
- action: "unset",
3091
- name
3092
- })
3093
- });
3094
- }
3095
- //#endregion
3096
- //#region src/auto-reply/reply/commands-mcp.ts
3097
- function renderJsonBlock$1(label, value) {
3098
- return `${label}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
3099
- }
3100
- const handleMcpCommand = async (params, allowTextCommands) => {
3101
- if (!allowTextCommands) return null;
3102
- const mcpCommand = parseMcpCommand(params.command.commandBodyNormalized);
3103
- if (!mcpCommand) return null;
3104
- const unauthorized = rejectUnauthorizedCommand(params, "/mcp");
3105
- if (unauthorized) return unauthorized;
3106
- const nonOwner = mcpCommand.action === "show" && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/mcp");
3107
- if (nonOwner) return nonOwner;
3108
- const disabled = requireCommandFlagEnabled(params.cfg, {
3109
- label: "/mcp",
3110
- configKey: "mcp"
3111
- });
3112
- if (disabled) return disabled;
3113
- if (mcpCommand.action === "error") return {
3114
- shouldContinue: false,
3115
- reply: { text: `āš ļø ${mcpCommand.message}` }
3116
- };
3117
- if (mcpCommand.action === "show") {
3118
- const loaded = await listConfiguredMcpServers();
3119
- if (!loaded.ok) return {
3120
- shouldContinue: false,
3121
- reply: { text: `āš ļø ${loaded.error}` }
3122
- };
3123
- if (mcpCommand.name) {
3124
- const server = loaded.mcpServers[mcpCommand.name];
3125
- if (!server) return {
3126
- shouldContinue: false,
3127
- reply: { text: `šŸ”Œ No MCP server named "${mcpCommand.name}" in ${loaded.path}.` }
3128
- };
3129
- return {
3130
- shouldContinue: false,
3131
- reply: { text: renderJsonBlock$1(`šŸ”Œ MCP server "${mcpCommand.name}" (${loaded.path})`, server) }
3132
- };
3133
- }
3134
- if (Object.keys(loaded.mcpServers).length === 0) return {
3135
- shouldContinue: false,
3136
- reply: { text: `šŸ”Œ No MCP servers configured in ${loaded.path}.` }
3137
- };
3138
- return {
3139
- shouldContinue: false,
3140
- reply: { text: renderJsonBlock$1(`šŸ”Œ MCP servers (${loaded.path})`, loaded.mcpServers) }
3141
- };
3142
- }
3143
- const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
3144
- label: "/mcp write",
3145
- allowedScopes: ["operator.admin"],
3146
- missingText: "āŒ /mcp set|unset requires operator.admin for gateway clients."
3147
- });
3148
- if (missingAdminScope) return missingAdminScope;
3149
- if (mcpCommand.action === "set") {
3150
- const result = await setConfiguredMcpServer({
3151
- name: mcpCommand.name,
3152
- server: mcpCommand.value
3153
- });
3154
- if (!result.ok) return {
3155
- shouldContinue: false,
3156
- reply: { text: `āš ļø ${result.error}` }
3157
- };
3158
- return {
3159
- shouldContinue: false,
3160
- reply: { text: `šŸ”Œ MCP server "${mcpCommand.name}" saved to ${result.path}.` }
3161
- };
3162
- }
3163
- const result = await unsetConfiguredMcpServer({ name: mcpCommand.name });
3164
- if (!result.ok) return {
3165
- shouldContinue: false,
3166
- reply: { text: `āš ļø ${result.error}` }
3167
- };
3168
- if (!result.removed) return {
3169
- shouldContinue: false,
3170
- reply: { text: `šŸ”Œ No MCP server named "${mcpCommand.name}" in ${result.path}.` }
3171
- };
3172
- return {
3173
- shouldContinue: false,
3174
- reply: { text: `šŸ”Œ MCP server "${mcpCommand.name}" removed from ${result.path}.` }
3175
- };
3176
- };
3177
- //#endregion
3178
- //#region src/auto-reply/reply/commands-plugin.ts
3179
- /**
3180
- * Plugin Command Handler
3181
- *
3182
- * Handles commands registered by plugins, bypassing the LLM agent.
3183
- * This handler is called before built-in command handlers.
3184
- */
3185
- /**
3186
- * Handle plugin-registered commands.
3187
- * Returns a result if a plugin command was matched and executed,
3188
- * or null to continue to the next handler.
3189
- */
3190
- const handlePluginCommand = async (params, allowTextCommands) => {
3191
- const { command, cfg } = params;
3192
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3193
- if (!allowTextCommands) return null;
3194
- const match = matchPluginCommand(command.commandBodyNormalized);
3195
- if (!match) return null;
3196
- return {
3197
- shouldContinue: false,
3198
- reply: await executePluginCommand({
3199
- command: match.command,
3200
- args: match.args,
3201
- senderId: command.senderId,
3202
- channel: command.channel,
3203
- channelId: command.channelId,
3204
- isAuthorizedSender: command.isAuthorizedSender,
3205
- gatewayClientScopes: params.ctx.GatewayClientScopes,
3206
- sessionKey: params.sessionKey,
3207
- sessionId: targetSessionEntry?.sessionId,
3208
- sessionFile: targetSessionEntry?.sessionFile,
3209
- commandBody: command.commandBodyNormalized,
3210
- config: cfg,
3211
- from: command.from,
3212
- to: command.to,
3213
- accountId: params.ctx.AccountId ?? void 0,
3214
- messageThreadId: typeof params.ctx.MessageThreadId === "string" || typeof params.ctx.MessageThreadId === "number" ? params.ctx.MessageThreadId : void 0,
3215
- threadParentId: normalizeOptionalString(params.ctx.ThreadParentId)
3216
- })
3217
- };
3218
- };
3219
- //#endregion
3220
- //#region src/auto-reply/reply/plugins-commands.ts
3221
- function parsePluginsCommand(raw) {
3222
- const match = raw.match(/^\/plugins?(?:\s+(.*))?$/i);
3223
- if (!match) return null;
3224
- const tail = normalizeOptionalString(match?.[1]) ?? "";
3225
- if (!tail) return { action: "list" };
3226
- const [rawAction, ...rest] = tail.split(/\s+/);
3227
- const action = normalizeOptionalLowercaseString(rawAction);
3228
- const name = rest.join(" ").trim();
3229
- if (action === "list") return name ? {
3230
- action: "error",
3231
- message: "Usage: /plugins list|inspect|show|get|enable|disable [plugin]"
3232
- } : { action: "list" };
3233
- if (action === "inspect" || action === "show" || action === "get") return {
3234
- action: "inspect",
3235
- name: name || void 0
3236
- };
3237
- if (action === "install" || action === "add") {
3238
- if (!name) return {
3239
- action: "error",
3240
- message: "Usage: /plugins install <path|archive|npm-spec|clawhub:pkg>"
3241
- };
3242
- return {
3243
- action: "install",
3244
- spec: name
3245
- };
3246
- }
3247
- if (action === "enable" || action === "disable") {
3248
- if (!name) return {
3249
- action: "error",
3250
- message: `Usage: /plugins ${action} <plugin-id-or-name>`
3251
- };
3252
- return {
3253
- action,
3254
- name
3255
- };
3256
- }
3257
- return {
3258
- action: "error",
3259
- message: "Usage: /plugins list|inspect|show|get|install|enable|disable [plugin]"
3260
- };
3261
- }
3262
- //#endregion
3263
- //#region src/auto-reply/reply/commands-plugins.ts
3264
- function renderJsonBlock(label, value) {
3265
- return `${label}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
3266
- }
3267
- function buildPluginInspectJson(params) {
3268
- const inspect = buildPluginInspectReport({
3269
- id: params.id,
3270
- config: params.config,
3271
- report: params.report
3272
- });
3273
- if (!inspect) return null;
3274
- return {
3275
- inspect,
3276
- compatibilityWarnings: inspect.compatibility.map((warning) => ({
3277
- code: warning.code,
3278
- severity: warning.severity,
3279
- message: formatPluginCompatibilityNotice(warning)
3280
- })),
3281
- install: params.config.plugins?.installs?.[inspect.plugin.id] ?? null
3282
- };
3283
- }
3284
- function buildAllPluginInspectJson(params) {
3285
- return buildAllPluginInspectReports({
3286
- config: params.config,
3287
- report: params.report
3288
- }).map((inspect) => ({
3289
- inspect,
3290
- compatibilityWarnings: inspect.compatibility.map((warning) => ({
3291
- code: warning.code,
3292
- severity: warning.severity,
3293
- message: formatPluginCompatibilityNotice(warning)
3294
- })),
3295
- install: params.config.plugins?.installs?.[inspect.plugin.id] ?? null
3296
- }));
3297
- }
3298
- function formatPluginLabel(plugin) {
3299
- if (!plugin.name || plugin.name === plugin.id) return plugin.id;
3300
- return `${plugin.name} (${plugin.id})`;
3301
- }
3302
- function formatPluginsList(report) {
3303
- if (report.plugins.length === 0) return `šŸ”Œ No plugins found for workspace ${report.workspaceDir ?? "(unknown workspace)"}.`;
3304
- return [`šŸ”Œ Plugins (${report.plugins.filter((plugin) => plugin.status === "loaded").length}/${report.plugins.length} loaded)`, ...report.plugins.map((plugin) => {
3305
- const format = plugin.bundleFormat ? `${plugin.format ?? "genesis"}/${plugin.bundleFormat}` : plugin.format ?? "genesis";
3306
- return `- ${formatPluginLabel(plugin)} [${plugin.status}] ${format}`;
3307
- })].join("\n");
3308
- }
3309
- function findPlugin(report, rawName) {
3310
- const target = normalizeOptionalLowercaseString(rawName);
3311
- if (!target) return;
3312
- return report.plugins.find((plugin) => normalizeOptionalLowercaseString(plugin.id) === target || normalizeOptionalLowercaseString(plugin.name) === target);
3313
- }
3314
- function looksLikeLocalPluginInstallSpec(raw) {
3315
- return raw.startsWith(".") || raw.startsWith("~") || raw.startsWith("/") || raw.endsWith(".ts") || raw.endsWith(".js") || raw.endsWith(".mjs") || raw.endsWith(".cjs") || raw.endsWith(".tgz") || raw.endsWith(".tar.gz") || raw.endsWith(".tar") || raw.endsWith(".zip");
3316
- }
3317
- async function installPluginFromPluginsCommand(params) {
3318
- const fileSpec = resolveFileNpmSpecToLocalPath(params.raw);
3319
- if (fileSpec && !fileSpec.ok) return {
3320
- ok: false,
3321
- error: fileSpec.error
3322
- };
3323
- const resolved = resolveUserPath(fileSpec && fileSpec.ok ? fileSpec.path : params.raw);
3324
- if (fs.existsSync(resolved)) {
3325
- const result = await installPluginFromPath({
3326
- path: resolved,
3327
- logger: createPluginInstallLogger()
3328
- });
3329
- if (!result.ok) return {
3330
- ok: false,
3331
- error: result.error
3332
- };
3333
- clearPluginManifestRegistryCache();
3334
- const source = resolveArchiveKind(resolved) ? "archive" : "path";
3335
- await persistPluginInstall({
3336
- config: params.config,
3337
- pluginId: result.pluginId,
3338
- install: {
3339
- source,
3340
- sourcePath: resolved,
3341
- installPath: result.targetDir,
3342
- version: result.version
3343
- }
3344
- });
3345
- return {
3346
- ok: true,
3347
- pluginId: result.pluginId
3348
- };
3349
- }
3350
- if (looksLikeLocalPluginInstallSpec(params.raw)) return {
3351
- ok: false,
3352
- error: `Path not found: ${resolved}`
3353
- };
3354
- if (parseClawHubPluginSpec(params.raw)) {
3355
- const result = await installPluginFromClawHub({
3356
- spec: params.raw,
3357
- logger: createPluginInstallLogger()
3358
- });
3359
- if (!result.ok) return {
3360
- ok: false,
3361
- error: result.error
3362
- };
3363
- clearPluginManifestRegistryCache();
3364
- await persistPluginInstall({
3365
- config: params.config,
3366
- pluginId: result.pluginId,
3367
- install: {
3368
- source: "clawhub",
3369
- spec: params.raw,
3370
- installPath: result.targetDir,
3371
- version: result.version,
3372
- integrity: result.clawhub.integrity,
3373
- resolvedAt: result.clawhub.resolvedAt,
3374
- clawhubUrl: result.clawhub.clawhubUrl,
3375
- clawhubPackage: result.clawhub.clawhubPackage,
3376
- clawhubFamily: result.clawhub.clawhubFamily,
3377
- clawhubChannel: result.clawhub.clawhubChannel
3378
- }
3379
- });
3380
- return {
3381
- ok: true,
3382
- pluginId: result.pluginId
3383
- };
3384
- }
3385
- const preferredClawHubSpec = buildPreferredClawHubSpec(params.raw);
3386
- if (preferredClawHubSpec) {
3387
- const clawhubResult = await installPluginFromClawHub({
3388
- spec: preferredClawHubSpec,
3389
- logger: createPluginInstallLogger()
3390
- });
3391
- if (clawhubResult.ok) {
3392
- clearPluginManifestRegistryCache();
3393
- await persistPluginInstall({
3394
- config: params.config,
3395
- pluginId: clawhubResult.pluginId,
3396
- install: {
3397
- source: "clawhub",
3398
- spec: preferredClawHubSpec,
3399
- installPath: clawhubResult.targetDir,
3400
- version: clawhubResult.version,
3401
- integrity: clawhubResult.clawhub.integrity,
3402
- resolvedAt: clawhubResult.clawhub.resolvedAt,
3403
- clawhubUrl: clawhubResult.clawhub.clawhubUrl,
3404
- clawhubPackage: clawhubResult.clawhub.clawhubPackage,
3405
- clawhubFamily: clawhubResult.clawhub.clawhubFamily,
3406
- clawhubChannel: clawhubResult.clawhub.clawhubChannel
3407
- }
3408
- });
3409
- return {
3410
- ok: true,
3411
- pluginId: clawhubResult.pluginId
3412
- };
3413
- }
3414
- if (decidePreferredClawHubFallback(clawhubResult) !== "fallback_to_npm") return {
3415
- ok: false,
3416
- error: clawhubResult.error
3417
- };
3418
- }
3419
- const result = await installPluginFromNpmSpec({
3420
- spec: params.raw,
3421
- logger: createPluginInstallLogger()
3422
- });
3423
- if (!result.ok) return {
3424
- ok: false,
3425
- error: result.error
3426
- };
3427
- clearPluginManifestRegistryCache();
3428
- const installRecord = buildNpmInstallRecordFields({
3429
- spec: params.raw,
3430
- installPath: result.targetDir,
3431
- version: result.version,
3432
- resolution: result.npmResolution
3433
- });
3434
- await persistPluginInstall({
3435
- config: params.config,
3436
- pluginId: result.pluginId,
3437
- install: installRecord
3438
- });
3439
- return {
3440
- ok: true,
3441
- pluginId: result.pluginId
3442
- };
3443
- }
3444
- async function loadPluginCommandState(workspaceDir, options) {
3445
- const snapshot = await readConfigFileSnapshot();
3446
- if (!snapshot.valid) return {
3447
- ok: false,
3448
- path: snapshot.path,
3449
- error: "Config file is invalid; fix it before using /plugins."
3450
- };
3451
- const config = structuredClone(snapshot.resolved);
3452
- return {
3453
- ok: true,
3454
- path: snapshot.path,
3455
- config,
3456
- report: options?.loadModules === true ? buildPluginDiagnosticsReport({
3457
- config,
3458
- workspaceDir
3459
- }) : buildPluginSnapshotReport({
3460
- config,
3461
- workspaceDir
3462
- })
3463
- };
3464
- }
3465
- async function loadPluginCommandConfig() {
3466
- const snapshot = await readConfigFileSnapshot();
3467
- if (!snapshot.valid) return {
3468
- ok: false,
3469
- path: snapshot.path,
3470
- error: "Config file is invalid; fix it before using /plugins."
3471
- };
3472
- return {
3473
- ok: true,
3474
- path: snapshot.path,
3475
- config: structuredClone(snapshot.resolved)
3476
- };
3477
- }
3478
- const handlePluginsCommand = async (params, allowTextCommands) => {
3479
- if (!allowTextCommands) return null;
3480
- const pluginsCommand = parsePluginsCommand(params.command.commandBodyNormalized);
3481
- if (!pluginsCommand) return null;
3482
- const unauthorized = rejectUnauthorizedCommand(params, "/plugins");
3483
- if (unauthorized) return unauthorized;
3484
- const nonOwner = (pluginsCommand.action === "list" || pluginsCommand.action === "inspect") && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/plugins");
3485
- if (nonOwner) return nonOwner;
3486
- const disabled = requireCommandFlagEnabled(params.cfg, {
3487
- label: "/plugins",
3488
- configKey: "plugins"
3489
- });
3490
- if (disabled) return disabled;
3491
- if (pluginsCommand.action === "error") return {
3492
- shouldContinue: false,
3493
- reply: { text: `āš ļø ${pluginsCommand.message}` }
3494
- };
3495
- const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
3496
- label: "/plugins write",
3497
- allowedScopes: ["operator.admin"],
3498
- missingText: "āŒ /plugins install|enable|disable requires operator.admin for gateway clients."
3499
- });
3500
- if (missingAdminScope) return missingAdminScope;
3501
- if (pluginsCommand.action === "install") {
3502
- const loadedConfig = await loadPluginCommandConfig();
3503
- if (!loadedConfig.ok) return {
3504
- shouldContinue: false,
3505
- reply: { text: `āš ļø ${loadedConfig.error}` }
3506
- };
3507
- const installed = await installPluginFromPluginsCommand({
3508
- raw: pluginsCommand.spec,
3509
- config: loadedConfig.config
3510
- });
3511
- if (!installed.ok) return {
3512
- shouldContinue: false,
3513
- reply: { text: `āš ļø ${installed.error}` }
3514
- };
3515
- return {
3516
- shouldContinue: false,
3517
- reply: { text: `šŸ”Œ Installed plugin "${installed.pluginId}". Restart the gateway to load plugins.` }
3518
- };
3519
- }
3520
- const loaded = await loadPluginCommandState(params.workspaceDir, { loadModules: pluginsCommand.action !== "list" });
3521
- if (!loaded.ok) return {
3522
- shouldContinue: false,
3523
- reply: { text: `āš ļø ${loaded.error}` }
3524
- };
3525
- if (pluginsCommand.action === "list") return {
3526
- shouldContinue: false,
3527
- reply: { text: formatPluginsList(loaded.report) }
3528
- };
3529
- if (pluginsCommand.action === "inspect") {
3530
- if (!pluginsCommand.name) return {
3531
- shouldContinue: false,
3532
- reply: { text: formatPluginsList(loaded.report) }
3533
- };
3534
- if (normalizeOptionalLowercaseString(pluginsCommand.name) === "all") return {
3535
- shouldContinue: false,
3536
- reply: { text: renderJsonBlock("šŸ”Œ Plugins", buildAllPluginInspectJson(loaded)) }
3537
- };
3538
- const payload = buildPluginInspectJson({
3539
- id: pluginsCommand.name,
3540
- config: loaded.config,
3541
- report: loaded.report
3542
- });
3543
- if (!payload) return {
3544
- shouldContinue: false,
3545
- reply: { text: `šŸ”Œ No plugin named "${pluginsCommand.name}" found.` }
3546
- };
3547
- return {
3548
- shouldContinue: false,
3549
- reply: { text: renderJsonBlock(`šŸ”Œ Plugin "${payload.inspect.plugin.id}"`, {
3550
- ...payload.inspect,
3551
- compatibilityWarnings: payload.compatibilityWarnings,
3552
- install: payload.install
3553
- }) }
3554
- };
3555
- }
3556
- const plugin = findPlugin(loaded.report, pluginsCommand.name);
3557
- if (!plugin) return {
3558
- shouldContinue: false,
3559
- reply: { text: `šŸ”Œ No plugin named "${pluginsCommand.name}" found.` }
3560
- };
3561
- const validated = validateConfigObjectWithPlugins(setPluginEnabledInConfig(structuredClone(loaded.config), plugin.id, pluginsCommand.action === "enable"));
3562
- if (!validated.ok) {
3563
- const issue = validated.issues[0];
3564
- return {
3565
- shouldContinue: false,
3566
- reply: { text: `āš ļø Config invalid after /plugins ${pluginsCommand.action} (${issue.path}: ${issue.message}).` }
3567
- };
3568
- }
3569
- await writeConfigFile(validated.config);
3570
- return {
3571
- shouldContinue: false,
3572
- reply: { text: `šŸ”Œ Plugin "${plugin.id}" ${pluginsCommand.action}d in ${loaded.path}. Restart the gateway to apply.` }
3573
- };
3574
- };
3575
- //#endregion
3576
- //#region src/auto-reply/send-policy.ts
3577
- function normalizeSendPolicyOverride(raw) {
3578
- const value = normalizeOptionalLowercaseString(raw);
3579
- if (!value) return;
3580
- if (value === "allow" || value === "on") return "allow";
3581
- if (value === "deny" || value === "off") return "deny";
3582
- }
3583
- function parseSendPolicyCommand(raw) {
3584
- if (!raw) return { hasCommand: false };
3585
- const trimmed = raw.trim();
3586
- if (!trimmed) return { hasCommand: false };
3587
- const match = normalizeCommandBody(stripInboundMetadata(trimmed)).match(/^\/send(?:\s+([a-zA-Z]+))?\s*$/i);
3588
- if (!match) return { hasCommand: false };
3589
- const token = normalizeOptionalLowercaseString(match[1]);
3590
- if (!token) return { hasCommand: true };
3591
- if (token === "inherit" || token === "default" || token === "reset") return {
3592
- hasCommand: true,
3593
- mode: "inherit"
3594
- };
3595
- return {
3596
- hasCommand: true,
3597
- mode: normalizeSendPolicyOverride(token)
3598
- };
3599
- }
3600
- //#endregion
3601
- //#region src/auto-reply/reply/commands-session-store.ts
3602
- async function persistSessionEntry(params) {
3603
- if (!params.sessionEntry || !params.sessionStore || !params.sessionKey) return false;
3604
- params.sessionEntry.updatedAt = Date.now();
3605
- params.sessionStore[params.sessionKey] = params.sessionEntry;
3606
- if (params.storePath) await updateSessionStore(params.storePath, (store) => {
3607
- store[params.sessionKey] = params.sessionEntry;
3608
- });
3609
- return true;
3610
- }
3611
- async function persistAbortTargetEntry(params) {
3612
- const { entry, key, sessionStore, storePath, abortCutoff } = params;
3613
- if (!entry || !key || !sessionStore) return false;
3614
- entry.abortedLastRun = true;
3615
- applyAbortCutoffToSessionEntry(entry, abortCutoff);
3616
- entry.updatedAt = Date.now();
3617
- sessionStore[key] = entry;
3618
- if (storePath) await updateSessionStore(storePath, (store) => {
3619
- const nextEntry = store[key] ?? entry;
3620
- if (!nextEntry) return;
3621
- nextEntry.abortedLastRun = true;
3622
- applyAbortCutoffToSessionEntry(nextEntry, abortCutoff);
3623
- nextEntry.updatedAt = Date.now();
3624
- store[key] = nextEntry;
3625
- });
3626
- return true;
3627
- }
3628
- //#endregion
3629
- //#region src/auto-reply/reply/commands-session-abort.ts
3630
- async function abortEmbeddedPiRunForSession(sessionId) {
3631
- const { abortEmbeddedPiRun } = await import("./runs-DWOm31T_.js");
3632
- abortEmbeddedPiRun(sessionId);
3633
- }
3634
- function resolveAbortTarget(params) {
3635
- const targetSessionKey = normalizeOptionalString(params.ctx.CommandTargetSessionKey) || params.sessionKey;
3636
- const { entry, key } = resolveSessionEntryForKey(params.sessionStore, targetSessionKey);
3637
- if (entry && key) return {
3638
- entry,
3639
- key,
3640
- sessionId: replyRunRegistry.resolveSessionId(key) ?? entry.sessionId
3641
- };
3642
- if (params.sessionEntry && params.sessionKey && (!targetSessionKey || targetSessionKey === params.sessionKey)) return {
3643
- entry: params.sessionEntry,
3644
- key: params.sessionKey,
3645
- sessionId: replyRunRegistry.resolveSessionId(params.sessionKey) ?? params.sessionEntry.sessionId
3646
- };
3647
- return {
3648
- entry: void 0,
3649
- key: targetSessionKey,
3650
- sessionId: targetSessionKey ? replyRunRegistry.resolveSessionId(targetSessionKey) : void 0
3651
- };
3652
- }
3653
- function resolveAbortCutoffForTarget(params) {
3654
- if (!shouldPersistAbortCutoff({
3655
- commandSessionKey: params.commandSessionKey,
3656
- targetSessionKey: params.targetSessionKey
3657
- })) return;
3658
- return resolveAbortCutoffFromContext(params.ctx);
3659
- }
3660
- async function applyAbortTarget(params) {
3661
- const { abortTarget } = params;
3662
- if (abortTarget.key) replyRunRegistry.abort(abortTarget.key);
3663
- if (abortTarget.sessionId) await abortEmbeddedPiRunForSession(abortTarget.sessionId);
3664
- if (!await persistAbortTargetEntry({
3665
- entry: abortTarget.entry,
3666
- key: abortTarget.key,
3667
- sessionStore: params.sessionStore,
3668
- storePath: params.storePath,
3669
- abortCutoff: params.abortCutoff
3670
- }) && params.abortKey) setAbortMemory(params.abortKey, true);
3671
- }
3672
- function buildAbortTargetApplyParams(params, abortTarget) {
3673
- return {
3674
- abortTarget,
3675
- sessionStore: params.sessionStore,
3676
- storePath: params.storePath,
3677
- abortKey: params.command.abortKey,
3678
- abortCutoff: resolveAbortCutoffForTarget({
3679
- ctx: params.ctx,
3680
- commandSessionKey: params.sessionKey,
3681
- targetSessionKey: abortTarget.key
3682
- })
3683
- };
3684
- }
3685
- const handleStopCommand = async (params, allowTextCommands) => {
3686
- if (!allowTextCommands) return null;
3687
- if (params.command.commandBodyNormalized !== "/stop") return null;
3688
- const unauthorizedStop = rejectUnauthorizedCommand(params, "/stop");
3689
- if (unauthorizedStop) return unauthorizedStop;
3690
- const abortTarget = resolveAbortTarget({
3691
- ctx: params.ctx,
3692
- sessionKey: params.sessionKey,
3693
- sessionEntry: params.sessionEntry,
3694
- sessionStore: params.sessionStore
3695
- });
3696
- const cleared = clearSessionQueues([abortTarget.key, abortTarget.sessionId]);
3697
- if (cleared.followupCleared > 0 || cleared.laneCleared > 0) logVerbose(`stop: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`);
3698
- await applyAbortTarget(buildAbortTargetApplyParams(params, abortTarget));
3699
- await triggerInternalHook(createInternalHookEvent("command", "stop", abortTarget.key ?? params.sessionKey ?? "", {
3700
- sessionEntry: abortTarget.entry,
3701
- sessionId: abortTarget.sessionId,
3702
- commandSource: params.command.surface,
3703
- senderId: params.command.senderId
3704
- }));
3705
- const { stopped } = stopSubagentsForRequester({
3706
- cfg: params.cfg,
3707
- requesterSessionKey: abortTarget.key ?? params.sessionKey
3708
- });
3709
- return {
3710
- shouldContinue: false,
3711
- reply: { text: formatAbortReplyText(stopped) }
3712
- };
3713
- };
3714
- const handleAbortTrigger = async (params, allowTextCommands) => {
3715
- if (!allowTextCommands) return null;
3716
- if (!isAbortTrigger(params.command.rawBodyNormalized)) return null;
3717
- const unauthorizedAbortTrigger = rejectUnauthorizedCommand(params, "abort trigger");
3718
- if (unauthorizedAbortTrigger) return unauthorizedAbortTrigger;
3719
- await applyAbortTarget(buildAbortTargetApplyParams(params, resolveAbortTarget({
3720
- ctx: params.ctx,
3721
- sessionKey: params.sessionKey,
3722
- sessionEntry: params.sessionEntry,
3723
- sessionStore: params.sessionStore
3724
- })));
3725
- return {
3726
- shouldContinue: false,
3727
- reply: { text: "āš™ļø Agent was aborted." }
3728
- };
3729
- };
3730
- //#endregion
3731
- //#region src/auto-reply/reply/commands-session.ts
3732
- const SESSION_DURATION_OFF_VALUES = new Set([
3733
- "off",
3734
- "disable",
3735
- "disabled",
3736
- "none",
3737
- "0"
3738
- ]);
3739
- const SESSION_ACTION_IDLE = "idle";
3740
- const SESSION_ACTION_MAX_AGE = "max-age";
3741
- function buildRestartCommandSentinel(params) {
3742
- const sessionKey = normalizeOptionalString(params.sessionKey);
3743
- if (!sessionKey) return null;
3744
- const { deliveryContext, threadId } = extractDeliveryInfo(sessionKey);
3745
- return {
3746
- kind: "restart",
3747
- status: "ok",
3748
- ts: Date.now(),
3749
- sessionKey,
3750
- deliveryContext,
3751
- threadId,
3752
- message: "/restart",
3753
- continuation: buildRestartSuccessContinuation({ sessionKey }),
3754
- doctorHint: formatDoctorNonInteractiveHint(),
3755
- stats: {
3756
- mode: "gateway.restart",
3757
- reason: "/restart"
3758
- }
3759
- };
3760
- }
3761
- function resolveSessionCommandUsage() {
3762
- return "Usage: /session idle <duration|off> | /session max-age <duration|off> (example: /session idle 24h)";
3763
- }
3764
- function parseSessionDurationMs(raw) {
3765
- const normalized = normalizeOptionalLowercaseString(raw);
3766
- if (!normalized) throw new Error("missing duration");
3767
- if (SESSION_DURATION_OFF_VALUES.has(normalized)) return 0;
3768
- if (/^\d+(?:\.\d+)?$/.test(normalized)) {
3769
- const hours = Number(normalized);
3770
- if (!Number.isFinite(hours) || hours < 0) throw new Error("invalid duration");
3771
- return Math.round(hours * 60 * 60 * 1e3);
3772
- }
3773
- return parseDurationMs(normalized, { defaultUnit: "h" });
3774
- }
3775
- function formatSessionExpiry(expiresAt) {
3776
- return new Date(expiresAt).toISOString();
3777
- }
3778
- function resolveSessionBindingDurationMs(binding, key, fallbackMs) {
3779
- const raw = binding.metadata?.[key];
3780
- if (typeof raw !== "number" || !Number.isFinite(raw)) return fallbackMs;
3781
- return Math.max(0, Math.floor(raw));
3782
- }
3783
- function resolveSessionBindingLastActivityAt(binding) {
3784
- const raw = binding.metadata?.lastActivityAt;
3785
- if (typeof raw !== "number" || !Number.isFinite(raw)) return binding.boundAt;
3786
- return Math.max(Math.floor(raw), binding.boundAt);
3787
- }
3788
- function resolveSessionBindingBoundBy(binding) {
3789
- const raw = binding.metadata?.boundBy;
3790
- return normalizeOptionalString(raw) ?? "";
3791
- }
3792
- function isSessionBindingRecord(binding) {
3793
- return "bindingId" in binding;
3794
- }
3795
- function resolveUpdatedLifecycleDurationMs(binding, key) {
3796
- if (!isSessionBindingRecord(binding)) {
3797
- const raw = binding[key];
3798
- if (typeof raw === "number" && Number.isFinite(raw)) return Math.max(0, Math.floor(raw));
3799
- }
3800
- if (!isSessionBindingRecord(binding)) return;
3801
- const raw = binding.metadata?.[key];
3802
- if (typeof raw !== "number" || !Number.isFinite(raw)) return;
3803
- return Math.max(0, Math.floor(raw));
3804
- }
3805
- function toUpdatedLifecycleBinding(binding) {
3806
- const lastActivityAt = isSessionBindingRecord(binding) ? resolveSessionBindingLastActivityAt(binding) : Math.max(Math.floor(binding.lastActivityAt), binding.boundAt);
3807
- return {
3808
- boundAt: binding.boundAt,
3809
- lastActivityAt,
3810
- idleTimeoutMs: resolveUpdatedLifecycleDurationMs(binding, "idleTimeoutMs"),
3811
- maxAgeMs: resolveUpdatedLifecycleDurationMs(binding, "maxAgeMs")
3812
- };
3813
- }
3814
- function resolveUpdatedBindingExpiry(params) {
3815
- const expiries = params.bindings.map((binding) => {
3816
- if (params.action === SESSION_ACTION_IDLE) {
3817
- const idleTimeoutMs = typeof binding.idleTimeoutMs === "number" && Number.isFinite(binding.idleTimeoutMs) ? Math.max(0, Math.floor(binding.idleTimeoutMs)) : 0;
3818
- if (idleTimeoutMs <= 0) return;
3819
- return Math.max(binding.lastActivityAt, binding.boundAt) + idleTimeoutMs;
3820
- }
3821
- const maxAgeMs = typeof binding.maxAgeMs === "number" && Number.isFinite(binding.maxAgeMs) ? Math.max(0, Math.floor(binding.maxAgeMs)) : 0;
3822
- if (maxAgeMs <= 0) return;
3823
- return binding.boundAt + maxAgeMs;
3824
- }).filter((expiresAt) => typeof expiresAt === "number");
3825
- if (expiries.length === 0) return;
3826
- return Math.min(...expiries);
3827
- }
3828
- const handleActivationCommand = async (params, allowTextCommands) => {
3829
- if (!allowTextCommands) return null;
3830
- const activationCommand = parseActivationCommand(params.command.commandBodyNormalized);
3831
- if (!activationCommand.hasCommand) return null;
3832
- if (!params.isGroup) return {
3833
- shouldContinue: false,
3834
- reply: { text: "āš™ļø Group activation only applies to group chats." }
3835
- };
3836
- if (!params.command.isAuthorizedSender) {
3837
- logVerbose(`Ignoring /activation from unauthorized sender in group: ${params.command.senderId || "<unknown>"}`);
3838
- return { shouldContinue: false };
3839
- }
3840
- if (!activationCommand.mode) return {
3841
- shouldContinue: false,
3842
- reply: { text: "āš™ļø Usage: /activation mention|always" }
3843
- };
3844
- if (params.sessionEntry && params.sessionStore && params.sessionKey) {
3845
- params.sessionEntry.groupActivation = activationCommand.mode;
3846
- params.sessionEntry.groupActivationNeedsSystemIntro = true;
3847
- await persistSessionEntry(params);
3848
- }
3849
- return {
3850
- shouldContinue: false,
3851
- reply: { text: `āš™ļø Group activation set to ${activationCommand.mode}.` }
3852
- };
3853
- };
3854
- const handleSendPolicyCommand = async (params, allowTextCommands) => {
3855
- if (!allowTextCommands) return null;
3856
- const sendPolicyCommand = parseSendPolicyCommand(params.command.commandBodyNormalized);
3857
- if (!sendPolicyCommand.hasCommand) return null;
3858
- const unauthorizedResult = rejectUnauthorizedCommand(params, "/send");
3859
- if (unauthorizedResult) return unauthorizedResult;
3860
- const nonOwnerResult = rejectNonOwnerCommand(params, "/send");
3861
- if (nonOwnerResult) return nonOwnerResult;
3862
- if (!sendPolicyCommand.mode) return {
3863
- shouldContinue: false,
3864
- reply: { text: "āš™ļø Usage: /send on|off|inherit" }
3865
- };
3866
- if (params.sessionEntry && params.sessionStore && params.sessionKey) {
3867
- if (sendPolicyCommand.mode === "inherit") delete params.sessionEntry.sendPolicy;
3868
- else params.sessionEntry.sendPolicy = sendPolicyCommand.mode;
3869
- await persistSessionEntry(params);
3870
- }
3871
- return {
3872
- shouldContinue: false,
3873
- reply: { text: `āš™ļø Send policy set to ${sendPolicyCommand.mode === "inherit" ? "inherit" : sendPolicyCommand.mode === "allow" ? "on" : "off"}.` }
3874
- };
3875
- };
3876
- const handleUsageCommand = async (params, allowTextCommands) => {
3877
- if (!allowTextCommands) return null;
3878
- const normalized = params.command.commandBodyNormalized;
3879
- if (normalized !== "/usage" && !normalized.startsWith("/usage ")) return null;
3880
- if (!params.command.isAuthorizedSender) {
3881
- logVerbose(`Ignoring /usage from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3882
- return { shouldContinue: false };
3883
- }
3884
- const rawArgs = normalized === "/usage" ? "" : normalized.slice(6).trim();
3885
- const requested = rawArgs ? normalizeUsageDisplay(rawArgs) : void 0;
3886
- if (normalizeLowercaseStringOrEmpty(rawArgs).startsWith("cost")) {
3887
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3888
- const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
3889
- sessionKey: params.sessionKey,
3890
- config: params.cfg
3891
- }) : params.agentId;
3892
- const sessionSummary = await loadSessionCostSummary({
3893
- sessionId: targetSessionEntry?.sessionId,
3894
- sessionEntry: targetSessionEntry,
3895
- sessionFile: targetSessionEntry?.sessionFile,
3896
- config: params.cfg,
3897
- agentId: sessionAgentId
3898
- });
3899
- const summary = await loadCostUsageSummary({
3900
- days: 30,
3901
- config: params.cfg
3902
- });
3903
- const sessionCost = formatUsd(sessionSummary?.totalCost);
3904
- const sessionTokens = sessionSummary?.totalTokens ? formatTokenCount(sessionSummary.totalTokens) : void 0;
3905
- const sessionSuffix = (sessionSummary?.missingCostEntries ?? 0) > 0 ? " (partial)" : "";
3906
- const sessionLine = sessionCost || sessionTokens ? `Session ${sessionCost ?? "n/a"}${sessionSuffix}${sessionTokens ? ` Ā· ${sessionTokens} tokens` : ""}` : "Session n/a";
3907
- const todayKey = (/* @__PURE__ */ new Date()).toLocaleDateString("en-CA");
3908
- const todayEntry = summary.daily.find((entry) => entry.date === todayKey);
3909
- const todayCost = formatUsd(todayEntry?.totalCost);
3910
- const todaySuffix = (todayEntry?.missingCostEntries ?? 0) > 0 ? " (partial)" : "";
3911
- const todayLine = `Today ${todayCost ?? "n/a"}${todaySuffix}`;
3912
- const last30Cost = formatUsd(summary.totals.totalCost);
3913
- const last30Suffix = summary.totals.missingCostEntries > 0 ? " (partial)" : "";
3914
- return {
3915
- shouldContinue: false,
3916
- reply: { text: `šŸ’ø Usage cost\n${sessionLine}\n${todayLine}\n${`Last 30d ${last30Cost ?? "n/a"}${last30Suffix}`}` }
3917
- };
3918
- }
3919
- if (rawArgs && !requested) return {
3920
- shouldContinue: false,
3921
- reply: { text: "āš™ļø Usage: /usage off|tokens|full|cost" }
3922
- };
3923
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3924
- const currentRaw = targetSessionEntry?.responseUsage;
3925
- const current = resolveResponseUsageMode(currentRaw);
3926
- const next = requested ?? (current === "off" ? "tokens" : current === "tokens" ? "full" : "off");
3927
- if (targetSessionEntry && params.sessionStore && params.sessionKey) {
3928
- if (next === "off") delete targetSessionEntry.responseUsage;
3929
- else targetSessionEntry.responseUsage = next;
3930
- params.sessionStore[params.sessionKey] = targetSessionEntry;
3931
- await persistSessionEntry({
3932
- ...params,
3933
- sessionEntry: targetSessionEntry
3934
- });
3935
- }
3936
- return {
3937
- shouldContinue: false,
3938
- reply: { text: `āš™ļø Usage footer: ${next}.` }
3939
- };
3940
- };
3941
- const handleFastCommand = async (params, allowTextCommands) => {
3942
- if (!allowTextCommands) return null;
3943
- const normalized = params.command.commandBodyNormalized;
3944
- if (normalized !== "/fast" && !normalized.startsWith("/fast ")) return null;
3945
- if (!params.command.isAuthorizedSender) {
3946
- logVerbose(`Ignoring /fast from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3947
- return { shouldContinue: false };
3948
- }
3949
- const rawMode = normalizeLowercaseStringOrEmpty(normalized === "/fast" ? "" : normalized.slice(5).trim());
3950
- if (!rawMode || rawMode === "status") {
3951
- const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3952
- const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
3953
- sessionKey: params.sessionKey,
3954
- config: params.cfg
3955
- }) : params.agentId;
3956
- const state = resolveFastModeState({
3957
- cfg: params.cfg,
3958
- provider: params.provider,
3959
- model: params.model,
3960
- agentId: sessionAgentId,
3961
- sessionEntry: targetSessionEntry
3962
- });
3963
- const suffix = state.source === "agent" ? " (agent)" : state.source === "config" ? " (config)" : state.source === "default" ? " (default)" : "";
3964
- return {
3965
- shouldContinue: false,
3966
- reply: { text: `āš™ļø Current fast mode: ${state.enabled ? "on" : "off"}${suffix}.` }
3967
- };
3968
- }
3969
- const nextMode = normalizeFastMode(rawMode);
3970
- if (nextMode === void 0) return {
3971
- shouldContinue: false,
3972
- reply: { text: "āš™ļø Usage: /fast status|on|off" }
3973
- };
3974
- if (params.sessionEntry && params.sessionStore && params.sessionKey) {
3975
- params.sessionEntry.fastMode = nextMode;
3976
- await persistSessionEntry(params);
3977
- }
3978
- return {
3979
- shouldContinue: false,
3980
- reply: { text: `āš™ļø Fast mode ${nextMode ? "enabled" : "disabled"}.` }
3981
- };
3982
- };
3983
- const handleSessionCommand = async (params, allowTextCommands) => {
3984
- if (!allowTextCommands) return null;
3985
- const normalized = params.command.commandBodyNormalized;
3986
- if (!/^\/session(?:\s|$)/.test(normalized)) return null;
3987
- if (!params.command.isAuthorizedSender) {
3988
- logVerbose(`Ignoring /session from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3989
- return { shouldContinue: false };
3990
- }
3991
- const tokens = normalized.slice(8).trim().split(/\s+/).filter(Boolean);
3992
- const action = normalizeOptionalLowercaseString(tokens[0]);
3993
- if (action !== SESSION_ACTION_IDLE && action !== SESSION_ACTION_MAX_AGE) return {
3994
- shouldContinue: false,
3995
- reply: { text: resolveSessionCommandUsage() }
3996
- };
3997
- const channelId = params.command.channelId ?? normalizeChannelId$1(resolveCommandSurfaceChannel(params)) ?? void 0;
3998
- const commandConversationBindings = channelId ? getChannelPlugin(channelId)?.conversationBindings : void 0;
3999
- const commandSupportsCurrentConversationBinding = Boolean(commandConversationBindings?.supportsCurrentConversationBinding);
4000
- const commandSupportsLifecycleUpdate = action === SESSION_ACTION_IDLE ? typeof commandConversationBindings?.setIdleTimeoutBySessionKey === "function" : typeof commandConversationBindings?.setMaxAgeBySessionKey === "function";
4001
- const bindingContext = resolveConversationBindingContextFromAcpCommand(params);
4002
- if (!bindingContext) {
4003
- if (!channelId || !commandSupportsCurrentConversationBinding || !commandSupportsLifecycleUpdate) return {
4004
- shouldContinue: false,
4005
- reply: { text: "āš ļø /session idle and /session max-age are currently available only on channels that support focused conversation bindings." }
4006
- };
4007
- return {
4008
- shouldContinue: false,
4009
- reply: { text: "āš ļø /session idle and /session max-age must be run inside a focused conversation." }
4010
- };
4011
- }
4012
- const resolvedChannelId = bindingContext.channel || channelId;
4013
- const conversationBindings = resolvedChannelId ? getChannelPlugin(resolvedChannelId)?.conversationBindings : void 0;
4014
- const supportsCurrentConversationBinding = Boolean(conversationBindings?.supportsCurrentConversationBinding);
4015
- const supportsLifecycleUpdate = action === SESSION_ACTION_IDLE ? typeof conversationBindings?.setIdleTimeoutBySessionKey === "function" : typeof conversationBindings?.setMaxAgeBySessionKey === "function";
4016
- if (!resolvedChannelId || !supportsCurrentConversationBinding || !supportsLifecycleUpdate) return {
4017
- shouldContinue: false,
4018
- reply: { text: "āš ļø /session idle and /session max-age are currently available only on channels that support focused conversation bindings." }
4019
- };
4020
- const activeBinding = getSessionBindingService().resolveByConversation(bindingContext);
4021
- if (!activeBinding) return {
4022
- shouldContinue: false,
4023
- reply: { text: "ā„¹ļø This conversation is not currently focused." }
4024
- };
4025
- const idleTimeoutMs = resolveSessionBindingDurationMs(activeBinding, "idleTimeoutMs", 1440 * 60 * 1e3);
4026
- const idleExpiresAt = idleTimeoutMs > 0 ? resolveSessionBindingLastActivityAt(activeBinding) + idleTimeoutMs : void 0;
4027
- const maxAgeMs = resolveSessionBindingDurationMs(activeBinding, "maxAgeMs", 0);
4028
- const maxAgeExpiresAt = maxAgeMs > 0 ? activeBinding.boundAt + maxAgeMs : void 0;
4029
- const durationArgRaw = tokens.slice(1).join("");
4030
- if (!durationArgRaw) {
4031
- if (action === SESSION_ACTION_IDLE) {
4032
- if (typeof idleExpiresAt === "number" && Number.isFinite(idleExpiresAt) && idleExpiresAt > Date.now()) return {
4033
- shouldContinue: false,
4034
- reply: { text: `ā„¹ļø Idle timeout active (${formatThreadBindingDurationLabel(idleTimeoutMs)}, next auto-unfocus at ${formatSessionExpiry(idleExpiresAt)}).` }
4035
- };
4036
- return {
4037
- shouldContinue: false,
4038
- reply: { text: "ā„¹ļø Idle timeout is currently disabled for this focused session." }
4039
- };
4040
- }
4041
- if (typeof maxAgeExpiresAt === "number" && Number.isFinite(maxAgeExpiresAt) && maxAgeExpiresAt > Date.now()) return {
4042
- shouldContinue: false,
4043
- reply: { text: `ā„¹ļø Max age active (${formatThreadBindingDurationLabel(maxAgeMs)}, hard auto-unfocus at ${formatSessionExpiry(maxAgeExpiresAt)}).` }
4044
- };
4045
- return {
4046
- shouldContinue: false,
4047
- reply: { text: "ā„¹ļø Max age is currently disabled for this focused session." }
4048
- };
4049
- }
4050
- const senderId = normalizeOptionalString(params.command.senderId) ?? "";
4051
- const boundBy = resolveSessionBindingBoundBy(activeBinding);
4052
- if (boundBy && boundBy !== "system" && senderId && senderId !== boundBy) return {
4053
- shouldContinue: false,
4054
- reply: { text: `āš ļø Only ${boundBy} can update session lifecycle settings for this conversation.` }
4055
- };
4056
- let durationMs;
4057
- try {
4058
- durationMs = parseSessionDurationMs(durationArgRaw);
4059
- } catch {
4060
- return {
4061
- shouldContinue: false,
4062
- reply: { text: resolveSessionCommandUsage() }
4063
- };
4064
- }
4065
- const updatedBindings = action === SESSION_ACTION_IDLE ? setChannelConversationBindingIdleTimeoutBySessionKey({
4066
- channelId: bindingContext.channel,
4067
- targetSessionKey: activeBinding.targetSessionKey,
4068
- accountId: bindingContext.accountId,
4069
- idleTimeoutMs: durationMs
4070
- }) : setChannelConversationBindingMaxAgeBySessionKey({
4071
- channelId: bindingContext.channel,
4072
- targetSessionKey: activeBinding.targetSessionKey,
4073
- accountId: bindingContext.accountId,
4074
- maxAgeMs: durationMs
4075
- });
4076
- if (updatedBindings.length === 0) return {
4077
- shouldContinue: false,
4078
- reply: { text: action === SESSION_ACTION_IDLE ? "āš ļø Failed to update idle timeout for the current binding." : "āš ļø Failed to update max age for the current binding." }
4079
- };
4080
- if (durationMs <= 0) return {
4081
- shouldContinue: false,
4082
- reply: { text: action === SESSION_ACTION_IDLE ? `āœ… Idle timeout disabled for ${updatedBindings.length} binding${updatedBindings.length === 1 ? "" : "s"}.` : `āœ… Max age disabled for ${updatedBindings.length} binding${updatedBindings.length === 1 ? "" : "s"}.` }
4083
- };
4084
- const nextExpiry = resolveUpdatedBindingExpiry({
4085
- action,
4086
- bindings: updatedBindings.map((binding) => toUpdatedLifecycleBinding(binding))
4087
- });
4088
- const expiryLabel = typeof nextExpiry === "number" && Number.isFinite(nextExpiry) ? formatSessionExpiry(nextExpiry) : "n/a";
4089
- return {
4090
- shouldContinue: false,
4091
- reply: { text: action === SESSION_ACTION_IDLE ? `āœ… Idle timeout set to ${formatThreadBindingDurationLabel(durationMs)} for ${updatedBindings.length} binding${updatedBindings.length === 1 ? "" : "s"} (next auto-unfocus at ${expiryLabel}).` : `āœ… Max age set to ${formatThreadBindingDurationLabel(durationMs)} for ${updatedBindings.length} binding${updatedBindings.length === 1 ? "" : "s"} (hard auto-unfocus at ${expiryLabel}).` }
4092
- };
4093
- };
4094
- const handleRestartCommand = async (params, allowTextCommands) => {
4095
- if (!allowTextCommands) return null;
4096
- if (params.command.commandBodyNormalized !== "/restart") return null;
4097
- if (!params.command.isAuthorizedSender) {
4098
- logVerbose(`Ignoring /restart from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
4099
- return { shouldContinue: false };
4100
- }
4101
- const nonOwner = rejectNonOwnerCommand(params, "/restart");
4102
- if (nonOwner) return nonOwner;
4103
- if (!isRestartEnabled(params.cfg)) return {
4104
- shouldContinue: false,
4105
- reply: { text: "āš ļø /restart is disabled (commands.restart=false)." }
4106
- };
4107
- const hasSigusr1Listener = process.listenerCount("SIGUSR1") > 0;
4108
- const sentinelPayload = buildRestartCommandSentinel(params);
4109
- if (hasSigusr1Listener) {
4110
- let sentinelPath = null;
4111
- scheduleGatewaySigusr1Restart({
4112
- reason: "/restart",
4113
- emitHooks: sentinelPayload ? {
4114
- beforeEmit: async () => {
4115
- sentinelPath = await writeRestartSentinel(sentinelPayload);
4116
- },
4117
- afterEmitRejected: async () => {
4118
- await removeRestartSentinelFile(sentinelPath);
4119
- }
4120
- } : void 0
4121
- });
4122
- return {
4123
- shouldContinue: false,
4124
- reply: { text: "āš™ļø Restarting Genesis in-process (SIGUSR1); back in a few seconds." }
4125
- };
4126
- }
4127
- let sentinelPath = null;
4128
- try {
4129
- if (sentinelPayload) sentinelPath = await writeRestartSentinel(sentinelPayload);
4130
- } catch (err) {
4131
- logVerbose(`failed to write /restart sentinel: ${String(err)}`);
4132
- return {
4133
- shouldContinue: false,
4134
- reply: { text: "āš ļø Restart failed: could not persist the post-restart acknowledgement." }
4135
- };
4136
- }
4137
- const restartMethod = triggerGenesisRestart();
4138
- if (!restartMethod.ok) {
4139
- await removeRestartSentinelFile(sentinelPath);
4140
- const detail = restartMethod.detail ? ` Details: ${restartMethod.detail}` : "";
4141
- return {
4142
- shouldContinue: false,
4143
- reply: { text: `āš ļø Restart failed (${restartMethod.method}).${detail}` }
4144
- };
4145
- }
4146
- return {
4147
- shouldContinue: false,
4148
- reply: { text: `āš™ļø Restarting Genesis via ${restartMethod.method}; give me a few seconds to come back online.` }
4149
- };
4150
- };
4151
- //#endregion
4152
- //#region src/auto-reply/reply/commands-subagents.ts
4153
- let actionAgentsPromise = null;
4154
- let actionFocusPromise = null;
4155
- let actionHelpPromise = null;
4156
- let actionInfoPromise = null;
4157
- let actionKillPromise = null;
4158
- let actionListPromise = null;
4159
- let actionLogPromise = null;
4160
- let actionSendPromise = null;
4161
- let actionSpawnPromise = null;
4162
- let actionUnfocusPromise = null;
4163
- let controlRuntimePromise = null;
4164
- function loadAgentsAction() {
4165
- actionAgentsPromise ??= import("./action-agents-SNCscX_-.js");
4166
- return actionAgentsPromise;
4167
- }
4168
- function loadFocusAction() {
4169
- actionFocusPromise ??= import("./action-focus-B2s0PF2E.js");
4170
- return actionFocusPromise;
4171
- }
4172
- function loadHelpAction() {
4173
- actionHelpPromise ??= import("./action-help-CXKbyaZ7.js");
4174
- return actionHelpPromise;
4175
- }
4176
- function loadInfoAction() {
4177
- actionInfoPromise ??= import("./action-info-B3IDKxWu.js");
4178
- return actionInfoPromise;
4179
- }
4180
- function loadKillAction() {
4181
- actionKillPromise ??= import("./action-kill-idGvCNhT.js");
4182
- return actionKillPromise;
4183
- }
4184
- function loadListAction() {
4185
- actionListPromise ??= import("./action-list-Di7gO3qL.js");
4186
- return actionListPromise;
4187
- }
4188
- function loadLogAction() {
4189
- actionLogPromise ??= import("./action-log-BCsz-gFi.js");
4190
- return actionLogPromise;
4191
- }
4192
- function loadSendAction() {
4193
- actionSendPromise ??= import("./action-send-DLsdZnVc.js");
4194
- return actionSendPromise;
4195
- }
4196
- function loadSpawnAction() {
4197
- actionSpawnPromise ??= import("./action-spawn-DhKEOdL0.js");
4198
- return actionSpawnPromise;
4199
- }
4200
- function loadUnfocusAction() {
4201
- actionUnfocusPromise ??= import("./action-unfocus-Dh7ti5UP.js");
4202
- return actionUnfocusPromise;
4203
- }
4204
- function loadControlRuntime() {
4205
- controlRuntimePromise ??= import("./commands-subagents-control.runtime-C8ufgKPI.js");
4206
- return controlRuntimePromise;
4207
- }
4208
- const handleSubagentsCommand = async (params, allowTextCommands) => {
4209
- if (!allowTextCommands) return null;
4210
- const normalized = params.command.commandBodyNormalized;
4211
- const handledPrefix = resolveHandledPrefix(normalized);
4212
- if (!handledPrefix) return null;
4213
- if (!params.command.isAuthorizedSender) {
4214
- logVerbose(`Ignoring ${handledPrefix} from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
4215
- return { shouldContinue: false };
4216
- }
4217
- const restTokens = normalized.slice(handledPrefix.length).trim().split(/\s+/).filter(Boolean);
4218
- const action = resolveSubagentsAction({
4219
- handledPrefix,
4220
- restTokens
4221
- });
4222
- if (!action) return (await loadHelpAction()).handleSubagentsHelpAction();
4223
- const requesterKey = action === "spawn" ? resolveRequesterSessionKey(params, { preferCommandTarget: true }) : resolveRequesterSessionKey(params);
4224
- if (!requesterKey) return stopWithText("āš ļø Missing session key.");
4225
- const ctx = {
4226
- params,
4227
- handledPrefix,
4228
- requesterKey,
4229
- runs: (await loadControlRuntime()).listControlledSubagentRuns(requesterKey),
4230
- restTokens
4231
- };
4232
- switch (action) {
4233
- case "help": return (await loadHelpAction()).handleSubagentsHelpAction();
4234
- case "agents": return (await loadAgentsAction()).handleSubagentsAgentsAction(ctx);
4235
- case "focus": return await (await loadFocusAction()).handleSubagentsFocusAction(ctx);
4236
- case "unfocus": return await (await loadUnfocusAction()).handleSubagentsUnfocusAction(ctx);
4237
- case "list": return (await loadListAction()).handleSubagentsListAction(ctx);
4238
- case "kill": return await (await loadKillAction()).handleSubagentsKillAction(ctx);
4239
- case "info": return (await loadInfoAction()).handleSubagentsInfoAction(ctx);
4240
- case "log": return await (await loadLogAction()).handleSubagentsLogAction(ctx);
4241
- case "send": return await (await loadSendAction()).handleSubagentsSendAction(ctx, false);
4242
- case "steer": return await (await loadSendAction()).handleSubagentsSendAction(ctx, true);
4243
- case "spawn": return await (await loadSpawnAction()).handleSubagentsSpawnAction(ctx);
4244
- default: return (await loadHelpAction()).handleSubagentsHelpAction();
4245
- }
4246
- };
4247
- //#endregion
4248
- //#region src/auto-reply/reply/commands-tasks.ts
4249
- const MAX_VISIBLE_TASKS = 5;
4250
- const TASK_STATUS_ICONS = {
4251
- queued: "🟔",
4252
- running: "🟢",
4253
- succeeded: "āœ…",
4254
- failed: "šŸ”“",
4255
- timed_out: "ā±ļø",
4256
- cancelled: "āšŖļø",
4257
- lost: "āš ļø"
4258
- };
4259
- const TASK_RUNTIME_LABELS = {
4260
- subagent: "Subagent",
4261
- acp: "ACP",
4262
- cli: "CLI",
4263
- cron: "Cron"
4264
- };
4265
- function formatTaskHeadline(snapshot) {
4266
- if (snapshot.totalCount === 0) return "All clear - nothing linked to this session right now.";
4267
- return `Current session: ${snapshot.activeCount} active Ā· ${snapshot.totalCount} total`;
4268
- }
4269
- function formatAgentFallbackLine(agentId) {
4270
- const snapshot = buildTaskStatusSnapshot(listTasksForAgentIdForStatus(agentId));
4271
- if (snapshot.totalCount === 0) return;
4272
- return `Agent-local: ${snapshot.activeCount} active Ā· ${snapshot.totalCount} total`;
4273
- }
4274
- function formatTaskTiming(task) {
4275
- if (task.status === "running") {
4276
- const startedAt = task.startedAt ?? task.createdAt;
4277
- return `elapsed ${formatDurationCompact(Date.now() - startedAt, { spaced: true }) ?? "0s"}`;
4278
- }
4279
- if (task.status === "queued") return `queued ${formatTimeAgo(Date.now() - task.createdAt)}`;
4280
- const endedAt = task.endedAt ?? task.lastEventAt ?? task.createdAt;
4281
- return `finished ${formatTimeAgo(Date.now() - endedAt)}`;
4282
- }
4283
- function formatTaskDetail(task) {
4284
- return formatTaskStatusDetail(task);
4285
- }
4286
- function formatVisibleTask(task, index) {
4287
- const title = formatTaskStatusTitle(task);
4288
- const status = task.status.replaceAll("_", " ");
4289
- const timing = formatTaskTiming(task);
4290
- const detail = formatTaskDetail(task);
4291
- const meta = [
4292
- TASK_RUNTIME_LABELS[task.runtime],
4293
- status,
4294
- timing
4295
- ].filter(Boolean).join(" Ā· ");
4296
- const lines = [`${index + 1}. ${TASK_STATUS_ICONS[task.status]} ${title}`, ` ${meta}`];
4297
- if (detail) lines.push(` ${detail}`);
4298
- return lines.join("\n");
4299
- }
4300
- function buildTasksText(params) {
4301
- const sessionSnapshot = buildTaskStatusSnapshot(listTasksForSessionKeyForStatus(params.sessionKey));
4302
- const lines = ["šŸ“‹ Tasks", formatTaskHeadline(sessionSnapshot)];
4303
- if (sessionSnapshot.totalCount > 0) {
4304
- const visible = sessionSnapshot.visible.slice(0, MAX_VISIBLE_TASKS);
4305
- lines.push("");
4306
- for (const [index, task] of visible.entries()) {
4307
- lines.push(formatVisibleTask(task, index));
4308
- if (index < visible.length - 1) lines.push("");
4309
- }
4310
- const hiddenCount = sessionSnapshot.visible.length - visible.length;
4311
- if (hiddenCount > 0) lines.push("", `+${hiddenCount} more recent task${hiddenCount === 1 ? "" : "s"}`);
4312
- return lines.join("\n");
4313
- }
4314
- const agentFallback = formatAgentFallbackLine(params.agentId);
4315
- if (agentFallback) lines.push(agentFallback);
4316
- return lines.join("\n");
4317
- }
4318
- async function buildTasksReply(params) {
4319
- const agentId = resolveSessionAgentId({
4320
- sessionKey: params.sessionKey,
4321
- config: params.cfg
4322
- });
4323
- return { text: buildTasksText({
4324
- sessionKey: params.sessionKey,
4325
- agentId
4326
- }) };
4327
- }
4328
- const handleTasksCommand = async (params, allowTextCommands) => {
4329
- if (!allowTextCommands) return null;
4330
- const normalized = params.command.commandBodyNormalized;
4331
- if (normalized !== "/tasks" && !normalized.startsWith("/tasks ")) return null;
4332
- if (!params.command.isAuthorizedSender) {
4333
- logVerbose(`Ignoring /tasks from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
4334
- return { shouldContinue: false };
4335
- }
4336
- if (normalized !== "/tasks") return {
4337
- shouldContinue: false,
4338
- reply: { text: "Usage: /tasks" }
4339
- };
4340
- return {
4341
- shouldContinue: false,
4342
- reply: await buildTasksReply(params)
4343
- };
4344
- };
4345
- //#endregion
4346
- //#region src/auto-reply/reply/commands-tts.ts
4347
- function parseTtsCommand(normalized) {
4348
- if (normalized === "/tts") return {
4349
- action: "status",
4350
- args: ""
4351
- };
4352
- if (!normalized.startsWith("/tts ")) return null;
4353
- const rest = normalized.slice(5).trim();
4354
- if (!rest) return {
4355
- action: "status",
4356
- args: ""
4357
- };
4358
- const [action, ...tail] = rest.split(/\s+/);
4359
- return {
4360
- action: normalizeOptionalLowercaseString(action) ?? "",
4361
- args: normalizeOptionalString(tail.join(" ")) ?? ""
4362
- };
4363
- }
4364
- function formatAttemptDetails(attempts) {
4365
- if (!attempts || attempts.length === 0) return;
4366
- return attempts.map((attempt) => {
4367
- const reason = attempt.reasonCode === "success" ? "ok" : attempt.reasonCode;
4368
- const latency = Number.isFinite(attempt.latencyMs) ? ` ${attempt.latencyMs}ms` : "";
4369
- return `${attempt.provider}:${attempt.outcome}(${reason})${latency}`;
4370
- }).join(", ");
4371
- }
4372
- function ttsUsage() {
4373
- return { text: "šŸ”Š **TTS (Text-to-Speech) Help**\n\n**Commands:**\n• /tts on — Enable automatic TTS for replies\n• /tts off — Disable TTS\n• /tts status — Show current settings\n• /tts provider [name] — View/change provider\n• /tts limit [number] — View/change text limit\n• /tts summary [on|off] — View/change auto-summary\n• /tts audio <text> — Generate audio from text\n\n**Providers:**\nUse /tts provider to list the registered speech providers and their status.\n\n**Text Limit (default: 1500, max: 4096):**\nWhen text exceeds the limit:\n• Summary ON: AI summarizes, then generates audio\n• Summary OFF: Truncates text, then generates audio\n\n**Examples:**\n/tts provider <id>\n/tts limit 2000\n/tts audio Hello, this is a test!" };
4374
- }
4375
- const handleTtsCommands = async (params, allowTextCommands) => {
4376
- if (!allowTextCommands) return null;
4377
- const parsed = parseTtsCommand(params.command.commandBodyNormalized);
4378
- if (!parsed) return null;
4379
- if (!params.command.isAuthorizedSender) {
4380
- logVerbose(`Ignoring TTS command from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
4381
- return { shouldContinue: false };
4382
- }
4383
- const config = resolveTtsConfig(params.cfg);
4384
- const prefsPath = resolveTtsPrefsPath(config);
4385
- const action = parsed.action;
4386
- const args = parsed.args;
4387
- if (action === "help") return {
4388
- shouldContinue: false,
4389
- reply: ttsUsage()
4390
- };
4391
- if (action === "on") {
4392
- setTtsEnabled(prefsPath, true);
4393
- return {
4394
- shouldContinue: false,
4395
- reply: { text: "šŸ”Š TTS enabled." }
4396
- };
4397
- }
4398
- if (action === "off") {
4399
- setTtsEnabled(prefsPath, false);
4400
- return {
4401
- shouldContinue: false,
4402
- reply: { text: "šŸ”‡ TTS disabled." }
4403
- };
4404
- }
4405
- if (action === "audio") {
4406
- if (!args.trim()) return {
4407
- shouldContinue: false,
4408
- reply: { text: "šŸŽ¤ Generate audio from text.\n\nUsage: /tts audio <text>\nExample: /tts audio Hello, this is a test!" }
4409
- };
4410
- const start = Date.now();
4411
- const result = await textToSpeech({
4412
- text: args,
4413
- cfg: params.cfg,
4414
- channel: params.command.channel,
4415
- prefsPath
4416
- });
4417
- if (result.success && result.audioPath) {
4418
- setLastTtsAttempt({
4419
- timestamp: Date.now(),
4420
- success: true,
4421
- textLength: args.length,
4422
- summarized: false,
4423
- provider: result.provider,
4424
- fallbackFrom: result.fallbackFrom,
4425
- attemptedProviders: result.attemptedProviders,
4426
- attempts: result.attempts,
4427
- latencyMs: result.latencyMs
4428
- });
4429
- return {
4430
- shouldContinue: false,
4431
- reply: {
4432
- mediaUrl: result.audioPath,
4433
- audioAsVoice: result.voiceCompatible === true,
4434
- trustedLocalMedia: true,
4435
- spokenText: args
4436
- }
4437
- };
4438
- }
4439
- setLastTtsAttempt({
4440
- timestamp: Date.now(),
4441
- success: false,
4442
- textLength: args.length,
4443
- summarized: false,
4444
- attemptedProviders: result.attemptedProviders,
4445
- attempts: result.attempts,
4446
- error: result.error,
4447
- latencyMs: Date.now() - start
4448
- });
4449
- return {
4450
- shouldContinue: false,
4451
- reply: { text: `āŒ Error generating audio: ${result.error ?? "unknown error"}` }
4452
- };
4453
- }
4454
- if (action === "provider") {
4455
- const currentProvider = getTtsProvider(config, prefsPath);
4456
- if (!args.trim()) {
4457
- const providers = listSpeechProviders(params.cfg);
4458
- return {
4459
- shouldContinue: false,
4460
- reply: { text: `šŸŽ™ļø TTS provider\nPrimary: ${currentProvider}\n` + providers.map((provider) => `${provider.label}: ${provider.isConfigured({
4461
- cfg: params.cfg,
4462
- providerConfig: getResolvedSpeechProviderConfig(config, provider.id, params.cfg),
4463
- timeoutMs: config.timeoutMs
4464
- }) ? "āœ…" : "āŒ"}`).join("\n") + `\nUsage: /tts provider <id>` }
4465
- };
4466
- }
4467
- const requested = normalizeOptionalLowercaseString(args) ?? "";
4468
- const resolvedProvider = getSpeechProvider(requested, params.cfg);
4469
- if (!resolvedProvider) return {
4470
- shouldContinue: false,
4471
- reply: ttsUsage()
4472
- };
4473
- const nextProvider = canonicalizeSpeechProviderId(requested, params.cfg) ?? resolvedProvider.id;
4474
- setTtsProvider(prefsPath, nextProvider);
4475
- return {
4476
- shouldContinue: false,
4477
- reply: { text: `āœ… TTS provider set to ${nextProvider}.` }
4478
- };
4479
- }
4480
- if (action === "limit") {
4481
- if (!args.trim()) return {
4482
- shouldContinue: false,
4483
- reply: { text: `šŸ“ TTS limit: ${getTtsMaxLength(prefsPath)} characters.\n\nText longer than this triggers summary (if enabled).\nRange: 100-4096 chars (Telegram max).\n\nTo change: /tts limit <number>\nExample: /tts limit 2000` }
4484
- };
4485
- const next = Number.parseInt(args.trim(), 10);
4486
- if (!Number.isFinite(next) || next < 100 || next > 4096) return {
4487
- shouldContinue: false,
4488
- reply: { text: "āŒ Limit must be between 100 and 4096 characters." }
4489
- };
4490
- setTtsMaxLength(prefsPath, next);
4491
- return {
4492
- shouldContinue: false,
4493
- reply: { text: `āœ… TTS limit set to ${next} characters.` }
4494
- };
4495
- }
4496
- if (action === "summary") {
4497
- if (!args.trim()) {
4498
- const enabled = isSummarizationEnabled(prefsPath);
4499
- const maxLen = getTtsMaxLength(prefsPath);
4500
- return {
4501
- shouldContinue: false,
4502
- reply: { text: `šŸ“ TTS auto-summary: ${enabled ? "on" : "off"}.\n\nWhen text exceeds ${maxLen} chars:\n• ON: summarizes text, then generates audio\n• OFF: truncates text, then generates audio\n\nTo change: /tts summary on | off` }
4503
- };
4504
- }
4505
- const requested = normalizeOptionalLowercaseString(args) ?? "";
4506
- if (requested !== "on" && requested !== "off") return {
4507
- shouldContinue: false,
4508
- reply: ttsUsage()
4509
- };
4510
- setSummarizationEnabled(prefsPath, requested === "on");
4511
- return {
4512
- shouldContinue: false,
4513
- reply: { text: requested === "on" ? "āœ… TTS auto-summary enabled." : "āŒ TTS auto-summary disabled." }
4514
- };
4515
- }
4516
- if (action === "status") {
4517
- const enabled = isTtsEnabled(config, prefsPath);
4518
- const provider = getTtsProvider(config, prefsPath);
4519
- const hasKey = isTtsProviderConfigured(config, provider, params.cfg);
4520
- const maxLength = getTtsMaxLength(prefsPath);
4521
- const summarize = isSummarizationEnabled(prefsPath);
4522
- const last = getLastTtsAttempt();
4523
- const lines = [
4524
- "šŸ“Š TTS status",
4525
- `State: ${enabled ? "āœ… enabled" : "āŒ disabled"}`,
4526
- `Provider: ${provider} (${hasKey ? "āœ… configured" : "āŒ not configured"})`,
4527
- `Text limit: ${maxLength} chars`,
4528
- `Auto-summary: ${summarize ? "on" : "off"}`
4529
- ];
4530
- if (last) {
4531
- const timeAgo = Math.round((Date.now() - last.timestamp) / 1e3);
4532
- lines.push("");
4533
- lines.push(`Last attempt (${timeAgo}s ago): ${last.success ? "āœ…" : "āŒ"}`);
4534
- lines.push(`Text: ${last.textLength} chars${last.summarized ? " (summarized)" : ""}`);
4535
- if (last.success) {
4536
- lines.push(`Provider: ${last.provider ?? "unknown"}`);
4537
- if (last.fallbackFrom && last.provider && last.fallbackFrom !== last.provider) lines.push(`Fallback: ${last.fallbackFrom} -> ${last.provider}`);
4538
- if (last.attemptedProviders && last.attemptedProviders.length > 1) lines.push(`Attempts: ${last.attemptedProviders.join(" -> ")}`);
4539
- const details = formatAttemptDetails(last.attempts);
4540
- if (details) lines.push(`Attempt details: ${details}`);
4541
- lines.push(`Latency: ${last.latencyMs ?? 0}ms`);
4542
- } else if (last.error) {
4543
- lines.push(`Error: ${last.error}`);
4544
- if (last.attemptedProviders && last.attemptedProviders.length > 0) lines.push(`Attempts: ${last.attemptedProviders.join(" -> ")}`);
4545
- const details = formatAttemptDetails(last.attempts);
4546
- if (details) lines.push(`Attempt details: ${details}`);
4547
- }
4548
- }
4549
- return {
4550
- shouldContinue: false,
4551
- reply: { text: lines.join("\n") }
4552
- };
4553
- }
4554
- return {
4555
- shouldContinue: false,
4556
- reply: ttsUsage()
4557
- };
4558
- };
4559
- //#endregion
4560
- //#region src/auto-reply/reply/commands-handlers.runtime.ts
4561
- function loadCommandHandlers() {
4562
- return [
4563
- handlePluginCommand,
4564
- handleBtwCommand,
4565
- handleBashCommand,
4566
- handleActivationCommand,
4567
- handleSendPolicyCommand,
4568
- handleFastCommand,
4569
- handleUsageCommand,
4570
- handleSessionCommand,
4571
- handleRestartCommand,
4572
- handleTtsCommands,
4573
- handleHelpCommand,
4574
- handleCommandsListCommand,
4575
- handleToolsCommand,
4576
- handleStatusCommand,
4577
- handleTasksCommand,
4578
- handleAllowlistCommand,
4579
- handleApproveCommand,
4580
- handleContextCommand,
4581
- handleExportSessionCommand,
4582
- handleExportTrajectoryCommand,
4583
- handleWhoamiCommand,
4584
- handleSubagentsCommand,
4585
- handleAcpCommand,
4586
- handleMcpCommand,
4587
- handlePluginsCommand,
4588
- handleConfigCommand,
4589
- handleDebugCommand,
4590
- handleModelsCommand,
4591
- handleStopCommand,
4592
- handleCompactCommand,
4593
- handleAbortTrigger
4594
- ];
4595
- }
4596
- //#endregion
4597
- export { loadCommandHandlers };