@pixelzx/genesis 2026.5.3-2 → 2026.5.3-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 (1066) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/.buildstamp +1 -1
  3. package/dist/abort-91r4UulC.js +201 -0
  4. package/dist/abort.runtime-B9mJXpA7.js +2 -0
  5. package/dist/abort.runtime.js +1 -1
  6. package/dist/accounts-47VdxmAV.js +2 -0
  7. package/dist/accounts-CuCpc987.js +107 -0
  8. package/dist/accounts-xW4yEmC0.js +104 -0
  9. package/dist/acp-cli-NxFXWO1M.js +2193 -0
  10. package/dist/acp-spawn-DbkpHyE1.js +1093 -0
  11. package/dist/acp-spawn-QASKm_on.js +2 -0
  12. package/dist/acp-stateful-target-driver-BHyMcz1t.js +89 -0
  13. package/dist/action-agents-6PpsUM02.js +67 -0
  14. package/dist/action-focus-B4kHRvRY.js +132 -0
  15. package/dist/action-help-C5lxx1KX.js +7 -0
  16. package/dist/action-info-oy2vw7kF.js +101 -0
  17. package/dist/action-kill-CD139kh2.js +33 -0
  18. package/dist/action-list-DZ9teqOY.js +21 -0
  19. package/dist/action-log-gxlq_2Rp.js +30 -0
  20. package/dist/action-send-BurQ0zyV.js +39 -0
  21. package/dist/action-spawn-DxOHnNm7.js +47 -0
  22. package/dist/action-unfocus-CugM3XlM.js +29 -0
  23. package/dist/actions.runtime--ihN7Wd6.js +5 -0
  24. package/dist/actions.runtime-ib-izjF7.js +18 -0
  25. package/dist/actions.runtime.js +1 -1
  26. package/dist/agent-command-C2ZVqozq.js +874 -0
  27. package/dist/agent-harness-runtime-DgUskfxp.js +144 -0
  28. package/dist/agent-lSBQDJ_c.js +2 -0
  29. package/dist/agent-runner-utils-CQHnUCgQ.js +239 -0
  30. package/dist/agent-runner.runtime-CVwomI1B.js +3455 -0
  31. package/dist/agent-runner.runtime.js +1 -1
  32. package/dist/agent-runtime-DJ7En7GB.js +18 -0
  33. package/dist/agents-CDEITLQb.js +5 -0
  34. package/dist/agents-NqAmW65Y.js +952 -0
  35. package/dist/aliases-8yRNckmx.js +2 -0
  36. package/dist/aliases-DA8MRgQS.js +96 -0
  37. package/dist/api-CJi25G9E.js +139 -0
  38. package/dist/api-Cu958cYM.js +5 -0
  39. package/dist/api-DkzCGtG_.js +3 -0
  40. package/dist/approval-gateway-resolver-DOKXw6ku.js +29 -0
  41. package/dist/approval-gateway-runtime-Bv8CqHQS.js +2 -0
  42. package/dist/approval-handler-runtime-ZtFxOtrw.js +439 -0
  43. package/dist/approval-native-runtime-DAtNdlUh.js +729 -0
  44. package/dist/attempt-execution.runtime-RtO9GkMH.js +509 -0
  45. package/dist/attempt-execution.runtime.js +1 -1
  46. package/dist/attempt.prompt-helpers-CBqQ9_m3.js +218 -0
  47. package/dist/attempt.tool-run-context-DpZtz1o7.js +933 -0
  48. package/dist/audit-C-2uIqda.js +939 -0
  49. package/dist/audit.runtime-CmbX_Mhw.js +7 -0
  50. package/dist/audit.runtime.js +1 -1
  51. package/dist/auth-DQKEcU2i.js +2 -0
  52. package/dist/auth-kVluPSY6.js +383 -0
  53. package/dist/auth-order-BrWB3inY.js +96 -0
  54. package/dist/auth-order-DCT4hb8Z.js +2 -0
  55. package/dist/bash-tools-CfLkHd-r.js +2824 -0
  56. package/dist/bash-tools-xGRQBXVi.js +3 -0
  57. package/dist/binding-routing-DcVihFHn.js +85 -0
  58. package/dist/binding-targets-CM036UnT.js +121 -0
  59. package/dist/bridge-server-IJqt4FlL.js +113 -0
  60. package/dist/browser-control-auth-D_ENihgB.js +2 -0
  61. package/dist/browser-node-runtime-CgC9vaCW.js +12 -0
  62. package/dist/browser-profiles-DXSDH0AX.js +2 -0
  63. package/dist/browser-runtime-DlIrKgom.js +387 -0
  64. package/dist/browser-setup-tools-CzwG2Hi7.js +13 -0
  65. package/dist/build-DyITSIDX.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-45FewBaL.js +329 -0
  70. package/dist/call-BqBKDI9u.js +3 -0
  71. package/dist/call.runtime-6-vv8hKu.js +2 -0
  72. package/dist/call.runtime.js +1 -1
  73. package/dist/capability-cli-mXxaAg87.js +1401 -0
  74. package/dist/catchup-DZItnQoF.js +300 -0
  75. package/dist/channel-4_07fZor.js +1174 -0
  76. package/dist/channel-BypEOihB.js +226 -0
  77. package/dist/channel-CPaewlgu.js +1802 -0
  78. package/dist/channel-CZ55XiAG.js +1320 -0
  79. package/dist/channel-Ccfv73or.js +595 -0
  80. package/dist/channel-CzsHgYiG.js +350 -0
  81. package/dist/channel-D4vHC37-.js +491 -0
  82. package/dist/channel-DRykWnyQ.js +1100 -0
  83. package/dist/channel-Dv_sqItB.js +840 -0
  84. package/dist/channel-Rka7SmcE.js +453 -0
  85. package/dist/channel-YXjNVZ70.js +297 -0
  86. package/dist/channel-core-BWePKW2T.js +5 -0
  87. package/dist/channel-inbound-B8tlgRz9.js +31 -0
  88. package/dist/channel-plugin-runtime-BSquEWfT.js +771 -0
  89. package/dist/channel-runtime-DyoiUzHM.js +425 -0
  90. package/dist/channel.runtime-BNUQYyCS.js +34702 -0
  91. package/dist/channel.runtime-BSYg7-dS.js +109 -0
  92. package/dist/channel.runtime-C3YAtGah.js +2364 -0
  93. package/dist/channel.runtime-CZggGgop.js +430 -0
  94. package/dist/channel.runtime-ZWHikPHo.js +89 -0
  95. package/dist/channel.runtime-aOaQbZea.js +4 -0
  96. package/dist/channel.runtime-puS1jfmK.js +576 -0
  97. package/dist/channel.runtime.js +1 -1
  98. package/dist/channel.setup-B2_426hq.js +10 -0
  99. package/dist/channels-cli-jNLEPssf.js +267 -0
  100. package/dist/channels-eG2v9IVY.js +827 -0
  101. package/dist/chat-BQEVN8XR.js +2757 -0
  102. package/dist/clawbot-cli-CSsLvJhI.js +9 -0
  103. package/dist/cli/daemon-cli.js +3 -3
  104. package/dist/cli-7D9AzMj2.js +219 -0
  105. package/dist/cli-CfP5iSkW.js +2 -0
  106. package/dist/cli-KSwNK8zo.js +72 -0
  107. package/dist/cli-LF3vrSmQ.js +2 -0
  108. package/dist/cli-runner-C-yyW9Mw.js +286 -0
  109. package/dist/cli-runner.runtime-BPTwiZtI.js +4 -0
  110. package/dist/cli-runner.runtime-CZ7aFUiV.js +3 -0
  111. package/dist/cli-runner.runtime.js +1 -1
  112. package/dist/cli-startup-metadata.json +2 -2
  113. package/dist/cli.runtime-BkxOxJn0.js +1261 -0
  114. package/dist/cli.runtime.js +1 -1
  115. package/dist/client-BeAVbxBQ.js +138 -0
  116. package/dist/client-DWrM2Yms.js +2742 -0
  117. package/dist/command-auth-TXkwHike.js +76 -0
  118. package/dist/command-config-resolution-BQUvy5ZL.js +2 -0
  119. package/dist/command-config-resolution-CiffKnhz.js +23 -0
  120. package/dist/command-config-resolution.runtime-DWe34jdz.js +2 -0
  121. package/dist/command-config-resolution.runtime.js +1 -1
  122. package/dist/command-registry-BI5Ce-0X.js +9 -0
  123. package/dist/command-registry-CZ-Rk9No.js +4 -0
  124. package/dist/command-registry-core-CqSjfb7e.js +104 -0
  125. package/dist/command-secret-gateway-RYlrkM8e.js +528 -0
  126. package/dist/command-status.runtime-9RuTTw7H.js +87 -0
  127. package/dist/command-status.runtime.js +1 -1
  128. package/dist/commands-acp-DNlM5COD.js +77 -0
  129. package/dist/commands-compact.runtime-Dbbx-Ps6.js +10 -0
  130. package/dist/commands-compact.runtime.js +1 -1
  131. package/dist/commands-handlers.runtime-J4HmYPML.js +4596 -0
  132. package/dist/commands-handlers.runtime.js +1 -1
  133. package/dist/commands-status-BpCtSlHL.js +16 -0
  134. package/dist/commands-status.runtime-B5lz9wwA.js +3 -0
  135. package/dist/commands-status.runtime.js +1 -1
  136. package/dist/commands-subagents-control.runtime-BlMDlblZ.js +2 -0
  137. package/dist/commands-subagents-control.runtime-RvrJJSNg.js +3 -0
  138. package/dist/commands-subagents-control.runtime.js +1 -1
  139. package/dist/commands-system-prompt-DuLI1Zhj.js +158 -0
  140. package/dist/commands-system-prompt-aXNuSW_q.js +2 -0
  141. package/dist/commands.runtime-Cvb5f7IP.js +166 -0
  142. package/dist/commands.runtime.js +1 -1
  143. package/dist/compact-CEtFY3x7.js +1118 -0
  144. package/dist/compact.runtime-BEuz-f53.js +12 -0
  145. package/dist/compact.runtime.js +1 -1
  146. package/dist/completion-cli-Du1dkhoP.js +313 -0
  147. package/dist/config-Mu4QhWzJ.js +248 -0
  148. package/dist/config-cli-DUUIMEUP.js +1073 -0
  149. package/dist/configure-DLxdFMCs.js +2 -0
  150. package/dist/configure-DQZRoD0Y.js +1244 -0
  151. package/dist/connect-options-CR5cdO4W.js +699 -0
  152. package/dist/control-auth-DLnHsBZt.js +125 -0
  153. package/dist/control-service-B035Oo8M.js +156 -0
  154. package/dist/control-ui/assets/agents-1LSJ-6PP.js +949 -0
  155. package/dist/control-ui/assets/channel-config-extras-BQz7hQLy.js +2 -0
  156. package/dist/control-ui/assets/channels-Pd3YLhy4.js +353 -0
  157. package/dist/control-ui/assets/cron-DME74GWr.js +933 -0
  158. package/dist/control-ui/assets/de-C0ZR8sDB.js +2 -0
  159. package/dist/control-ui/assets/debug-B4No9QzL.js +94 -0
  160. package/dist/control-ui/assets/es-C6bU_TtU.js +2 -0
  161. package/dist/control-ui/assets/format-CU5rVzG3.js +9 -0
  162. package/dist/control-ui/assets/fr-D5DeTmNv.js +2 -0
  163. package/dist/control-ui/assets/id-D2rVEDjJ.js +2 -0
  164. package/dist/control-ui/assets/index-BL88Y9ha.js +6308 -0
  165. package/dist/control-ui/assets/instances-BrcIASdv.js +57 -0
  166. package/dist/control-ui/assets/ja-JP-Dn3lisLY.js +2 -0
  167. package/dist/control-ui/assets/ko-DxD_1Zk0.js +2 -0
  168. package/dist/control-ui/assets/logs-BCK7QB61.js +74 -0
  169. package/dist/control-ui/assets/nodes-DBgRvAW9.js +436 -0
  170. package/dist/control-ui/assets/pl-DqfELhXe.js +2 -0
  171. package/dist/control-ui/assets/pt-BR-CyYqgZQ0.js +2 -0
  172. package/dist/control-ui/assets/sessions-xAeiynNF.js +306 -0
  173. package/dist/control-ui/assets/skills-DnzXHEWh.js +314 -0
  174. package/dist/control-ui/assets/skills-shared-DUcVMOWy.js +11 -0
  175. package/dist/control-ui/assets/string-coerce-Cdiw640X.js +3 -0
  176. package/dist/control-ui/assets/th-Cdunu1Yf.js +2 -0
  177. package/dist/control-ui/assets/tr-BVk27ysg.js +2 -0
  178. package/dist/control-ui/assets/uk-CI_KWzZt.js +2 -0
  179. package/dist/control-ui/assets/wallet-BDUGnhoA.js +195 -0
  180. package/dist/control-ui/assets/zh-CN-Iit1vnHx.js +2 -0
  181. package/dist/control-ui/assets/zh-TW-hVvjG-ie.js +2 -0
  182. package/dist/control-ui/index.html +3 -3
  183. package/dist/control-ui-BdRLK7I-.js +664 -0
  184. package/dist/conversation-id-BM-V07Pl.js +235 -0
  185. package/dist/conversation-id-BghRIfxG.js +38 -0
  186. package/dist/conversation-runtime-C4gObsh2.js +31 -0
  187. package/dist/core-ChqnJuFH.js +275 -0
  188. package/dist/cron-cli-C5Gndyos.js +713 -0
  189. package/dist/daemon-cli-ZzTGcINw.js +12 -0
  190. package/dist/delegate-BulXNglP.js +64 -0
  191. package/dist/detached-task-runtime-vv5lDMJn.js +73 -0
  192. package/dist/devices-cli-DIvpz4kL.js +496 -0
  193. package/dist/diagnostics-C8iZ-TW3.js +154 -0
  194. package/dist/direct-dm-DtDot5lO.js +64 -0
  195. package/dist/dispatch-CswKkiWZ.js +1131 -0
  196. package/dist/dispatch-acp-B6BY7PnM.js +981 -0
  197. package/dist/dispatch-acp-manager.runtime-9d1-ds6W.js +3 -0
  198. package/dist/dispatch-acp-manager.runtime.js +1 -1
  199. package/dist/dispatch-acp.runtime-B3XBEEra.js +19 -0
  200. package/dist/dispatch-acp.runtime.js +1 -1
  201. package/dist/doctor-device-pairing-B9xoU-b0.js +307 -0
  202. package/dist/doctor-gateway-daemon-flow-CBRay2wn.js +250 -0
  203. package/dist/doctor-gateway-health-Pv5QfyCN.js +60 -0
  204. package/dist/doctor-health-contributions-BQZqHOsI.js +486 -0
  205. package/dist/doctor-health-sIYTca3Z.js +59 -0
  206. package/dist/doctor-prompter-Bl7VEFRB.js +56 -0
  207. package/dist/doctor-workspace-status-COpJU_Sy.js +75 -0
  208. package/dist/dreaming-B-Ij18RW.js +1574 -0
  209. package/dist/dreaming-narrative-Dlq1B1wL.js +595 -0
  210. package/dist/embedded-gateway-stub.runtime-DxH4W_Ct.js +9 -0
  211. package/dist/embedded-gateway-stub.runtime.js +1 -1
  212. package/dist/embeddings-http-Dwm0-7xN.js +205 -0
  213. package/dist/entry.js +2 -2
  214. package/dist/exec-approvals-cli-NfwQ3x1C.js +498 -0
  215. package/dist/extensionAPI.js +1 -1
  216. package/dist/extensions/active-memory/index.js +1 -1
  217. package/dist/extensions/bluebubbles/api.js +3 -3
  218. package/dist/extensions/bluebubbles/channel-plugin-api.js +1 -1
  219. package/dist/extensions/browser/browser-bridge.js +1 -1
  220. package/dist/extensions/browser/browser-config.js +4 -4
  221. package/dist/extensions/browser/browser-control-auth.js +2 -2
  222. package/dist/extensions/browser/browser-doctor.js +2 -2
  223. package/dist/extensions/browser/browser-maintenance.js +2 -2
  224. package/dist/extensions/browser/browser-profiles.js +2 -2
  225. package/dist/extensions/browser/browser-runtime-api.js +10 -10
  226. package/dist/extensions/browser/index.js +1 -1
  227. package/dist/extensions/browser/plugin-registration.js +1 -1
  228. package/dist/extensions/browser/register.runtime.js +3 -3
  229. package/dist/extensions/browser/runtime-api.js +11 -11
  230. package/dist/extensions/browser/test-support.js +1 -1
  231. package/dist/extensions/device-pair/api.js +1 -1
  232. package/dist/extensions/device-pair/index.js +3 -3
  233. package/dist/extensions/device-pair/notify.js +1 -1
  234. package/dist/extensions/device-pair/pair-command-approve.js +1 -1
  235. package/dist/extensions/google-meet/index.js +2 -2
  236. package/dist/extensions/imessage/api.js +3 -3
  237. package/dist/extensions/imessage/channel-plugin-api.js +1 -1
  238. package/dist/extensions/imessage/runtime-api.js +3 -3
  239. package/dist/extensions/irc/api.js +2 -2
  240. package/dist/extensions/irc/channel-plugin-api.js +1 -1
  241. package/dist/extensions/line/api.js +2 -2
  242. package/dist/extensions/line/channel-plugin-api.js +1 -1
  243. package/dist/extensions/line/contract-api.js +1 -1
  244. package/dist/extensions/line/runtime-api.js +4 -4
  245. package/dist/extensions/line/setup-api.js +1 -1
  246. package/dist/extensions/llm-task/index.js +2 -2
  247. package/dist/extensions/lobster/index.js +3 -3
  248. package/dist/extensions/lobster/runtime-api.js +1 -1
  249. package/dist/extensions/mattermost/api.js +1 -1
  250. package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
  251. package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
  252. package/dist/extensions/mattermost/policy-api.js +1 -1
  253. package/dist/extensions/mattermost/runtime-api.js +4 -4
  254. package/dist/extensions/mattermost/slash-route-api.js +1 -1
  255. package/dist/extensions/memory-core/api.js +1 -1
  256. package/dist/extensions/memory-core/cli-metadata.js +2 -2
  257. package/dist/extensions/memory-core/index.js +3 -3
  258. package/dist/extensions/memory-lancedb/cli-metadata.js +1 -1
  259. package/dist/extensions/msteams/api.js +1 -1
  260. package/dist/extensions/msteams/channel-plugin-api.js +1 -1
  261. package/dist/extensions/msteams/runtime-api.js +3 -3
  262. package/dist/extensions/msteams/test-api.js +1 -1
  263. package/dist/extensions/nextcloud-talk/api.js +1 -1
  264. package/dist/extensions/nextcloud-talk/channel-plugin-api.js +1 -1
  265. package/dist/extensions/nextcloud-talk/runtime-api.js +2 -2
  266. package/dist/extensions/openshell/index.js +2 -2
  267. package/dist/extensions/signal/api.js +6 -6
  268. package/dist/extensions/signal/channel-plugin-api.js +1 -1
  269. package/dist/extensions/signal/reaction-runtime-api.js +1 -1
  270. package/dist/extensions/signal/runtime-api.js +7 -7
  271. package/dist/extensions/skill-workshop/api.js +1 -1
  272. package/dist/extensions/skill-workshop/index.js +1 -1
  273. package/dist/extensions/synology-chat/api.js +1 -1
  274. package/dist/extensions/synology-chat/channel-plugin-api.js +1 -1
  275. package/dist/extensions/tlon/api.js +2 -2
  276. package/dist/extensions/tlon/channel-plugin-api.js +1 -1
  277. package/dist/extensions/tlon/runtime-api.js +1 -1
  278. package/dist/extensions/tlon/test-api.js +1 -1
  279. package/dist/extensions/twitch/api.js +1 -1
  280. package/dist/extensions/twitch/channel-plugin-api.js +1 -1
  281. package/dist/extensions/twitch/setup-plugin-api.js +1 -1
  282. package/dist/extensions/zalo/api.js +3 -3
  283. package/dist/extensions/zalo/channel-plugin-api.js +1 -1
  284. package/dist/extensions/zalo/runtime-api.js +2 -2
  285. package/dist/extensions/zalo/setup-api.js +2 -2
  286. package/dist/extensions/zalouser/api.js +3 -3
  287. package/dist/extensions/zalouser/channel-plugin-api.js +1 -1
  288. package/dist/extensions/zalouser/runtime-api.js +6 -6
  289. package/dist/extensions/zalouser/setup-plugin-api.js +1 -1
  290. package/dist/extensions/zalouser/test-api.js +1 -1
  291. package/dist/fallbacks-BFYvKUnY.js +31 -0
  292. package/dist/fallbacks-Dln-Fm7a.js +2 -0
  293. package/dist/fallbacks-shared-BtC9lu5P.js +111 -0
  294. package/dist/gateway-CLjt4Ubu.js +115 -0
  295. package/dist/gateway-cli-jaaJ3fg-.js +1325 -0
  296. package/dist/gateway-rpc-B0bKGYQt.js +14 -0
  297. package/dist/gateway-rpc.runtime-CDyIcCe7.js +23 -0
  298. package/dist/gateway-rpc.runtime.js +1 -1
  299. package/dist/gateway-runtime-BxG-mEQr.js +15 -0
  300. package/dist/gateway-status-v2j9MIsq.js +584 -0
  301. package/dist/genesis-tools-CES2sMWo.js +8998 -0
  302. package/dist/genesis-tools.runtime-BzLXBcui.js +2 -0
  303. package/dist/genesis-tools.runtime.js +1 -1
  304. package/dist/get-reply-7p41dlff.js +3879 -0
  305. package/dist/get-reply-from-config.runtime-u3yCD2PM.js +2 -0
  306. package/dist/get-reply-from-config.runtime.js +1 -1
  307. package/dist/graph-users-IT2wmMx0.js +1337 -0
  308. package/dist/health-BFcoKWr0.js +469 -0
  309. package/dist/health-DRvLyY-r.js +3 -0
  310. package/dist/heartbeat-runner-BHjLQL2M.js +1292 -0
  311. package/dist/heartbeat-runner-DqEJGTLj.js +5 -0
  312. package/dist/heartbeat-runner.runtime-Cmx1SSZn.js +4 -0
  313. package/dist/heartbeat-runner.runtime.js +1 -1
  314. package/dist/hooks-cli-DDT-e8cJ.js +433 -0
  315. package/dist/http-endpoint-helpers-Dj8t0Siy.js +41 -0
  316. package/dist/http-utils-Dwz38Ezf.js +924 -0
  317. package/dist/image-fallbacks-D7OPvToB.js +31 -0
  318. package/dist/image-fallbacks-Dz8AR8dy.js +2 -0
  319. package/dist/inbound-reply-dispatch-DAPsCNCR.js +73 -0
  320. package/dist/index.js +2 -2
  321. package/dist/infra-runtime-DwyCbqnF.js +39 -0
  322. package/dist/init-ff-VGINj.js +59 -0
  323. package/dist/library-DJHGahez.js +45 -0
  324. package/dist/lifecycle-Wn699Yk2.js +229 -0
  325. package/dist/lifecycle-jhG_0376.js +571 -0
  326. package/dist/lifecycle.runtime-DEQnEWhs.js +2 -0
  327. package/dist/lifecycle.runtime.js +1 -1
  328. package/dist/list-BpmdsUg2.js +2 -0
  329. package/dist/list-Bx1ShIyl.js +1201 -0
  330. package/dist/list-CrwKhvg6.js +130 -0
  331. package/dist/list-DMu11V_u.js +2 -0
  332. package/dist/list.probe-uEkIls1j.js +419 -0
  333. package/dist/llm-slug-generator-CLSA0uws.js +79 -0
  334. package/dist/llm-slug-generator.js +1 -1
  335. package/dist/load-config-Dez1SxKa.js +35 -0
  336. package/dist/local-dispatch.runtime-Dxyktykf.js +8 -0
  337. package/dist/local-dispatch.runtime.js +1 -1
  338. package/dist/logs-cli-DrKLI45U.js +265 -0
  339. package/dist/logs-cli.runtime-WU3d8rj3.js +2 -0
  340. package/dist/logs-cli.runtime.js +1 -1
  341. package/dist/main-session-restart-recovery-CDpXwlsb.js +206 -0
  342. package/dist/managed-image-attachments-CTfAUhir.js +2 -0
  343. package/dist/managed-image-attachments-DwCKRLRN.js +635 -0
  344. package/dist/manager-C8C_r6-q.js +2057 -0
  345. package/dist/manager-DNh85N31.js +2 -0
  346. package/dist/markdown-to-line-CeMQCPsl.js +790 -0
  347. package/dist/mcp/plugin-tools-serve.js +1 -1
  348. package/dist/mcp-cli-CilsONVQ.js +724 -0
  349. package/dist/mcp-http-DMgw2M1d.js +529 -0
  350. package/dist/memory-core-host-runtime-cli-C4pnPS3_.js +9 -0
  351. package/dist/message-BodHPIzX.js +231 -0
  352. package/dist/message-action-runner-PKW742hU.js +1406 -0
  353. package/dist/message-action-runner-VdRgHq0O.js +2 -0
  354. package/dist/message-actions-C6yR-dy_.js +143 -0
  355. package/dist/message.gateway.runtime-CXGM9Aaa.js +2 -0
  356. package/dist/message.gateway.runtime.js +1 -1
  357. package/dist/method-scopes-Dut0EB9J.js +209 -0
  358. package/dist/models-cli-CZt8Jsll.js +219 -0
  359. package/dist/models-http-Dcpveulc.js +92 -0
  360. package/dist/monitor--Wv4TIXO.js +671 -0
  361. package/dist/monitor-82G9E74P.js +1237 -0
  362. package/dist/monitor-BbRyKgwH.js +2 -0
  363. package/dist/monitor-CC0s4dOX.js +1459 -0
  364. package/dist/monitor-CQsFb8eQ.js +788 -0
  365. package/dist/monitor-Co1hvULI.js +1661 -0
  366. package/dist/monitor-auth-6Kflwyie.js +207 -0
  367. package/dist/monitor-processing-B7uKpWo4.js +1974 -0
  368. package/dist/monitor.runtime-CSS_UmaS.js +2 -0
  369. package/dist/monitor.runtime.js +1 -1
  370. package/dist/monitor.webhook-DGN7_Sjs.js +180 -0
  371. package/dist/msteams-Cq2ldWey.js +35 -0
  372. package/dist/native-hook-relay-DtU42QnM.js +519 -0
  373. package/dist/nextcloud-talk-CkxtLN3A.js +17 -0
  374. package/dist/node-cli-BlCoOoMf.js +2506 -0
  375. package/dist/nodes-cli-BspoieXR.js +1046 -0
  376. package/dist/nodes-utils-CbFMjmDs.js +84 -0
  377. package/dist/nodes.helpers-K9f4_mBF.js +34 -0
  378. package/dist/notify-CyQE1_Xr.js +315 -0
  379. package/dist/onboard-BvLD3Wm8.js +632 -0
  380. package/dist/onboard-helpers-0XhcwDte.js +204 -0
  381. package/dist/onboard-helpers-B8ISwJON.js +6 -0
  382. package/dist/onboard-remote-BRM4DH6p.js +193 -0
  383. package/dist/onboard-remote-Blun0y8J.js +2 -0
  384. package/dist/onboard-skills-CTHeVmHt.js +2 -0
  385. package/dist/onboard-skills-D_29CQ3l.js +134 -0
  386. package/dist/openai-http-CFWiPGqM.js +500 -0
  387. package/dist/openresponses-http-8gJVvkvj.js +1128 -0
  388. package/dist/operator-approvals-client-CD4Ta4mU.js +68 -0
  389. package/dist/outbound.runtime-djlPw0h_.js +2 -0
  390. package/dist/outbound.runtime.js +1 -1
  391. package/dist/pair-command-approve-CJX4gh1-.js +44 -0
  392. package/dist/persistent-bindings.lifecycle-BW_emuP7.js +85 -0
  393. package/dist/persistent-bindings.lifecycle-C1SX_Q_K.js +2 -0
  394. package/dist/pi-embedded-DD7aPF12.js +2905 -0
  395. package/dist/pi-embedded-PW48UsXW.js +4 -0
  396. package/dist/pi-embedded.runtime-CqhLxSYX.js +4 -0
  397. package/dist/pi-embedded.runtime.js +1 -1
  398. package/dist/pi-tool-definition-adapter-C1Prxd-M.js +217 -0
  399. package/dist/pi-tools-pw6Tseqi.js +1057 -0
  400. package/dist/pi-tools.before-tool-call-BSfbqmdy.js +433 -0
  401. package/dist/pi-tools.before-tool-call-Vdpw6m1Q.js +2 -0
  402. package/dist/plugin-Bkk7yfMh.js +12195 -0
  403. package/dist/plugin-enabled-B7310bjm.js +140 -0
  404. package/dist/plugin-registration-ClydMGPd.js +23 -0
  405. package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
  406. package/dist/plugin-sdk/acp-binding-runtime.js +1 -1
  407. package/dist/plugin-sdk/acp-runtime.js +2 -2
  408. package/dist/plugin-sdk/agent-harness-runtime.js +5 -5
  409. package/dist/plugin-sdk/agent-harness.js +6 -6
  410. package/dist/plugin-sdk/agent-runtime.js +2 -2
  411. package/dist/plugin-sdk/approval-gateway-runtime.js +2 -2
  412. package/dist/plugin-sdk/approval-handler-runtime.js +3 -3
  413. package/dist/plugin-sdk/approval-runtime.js +1 -1
  414. package/dist/plugin-sdk/browser-node-runtime.js +4 -4
  415. package/dist/plugin-sdk/browser-setup-tools.js +3 -3
  416. package/dist/plugin-sdk/browser-support.js +7 -7
  417. package/dist/plugin-sdk/channel-core.js +2 -2
  418. package/dist/plugin-sdk/channel-inbound.js +2 -2
  419. package/dist/plugin-sdk/command-auth.js +1 -1
  420. package/dist/plugin-sdk/command-status-runtime.js +1 -1
  421. package/dist/plugin-sdk/compat.js +1 -1
  422. package/dist/plugin-sdk/conversation-binding-runtime.js +1 -1
  423. package/dist/plugin-sdk/conversation-runtime.js +3 -3
  424. package/dist/plugin-sdk/core.js +2 -2
  425. package/dist/plugin-sdk/direct-dm.js +1 -1
  426. package/dist/plugin-sdk/gateway-runtime.js +3 -3
  427. package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
  428. package/dist/plugin-sdk/index.js +1 -1
  429. package/dist/plugin-sdk/infra-runtime.js +2 -2
  430. package/dist/plugin-sdk/irc.js +2 -2
  431. package/dist/plugin-sdk/matrix.js +1 -1
  432. package/dist/plugin-sdk/memory-core-host-runtime-cli.js +2 -2
  433. package/dist/plugin-sdk/memory-core.js +2 -2
  434. package/dist/plugin-sdk/msteams.js +2 -2
  435. package/dist/plugin-sdk/nextcloud-talk.js +2 -2
  436. package/dist/plugin-sdk/nostr.js +1 -1
  437. package/dist/plugin-sdk/reply-dispatch-runtime.js +1 -1
  438. package/dist/plugin-sdk/reply-runtime.js +4 -4
  439. package/dist/plugin-sdk/runtime-secret-resolution.js +1 -1
  440. package/dist/plugin-sdk/runtime.js +2 -2
  441. package/dist/plugin-sdk/session-visibility.js +1 -1
  442. package/dist/plugin-sdk/src/gateway/protocol/index.d.ts +43 -3
  443. package/dist/plugin-sdk/src/gateway/protocol/schema/protocol-schemas.d.ts +40 -0
  444. package/dist/plugin-sdk/src/gateway/protocol/schema/wallet.d.ts +44 -0
  445. package/dist/plugin-sdk/testing.js +4 -4
  446. package/dist/plugin-sdk/tlon.js +1 -1
  447. package/dist/plugin-sdk/zalo.js +1 -1
  448. package/dist/plugin-sdk/zalouser.js +1 -1
  449. package/dist/plugin-service-BuKwEFP2.js +2890 -0
  450. package/dist/plugins/runtime/index.js +1 -1
  451. package/dist/policy-B-SG_MoX.js +328 -0
  452. package/dist/postinstall-inventory.json +440 -440
  453. package/dist/prepare.runtime-DCvn4PA9.js +815 -0
  454. package/dist/prepare.runtime.js +1 -1
  455. package/dist/probe-BM2lSGpq.js +1443 -0
  456. package/dist/probe-C-OcrhHU.js +241 -0
  457. package/dist/probe-C-zomfHC.js +74 -0
  458. package/dist/probe-CktNHncO.js +2 -0
  459. package/dist/probe-DvEzC7Yt.js +2 -0
  460. package/dist/probe-UYnzau7s.js +2205 -0
  461. package/dist/probe-VShtyoQP.js +45 -0
  462. package/dist/program-B1Zbl29n.js +111 -0
  463. package/dist/prompt-select-styled-BFiy7KFb.js +20 -0
  464. package/dist/provider-dispatcher-C_R0buEs.js +22 -0
  465. package/dist/provider-dispatcher-DMjvnMg1.js +2 -0
  466. package/dist/qr-cli-CIMpiVqT.js +2 -0
  467. package/dist/qr-cli-Chl8J_dU.js +349 -0
  468. package/dist/reaction-runtime-api-BNJMHeSk.js +116 -0
  469. package/dist/reactions-2lggXKxe.js +998 -0
  470. package/dist/register-service-commands-ayYMhoTG.js +71 -0
  471. package/dist/register.agent-j81xGvIr.js +247 -0
  472. package/dist/register.configure-Ceqf8SV4.js +15 -0
  473. package/dist/register.maintenance-CS92zJrF.js +438 -0
  474. package/dist/register.message-BYxUGLpc.js +329 -0
  475. package/dist/register.onboard-YkI-xo9t.js +81 -0
  476. package/dist/register.runtime-CmvxwCiw.js +81 -0
  477. package/dist/register.runtime.js +1 -1
  478. package/dist/register.setup-CNdTgu3R.js +150 -0
  479. package/dist/register.status-health-sessions-BX2GmWTc.js +1215 -0
  480. package/dist/register.subclis-BeGY5cHF.js +3 -0
  481. package/dist/register.subclis-COA10rio.js +29 -0
  482. package/dist/register.subclis-core-DBrCeLqN.js +243 -0
  483. package/dist/register.wallet-D2TECwG5.js +159 -0
  484. package/dist/reply-dispatch-runtime-CNsrlQxq.js +13 -0
  485. package/dist/reply-runtime-Cqu1YNSD.js +11 -0
  486. package/dist/reply.runtime-DjHQKkER.js +2 -0
  487. package/dist/reply.runtime.js +1 -1
  488. package/dist/restart-health-BvQlMuSR.js +2 -0
  489. package/dist/restart-health-Ddm7Ehby.js +202 -0
  490. package/dist/root-help-3kWD5VLI.js +44 -0
  491. package/dist/routes-BCZzdzw2.js +2 -0
  492. package/dist/routes-CA0DoP7S.js +3340 -0
  493. package/dist/rpc-BzPBQ5ql.js +61 -0
  494. package/dist/rpc.runtime-B8NzeUIK.js +21 -0
  495. package/dist/rpc.runtime.js +1 -1
  496. package/dist/run-delivery.runtime-Cx2tDADi.js +530 -0
  497. package/dist/run-delivery.runtime.js +1 -1
  498. package/dist/run-embedded.runtime-B9SGhBV5.js +4 -0
  499. package/dist/run-embedded.runtime.js +1 -1
  500. package/dist/run-execution-cli.runtime-D3gnOlIV.js +4 -0
  501. package/dist/run-execution-cli.runtime.js +1 -1
  502. package/dist/run-executor.runtime-BwsKj4NN.js +277 -0
  503. package/dist/run-executor.runtime.js +1 -1
  504. package/dist/run-main-CJYy9aeX.js +516 -0
  505. package/dist/run-subagent-registry.runtime-CNCRhpSK.js +2 -0
  506. package/dist/run-subagent-registry.runtime.js +1 -1
  507. package/dist/run-wait-o2Yo35xt.js +135 -0
  508. package/dist/runtime-Co5LW-cY.js +973 -0
  509. package/dist/runtime-D98eGt1z.js +9 -0
  510. package/dist/runtime-api-DLRKboKD.js +4 -0
  511. package/dist/runtime-api-DW1jDnXG.js +9 -0
  512. package/dist/runtime-api-DqL2zvW_.js +14 -0
  513. package/dist/runtime-api-DtRkIQdm.js +9 -0
  514. package/dist/runtime-embedded-pi.runtime-_1BnpUsH.js +2 -0
  515. package/dist/runtime-embedded-pi.runtime.js +1 -1
  516. package/dist/runtime-internal-OmAlLFWl.js +2 -0
  517. package/dist/runtime-options-DXi_dUFt.js +275 -0
  518. package/dist/runtime-schema-Cao36tlZ.js +27748 -0
  519. package/dist/scan-CMs-eSKD.js +523 -0
  520. package/dist/scan-DaCjqwXa.js +2 -0
  521. package/dist/secrets-cli-DsCbOPd8.js +2101 -0
  522. package/dist/security-cli-DWpmdyKz.js +486 -0
  523. package/dist/selection-BY0XwQb0.js +7737 -0
  524. package/dist/selection-UBLsVuoF.js +2 -0
  525. package/dist/send-B7W0wAaA.js +156 -0
  526. package/dist/send-DVXD9_3G.js +102 -0
  527. package/dist/send.runtime-BkSytPZj.js +2 -0
  528. package/dist/send.runtime.js +1 -1
  529. package/dist/server-7ozS-gsn.js +77 -0
  530. package/dist/server-LmKuO2X1.js +13 -0
  531. package/dist/server-context-BdRn7wbe.js +2 -0
  532. package/dist/server-context-CC4pOAPX.js +846 -0
  533. package/dist/server-node-events-B677Q3os.js +481 -0
  534. package/dist/server-plugin-bootstrap-CR8RjVLB.js +2 -0
  535. package/dist/server-plugin-bootstrap-CYpLXOkm.js +11124 -0
  536. package/dist/server-restart-sentinel-Btcc7BTE.js +697 -0
  537. package/dist/server.impl-BkehWe_p.js +12726 -0
  538. package/dist/service-BWLndtz9.js +941 -0
  539. package/dist/session-kill-http-BN9Ql6UD.js +110 -0
  540. package/dist/session-reset-service-hNFKFmB3.js +471 -0
  541. package/dist/session-route-DErqiFgk.js +93 -0
  542. package/dist/session-status.runtime-Cu7JU8_U.js +2 -0
  543. package/dist/session-status.runtime.js +1 -1
  544. package/dist/session-subagent-reactivation.runtime-Bbagi0__.js +2 -0
  545. package/dist/session-subagent-reactivation.runtime.js +1 -1
  546. package/dist/session-tab-registry-D-OCT26z.js +491 -0
  547. package/dist/session-visibility-Ddr5Ae9L.js +147 -0
  548. package/dist/sessions-helpers-D0Kf9Ps4.js +304 -0
  549. package/dist/sessions-history-http-BmKrK99v.js +383 -0
  550. package/dist/sessions-patch-BtQ1tAvw.js +309 -0
  551. package/dist/sessions-resolve-BGLrS6vF.js +174 -0
  552. package/dist/sessions.runtime-CsAKVqcP.js +2 -0
  553. package/dist/sessions.runtime.js +1 -1
  554. package/dist/setup-C7ziOemv.js +495 -0
  555. package/dist/setup-api-CFdE6Bv6.js +29 -0
  556. package/dist/setup-core-DWygxvIO.js +176 -0
  557. package/dist/setup-core-IwixXKp3.js +171 -0
  558. package/dist/setup-surface--KMZi-cs.js +286 -0
  559. package/dist/setup-surface-Bo-J3N7I.js +403 -0
  560. package/dist/setup-surface-C-7l8TcU.js +219 -0
  561. package/dist/setup.finalize-D7dPxVDl.js +539 -0
  562. package/dist/setup.gateway-config-DmLcj4KK.js +250 -0
  563. package/dist/shared-CpqCPySw.js +76 -0
  564. package/dist/shared-D-tbPAY5.js +198 -0
  565. package/dist/shared-Dlx0gCmP.js +121 -0
  566. package/dist/slash-state-Cfz0x49w.js +1911 -0
  567. package/dist/src-BcGXLl_7.js +3974 -0
  568. package/dist/startup-context-oaWUXB8r.js +312 -0
  569. package/dist/status-B6NTLfIA.js +2 -0
  570. package/dist/status-BH2PSbt-.js +3 -0
  571. package/dist/status-BdqF0YGr.js +397 -0
  572. package/dist/status-C8o-eOFh.js +209 -0
  573. package/dist/status-D9GTZEx3.js +190 -0
  574. package/dist/status-all-CYFjOCcB.js +498 -0
  575. package/dist/status-json-command-DRbt8OgF.js +84 -0
  576. package/dist/status-json-wzJiFRSB.js +14 -0
  577. package/dist/status-runtime-shared-CI8_EqUP.js +257 -0
  578. package/dist/status-subagents.runtime-DrQmaLAc.js +18 -0
  579. package/dist/status-subagents.runtime.js +1 -1
  580. package/dist/status-text-DyIs2f8P.js +236 -0
  581. package/dist/status-yhOw1Z3M.js +2 -0
  582. package/dist/status.gateway-connection.runtime-Bjp2AscT.js +2 -0
  583. package/dist/status.gateway-connection.runtime.js +1 -1
  584. package/dist/status.gather-Blc_DKTK.js +2 -0
  585. package/dist/status.gather-CqgbE6TR.js +292 -0
  586. package/dist/status.runtime-DkTncdN7.js +2 -0
  587. package/dist/status.runtime.js +1 -1
  588. package/dist/status.scan-Dc4FTGEf.js +65 -0
  589. package/dist/status.scan-overview-B0rKBZWW.js +379 -0
  590. package/dist/status.scan.fast-json-BhqvblxV.js +2 -0
  591. package/dist/status.scan.fast-json-DI6a0Tv9.js +132 -0
  592. package/dist/status.summary-CoKGnSoy.js +214 -0
  593. package/dist/status.summary-DrWqIllD.js +2 -0
  594. package/dist/subagent-announce-CgnWmHmH.js +351 -0
  595. package/dist/subagent-announce-delivery-DHVVJyea.js +726 -0
  596. package/dist/subagent-announce-output-d58DNnV0.js +364 -0
  597. package/dist/subagent-control-DsUeBdrz.js +506 -0
  598. package/dist/subagent-followup.runtime-BKyKE6nN.js +68 -0
  599. package/dist/subagent-followup.runtime.js +1 -1
  600. package/dist/subagent-orphan-recovery-_O6G65C-.js +305 -0
  601. package/dist/subagent-registry-BYuzIniG.js +1753 -0
  602. package/dist/subagent-registry-D0GzSMp0.js +3 -0
  603. package/dist/subagent-registry.runtime.js +1 -1
  604. package/dist/subagent-spawn-B6iHzxd0.js +1005 -0
  605. package/dist/system-cli-DPiT7dwA.js +59 -0
  606. package/dist/targets-DOHhYtK7.js +67 -0
  607. package/dist/task-executor-Bxg0f08x.js +360 -0
  608. package/dist/task-owner-access-Ymx7tKev.js +74 -0
  609. package/dist/task-registry-CQnnTGmN.js +2366 -0
  610. package/dist/task-registry-delivery-runtime-BSBXpDV6.js +2 -0
  611. package/dist/task-registry-delivery-runtime-D-Za0_P9.js +3 -0
  612. package/dist/task-registry.maintenance-BZpViOdb.js +2 -0
  613. package/dist/task-registry.maintenance-r46lgwwF.js +416 -0
  614. package/dist/telegram/token.js +1 -1
  615. package/dist/testing-2KPIcA5D.js +575 -0
  616. package/dist/text-report-BJwJgnEZ.js +587 -0
  617. package/dist/tool-resolution-CjlqPoX2.js +90 -0
  618. package/dist/tools-effective-inventory-C5X-_cBY.js +152 -0
  619. package/dist/tools-invoke-http-Cza5U0A9.js +206 -0
  620. package/dist/trash-K2na6Iz1.js +24 -0
  621. package/dist/tui-cli-l39_SXF6.js +4573 -0
  622. package/dist/update-cli-Iq8wyl0W.js +1728 -0
  623. package/dist/upgrade-1nwb0oPp.js +1226 -0
  624. package/dist/video-generation-task-status-Du2MUfI2.js +163 -0
  625. package/dist/wait-for-idle-before-flush-hJ-dtR6o.js +5986 -0
  626. package/package.json +1 -1
  627. package/dist/abort-BSgJMMy0.js +0 -201
  628. package/dist/abort.runtime-DSaqOkLi.js +0 -2
  629. package/dist/accounts-BYrE99V8.js +0 -107
  630. package/dist/accounts-Cw3U0GZS.js +0 -104
  631. package/dist/accounts-D3rbUrwm.js +0 -2
  632. package/dist/acp-cli-DeB5Rsjc.js +0 -2193
  633. package/dist/acp-spawn-CB_1HLYK.js +0 -1093
  634. package/dist/acp-spawn-DC-CjxhI.js +0 -2
  635. package/dist/acp-stateful-target-driver-B5hgjDME.js +0 -89
  636. package/dist/action-agents-de8OAj0v.js +0 -67
  637. package/dist/action-focus-CrHvpYTM.js +0 -132
  638. package/dist/action-help-DPabNXHZ.js +0 -7
  639. package/dist/action-info-CWAj-tKU.js +0 -101
  640. package/dist/action-kill-BvKs859S.js +0 -33
  641. package/dist/action-list-fiRrNbSX.js +0 -21
  642. package/dist/action-log-dn5JEtP_.js +0 -30
  643. package/dist/action-send-8A83W-vV.js +0 -39
  644. package/dist/action-spawn-VIuLWipE.js +0 -47
  645. package/dist/action-unfocus-D70HiUtC.js +0 -29
  646. package/dist/actions.runtime-BR7boyHX.js +0 -18
  647. package/dist/actions.runtime-GiNRcV0z.js +0 -5
  648. package/dist/agent-63D0MSuN.js +0 -2
  649. package/dist/agent-command-DpCldQUr.js +0 -874
  650. package/dist/agent-harness-runtime-CuxCjKHu.js +0 -144
  651. package/dist/agent-runner-utils-2KK7Tvwt.js +0 -239
  652. package/dist/agent-runner.runtime-B7-jeAE1.js +0 -3455
  653. package/dist/agent-runtime-B0LeqEC4.js +0 -18
  654. package/dist/agents-BKMfctCm.js +0 -5
  655. package/dist/agents-C_pD02YQ.js +0 -952
  656. package/dist/aliases-COyeblK9.js +0 -2
  657. package/dist/aliases-y-1ktZ4q.js +0 -96
  658. package/dist/api-C4eLLyHi.js +0 -139
  659. package/dist/api-DDQ1U9Y1.js +0 -3
  660. package/dist/api-DE42IEbe.js +0 -5
  661. package/dist/approval-gateway-resolver-B1vyfdsY.js +0 -29
  662. package/dist/approval-gateway-runtime-BspnMTAu.js +0 -2
  663. package/dist/approval-handler-runtime-BrOWxNQ7.js +0 -439
  664. package/dist/approval-native-runtime-amzGMScp.js +0 -729
  665. package/dist/attempt-execution.runtime-Bmw2z2TO.js +0 -509
  666. package/dist/attempt.prompt-helpers-BI35hO5A.js +0 -218
  667. package/dist/attempt.tool-run-context-CdMIupu1.js +0 -933
  668. package/dist/audit-CHoh7JgT.js +0 -939
  669. package/dist/audit.runtime-CZORspf5.js +0 -7
  670. package/dist/auth-9Vcx6Cmf.js +0 -383
  671. package/dist/auth-Dm3T2Azg.js +0 -2
  672. package/dist/auth-order-D4kOyxOC.js +0 -96
  673. package/dist/auth-order-XAV7PznW.js +0 -2
  674. package/dist/bash-tools-DCcnMXV5.js +0 -3
  675. package/dist/bash-tools-RvcvKJ6T.js +0 -2824
  676. package/dist/binding-routing-Bn1RJI3D.js +0 -85
  677. package/dist/binding-targets-DOB7nrnI.js +0 -121
  678. package/dist/bridge-server-CNv6vH_N.js +0 -113
  679. package/dist/browser-control-auth-BW5AsYZM.js +0 -2
  680. package/dist/browser-node-runtime-e_5J-t2m.js +0 -12
  681. package/dist/browser-profiles-V--grSvf.js +0 -2
  682. package/dist/browser-runtime-K7qKfdJO.js +0 -387
  683. package/dist/browser-setup-tools-RQ8B4E_8.js +0 -13
  684. package/dist/build-IWaXKaQo.js +0 -550
  685. package/dist/call-DMoCOQgN.js +0 -329
  686. package/dist/call-DR29cjQ8.js +0 -3
  687. package/dist/call.runtime-CPFzabci.js +0 -2
  688. package/dist/capability-cli-BqaYg27d.js +0 -1401
  689. package/dist/catchup-CkMkjMjm.js +0 -300
  690. package/dist/channel-7-Cy5vdE.js +0 -1320
  691. package/dist/channel-B0LKbN9a.js +0 -1802
  692. package/dist/channel-C5SikvTn.js +0 -1174
  693. package/dist/channel-CGef-OxR.js +0 -1100
  694. package/dist/channel-CqHnAQJn.js +0 -350
  695. package/dist/channel-D3_wWplf.js +0 -595
  696. package/dist/channel-DRek8wwh.js +0 -453
  697. package/dist/channel-DYRwgk_C.js +0 -297
  698. package/dist/channel-DxbCZT0P.js +0 -226
  699. package/dist/channel-core-a5qj8qsH.js +0 -5
  700. package/dist/channel-inbound-CozRn3n-.js +0 -31
  701. package/dist/channel-plugin-runtime-DsiFaHL9.js +0 -771
  702. package/dist/channel-runtime-C8zLNzEP.js +0 -425
  703. package/dist/channel-v0PxXI_J.js +0 -491
  704. package/dist/channel-yHVk-YRx.js +0 -840
  705. package/dist/channel.runtime-C1rseTPL.js +0 -430
  706. package/dist/channel.runtime-Ci6Q1Cuv.js +0 -576
  707. package/dist/channel.runtime-CvOa3gYA.js +0 -109
  708. package/dist/channel.runtime-CwZodUOR.js +0 -34702
  709. package/dist/channel.runtime-DaP1Ann2.js +0 -89
  710. package/dist/channel.runtime-ie3egHX0.js +0 -4
  711. package/dist/channel.runtime-p_ELA91e.js +0 -2364
  712. package/dist/channel.setup-D1_1xjgF.js +0 -10
  713. package/dist/channels-Cx8uAXLx.js +0 -827
  714. package/dist/channels-cli-BCCSvZCu.js +0 -267
  715. package/dist/chat-CjH9IZPG.js +0 -2757
  716. package/dist/clawbot-cli-BW8txesR.js +0 -9
  717. package/dist/cli-BosrhIZ9.js +0 -72
  718. package/dist/cli-CHvS1B5Q.js +0 -2
  719. package/dist/cli-DJz9OCkF.js +0 -219
  720. package/dist/cli-DOiNFMc7.js +0 -2
  721. package/dist/cli-runner-CHk3q2MH.js +0 -286
  722. package/dist/cli-runner.runtime-mvuDOXO3.js +0 -4
  723. package/dist/cli-runner.runtime-rlm7f8Qi.js +0 -3
  724. package/dist/cli.runtime-BbTMs2tV.js +0 -1261
  725. package/dist/client-D1dJTyU7.js +0 -2722
  726. package/dist/client-JBM4I6b2.js +0 -138
  727. package/dist/command-auth-BbFsneAK.js +0 -76
  728. package/dist/command-config-resolution-DXhw734i.js +0 -23
  729. package/dist/command-config-resolution-poOTs26D.js +0 -2
  730. package/dist/command-config-resolution.runtime-BgBhROMr.js +0 -2
  731. package/dist/command-registry-BVFXhcOs.js +0 -4
  732. package/dist/command-registry-ClQXv5Dl.js +0 -9
  733. package/dist/command-registry-core-CAhTYQrv.js +0 -104
  734. package/dist/command-secret-gateway-DFTMkW7_.js +0 -528
  735. package/dist/command-status.runtime-DGPtSexy.js +0 -87
  736. package/dist/commands-acp-_nV8wWKt.js +0 -77
  737. package/dist/commands-compact.runtime-_vHyAiKz.js +0 -10
  738. package/dist/commands-handlers.runtime-CLi0aZTH.js +0 -4596
  739. package/dist/commands-status-HRJORs2e.js +0 -16
  740. package/dist/commands-status.runtime-CM9-gifT.js +0 -3
  741. package/dist/commands-subagents-control.runtime-BKBLELS1.js +0 -3
  742. package/dist/commands-subagents-control.runtime-Bv0x4ibi.js +0 -2
  743. package/dist/commands-system-prompt-B139cQlX.js +0 -2
  744. package/dist/commands-system-prompt-DuaobSBO.js +0 -158
  745. package/dist/commands.runtime-DSCXdZki.js +0 -166
  746. package/dist/compact-LzyN5PMu.js +0 -1118
  747. package/dist/compact.runtime-BJLpfnFS.js +0 -12
  748. package/dist/completion-cli-D8STecUS.js +0 -313
  749. package/dist/config-BrdI5ZyV.js +0 -248
  750. package/dist/config-cli-CdYXdQ9l.js +0 -1073
  751. package/dist/configure-07tFzclw.js +0 -1244
  752. package/dist/configure-CbEEjQYo.js +0 -2
  753. package/dist/connect-options-DqbkNROZ.js +0 -699
  754. package/dist/control-auth-DoDKg0VV.js +0 -125
  755. package/dist/control-service-BGluFHoB.js +0 -156
  756. package/dist/control-ui/assets/agents-DIlUBXrj.js +0 -949
  757. package/dist/control-ui/assets/channel-config-extras-BGlC1vk-.js +0 -2
  758. package/dist/control-ui/assets/channels-DkrHc4ne.js +0 -353
  759. package/dist/control-ui/assets/cron-B-r1qhzN.js +0 -933
  760. package/dist/control-ui/assets/de-4NcQrfyt.js +0 -2
  761. package/dist/control-ui/assets/debug-BNsI96cZ.js +0 -94
  762. package/dist/control-ui/assets/es-CrrRGWtR.js +0 -2
  763. package/dist/control-ui/assets/format-DPX2rt4X.js +0 -9
  764. package/dist/control-ui/assets/fr-D5W-tLOJ.js +0 -2
  765. package/dist/control-ui/assets/id-D553RZfz.js +0 -2
  766. package/dist/control-ui/assets/index-BNEyEtwP.js +0 -6308
  767. package/dist/control-ui/assets/instances-18Qi3xmu.js +0 -57
  768. package/dist/control-ui/assets/ja-JP-BqS1ssGF.js +0 -2
  769. package/dist/control-ui/assets/ko-CaE3K0VZ.js +0 -2
  770. package/dist/control-ui/assets/logs-DLWCXFsv.js +0 -74
  771. package/dist/control-ui/assets/nodes-BYrv5bpJ.js +0 -436
  772. package/dist/control-ui/assets/pl-CvV8uM6B.js +0 -2
  773. package/dist/control-ui/assets/pt-BR-DhkGCPIb.js +0 -2
  774. package/dist/control-ui/assets/sessions-Dzj0Stfl.js +0 -306
  775. package/dist/control-ui/assets/skills-CTsU9T-x.js +0 -314
  776. package/dist/control-ui/assets/skills-shared-DkdwCfRw.js +0 -11
  777. package/dist/control-ui/assets/string-coerce-Dq6kwRii.js +0 -3
  778. package/dist/control-ui/assets/th-BWa0iFp9.js +0 -2
  779. package/dist/control-ui/assets/tr-CIyWcYOQ.js +0 -2
  780. package/dist/control-ui/assets/uk-Dddui7S3.js +0 -2
  781. package/dist/control-ui/assets/wallet-DRK53ouz.js +0 -93
  782. package/dist/control-ui/assets/zh-CN-DrnaMCjT.js +0 -2
  783. package/dist/control-ui/assets/zh-TW-AAoU4b-j.js +0 -2
  784. package/dist/control-ui-e8ifrzMw.js +0 -664
  785. package/dist/conversation-id-D_Z9mqfh.js +0 -235
  786. package/dist/conversation-id-Dp8o7Hf7.js +0 -38
  787. package/dist/conversation-runtime-B1TCRdfm.js +0 -31
  788. package/dist/core-BTxiBxhe.js +0 -275
  789. package/dist/cron-cli-D5WHyG5z.js +0 -713
  790. package/dist/daemon-cli-CbJ5WTkZ.js +0 -12
  791. package/dist/delegate-Bvy2iFqj.js +0 -64
  792. package/dist/detached-task-runtime-CdQlbOaF.js +0 -73
  793. package/dist/devices-cli-CHKYPFQk.js +0 -496
  794. package/dist/diagnostics-DXBnZZDV.js +0 -154
  795. package/dist/direct-dm-DscQrdWj.js +0 -64
  796. package/dist/dispatch-CsJVa2_C.js +0 -1131
  797. package/dist/dispatch-acp-C5r7kMjF.js +0 -981
  798. package/dist/dispatch-acp-manager.runtime-BmaeIQYw.js +0 -3
  799. package/dist/dispatch-acp.runtime-CrPqsjE7.js +0 -19
  800. package/dist/doctor-device-pairing-BIWNe_Jn.js +0 -307
  801. package/dist/doctor-gateway-daemon-flow-B1w_mTCi.js +0 -250
  802. package/dist/doctor-gateway-health-PGrHhbuk.js +0 -60
  803. package/dist/doctor-health-CjIXOYaZ.js +0 -59
  804. package/dist/doctor-health-contributions-Gewam3A0.js +0 -486
  805. package/dist/doctor-prompter-C_nZk0eT.js +0 -56
  806. package/dist/doctor-workspace-status-HNtMY9tr.js +0 -75
  807. package/dist/dreaming-6bEi10m2.js +0 -1574
  808. package/dist/dreaming-narrative-C8-bcUG0.js +0 -595
  809. package/dist/embedded-gateway-stub.runtime-DBFo1O2n.js +0 -9
  810. package/dist/embeddings-http-DI8wVPpp.js +0 -205
  811. package/dist/exec-approvals-cli-CElurcBk.js +0 -498
  812. package/dist/fallbacks-B5Ph7HO-.js +0 -31
  813. package/dist/fallbacks-DVBCWaCR.js +0 -2
  814. package/dist/fallbacks-shared-DJEGkADy.js +0 -111
  815. package/dist/gateway-CjtKuAFO.js +0 -115
  816. package/dist/gateway-cli-UeLtu8Gv.js +0 -1325
  817. package/dist/gateway-rpc-E2ZcD2Pb.js +0 -14
  818. package/dist/gateway-rpc.runtime-D9oxEGVM.js +0 -23
  819. package/dist/gateway-runtime-DUkvmYNT.js +0 -15
  820. package/dist/gateway-status-B2yemMI1.js +0 -584
  821. package/dist/genesis-tools-DkQyKJJH.js +0 -8998
  822. package/dist/genesis-tools.runtime-C--92dxG.js +0 -2
  823. package/dist/get-reply-from-config.runtime-DVW2Z3Xz.js +0 -2
  824. package/dist/get-reply-qcf7h9-q.js +0 -3879
  825. package/dist/graph-users-C-ZMFjxP.js +0 -1337
  826. package/dist/health-CQgtKb-a.js +0 -469
  827. package/dist/health-CVQcF_SU.js +0 -3
  828. package/dist/heartbeat-runner-BMpI76oC.js +0 -1292
  829. package/dist/heartbeat-runner-tlqZ2QRH.js +0 -5
  830. package/dist/heartbeat-runner.runtime-BLaJ1moj.js +0 -4
  831. package/dist/hooks-cli-UJV1DwY_.js +0 -433
  832. package/dist/http-endpoint-helpers-BKYK0lXJ.js +0 -41
  833. package/dist/http-utils-CSMhLOmU.js +0 -924
  834. package/dist/image-fallbacks-B1kkwX5i.js +0 -31
  835. package/dist/image-fallbacks-BLVKYnSI.js +0 -2
  836. package/dist/inbound-reply-dispatch-KxpaEPy-.js +0 -73
  837. package/dist/infra-runtime-B7Bioutr.js +0 -39
  838. package/dist/init-BbDgno6y.js +0 -59
  839. package/dist/library-wOAms75w.js +0 -45
  840. package/dist/lifecycle--fVDSapD.js +0 -229
  841. package/dist/lifecycle-DsoPNmHR.js +0 -571
  842. package/dist/lifecycle.runtime-B6D7-MbQ.js +0 -2
  843. package/dist/list-B99x_eEq.js +0 -2
  844. package/dist/list-Bg9vO-vK.js +0 -1201
  845. package/dist/list-CJFvAL5B.js +0 -130
  846. package/dist/list-CXO2Pv7s.js +0 -2
  847. package/dist/list.probe-DvT83QeD.js +0 -419
  848. package/dist/llm-slug-generator-Dk-2o6wu.js +0 -79
  849. package/dist/load-config-DcSdLvU4.js +0 -35
  850. package/dist/local-dispatch.runtime-CeUL5zUz.js +0 -8
  851. package/dist/logs-cli-CkO4A9e_.js +0 -265
  852. package/dist/logs-cli.runtime-CjZMd8Ps.js +0 -2
  853. package/dist/main-session-restart-recovery-Yaowxz1V.js +0 -206
  854. package/dist/managed-image-attachments-BRkGH8id.js +0 -635
  855. package/dist/managed-image-attachments-CVQmQz19.js +0 -2
  856. package/dist/manager-ClvLmUep.js +0 -2057
  857. package/dist/manager-DLd5DOHM.js +0 -2
  858. package/dist/markdown-to-line-DdcFUlNP.js +0 -790
  859. package/dist/mcp-cli-Bg0n1yvO.js +0 -724
  860. package/dist/mcp-http-DwN4JtLF.js +0 -529
  861. package/dist/memory-core-host-runtime-cli-DokggwF4.js +0 -9
  862. package/dist/message-A6K1Uln8.js +0 -231
  863. package/dist/message-action-runner-By12iwmY.js +0 -1406
  864. package/dist/message-action-runner-DB7vQjDX.js +0 -2
  865. package/dist/message-actions-p0tyiJsp.js +0 -143
  866. package/dist/message.gateway.runtime-x9oPkfCV.js +0 -2
  867. package/dist/method-scopes-C2W7BZE-.js +0 -208
  868. package/dist/models-cli-BLajRwW5.js +0 -219
  869. package/dist/models-http-CbY-2ddw.js +0 -92
  870. package/dist/monitor-2gr47zvz.js +0 -2
  871. package/dist/monitor-CG9Xn5kb.js +0 -1237
  872. package/dist/monitor-CJXWP42d.js +0 -1661
  873. package/dist/monitor-V8PDbadr.js +0 -1459
  874. package/dist/monitor-Yea6MUcs.js +0 -671
  875. package/dist/monitor-_RMYsKC-.js +0 -788
  876. package/dist/monitor-auth-Ds-_E_h_.js +0 -207
  877. package/dist/monitor-processing-C7thbjUR.js +0 -1974
  878. package/dist/monitor.runtime-TBmnIKD-.js +0 -2
  879. package/dist/monitor.webhook-DSkuylzE.js +0 -180
  880. package/dist/msteams-KM-ToWtn.js +0 -35
  881. package/dist/native-hook-relay-BDz0eLdj.js +0 -519
  882. package/dist/nextcloud-talk-Bx1j4jh0.js +0 -17
  883. package/dist/node-cli-aEN8rLyY.js +0 -2506
  884. package/dist/nodes-cli-Dv0SFhFx.js +0 -1046
  885. package/dist/nodes-utils-DQExHgOK.js +0 -84
  886. package/dist/nodes.helpers-BkElz_SG.js +0 -34
  887. package/dist/notify-DH8p0jbK.js +0 -315
  888. package/dist/onboard-DKgQvVgg.js +0 -632
  889. package/dist/onboard-helpers-BLaaRiIQ.js +0 -204
  890. package/dist/onboard-helpers-CxDujxN_.js +0 -6
  891. package/dist/onboard-remote-BHcS99gt.js +0 -193
  892. package/dist/onboard-remote-CxD-xQ89.js +0 -2
  893. package/dist/onboard-skills-D2X91a-l.js +0 -2
  894. package/dist/onboard-skills-Z8VWQOTM.js +0 -134
  895. package/dist/openai-http-D6U8-gsV.js +0 -500
  896. package/dist/openresponses-http-8Gzpx-dY.js +0 -1128
  897. package/dist/operator-approvals-client-CPBdQHpS.js +0 -68
  898. package/dist/outbound.runtime-DyUVsM-o.js +0 -2
  899. package/dist/pair-command-approve-iifXVm-A.js +0 -44
  900. package/dist/persistent-bindings.lifecycle-D0KiOOHL.js +0 -2
  901. package/dist/persistent-bindings.lifecycle-Dg5f2-ZX.js +0 -85
  902. package/dist/pi-embedded-CIvfsFDK.js +0 -2905
  903. package/dist/pi-embedded-DfKObnKr.js +0 -4
  904. package/dist/pi-embedded.runtime-CSRgPcMe.js +0 -4
  905. package/dist/pi-tool-definition-adapter-BK1Jgz8u.js +0 -217
  906. package/dist/pi-tools-xZFkQObl.js +0 -1057
  907. package/dist/pi-tools.before-tool-call-Cvql1Guc.js +0 -433
  908. package/dist/pi-tools.before-tool-call-DM-LeYVv.js +0 -2
  909. package/dist/plugin-BCMcHdm8.js +0 -12195
  910. package/dist/plugin-enabled-CfU6MzpX.js +0 -140
  911. package/dist/plugin-registration-5A3P83yn.js +0 -23
  912. package/dist/plugin-service-C3tJzbuH.js +0 -2890
  913. package/dist/policy-C4Ko4jxG.js +0 -328
  914. package/dist/prepare.runtime-D73JEx7U.js +0 -815
  915. package/dist/probe-3YRw5INl.js +0 -2
  916. package/dist/probe-B1B8f2xn.js +0 -74
  917. package/dist/probe-BOowi-Kq.js +0 -45
  918. package/dist/probe-BTjPGJW1.js +0 -2
  919. package/dist/probe-BcltnB3e.js +0 -2205
  920. package/dist/probe-DIRzDUPK.js +0 -1443
  921. package/dist/probe-r4-jBkoJ.js +0 -241
  922. package/dist/program-Dfu5UhC1.js +0 -111
  923. package/dist/prompt-select-styled-Dbu9qalJ.js +0 -20
  924. package/dist/provider-dispatcher-4wt-ZeZZ.js +0 -2
  925. package/dist/provider-dispatcher-C2UhWO1m.js +0 -22
  926. package/dist/qr-cli-BuDd3ifv.js +0 -2
  927. package/dist/qr-cli-DqP37LYz.js +0 -349
  928. package/dist/reaction-runtime-api-Bvz0Pveq.js +0 -116
  929. package/dist/reactions-DN1UVx3u.js +0 -998
  930. package/dist/register-service-commands-DwSQt0X_.js +0 -71
  931. package/dist/register.agent-clbTKCyG.js +0 -247
  932. package/dist/register.configure-ByRQumwS.js +0 -15
  933. package/dist/register.maintenance-irO_yFnN.js +0 -438
  934. package/dist/register.message-BV2yRYIp.js +0 -329
  935. package/dist/register.onboard-DNcKmHVS.js +0 -81
  936. package/dist/register.runtime-BfeanYPK.js +0 -81
  937. package/dist/register.setup-DtWiNL2V.js +0 -150
  938. package/dist/register.status-health-sessions-D0SdMPNv.js +0 -1215
  939. package/dist/register.subclis-CQQMGIv7.js +0 -3
  940. package/dist/register.subclis-CYMsqdxE.js +0 -29
  941. package/dist/register.subclis-core-DWDlwb58.js +0 -243
  942. package/dist/register.wallet-CR3_wMxj.js +0 -159
  943. package/dist/reply-dispatch-runtime-C3eU1JDN.js +0 -13
  944. package/dist/reply-runtime-CDVJcLIY.js +0 -11
  945. package/dist/reply.runtime-CreZjwrI.js +0 -2
  946. package/dist/restart-health-D6gHXWN7.js +0 -202
  947. package/dist/restart-health-DPEaVmNm.js +0 -2
  948. package/dist/root-help-CtpK6G48.js +0 -44
  949. package/dist/routes-BLmIMxHE.js +0 -2
  950. package/dist/routes-DVK0yoCk.js +0 -3340
  951. package/dist/rpc-B284aspW.js +0 -61
  952. package/dist/rpc.runtime-_Lr6h1P2.js +0 -21
  953. package/dist/run-delivery.runtime-Vl9zviox.js +0 -530
  954. package/dist/run-embedded.runtime-BxfpUMvk.js +0 -4
  955. package/dist/run-execution-cli.runtime-DuoOsLmQ.js +0 -4
  956. package/dist/run-executor.runtime-CnNmatiS.js +0 -277
  957. package/dist/run-main-Bk3B1Ycl.js +0 -516
  958. package/dist/run-subagent-registry.runtime-DYsO0_RA.js +0 -2
  959. package/dist/run-wait-BMbf92lX.js +0 -135
  960. package/dist/runtime-CVfSbgJg.js +0 -973
  961. package/dist/runtime-D83Zw8_L.js +0 -9
  962. package/dist/runtime-api-BjXPh772.js +0 -9
  963. package/dist/runtime-api-BqLJECf1.js +0 -14
  964. package/dist/runtime-api-D0lP9bs_.js +0 -9
  965. package/dist/runtime-api-SC4yZOqC.js +0 -4
  966. package/dist/runtime-embedded-pi.runtime-BqxRowCu.js +0 -2
  967. package/dist/runtime-internal-BoBPttX5.js +0 -2
  968. package/dist/runtime-options-0mbgwVcn.js +0 -275
  969. package/dist/runtime-schema-DnS1dcv9.js +0 -27748
  970. package/dist/scan-0tDfQcbh.js +0 -523
  971. package/dist/scan-kap7E7fQ.js +0 -2
  972. package/dist/secrets-cli-C-MP3qxL.js +0 -2101
  973. package/dist/security-cli-YiMwABOV.js +0 -486
  974. package/dist/selection-B1YFEfhn.js +0 -7737
  975. package/dist/selection-yj1VeFgc.js +0 -2
  976. package/dist/send-ChDswQ8K.js +0 -102
  977. package/dist/send-m-3Wh6Ul.js +0 -156
  978. package/dist/send.runtime-HuAZWRMT.js +0 -2
  979. package/dist/server-1tAvo2uk.js +0 -77
  980. package/dist/server-CgWhiZaZ.js +0 -13
  981. package/dist/server-context-DC7VPNrP.js +0 -846
  982. package/dist/server-context-fbmj6rsw.js +0 -2
  983. package/dist/server-node-events-BMfbJz4h.js +0 -481
  984. package/dist/server-plugin-bootstrap-32-_V8s1.js +0 -11103
  985. package/dist/server-plugin-bootstrap-BOy3f_kr.js +0 -2
  986. package/dist/server-restart-sentinel-JaqT_c7z.js +0 -697
  987. package/dist/server.impl-ozoUfbJY.js +0 -12724
  988. package/dist/service-CHmvDejV.js +0 -926
  989. package/dist/session-kill-http-Bi16FXzX.js +0 -110
  990. package/dist/session-reset-service-0D6xi-ak.js +0 -471
  991. package/dist/session-route-CdIF_-j8.js +0 -93
  992. package/dist/session-status.runtime-BenL5h6z.js +0 -2
  993. package/dist/session-subagent-reactivation.runtime-VrwlEPse.js +0 -2
  994. package/dist/session-tab-registry-Cch43wvs.js +0 -491
  995. package/dist/session-visibility-BUY4AKE8.js +0 -147
  996. package/dist/sessions-helpers-C1ie4VY2.js +0 -304
  997. package/dist/sessions-history-http-DvqOoKZP.js +0 -383
  998. package/dist/sessions-patch-DIqqzD_r.js +0 -309
  999. package/dist/sessions-resolve-BI24rrsW.js +0 -174
  1000. package/dist/sessions.runtime-B8dy_jZO.js +0 -2
  1001. package/dist/setup-CIGRiYma.js +0 -495
  1002. package/dist/setup-api-C2z6aEmf.js +0 -29
  1003. package/dist/setup-core-DwswrxD9.js +0 -171
  1004. package/dist/setup-core-OrNOJ5Dt.js +0 -176
  1005. package/dist/setup-surface-DRkiJObE.js +0 -286
  1006. package/dist/setup-surface-Duar853m.js +0 -403
  1007. package/dist/setup-surface-te0vyu3k.js +0 -219
  1008. package/dist/setup.finalize-C4D2iTZK.js +0 -539
  1009. package/dist/setup.gateway-config-js5kJWDU.js +0 -250
  1010. package/dist/shared-BjQB2kM2.js +0 -76
  1011. package/dist/shared-CJH2czP-.js +0 -121
  1012. package/dist/shared-CcLhf2wk.js +0 -198
  1013. package/dist/slash-state-CKJGZHok.js +0 -1911
  1014. package/dist/src-CZ8XTjkB.js +0 -3974
  1015. package/dist/startup-context-BMpCePC2.js +0 -312
  1016. package/dist/status-BFeYb9-f.js +0 -2
  1017. package/dist/status-BOleDqu5.js +0 -190
  1018. package/dist/status-BgCUJLW2.js +0 -397
  1019. package/dist/status-DJ1sF6YO.js +0 -209
  1020. package/dist/status-DYJ_8ZJ7.js +0 -2
  1021. package/dist/status-all-CtEWqGEX.js +0 -498
  1022. package/dist/status-json-DTxIuLgj.js +0 -14
  1023. package/dist/status-json-command-CcMv7nYt.js +0 -84
  1024. package/dist/status-runtime-shared-DZDRmXg3.js +0 -257
  1025. package/dist/status-subagents.runtime-C-hQle1W.js +0 -18
  1026. package/dist/status-tDmBvO9G.js +0 -3
  1027. package/dist/status-text-BUpcmvrn.js +0 -236
  1028. package/dist/status.gateway-connection.runtime-wLOiGcpu.js +0 -2
  1029. package/dist/status.gather-B6sN0B8c.js +0 -2
  1030. package/dist/status.gather-BuL7jLue.js +0 -292
  1031. package/dist/status.runtime-_vK1iN8J.js +0 -2
  1032. package/dist/status.scan-CzfgmgTG.js +0 -65
  1033. package/dist/status.scan-overview-D_a6XXNl.js +0 -379
  1034. package/dist/status.scan.fast-json-Cyohwc40.js +0 -2
  1035. package/dist/status.scan.fast-json-EjCk_IC5.js +0 -132
  1036. package/dist/status.summary-DOPlWkvO.js +0 -2
  1037. package/dist/status.summary-SF9yDHoG.js +0 -214
  1038. package/dist/subagent-announce-delivery-BETmbzks.js +0 -726
  1039. package/dist/subagent-announce-eXVKLvvC.js +0 -351
  1040. package/dist/subagent-announce-output-DCnvTZwP.js +0 -364
  1041. package/dist/subagent-control-DOW_fAs-.js +0 -506
  1042. package/dist/subagent-followup.runtime-Bfdcsho3.js +0 -68
  1043. package/dist/subagent-orphan-recovery-B-_eOw_g.js +0 -305
  1044. package/dist/subagent-registry-B1giKhqf.js +0 -1753
  1045. package/dist/subagent-registry-C5VQw19R.js +0 -3
  1046. package/dist/subagent-spawn-C9Tn7SaR.js +0 -1005
  1047. package/dist/system-cli-CxNpT3gx.js +0 -59
  1048. package/dist/targets-dj8UJRJ6.js +0 -67
  1049. package/dist/task-executor-ICSmgHPw.js +0 -360
  1050. package/dist/task-owner-access-Do_-kA0r.js +0 -74
  1051. package/dist/task-registry-D5vWx8tX.js +0 -2366
  1052. package/dist/task-registry-delivery-runtime-NVZZb9QU.js +0 -3
  1053. package/dist/task-registry-delivery-runtime-yimT8mwg.js +0 -2
  1054. package/dist/task-registry.maintenance-B-hFV6uU.js +0 -2
  1055. package/dist/task-registry.maintenance-vCNDvYID.js +0 -416
  1056. package/dist/testing-DggItyHP.js +0 -575
  1057. package/dist/text-report-kxNx8vB8.js +0 -587
  1058. package/dist/tool-resolution-CfvU1QKh.js +0 -90
  1059. package/dist/tools-effective-inventory-JUjxx1jC.js +0 -152
  1060. package/dist/tools-invoke-http-B67672Wx.js +0 -206
  1061. package/dist/trash--zyy7_il.js +0 -24
  1062. package/dist/tui-cli-C9l1W8a5.js +0 -4573
  1063. package/dist/update-cli-CWD6kp5u.js +0 -1728
  1064. package/dist/upgrade-CtywVoEi.js +0 -1226
  1065. package/dist/video-generation-task-status-DtZ_rioL.js +0 -163
  1066. package/dist/wait-for-idle-before-flush-s-nJUXPe.js +0 -5986
@@ -0,0 +1,4596 @@
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-CRPT2IUI.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-DcheqK7J.js";
18
+ import { g as GATEWAY_CLIENT_NAMES, h as GATEWAY_CLIENT_MODES, r as isInternalMessageChannel, u as normalizeMessageChannel } from "./message-channel-D2Y7UhTM.js";
19
+ import { n as resolveChannelApprovalCapability } from "./plugins-CV-ZD2kz.js";
20
+ import { m as triggerInternalHook, n as createInternalHookEvent } from "./internal-hooks-B2c7dDLy.js";
21
+ import { x as prepareProviderRuntimeAuth } from "./provider-runtime-C4zeL6Ny.js";
22
+ import { t as ensureGenesisModelsJson } from "./models-config-Bvkqd1Ce.js";
23
+ import { g as resolveResponseUsageMode, m as normalizeUsageDisplay } from "./thinking-B2FO5LMN.js";
24
+ import { t as requireApiKey } from "./model-auth-runtime-shared-Btrjl2l2.js";
25
+ import { i as discoverModels, r as discoverAuthStorage } from "./pi-model-discovery-CHQCNHGr.js";
26
+ import { a as resolveSessionFilePathOptions, i as resolveSessionFilePath, r as resolveDefaultSessionStorePath } from "./paths-CyaKOUSX.js";
27
+ import { t as loadSessionStore } from "./store-load-CyttjdF2.js";
28
+ import { o as resolveFreshSessionTotalTokens } from "./types--vJusqfs.js";
29
+ import { o as updateSessionStore } from "./store-Cxyeks39.js";
30
+ import { t as extractDeliveryInfo } from "./sessions-BGtpdShC.js";
31
+ import { i as formatUsd, r as formatTokenCount } from "./usage-format-DV4f3qrf.js";
32
+ import { n as stripInboundMetadata } from "./strip-inbound-meta-BAmHhTY1.js";
33
+ import { t as diagnosticLogger } from "./diagnostic-runtime-BTAjlY1U.js";
34
+ import { n as redactSupportString } from "./diagnostic-support-redaction-DWtXt1M-.js";
35
+ 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-BY0XwQb0.js";
36
+ 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-BHFP4a6t.js";
37
+ import { t as analyzeBootstrapBudget } from "./bootstrap-budget-Daai1iOb.js";
38
+ import { h as resolveBootstrapTotalMaxChars, p as resolveBootstrapMaxChars } from "./pi-embedded-helpers-CdvDVhim.js";
39
+ import { n as resolveSandboxRuntimeStatus } from "./runtime-status-BazcwOVG.js";
40
+ import { i as resolveImageSanitizationLimits, n as sanitizeImageBlocks } from "./tool-images-Bifa6Wt5.js";
41
+ import { r as getApiKeyForModel } from "./model-auth-DNrwXaA3.js";
42
+ import { t as registerProviderStreamForModel } from "./provider-stream-BdJEcrTS.js";
43
+ import { m as stripToolResultDetails } from "./transport-stream-shared-BYZXSRl5.js";
44
+ import { i as unsetConfiguredMcpServer, r as setConfiguredMcpServer, t as listConfiguredMcpServers } from "./mcp-config-lGwUXp0E.js";
45
+ import { t as EmbeddedBlockChunker } from "./pi-embedded-block-chunker-Co4_Aktj.js";
46
+ import { r as callGateway } from "./call-45FewBaL.js";
47
+ import { d as writeRestartSentinel, n as buildRestartSuccessContinuation, r as formatDoctorNonInteractiveHint, s as removeRestartSentinelFile } from "./restart-sentinel-Di2uaSq1.js";
48
+ import { l as triggerGenesisRestart, o as scheduleGatewaySigusr1Restart } from "./restart-Dk2VCO5_.js";
49
+ import { i as resolveReplyToMode } from "./reply-threading-ChLAMydA.js";
50
+ import { _ as authorizeConfigWriteShared, b as resolveConfigWriteTargetFromPathShared, v as canBypassConfigWritePolicyShared, y as formatConfigWriteDeniedMessageShared } from "./channel-config-helpers-BVjCjs2H.js";
51
+ import { n as formatTaskStatusDetail, r as formatTaskStatusTitle, t as buildTaskStatusSnapshot } from "./task-status-Cw5Ekoq5.js";
52
+ import { a as clearSessionQueues } from "./queue-CAmq33Dw.js";
53
+ import { r as getSessionBindingService } from "./session-binding-service-CW4KC3dE.js";
54
+ import { h as replyRunRegistry, i as getActiveEmbeddedRunSnapshot } from "./runs-B8k9nDbi.js";
55
+ import "./diagnostic-D7UX-XQn.js";
56
+ import { t as formatDurationCompact } from "./format-duration-CIk89v72.js";
57
+ import "./sandbox-DcxncIId.js";
58
+ import { t as buildSystemPromptReport } from "./system-prompt-report-9yK0WPeJ.js";
59
+ import { n as estimateTokensFromChars } from "./cjk-chars-Cw_Ytzp3.js";
60
+ import { i as streamWithPayloadPatch } from "./moonshot-thinking-stream-wrappers-BWKJoBJT.js";
61
+ import { r as resolveModelWithRegistry } from "./model-DEdIMmhk.js";
62
+ import { i as matchPluginCommand, n as executePluginCommand } from "./commands-CQhNQh_q.js";
63
+ import { t as isApprovalNotFoundError } from "./approval-errors-BuFHKM2N.js";
64
+ import { r as normalizeCommandBody } from "./commands-registry-normalize-C2LvT7oh.js";
65
+ import { i as setAbortMemory, r as isAbortTrigger } from "./abort-primitives-BqRm94Ro.js";
66
+ import "./commands-registry-aHwimQdh.js";
67
+ import { n as formatTimeAgo } from "./format-relative-DBI0ON8M.js";
68
+ import { o as stripMentions, s as stripStructuralPrefixes } from "./mentions-UVaAO0Q0.js";
69
+ import { n as setChannelConversationBindingMaxAgeBySessionKey, t as setChannelConversationBindingIdleTimeoutBySessionKey } from "./conversation-bindings-DdUezI6O.js";
70
+ import { a as readChannelAllowFromStore, l as removeChannelAllowFromStoreEntry, t as addChannelAllowFromStoreEntry } from "./pairing-store-DtxyQ78F.js";
71
+ import { i as installPluginFromPath, r as installPluginFromNpmSpec } from "./install-CC5wRTCa.js";
72
+ import { l as resolveArchiveKind } from "./archive-c4xNWIrP.js";
73
+ import { n as isImplicitSameChatApprovalAuthorization } from "./approval-auth-helpers-B5ca_8Zq.js";
74
+ import { n as parseActivationCommand } from "./group-activation-DBUyCcKk.js";
75
+ import { t as resolveFastModeState } from "./fast-mode-BC09CjpN.js";
76
+ import { n as resolveSessionAuthProfileOverride } from "./session-override-D31eiWsJ.js";
77
+ import { n as extractExplicitGroupId, t as formatElevatedUnavailableMessage } from "./elevated-unavailable-YWSzsE-Q.js";
78
+ import { t as resolveRuntimePolicySessionKey } from "./runtime-policy-session-key-CQYorQe-.js";
79
+ import { a as shouldPersistAbortCutoff, i as resolveAbortCutoffFromContext, t as applyAbortCutoffToSessionEntry } from "./abort-cutoff-Bfe-t6aN.js";
80
+ import { t as resolveEffectiveToolInventory } from "./tools-effective-inventory-C5X-_cBY.js";
81
+ import { r as resolveConversationBindingContextFromAcpCommand } from "./conversation-binding-input-BEmRGliZ.js";
82
+ import { n as resolveSessionEntryForKey, r as stopSubagentsForRequester, t as formatAbortReplyText } from "./abort-91r4UulC.js";
83
+ import { t as extractBtwQuestion } from "./btw-command-C_PoQ81w.js";
84
+ import { t as formatThreadBindingDurationLabel } from "./thread-bindings-messages-BiA95c9o.js";
85
+ import { n as getSpeechProvider, r as listSpeechProviders, t as canonicalizeSpeechProviderId } from "./provider-registry-CJCZIRQp.js";
86
+ import { a as requireGatewayClientScopeForInternalChannel, i as requireCommandFlagEnabled, n as rejectNonOwnerCommand, r as rejectUnauthorizedCommand, t as buildDisabledCommandReply } from "./command-gates-CPTiKB_G.js";
87
+ import { t as handleAcpCommand } from "./commands-acp-DNlM5COD.js";
88
+ import { n as buildCommandsMessagePaginated, r as buildHelpMessage, t as buildCommandsMessage } from "./command-status-builders-w77F0pTE.js";
89
+ import { _ as getFinishedSession, v as getSession } from "./bash-tools.exec-runtime-B1jTSz0K.js";
90
+ import { t as listSkillCommandsForAgents } from "./skill-commands-BA34PY9U.js";
91
+ import { r as handleModelsCommand } from "./commands-models-rJBocry1.js";
92
+ import { n as setPluginEnabledInConfig } from "./enable-Ckyp8QNs.js";
93
+ import { r as createExecTool } from "./bash-tools-CfLkHd-r.js";
94
+ import { n as listTasksForAgentIdForStatus, r as listTasksForSessionKeyForStatus } from "./status-text-DyIs2f8P.js";
95
+ import { n as buildThreadingToolContext } from "./agent-runner-utils-CQHnUCgQ.js";
96
+ import { d as resolveChannelAccountId, f as resolveCommandSurfaceChannel, l as resolveSubagentsAction, o as resolveHandledPrefix, s as resolveRequesterSessionKey, u as stopWithText } from "./shared-D-tbPAY5.js";
97
+ import { t as buildToolsMessage } from "./status-C_dyWwf0.js";
98
+ import { t as parseConfigValue } from "./config-value-CPN42qpy.js";
99
+ import { t as resolveCommandsSystemPromptBundle } from "./commands-system-prompt-DuLI1Zhj.js";
100
+ import { a as writeSupportBundleDirectory, i as textSupportBundleFile, n as jsonlSupportBundleFile, r as supportBundleContents, t as jsonSupportBundleFile } from "./diagnostic-support-bundle-2WBfmkS-.js";
101
+ import { t as buildStatusReply } from "./commands-status-BpCtSlHL.js";
102
+ import { i as buildNpmInstallRecordFields, n as persistPluginInstall } from "./plugins-install-persist-DZUTlfUC.js";
103
+ import { m as parseClawHubPluginSpec } from "./clawhub-CZmeSSY3.js";
104
+ import { r as installPluginFromClawHub } from "./clawhub-ssHVhZYy.js";
105
+ import { a as buildPluginDiagnosticsReport, c as formatPluginCompatibilityNotice, o as buildPluginInspectReport, s as buildPluginSnapshotReport, t as buildAllPluginInspectReports } from "./status-DH8gfoZp.js";
106
+ import { a as decidePreferredClawHubFallback, i as createPluginInstallLogger, n as buildPreferredClawHubSpec, u as resolveFileNpmSpecToLocalPath } from "./plugins-command-helpers-TdKiv72_.js";
107
+ import { n as loadCostUsageSummary, r as loadSessionCostSummary } from "./session-cost-usage-B6EYIbiG.js";
108
+ import { fileURLToPath } from "node:url";
109
+ import fs from "node:fs";
110
+ import path from "node:path";
111
+ import { SessionManager } from "@mariozechner/pi-coding-agent";
112
+ import { streamSimple } from "@mariozechner/pi-ai";
113
+ //#region src/channels/plugins/config-writes.ts
114
+ function isInternalConfigWriteMessageChannel(channel) {
115
+ return normalizeLowercaseStringOrEmpty(channel) === "webchat";
116
+ }
117
+ function authorizeConfigWrite(params) {
118
+ return authorizeConfigWriteShared(params);
119
+ }
120
+ function resolveConfigWriteTargetFromPath(path) {
121
+ return resolveConfigWriteTargetFromPathShared({
122
+ path,
123
+ normalizeChannelId: (raw) => normalizeLowercaseStringOrEmpty(raw)
124
+ });
125
+ }
126
+ function canBypassConfigWritePolicy(params) {
127
+ return canBypassConfigWritePolicyShared({
128
+ ...params,
129
+ isInternalMessageChannel: isInternalConfigWriteMessageChannel
130
+ });
131
+ }
132
+ function formatConfigWriteDeniedMessage(params) {
133
+ return formatConfigWriteDeniedMessageShared(params);
134
+ }
135
+ //#endregion
136
+ //#region src/auto-reply/reply/config-write-authorization.ts
137
+ function resolveConfigWriteDeniedText(params) {
138
+ const writeAuth = authorizeConfigWrite({
139
+ cfg: params.cfg,
140
+ origin: {
141
+ channelId: params.channelId,
142
+ accountId: params.accountId
143
+ },
144
+ target: params.target,
145
+ allowBypass: canBypassConfigWritePolicy({
146
+ channel: params.channel ?? "",
147
+ gatewayClientScopes: params.gatewayClientScopes
148
+ })
149
+ });
150
+ if (writeAuth.allowed) return null;
151
+ return formatConfigWriteDeniedMessage({
152
+ result: writeAuth,
153
+ fallbackChannelId: params.channelId
154
+ });
155
+ }
156
+ //#endregion
157
+ //#region src/auto-reply/reply/commands-allowlist.ts
158
+ const ACTIONS = new Set([
159
+ "list",
160
+ "add",
161
+ "remove"
162
+ ]);
163
+ const SCOPES = new Set([
164
+ "dm",
165
+ "group",
166
+ "all"
167
+ ]);
168
+ function resolveAllowlistAccountId(params) {
169
+ const explicitAccountId = normalizeOptionalAccountId(params.parsedAccount);
170
+ if (explicitAccountId) return explicitAccountId;
171
+ const configuredDefaultAccountId = normalizeOptionalString(getChannelPlugin(params.channelId)?.config.defaultAccountId?.(params.cfg));
172
+ const ctxAccountId = normalizeOptionalAccountId(params.ctxAccountId);
173
+ return configuredDefaultAccountId || ctxAccountId || "default";
174
+ }
175
+ function parseAllowlistCommand(raw) {
176
+ const trimmed = raw.trim();
177
+ if (!(normalizeOptionalLowercaseString(trimmed) ?? "").startsWith("/allowlist")) return null;
178
+ const rest = trimmed.slice(10).trim();
179
+ if (!rest) return {
180
+ action: "list",
181
+ scope: "dm"
182
+ };
183
+ const tokens = rest.split(/\s+/);
184
+ let action = "list";
185
+ let scope = "dm";
186
+ let resolve = false;
187
+ let target = "both";
188
+ let channel;
189
+ let account;
190
+ const entryTokens = [];
191
+ let i = 0;
192
+ const firstAction = normalizeOptionalLowercaseString(tokens[i]);
193
+ if (firstAction && ACTIONS.has(firstAction)) {
194
+ action = firstAction;
195
+ i += 1;
196
+ }
197
+ const firstScope = normalizeOptionalLowercaseString(tokens[i]);
198
+ if (firstScope && SCOPES.has(firstScope)) {
199
+ scope = firstScope;
200
+ i += 1;
201
+ }
202
+ for (; i < tokens.length; i += 1) {
203
+ const token = tokens[i];
204
+ const lowered = normalizeOptionalLowercaseString(token) ?? "";
205
+ if (lowered === "--resolve" || lowered === "resolve") {
206
+ resolve = true;
207
+ continue;
208
+ }
209
+ if (lowered === "--config" || lowered === "config") {
210
+ target = "config";
211
+ continue;
212
+ }
213
+ if (lowered === "--store" || lowered === "store") {
214
+ target = "store";
215
+ continue;
216
+ }
217
+ if (lowered === "--channel" && tokens[i + 1]) {
218
+ channel = tokens[i + 1];
219
+ i += 1;
220
+ continue;
221
+ }
222
+ if (lowered === "--account" && tokens[i + 1]) {
223
+ account = tokens[i + 1];
224
+ i += 1;
225
+ continue;
226
+ }
227
+ const kv = token.split("=");
228
+ if (kv.length === 2) {
229
+ const key = normalizeOptionalLowercaseString(kv[0]);
230
+ const value = normalizeOptionalString(kv[1]);
231
+ if (key === "channel") {
232
+ if (value) channel = value;
233
+ continue;
234
+ }
235
+ if (key === "account") {
236
+ if (value) account = value;
237
+ continue;
238
+ }
239
+ const normalizedValue = normalizeOptionalLowercaseString(value);
240
+ if (key === "scope" && normalizedValue && SCOPES.has(normalizedValue)) {
241
+ scope = normalizedValue;
242
+ continue;
243
+ }
244
+ }
245
+ entryTokens.push(token);
246
+ }
247
+ if (action === "add" || action === "remove") {
248
+ const entry = entryTokens.join(" ").trim();
249
+ if (!entry) return {
250
+ action: "error",
251
+ message: "Usage: /allowlist add|remove <entry>"
252
+ };
253
+ return {
254
+ action,
255
+ scope,
256
+ entry,
257
+ channel,
258
+ account,
259
+ resolve,
260
+ target
261
+ };
262
+ }
263
+ return {
264
+ action: "list",
265
+ scope,
266
+ channel,
267
+ account,
268
+ resolve
269
+ };
270
+ }
271
+ function normalizeAllowFrom(params) {
272
+ const plugin = getChannelPlugin(params.channelId);
273
+ if (plugin?.config.formatAllowFrom) return plugin.config.formatAllowFrom({
274
+ cfg: params.cfg,
275
+ accountId: params.accountId,
276
+ allowFrom: params.values
277
+ });
278
+ return normalizeStringEntries(params.values);
279
+ }
280
+ function formatEntryList(entries, resolved) {
281
+ if (entries.length === 0) return "(none)";
282
+ return entries.map((entry) => {
283
+ const name = resolved?.get(entry);
284
+ return name ? `${entry} (${name})` : entry;
285
+ }).join(", ");
286
+ }
287
+ async function updatePairingStoreAllowlist(params) {
288
+ const storeEntry = {
289
+ channel: params.channelId,
290
+ entry: params.entry,
291
+ accountId: params.accountId
292
+ };
293
+ if (params.action === "add") {
294
+ await addChannelAllowFromStoreEntry(storeEntry);
295
+ return;
296
+ }
297
+ await removeChannelAllowFromStoreEntry(storeEntry);
298
+ if (params.accountId === "default") await removeChannelAllowFromStoreEntry({
299
+ channel: params.channelId,
300
+ entry: params.entry
301
+ });
302
+ }
303
+ function mapResolvedAllowlistNames(entries) {
304
+ const map = /* @__PURE__ */ new Map();
305
+ for (const entry of entries) if (entry.resolved && entry.name) map.set(entry.input, entry.name);
306
+ return map;
307
+ }
308
+ async function resolveAllowlistNames(params) {
309
+ return mapResolvedAllowlistNames(await getChannelPlugin(params.channelId)?.allowlist?.resolveNames?.({
310
+ cfg: params.cfg,
311
+ accountId: params.accountId,
312
+ scope: params.scope,
313
+ entries: params.entries
314
+ }) ?? []);
315
+ }
316
+ async function readAllowlistConfig(params) {
317
+ return await getChannelPlugin(params.channelId)?.allowlist?.readConfig?.({
318
+ cfg: params.cfg,
319
+ accountId: params.accountId
320
+ }) ?? {};
321
+ }
322
+ const handleAllowlistCommand = async (params, allowTextCommands) => {
323
+ if (!allowTextCommands) return null;
324
+ const parsed = parseAllowlistCommand(params.command.commandBodyNormalized);
325
+ if (!parsed) return null;
326
+ if (parsed.action === "error") return {
327
+ shouldContinue: false,
328
+ reply: { text: `āš ļø ${parsed.message}` }
329
+ };
330
+ const unauthorized = rejectUnauthorizedCommand(params, "/allowlist");
331
+ if (unauthorized) return unauthorized;
332
+ if (parsed.action !== "list") {
333
+ const nonOwner = rejectNonOwnerCommand(params, "/allowlist");
334
+ if (nonOwner) return nonOwner;
335
+ }
336
+ const channelId = normalizeChannelId(parsed.channel) ?? params.command.channelId ?? normalizeChannelId(params.command.channel);
337
+ if (!channelId) return {
338
+ shouldContinue: false,
339
+ reply: { text: "āš ļø Unknown channel. Add channel=<id> to the command." }
340
+ };
341
+ if (normalizeOptionalString(parsed.account) && !normalizeOptionalAccountId(parsed.account)) return {
342
+ shouldContinue: false,
343
+ reply: { text: "āš ļø Invalid account id. Reserved keys (__proto__, constructor, prototype) are blocked." }
344
+ };
345
+ const accountId = resolveAllowlistAccountId({
346
+ cfg: params.cfg,
347
+ channelId,
348
+ parsedAccount: parsed.account,
349
+ ctxAccountId: params.ctx.AccountId
350
+ });
351
+ const plugin = getChannelPlugin(channelId);
352
+ if (parsed.action === "list") {
353
+ const supportsStore = Boolean(plugin?.pairing);
354
+ if (!plugin?.allowlist?.readConfig && !supportsStore) return {
355
+ shouldContinue: false,
356
+ reply: { text: `āš ļø ${channelId} does not expose allowlist configuration.` }
357
+ };
358
+ const storeAllowFrom = supportsStore ? await readChannelAllowFromStore(channelId, process.env, accountId).catch(() => []) : [];
359
+ const configState = await readAllowlistConfig({
360
+ cfg: params.cfg,
361
+ channelId,
362
+ accountId
363
+ });
364
+ const dmAllowFrom = (configState.dmAllowFrom ?? []).map(String);
365
+ const groupAllowFrom = (configState.groupAllowFrom ?? []).map(String);
366
+ const groupOverrides = (configState.groupOverrides ?? []).map((entry) => ({
367
+ label: entry.label,
368
+ entries: entry.entries.map(String).filter(Boolean)
369
+ }));
370
+ const dmDisplay = normalizeAllowFrom({
371
+ cfg: params.cfg,
372
+ channelId,
373
+ accountId,
374
+ values: dmAllowFrom
375
+ });
376
+ const groupDisplay = normalizeAllowFrom({
377
+ cfg: params.cfg,
378
+ channelId,
379
+ accountId,
380
+ values: groupAllowFrom
381
+ });
382
+ const groupOverrideEntries = groupOverrides.flatMap((entry) => entry.entries);
383
+ const groupOverrideDisplay = normalizeAllowFrom({
384
+ cfg: params.cfg,
385
+ channelId,
386
+ accountId,
387
+ values: groupOverrideEntries
388
+ });
389
+ const resolvedDm = parsed.resolve && dmDisplay.length > 0 ? await resolveAllowlistNames({
390
+ cfg: params.cfg,
391
+ channelId,
392
+ accountId,
393
+ scope: "dm",
394
+ entries: dmDisplay
395
+ }) : void 0;
396
+ const resolvedGroup = parsed.resolve && groupOverrideDisplay.length > 0 ? await resolveAllowlistNames({
397
+ cfg: params.cfg,
398
+ channelId,
399
+ accountId,
400
+ scope: "group",
401
+ entries: groupOverrideDisplay
402
+ }) : void 0;
403
+ const lines = ["🧾 Allowlist"];
404
+ lines.push(`Channel: ${channelId}${accountId ? ` (account ${accountId})` : ""}`);
405
+ if (configState.dmPolicy) lines.push(`DM policy: ${configState.dmPolicy}`);
406
+ if (configState.groupPolicy) lines.push(`Group policy: ${configState.groupPolicy}`);
407
+ const showDm = parsed.scope === "dm" || parsed.scope === "all";
408
+ const showGroup = parsed.scope === "group" || parsed.scope === "all";
409
+ if (showDm) lines.push(`DM allowFrom (config): ${formatEntryList(dmDisplay, resolvedDm)}`);
410
+ if (supportsStore && storeAllowFrom.length > 0) {
411
+ const storeLabel = normalizeAllowFrom({
412
+ cfg: params.cfg,
413
+ channelId,
414
+ accountId,
415
+ values: storeAllowFrom
416
+ });
417
+ lines.push(`Paired allowFrom (store): ${formatEntryList(storeLabel)}`);
418
+ }
419
+ if (showGroup) {
420
+ if (groupAllowFrom.length > 0) lines.push(`Group allowFrom (config): ${formatEntryList(groupDisplay, resolvedGroup)}`);
421
+ if (groupOverrides.length > 0) {
422
+ lines.push("Group overrides:");
423
+ for (const entry of groupOverrides) {
424
+ const normalized = normalizeAllowFrom({
425
+ cfg: params.cfg,
426
+ channelId,
427
+ accountId,
428
+ values: entry.entries
429
+ });
430
+ lines.push(`- ${entry.label}: ${formatEntryList(normalized, resolvedGroup)}`);
431
+ }
432
+ }
433
+ }
434
+ return {
435
+ shouldContinue: false,
436
+ reply: { text: lines.join("\n") }
437
+ };
438
+ }
439
+ const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
440
+ label: "/allowlist write",
441
+ allowedScopes: ["operator.admin"],
442
+ missingText: "āŒ /allowlist add|remove requires operator.admin for gateway clients."
443
+ });
444
+ if (missingAdminScope) return missingAdminScope;
445
+ const disabled = requireCommandFlagEnabled(params.cfg, {
446
+ label: "/allowlist edits",
447
+ configKey: "config",
448
+ disabledVerb: "are"
449
+ });
450
+ if (disabled) return disabled;
451
+ const shouldUpdateConfig = parsed.target !== "store";
452
+ const shouldTouchStore = parsed.target !== "config" && Boolean(plugin?.pairing);
453
+ if (shouldUpdateConfig) {
454
+ if (parsed.scope === "all") return {
455
+ shouldContinue: false,
456
+ reply: { text: "āš ļø /allowlist add|remove requires scope dm or group." }
457
+ };
458
+ if (!plugin?.allowlist?.applyConfigEdit) return {
459
+ shouldContinue: false,
460
+ reply: { text: `āš ļø ${channelId} does not support ${parsed.scope} allowlist edits via /allowlist.` }
461
+ };
462
+ const snapshot = await readConfigFileSnapshot();
463
+ if (!snapshot.valid || !snapshot.parsed || typeof snapshot.parsed !== "object") return {
464
+ shouldContinue: false,
465
+ reply: { text: "āš ļø Config file is invalid; fix it before using /allowlist." }
466
+ };
467
+ const parsedConfig = structuredClone(snapshot.parsed);
468
+ const editResult = await plugin.allowlist.applyConfigEdit({
469
+ cfg: params.cfg,
470
+ parsedConfig,
471
+ accountId,
472
+ scope: parsed.scope,
473
+ action: parsed.action,
474
+ entry: parsed.entry
475
+ });
476
+ if (!editResult) return {
477
+ shouldContinue: false,
478
+ reply: { text: `āš ļø ${channelId} does not support ${parsed.scope} allowlist edits via /allowlist.` }
479
+ };
480
+ if (editResult.kind === "invalid-entry") return {
481
+ shouldContinue: false,
482
+ reply: { text: "āš ļø Invalid allowlist entry." }
483
+ };
484
+ const deniedText = resolveConfigWriteDeniedText({
485
+ cfg: params.cfg,
486
+ channel: params.command.channel,
487
+ channelId,
488
+ accountId,
489
+ gatewayClientScopes: params.ctx.GatewayClientScopes,
490
+ target: editResult.writeTarget
491
+ });
492
+ if (deniedText) return {
493
+ shouldContinue: false,
494
+ reply: { text: deniedText }
495
+ };
496
+ const configChanged = editResult.changed;
497
+ if (configChanged) {
498
+ const validated = validateConfigObjectWithPlugins(parsedConfig);
499
+ if (!validated.ok) {
500
+ const issue = validated.issues[0];
501
+ return {
502
+ shouldContinue: false,
503
+ reply: { text: `āš ļø Config invalid after update (${issue.path}: ${issue.message}).` }
504
+ };
505
+ }
506
+ await writeConfigFile(validated.config);
507
+ }
508
+ if (!configChanged && !shouldTouchStore) return {
509
+ shouldContinue: false,
510
+ reply: { text: parsed.action === "add" ? "āœ… Already allowlisted." : "āš ļø Entry not found." }
511
+ };
512
+ if (shouldTouchStore) await updatePairingStoreAllowlist({
513
+ action: parsed.action,
514
+ channelId,
515
+ accountId,
516
+ entry: parsed.entry
517
+ });
518
+ const actionLabel = parsed.action === "add" ? "added" : "removed";
519
+ const scopeLabel = parsed.scope === "dm" ? "DM" : "group";
520
+ const locations = [];
521
+ if (configChanged) locations.push(editResult.pathLabel);
522
+ if (shouldTouchStore) locations.push("pairing store");
523
+ return {
524
+ shouldContinue: false,
525
+ reply: { text: `āœ… ${scopeLabel} allowlist ${actionLabel}: ${locations.length > 0 ? locations.join(" + ") : "no-op"}.` }
526
+ };
527
+ }
528
+ if (!shouldTouchStore) return {
529
+ shouldContinue: false,
530
+ reply: { text: "āš ļø This channel does not support allowlist storage." }
531
+ };
532
+ await updatePairingStoreAllowlist({
533
+ action: parsed.action,
534
+ channelId,
535
+ accountId,
536
+ entry: parsed.entry
537
+ });
538
+ const actionLabel = parsed.action === "add" ? "added" : "removed";
539
+ return {
540
+ shouldContinue: false,
541
+ reply: { text: `āœ… ${parsed.scope === "dm" ? "DM" : "group"} allowlist ${actionLabel} in pairing store.` }
542
+ };
543
+ };
544
+ //#endregion
545
+ //#region src/infra/channel-approval-auth.ts
546
+ function resolveApprovalCommandAuthorization(params) {
547
+ const channel = normalizeMessageChannel(params.channel);
548
+ if (!channel) return {
549
+ authorized: true,
550
+ explicit: false
551
+ };
552
+ const approvalCapability = resolveChannelApprovalCapability(getChannelPlugin(channel));
553
+ const resolved = approvalCapability?.authorizeActorAction?.({
554
+ cfg: params.cfg,
555
+ accountId: params.accountId,
556
+ senderId: params.senderId,
557
+ action: "approve",
558
+ approvalKind: params.kind
559
+ });
560
+ if (!resolved) return {
561
+ authorized: true,
562
+ explicit: false
563
+ };
564
+ const implicitSameChatAuthorization = isImplicitSameChatApprovalAuthorization(resolved);
565
+ const availability = approvalCapability?.getActionAvailabilityState?.({
566
+ cfg: params.cfg,
567
+ accountId: params.accountId,
568
+ action: "approve",
569
+ approvalKind: params.kind
570
+ });
571
+ return {
572
+ authorized: resolved.authorized,
573
+ reason: resolved.reason,
574
+ explicit: resolved.authorized ? !implicitSameChatAuthorization && availability?.kind !== "disabled" : true
575
+ };
576
+ }
577
+ //#endregion
578
+ //#region src/auto-reply/reply/commands-approve.ts
579
+ const COMMAND_REGEX = /^\/?approve(?:\s|$)/i;
580
+ const FOREIGN_COMMAND_MENTION_REGEX = /^\/approve@([^\s]+)(?:\s|$)/i;
581
+ const DECISION_ALIASES = {
582
+ allow: "allow-once",
583
+ once: "allow-once",
584
+ "allow-once": "allow-once",
585
+ allowonce: "allow-once",
586
+ always: "allow-always",
587
+ "allow-always": "allow-always",
588
+ allowalways: "allow-always",
589
+ deny: "deny",
590
+ reject: "deny",
591
+ block: "deny"
592
+ };
593
+ const APPROVE_USAGE_TEXT = "Usage: /approve <id> <decision> (see the pending approval message for available decisions)";
594
+ function parseApproveCommand(raw) {
595
+ const trimmed = raw.trim();
596
+ if (FOREIGN_COMMAND_MENTION_REGEX.test(trimmed)) return {
597
+ ok: false,
598
+ error: "āŒ This /approve command targets a different Telegram bot."
599
+ };
600
+ const commandMatch = trimmed.match(COMMAND_REGEX);
601
+ if (!commandMatch) return null;
602
+ const rest = trimmed.slice(commandMatch[0].length).trim();
603
+ if (!rest) return {
604
+ ok: false,
605
+ error: APPROVE_USAGE_TEXT
606
+ };
607
+ const tokens = rest.split(/\s+/).filter(Boolean);
608
+ if (tokens.length < 2) return {
609
+ ok: false,
610
+ error: APPROVE_USAGE_TEXT
611
+ };
612
+ const first = normalizeLowercaseStringOrEmpty(tokens[0]);
613
+ const second = normalizeLowercaseStringOrEmpty(tokens[1]);
614
+ if (DECISION_ALIASES[first]) return {
615
+ ok: true,
616
+ decision: DECISION_ALIASES[first],
617
+ id: tokens.slice(1).join(" ").trim()
618
+ };
619
+ if (DECISION_ALIASES[second]) return {
620
+ ok: true,
621
+ decision: DECISION_ALIASES[second],
622
+ id: tokens[0]
623
+ };
624
+ return {
625
+ ok: false,
626
+ error: APPROVE_USAGE_TEXT
627
+ };
628
+ }
629
+ function buildResolvedByLabel(params) {
630
+ return `${params.command.channel}:${params.command.senderId ?? "unknown"}`;
631
+ }
632
+ function formatApprovalSubmitError(error) {
633
+ return formatErrorMessage(error);
634
+ }
635
+ function resolveApprovalMethods(params) {
636
+ if (params.approvalId.startsWith("plugin:")) return params.pluginAuthorization.authorized ? ["plugin.approval.resolve"] : [];
637
+ if (params.execAuthorization.authorized && params.pluginAuthorization.authorized) return ["exec.approval.resolve", "plugin.approval.resolve"];
638
+ if (params.execAuthorization.authorized) return ["exec.approval.resolve"];
639
+ if (params.pluginAuthorization.authorized) return ["plugin.approval.resolve"];
640
+ return [];
641
+ }
642
+ function resolveApprovalAuthorizationError(params) {
643
+ if (params.approvalId.startsWith("plugin:")) return params.pluginAuthorization.reason ?? "āŒ You are not authorized to approve this request.";
644
+ return params.execAuthorization.reason ?? params.pluginAuthorization.reason ?? "āŒ You are not authorized to approve this request.";
645
+ }
646
+ const handleApproveCommand = async (params, allowTextCommands) => {
647
+ if (!allowTextCommands) return null;
648
+ const normalized = params.command.commandBodyNormalized;
649
+ const parsed = parseApproveCommand(normalized);
650
+ if (!parsed) return null;
651
+ if (!parsed.ok) return {
652
+ shouldContinue: false,
653
+ reply: { text: parsed.error }
654
+ };
655
+ const isPluginId = parsed.id.startsWith("plugin:");
656
+ const effectiveAccountId = resolveChannelAccountId({
657
+ cfg: params.cfg,
658
+ ctx: params.ctx,
659
+ command: params.command
660
+ });
661
+ const approveCommandBehavior = resolveChannelApprovalCapability(getChannelPlugin(params.command.channel))?.resolveApproveCommandBehavior?.({
662
+ cfg: params.cfg,
663
+ accountId: effectiveAccountId,
664
+ senderId: params.command.senderId,
665
+ approvalKind: isPluginId ? "plugin" : "exec"
666
+ });
667
+ if (approveCommandBehavior?.kind === "ignore") return { shouldContinue: false };
668
+ if (approveCommandBehavior?.kind === "reply") return {
669
+ shouldContinue: false,
670
+ reply: { text: approveCommandBehavior.text }
671
+ };
672
+ const execApprovalAuthorization = resolveApprovalCommandAuthorization({
673
+ cfg: params.cfg,
674
+ channel: params.command.channel,
675
+ accountId: effectiveAccountId,
676
+ senderId: params.command.senderId,
677
+ kind: "exec"
678
+ });
679
+ const pluginApprovalAuthorization = resolveApprovalCommandAuthorization({
680
+ cfg: params.cfg,
681
+ channel: params.command.channel,
682
+ accountId: effectiveAccountId,
683
+ senderId: params.command.senderId,
684
+ kind: "plugin"
685
+ });
686
+ const hasExplicitApprovalAuthorization = execApprovalAuthorization.explicit && execApprovalAuthorization.authorized || pluginApprovalAuthorization.explicit && pluginApprovalAuthorization.authorized;
687
+ if (!params.command.isAuthorizedSender && !hasExplicitApprovalAuthorization) {
688
+ logVerbose(`Ignoring /approve from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
689
+ return { shouldContinue: false };
690
+ }
691
+ const missingScope = requireGatewayClientScopeForInternalChannel(params, {
692
+ label: "/approve",
693
+ allowedScopes: ["operator.approvals", "operator.admin"],
694
+ missingText: "āŒ /approve requires operator.approvals for gateway clients."
695
+ });
696
+ if (missingScope) return missingScope;
697
+ const resolvedBy = buildResolvedByLabel(params);
698
+ const callApprovalMethod = async (method) => {
699
+ await callGateway({
700
+ method,
701
+ params: {
702
+ id: parsed.id,
703
+ decision: parsed.decision
704
+ },
705
+ clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
706
+ clientDisplayName: `Chat approval (${resolvedBy})`,
707
+ mode: GATEWAY_CLIENT_MODES.BACKEND
708
+ });
709
+ };
710
+ const methods = resolveApprovalMethods({
711
+ approvalId: parsed.id,
712
+ execAuthorization: execApprovalAuthorization,
713
+ pluginAuthorization: pluginApprovalAuthorization
714
+ });
715
+ if (methods.length === 0) return {
716
+ shouldContinue: false,
717
+ reply: { text: resolveApprovalAuthorizationError({
718
+ approvalId: parsed.id,
719
+ execAuthorization: execApprovalAuthorization,
720
+ pluginAuthorization: pluginApprovalAuthorization
721
+ }) }
722
+ };
723
+ let lastError = null;
724
+ for (const [index, method] of methods.entries()) try {
725
+ await callApprovalMethod(method);
726
+ lastError = null;
727
+ break;
728
+ } catch (error) {
729
+ lastError = error;
730
+ const isLastMethod = index === methods.length - 1;
731
+ if (!isApprovalNotFoundError(error) || isLastMethod) return {
732
+ shouldContinue: false,
733
+ reply: { text: `āŒ Failed to submit approval: ${formatApprovalSubmitError(error)}` }
734
+ };
735
+ }
736
+ if (lastError) return {
737
+ shouldContinue: false,
738
+ reply: { text: `āŒ Failed to submit approval: ${formatApprovalSubmitError(lastError)}` }
739
+ };
740
+ return {
741
+ shouldContinue: false,
742
+ reply: { text: `āœ… Approval ${parsed.decision} submitted for ${parsed.id}.` }
743
+ };
744
+ };
745
+ //#endregion
746
+ //#region src/auto-reply/reply/bash-command.ts
747
+ const CHAT_BASH_SCOPE_KEY = "chat:bash";
748
+ const DEFAULT_FOREGROUND_MS = 2e3;
749
+ const MAX_FOREGROUND_MS = 3e4;
750
+ let activeJob = null;
751
+ function resolveForegroundMs(cfg) {
752
+ const raw = cfg.commands?.bashForegroundMs;
753
+ if (typeof raw !== "number" || Number.isNaN(raw)) return DEFAULT_FOREGROUND_MS;
754
+ return clampInt(raw, 0, MAX_FOREGROUND_MS);
755
+ }
756
+ function formatSessionSnippet(sessionId) {
757
+ const trimmed = sessionId.trim();
758
+ if (trimmed.length <= 12) return trimmed;
759
+ return `${trimmed.slice(0, 8)}…`;
760
+ }
761
+ function formatOutputBlock(text) {
762
+ const trimmed = text.trim();
763
+ if (!trimmed) return "(no output)";
764
+ return `\`\`\`txt\n${trimmed}\n\`\`\``;
765
+ }
766
+ function parseBashRequest(raw) {
767
+ const trimmed = raw.trimStart();
768
+ let restSource = "";
769
+ if (normalizeLowercaseStringOrEmpty(trimmed).startsWith("/bash")) {
770
+ const match = trimmed.match(/^\/bash(?:\s*:\s*|\s+|$)([\s\S]*)$/i);
771
+ if (!match) return null;
772
+ restSource = match[1] ?? "";
773
+ } else if (trimmed.startsWith("!")) {
774
+ restSource = trimmed.slice(1);
775
+ if (restSource.trimStart().startsWith(":")) restSource = restSource.trimStart().slice(1);
776
+ } else return null;
777
+ const rest = restSource.trimStart();
778
+ if (!rest) return { action: "help" };
779
+ const tokenMatch = rest.match(/^(\S+)(?:\s+([\s\S]+))?$/);
780
+ const token = normalizeOptionalString(tokenMatch?.[1]) ?? "";
781
+ const remainder = normalizeOptionalString(tokenMatch?.[2]) ?? "";
782
+ const lowered = normalizeLowercaseStringOrEmpty(token);
783
+ if (lowered === "poll") return {
784
+ action: "poll",
785
+ sessionId: remainder || void 0
786
+ };
787
+ if (lowered === "stop") return {
788
+ action: "stop",
789
+ sessionId: remainder || void 0
790
+ };
791
+ if (lowered === "help") return { action: "help" };
792
+ return {
793
+ action: "run",
794
+ command: rest
795
+ };
796
+ }
797
+ function resolveRawCommandBody(params) {
798
+ const stripped = stripStructuralPrefixes(params.ctx.CommandBody ?? params.ctx.RawBody ?? params.ctx.Body ?? "");
799
+ return params.isGroup ? stripMentions(stripped, params.ctx, params.cfg, params.agentId) : stripped;
800
+ }
801
+ function getScopedSession(sessionId) {
802
+ const running = getSession(sessionId);
803
+ if (running && running.scopeKey === CHAT_BASH_SCOPE_KEY) return { running };
804
+ const finished = getFinishedSession(sessionId);
805
+ if (finished && finished.scopeKey === CHAT_BASH_SCOPE_KEY) return { finished };
806
+ return {};
807
+ }
808
+ function ensureActiveJobState() {
809
+ if (!activeJob) return null;
810
+ if (activeJob.state === "starting") return activeJob;
811
+ const { running, finished } = getScopedSession(activeJob.sessionId);
812
+ if (running) return activeJob;
813
+ if (finished) {
814
+ activeJob = null;
815
+ return null;
816
+ }
817
+ activeJob = null;
818
+ return null;
819
+ }
820
+ function attachActiveWatcher(sessionId) {
821
+ if (!activeJob || activeJob.state !== "running") return;
822
+ if (activeJob.sessionId !== sessionId) return;
823
+ if (activeJob.watcherAttached) return;
824
+ const { running } = getScopedSession(sessionId);
825
+ const child = running?.child;
826
+ if (!child) return;
827
+ activeJob.watcherAttached = true;
828
+ child.once("close", () => {
829
+ if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
830
+ });
831
+ }
832
+ function buildUsageReply() {
833
+ return { text: [
834
+ "āš™ļø Usage:",
835
+ "- ! <command>",
836
+ "- !poll | ! poll",
837
+ "- !stop | ! stop",
838
+ "- /bash ... (alias; same subcommands as !)"
839
+ ].join("\n") };
840
+ }
841
+ async function handleBashChatCommand(params) {
842
+ if (!isCommandFlagEnabled(params.cfg, "bash")) return buildDisabledCommandReply({
843
+ label: "bash",
844
+ configKey: "bash",
845
+ docsUrl: "https://docs.genesis.ai/tools/slash-commands#config"
846
+ });
847
+ const agentId = params.agentId ?? resolveSessionAgentId({
848
+ sessionKey: params.sessionKey,
849
+ config: params.cfg
850
+ });
851
+ if (!params.elevated.enabled || !params.elevated.allowed) {
852
+ const runtimeSandboxed = resolveSandboxRuntimeStatus({
853
+ cfg: params.cfg,
854
+ sessionKey: resolveRuntimePolicySessionKey({
855
+ cfg: params.cfg,
856
+ ctx: params.ctx,
857
+ sessionKey: params.sessionKey
858
+ })
859
+ }).sandboxed;
860
+ return { text: formatElevatedUnavailableMessage({
861
+ runtimeSandboxed,
862
+ failures: params.elevated.failures,
863
+ sessionKey: params.sessionKey
864
+ }) };
865
+ }
866
+ const request = parseBashRequest(resolveRawCommandBody({
867
+ ctx: params.ctx,
868
+ cfg: params.cfg,
869
+ agentId,
870
+ isGroup: params.isGroup
871
+ }).trim());
872
+ if (!request) return { text: "āš ļø Unrecognized bash request." };
873
+ const liveJob = ensureActiveJobState();
874
+ if (request.action === "help") return buildUsageReply();
875
+ if (request.action === "poll") {
876
+ const sessionId = normalizeOptionalString(request.sessionId) || (liveJob?.state === "running" ? liveJob.sessionId : "");
877
+ if (!sessionId) return { text: "āš™ļø No active bash job." };
878
+ const { running, finished } = getScopedSession(sessionId);
879
+ if (running) {
880
+ attachActiveWatcher(sessionId);
881
+ const runtimeSec = Math.max(0, Math.floor((Date.now() - running.startedAt) / 1e3));
882
+ const tail = running.tail || "(no output yet)";
883
+ return { text: [
884
+ `āš™ļø bash still running (session ${formatSessionSnippet(sessionId)}, ${runtimeSec}s).`,
885
+ formatOutputBlock(tail),
886
+ "Hint: !stop (or /bash stop)"
887
+ ].join("\n") };
888
+ }
889
+ if (finished) {
890
+ if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
891
+ const exitLabel = finished.exitSignal ? `signal ${String(finished.exitSignal)}` : `code ${String(finished.exitCode ?? 0)}`;
892
+ return { text: [
893
+ `${finished.status === "completed" ? "āš™ļø" : "āš ļø"} bash finished (session ${formatSessionSnippet(sessionId)}).`,
894
+ `Exit: ${exitLabel}`,
895
+ formatOutputBlock(finished.aggregated || finished.tail)
896
+ ].join("\n") };
897
+ }
898
+ if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
899
+ return { text: `āš™ļø No bash session found for ${formatSessionSnippet(sessionId)}.` };
900
+ }
901
+ if (request.action === "stop") {
902
+ const sessionId = normalizeOptionalString(request.sessionId) || (liveJob?.state === "running" ? liveJob.sessionId : "");
903
+ if (!sessionId) return { text: "āš™ļø No active bash job." };
904
+ const { running } = getScopedSession(sessionId);
905
+ if (!running) {
906
+ if (activeJob?.state === "running" && activeJob.sessionId === sessionId) activeJob = null;
907
+ return { text: `āš™ļø No running bash job found for ${formatSessionSnippet(sessionId)}.` };
908
+ }
909
+ if (!running.backgrounded) return { text: `āš ļø Session ${formatSessionSnippet(sessionId)} is not backgrounded.` };
910
+ const pid = running.pid ?? running.child?.pid;
911
+ 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.` };
912
+ const { killProcessTree } = await import("./kill-tree-Be-ZU6Ay.js");
913
+ killProcessTree(pid);
914
+ return { text: `āš™ļø bash stopping (session ${formatSessionSnippet(sessionId)}). Use !poll ${sessionId} to confirm exit.` };
915
+ }
916
+ 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).` };
917
+ const commandText = request.command.trim();
918
+ if (!commandText) return buildUsageReply();
919
+ activeJob = {
920
+ state: "starting",
921
+ startedAt: Date.now(),
922
+ command: commandText
923
+ };
924
+ try {
925
+ const foregroundMs = resolveForegroundMs(params.cfg);
926
+ const shouldBackgroundImmediately = foregroundMs <= 0;
927
+ const timeoutSec = params.cfg.tools?.exec?.timeoutSec;
928
+ const notifyOnExit = params.cfg.tools?.exec?.notifyOnExit;
929
+ const notifyOnExitEmptySuccess = params.cfg.tools?.exec?.notifyOnExitEmptySuccess;
930
+ const result = await createExecTool({
931
+ scopeKey: CHAT_BASH_SCOPE_KEY,
932
+ allowBackground: true,
933
+ timeoutSec,
934
+ sessionKey: params.sessionKey,
935
+ notifyOnExit,
936
+ notifyOnExitEmptySuccess,
937
+ elevated: {
938
+ enabled: params.elevated.enabled,
939
+ allowed: params.elevated.allowed,
940
+ defaultLevel: "on"
941
+ }
942
+ }).execute("chat-bash", {
943
+ command: commandText,
944
+ background: shouldBackgroundImmediately,
945
+ yieldMs: shouldBackgroundImmediately ? void 0 : foregroundMs,
946
+ timeout: timeoutSec,
947
+ elevated: true
948
+ });
949
+ if (result.details?.status === "running") {
950
+ const sessionId = result.details.sessionId;
951
+ activeJob = {
952
+ state: "running",
953
+ sessionId,
954
+ startedAt: result.details.startedAt,
955
+ command: commandText,
956
+ watcherAttached: false
957
+ };
958
+ attachActiveWatcher(sessionId);
959
+ logVerbose(`Started bash session ${formatSessionSnippet(sessionId)}: ${commandText}`);
960
+ return { text: `āš™ļø bash started (session ${sessionId}). Still running; use !poll / !stop (or /bash poll / /bash stop).` };
961
+ }
962
+ activeJob = null;
963
+ const exitCode = result.details?.status === "completed" ? result.details.exitCode : 0;
964
+ const output = result.details?.status === "completed" ? result.details.aggregated : result.content.map((chunk) => chunk.type === "text" ? chunk.text : "").join("\n");
965
+ return { text: [
966
+ `āš™ļø bash: ${commandText}`,
967
+ `Exit: ${exitCode}`,
968
+ formatOutputBlock(output || "(no output)")
969
+ ].join("\n") };
970
+ } catch (err) {
971
+ activeJob = null;
972
+ const message = formatErrorMessage(err);
973
+ return { text: [`āš ļø bash failed: ${commandText}`, formatOutputBlock(message)].join("\n") };
974
+ }
975
+ }
976
+ //#endregion
977
+ //#region src/auto-reply/reply/commands-bash.ts
978
+ const handleBashCommand = async (params, allowTextCommands) => {
979
+ if (!allowTextCommands) return null;
980
+ const { command } = params;
981
+ const bashSlashRequested = command.commandBodyNormalized === "/bash" || command.commandBodyNormalized.startsWith("/bash ");
982
+ const bashBangRequested = command.commandBodyNormalized.startsWith("!");
983
+ if (!bashSlashRequested && !(bashBangRequested && command.isAuthorizedSender)) return null;
984
+ const unauthorized = rejectUnauthorizedCommand(params, "/bash");
985
+ if (unauthorized) return unauthorized;
986
+ const agentId = params.sessionKey ? resolveSessionAgentId({
987
+ sessionKey: params.sessionKey,
988
+ config: params.cfg
989
+ }) : params.agentId;
990
+ return {
991
+ shouldContinue: false,
992
+ reply: await handleBashChatCommand({
993
+ ctx: params.ctx,
994
+ cfg: params.cfg,
995
+ agentId,
996
+ sessionKey: params.sessionKey,
997
+ isGroup: params.isGroup,
998
+ elevated: params.elevated
999
+ })
1000
+ };
1001
+ };
1002
+ //#endregion
1003
+ //#region src/agents/btw.ts
1004
+ function collectTextContent(content) {
1005
+ return content.filter((part) => part.type === "text").map((part) => part.text).join("");
1006
+ }
1007
+ function collectThinkingContent(content) {
1008
+ return content.filter((part) => part.type === "thinking").map((part) => part.thinking).join("");
1009
+ }
1010
+ function buildBtwSystemPrompt() {
1011
+ return [
1012
+ "You are answering an ephemeral /btw side question about the current conversation.",
1013
+ "Use the conversation only as background context.",
1014
+ "Answer only the side question in the last user message.",
1015
+ "Do not continue, resume, or complete any unfinished task from the conversation.",
1016
+ "Do not emit tool calls, pseudo-tool calls, shell commands, file writes, patches, or code unless the side question explicitly asks for them.",
1017
+ "Do not say you will continue the main task after answering.",
1018
+ "If the question can be answered briefly, answer briefly."
1019
+ ].join("\n");
1020
+ }
1021
+ function buildBtwQuestionPrompt(question, inFlightPrompt) {
1022
+ const lines = ["Answer this side question only.", "Ignore any unfinished task in the conversation while answering it."];
1023
+ const trimmedPrompt = inFlightPrompt?.trim();
1024
+ 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.");
1025
+ lines.push("", "<btw_side_question>", question.trim(), "</btw_side_question>");
1026
+ return lines.join("\n");
1027
+ }
1028
+ function normalizeBtwContentBlocks(content) {
1029
+ if (Array.isArray(content)) return content;
1030
+ if (content && typeof content === "object") return [content];
1031
+ }
1032
+ function isBtwTextBlock(block) {
1033
+ if (!block || typeof block !== "object") return false;
1034
+ const record = block;
1035
+ return normalizeLowercaseStringOrEmpty(record.type) === "text" && typeof record.text === "string";
1036
+ }
1037
+ function isBtwImageBlock(block) {
1038
+ if (!block || typeof block !== "object") return false;
1039
+ const record = block;
1040
+ return normalizeLowercaseStringOrEmpty(record.type) === "image" && typeof record.data === "string" && typeof record.mimeType === "string";
1041
+ }
1042
+ async function sanitizeBtwUserMessage(params) {
1043
+ if (typeof params.message.content === "string") return params.message;
1044
+ const blocks = normalizeBtwContentBlocks(params.message.content);
1045
+ if (!blocks) return;
1046
+ const content = [];
1047
+ for (const block of blocks) {
1048
+ if (isBtwTextBlock(block)) {
1049
+ content.push({
1050
+ type: "text",
1051
+ text: block.text
1052
+ });
1053
+ continue;
1054
+ }
1055
+ if (!isBtwImageBlock(block)) continue;
1056
+ const { images } = await sanitizeImageBlocks([block], "btw:context", params.imageLimits);
1057
+ const image = images[0];
1058
+ if (image) content.push(image);
1059
+ }
1060
+ if (content.length === 0) return;
1061
+ return {
1062
+ ...params.message,
1063
+ content
1064
+ };
1065
+ }
1066
+ function sanitizeBtwAssistantMessage(message) {
1067
+ const rawContent = message.content;
1068
+ if (typeof rawContent === "string") {
1069
+ const trimmed = rawContent.trim();
1070
+ return trimmed.length > 0 ? {
1071
+ ...message,
1072
+ content: [{
1073
+ type: "text",
1074
+ text: trimmed
1075
+ }]
1076
+ } : void 0;
1077
+ }
1078
+ const blocks = normalizeBtwContentBlocks(rawContent);
1079
+ if (!blocks) return;
1080
+ const content = blocks.flatMap((block) => isBtwTextBlock(block) ? [{
1081
+ type: "text",
1082
+ text: block.text
1083
+ }] : []);
1084
+ if (content.length === 0) return;
1085
+ return {
1086
+ ...message,
1087
+ content
1088
+ };
1089
+ }
1090
+ async function toSimpleContextMessages(params) {
1091
+ const contextMessages = [];
1092
+ for (const message of params.messages) {
1093
+ if (!message || typeof message !== "object") continue;
1094
+ const role = message.role;
1095
+ if (role === "user") {
1096
+ const sanitizedMessage = await sanitizeBtwUserMessage({
1097
+ message,
1098
+ imageLimits: params.imageLimits
1099
+ });
1100
+ if (sanitizedMessage) contextMessages.push(sanitizedMessage);
1101
+ continue;
1102
+ }
1103
+ if (role !== "assistant") continue;
1104
+ const sanitizedMessage = sanitizeBtwAssistantMessage(message);
1105
+ if (sanitizedMessage) contextMessages.push(sanitizedMessage);
1106
+ }
1107
+ return stripToolResultDetails(contextMessages);
1108
+ }
1109
+ function resolveSessionTranscriptPath(params) {
1110
+ try {
1111
+ const agentId = params.sessionKey?.split(":")[1];
1112
+ const pathOpts = resolveSessionFilePathOptions({
1113
+ agentId,
1114
+ storePath: params.storePath
1115
+ });
1116
+ return resolveSessionFilePath(params.sessionId, params.sessionEntry, pathOpts);
1117
+ } catch (error) {
1118
+ diagnosticLogger.debug(`resolveSessionTranscriptPath failed: sessionId=${params.sessionId} err=${String(error)}`);
1119
+ return;
1120
+ }
1121
+ }
1122
+ async function resolveRuntimeModel(params) {
1123
+ await ensureGenesisModelsJson(params.cfg, params.agentDir);
1124
+ const modelRegistry = discoverModels(discoverAuthStorage(params.agentDir), params.agentDir);
1125
+ const model = resolveModelWithRegistry({
1126
+ provider: params.provider,
1127
+ modelId: params.model,
1128
+ modelRegistry,
1129
+ cfg: params.cfg
1130
+ });
1131
+ if (!model) throw new Error(`Unknown model: ${params.provider}/${params.model}`);
1132
+ return {
1133
+ model,
1134
+ authProfileId: await resolveSessionAuthProfileOverride({
1135
+ cfg: params.cfg,
1136
+ provider: params.provider,
1137
+ agentDir: params.agentDir,
1138
+ sessionEntry: params.sessionEntry,
1139
+ sessionStore: params.sessionStore,
1140
+ sessionKey: params.sessionKey,
1141
+ storePath: params.storePath,
1142
+ isNewSession: params.isNewSession
1143
+ }),
1144
+ authProfileIdSource: params.sessionEntry?.authProfileOverrideSource
1145
+ };
1146
+ }
1147
+ async function runBtwSideQuestion(params) {
1148
+ const sessionId = params.sessionEntry.sessionId?.trim();
1149
+ if (!sessionId) throw new Error("No active session context.");
1150
+ const sessionFile = resolveSessionTranscriptPath({
1151
+ sessionId,
1152
+ sessionEntry: params.sessionEntry,
1153
+ sessionKey: params.sessionKey,
1154
+ storePath: params.storePath
1155
+ });
1156
+ if (!sessionFile) throw new Error("No active session transcript.");
1157
+ const sessionManager = SessionManager.open(sessionFile);
1158
+ const activeRunSnapshot = getActiveEmbeddedRunSnapshot(sessionId);
1159
+ const imageLimits = resolveImageSanitizationLimits(params.cfg);
1160
+ let messages = [];
1161
+ let inFlightPrompt;
1162
+ if (Array.isArray(activeRunSnapshot?.messages) && activeRunSnapshot.messages.length > 0) {
1163
+ messages = await toSimpleContextMessages({
1164
+ messages: activeRunSnapshot.messages,
1165
+ imageLimits
1166
+ });
1167
+ inFlightPrompt = activeRunSnapshot.inFlightPrompt;
1168
+ } else if (activeRunSnapshot) {
1169
+ inFlightPrompt = activeRunSnapshot.inFlightPrompt;
1170
+ if (activeRunSnapshot.transcriptLeafId && sessionManager.branch) try {
1171
+ sessionManager.branch(activeRunSnapshot.transcriptLeafId);
1172
+ } catch (error) {
1173
+ diagnosticLogger.debug(`btw snapshot leaf unavailable: sessionId=${sessionId} leaf=${activeRunSnapshot.transcriptLeafId} err=${String(error)}`);
1174
+ sessionManager.resetLeaf?.();
1175
+ }
1176
+ else sessionManager.resetLeaf?.();
1177
+ } else {
1178
+ const leafEntry = sessionManager.getLeafEntry?.();
1179
+ if (leafEntry?.type === "message" && leafEntry.message?.role === "user") if (leafEntry.parentId && sessionManager.branch) sessionManager.branch(leafEntry.parentId);
1180
+ else sessionManager.resetLeaf?.();
1181
+ }
1182
+ if (messages.length === 0) {
1183
+ const sessionContext = sessionManager.buildSessionContext();
1184
+ messages = await toSimpleContextMessages({
1185
+ messages: Array.isArray(sessionContext.messages) ? sessionContext.messages : [],
1186
+ imageLimits
1187
+ });
1188
+ }
1189
+ if (messages.length === 0 && !inFlightPrompt?.trim()) throw new Error("No active session context.");
1190
+ const { model, authProfileId } = await resolveRuntimeModel({
1191
+ cfg: params.cfg,
1192
+ provider: params.provider,
1193
+ model: params.model,
1194
+ agentDir: params.agentDir,
1195
+ sessionEntry: params.sessionEntry,
1196
+ sessionStore: params.sessionStore,
1197
+ sessionKey: params.sessionKey,
1198
+ storePath: params.storePath,
1199
+ isNewSession: params.isNewSession
1200
+ });
1201
+ const apiKeyInfo = await getApiKeyForModel({
1202
+ model,
1203
+ cfg: params.cfg,
1204
+ profileId: authProfileId,
1205
+ agentDir: params.agentDir
1206
+ });
1207
+ let runtimeModel = model;
1208
+ let apiKey = apiKeyInfo.mode === "aws-sdk" && !apiKeyInfo.apiKey ? void 0 : requireApiKey(apiKeyInfo, model.provider);
1209
+ const sessionAgentId = resolveSessionAgentId({
1210
+ sessionKey: params.sessionKey,
1211
+ config: params.cfg
1212
+ });
1213
+ const workspaceDir = resolveAgentWorkspaceDir(params.cfg, sessionAgentId);
1214
+ if (apiKey) {
1215
+ const preparedAuth = await prepareProviderRuntimeAuth({
1216
+ provider: model.provider,
1217
+ config: params.cfg,
1218
+ workspaceDir,
1219
+ env: process.env,
1220
+ context: {
1221
+ config: params.cfg,
1222
+ agentDir: params.agentDir,
1223
+ workspaceDir,
1224
+ env: process.env,
1225
+ provider: model.provider,
1226
+ modelId: model.id,
1227
+ model,
1228
+ apiKey,
1229
+ authMode: apiKeyInfo.mode,
1230
+ profileId: authProfileId
1231
+ }
1232
+ });
1233
+ if (preparedAuth?.baseUrl) runtimeModel = {
1234
+ ...runtimeModel,
1235
+ baseUrl: preparedAuth.baseUrl
1236
+ };
1237
+ if (preparedAuth?.apiKey) apiKey = preparedAuth.apiKey;
1238
+ }
1239
+ const providerStreamFn = registerProviderStreamForModel({
1240
+ model: runtimeModel,
1241
+ cfg: params.cfg,
1242
+ agentDir: params.agentDir,
1243
+ workspaceDir,
1244
+ env: process.env
1245
+ });
1246
+ const chunker = params.opts?.onBlockReply && params.blockReplyChunking ? new EmbeddedBlockChunker(params.blockReplyChunking) : void 0;
1247
+ let emittedBlocks = 0;
1248
+ let blockEmitChain = Promise.resolve();
1249
+ let answerText = "";
1250
+ let reasoningText = "";
1251
+ let assistantStarted = false;
1252
+ let sawTextEvent = false;
1253
+ const emitBlockChunk = async (text) => {
1254
+ if (!text.trim() || !params.opts?.onBlockReply) return;
1255
+ emittedBlocks += 1;
1256
+ blockEmitChain = blockEmitChain.then(async () => {
1257
+ await params.opts?.onBlockReply?.({
1258
+ text,
1259
+ btw: { question: params.question }
1260
+ });
1261
+ });
1262
+ await blockEmitChain;
1263
+ };
1264
+ const stream = await streamWithPayloadPatch(providerStreamFn ?? streamSimple, runtimeModel, {
1265
+ systemPrompt: buildBtwSystemPrompt(),
1266
+ messages: [...messages, {
1267
+ role: "user",
1268
+ content: [{
1269
+ type: "text",
1270
+ text: buildBtwQuestionPrompt(params.question, inFlightPrompt)
1271
+ }],
1272
+ timestamp: Date.now()
1273
+ }]
1274
+ }, {
1275
+ apiKey,
1276
+ reasoning: void 0,
1277
+ signal: params.opts?.abortSignal
1278
+ }, (payloadObj) => {
1279
+ if (Array.isArray(payloadObj.tools) && payloadObj.tools.length === 0) delete payloadObj.tools;
1280
+ });
1281
+ let finalEvent;
1282
+ for await (const event of stream) {
1283
+ finalEvent = event.type === "done" || event.type === "error" ? event : finalEvent;
1284
+ if (!assistantStarted && (event.type === "text_start" || event.type === "start")) {
1285
+ assistantStarted = true;
1286
+ await params.opts?.onAssistantMessageStart?.();
1287
+ }
1288
+ if (event.type === "text_delta") {
1289
+ sawTextEvent = true;
1290
+ answerText += event.delta;
1291
+ chunker?.append(event.delta);
1292
+ if (chunker && params.resolvedBlockStreamingBreak === "text_end") chunker.drain({
1293
+ force: false,
1294
+ emit: (chunk) => void emitBlockChunk(chunk)
1295
+ });
1296
+ continue;
1297
+ }
1298
+ if (event.type === "text_end" && chunker && params.resolvedBlockStreamingBreak === "text_end") {
1299
+ chunker.drain({
1300
+ force: true,
1301
+ emit: (chunk) => void emitBlockChunk(chunk)
1302
+ });
1303
+ continue;
1304
+ }
1305
+ if (event.type === "thinking_delta") {
1306
+ reasoningText += event.delta;
1307
+ if (params.resolvedReasoningLevel !== "off") await params.opts?.onReasoningStream?.({
1308
+ text: reasoningText,
1309
+ isReasoning: true
1310
+ });
1311
+ continue;
1312
+ }
1313
+ if (event.type === "thinking_end" && params.resolvedReasoningLevel !== "off") await params.opts?.onReasoningEnd?.();
1314
+ }
1315
+ if (chunker && params.resolvedBlockStreamingBreak !== "text_end" && chunker.hasBuffered()) chunker.drain({
1316
+ force: true,
1317
+ emit: (chunk) => void emitBlockChunk(chunk)
1318
+ });
1319
+ await blockEmitChain;
1320
+ if (finalEvent?.type === "error") {
1321
+ const message = collectTextContent(finalEvent.error.content);
1322
+ throw new Error(message || finalEvent.error.errorMessage || "BTW failed.");
1323
+ }
1324
+ const finalMessage = finalEvent?.type === "done" ? finalEvent.message : void 0;
1325
+ if (finalMessage) {
1326
+ if (!sawTextEvent) answerText = collectTextContent(finalMessage.content);
1327
+ if (!reasoningText) reasoningText = collectThinkingContent(finalMessage.content);
1328
+ }
1329
+ const answer = answerText.trim();
1330
+ if (!answer) throw new Error("No BTW response generated.");
1331
+ if (emittedBlocks > 0) return;
1332
+ return { text: answer };
1333
+ }
1334
+ //#endregion
1335
+ //#region src/auto-reply/reply/commands-btw.ts
1336
+ const BTW_USAGE = "Usage: /btw <side question>";
1337
+ const handleBtwCommand = async (params, allowTextCommands) => {
1338
+ if (!allowTextCommands) return null;
1339
+ const question = extractBtwQuestion(params.command.commandBodyNormalized);
1340
+ if (question === null) return null;
1341
+ const unauthorized = rejectUnauthorizedCommand(params, "/btw");
1342
+ if (unauthorized) return unauthorized;
1343
+ if (!question) return {
1344
+ shouldContinue: false,
1345
+ reply: { text: BTW_USAGE }
1346
+ };
1347
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
1348
+ if (!targetSessionEntry?.sessionId) return {
1349
+ shouldContinue: false,
1350
+ reply: { text: "āš ļø /btw requires an active session with existing context." }
1351
+ };
1352
+ const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
1353
+ sessionKey: params.sessionKey,
1354
+ config: params.cfg
1355
+ }) : params.agentId;
1356
+ const agentDir = (sessionAgentId ? resolveAgentDir(params.cfg, sessionAgentId) : void 0) ?? params.agentDir;
1357
+ if (!agentDir) return {
1358
+ shouldContinue: false,
1359
+ reply: { text: "āš ļø /btw is unavailable because the active agent directory could not be resolved." }
1360
+ };
1361
+ try {
1362
+ await params.typing?.startTypingLoop();
1363
+ const reply = await runBtwSideQuestion({
1364
+ cfg: params.cfg,
1365
+ agentDir,
1366
+ provider: params.provider,
1367
+ model: params.model,
1368
+ question,
1369
+ sessionEntry: targetSessionEntry,
1370
+ sessionStore: params.sessionStore,
1371
+ sessionKey: params.sessionKey,
1372
+ storePath: params.storePath,
1373
+ resolvedThinkLevel: "off",
1374
+ resolvedReasoningLevel: "off",
1375
+ blockReplyChunking: params.blockReplyChunking,
1376
+ resolvedBlockStreamingBreak: params.resolvedBlockStreamingBreak,
1377
+ opts: params.opts,
1378
+ isNewSession: false
1379
+ });
1380
+ return {
1381
+ shouldContinue: false,
1382
+ reply: reply ? {
1383
+ ...reply,
1384
+ btw: { question }
1385
+ } : reply
1386
+ };
1387
+ } catch (error) {
1388
+ const message = error instanceof Error ? error.message.trim() : "";
1389
+ return {
1390
+ shouldContinue: false,
1391
+ reply: {
1392
+ text: `āš ļø /btw failed${message ? `: ${message}` : "."}`,
1393
+ btw: { question },
1394
+ isError: true
1395
+ }
1396
+ };
1397
+ }
1398
+ };
1399
+ //#endregion
1400
+ //#region src/auto-reply/reply/commands-compact.ts
1401
+ let compactRuntimePromise = null;
1402
+ function loadCompactRuntime() {
1403
+ compactRuntimePromise ??= import("./commands-compact.runtime-Dbbx-Ps6.js");
1404
+ return compactRuntimePromise;
1405
+ }
1406
+ function extractCompactInstructions(params) {
1407
+ const raw = stripStructuralPrefixes(params.rawBody ?? "");
1408
+ const trimmed = (params.isGroup ? stripMentions(raw, params.ctx, params.cfg, params.agentId) : raw).trim();
1409
+ if (!trimmed) return;
1410
+ const prefix = normalizeLowercaseStringOrEmpty(trimmed).startsWith("/compact") ? "/compact" : null;
1411
+ if (!prefix) return;
1412
+ let rest = trimmed.slice(prefix.length).trimStart();
1413
+ if (rest.startsWith(":")) rest = rest.slice(1).trimStart();
1414
+ return rest.length ? rest : void 0;
1415
+ }
1416
+ function isCompactionSkipReason(reason) {
1417
+ const text = normalizeOptionalLowercaseString(reason) ?? "";
1418
+ return text.includes("nothing to compact") || text.includes("below threshold") || text.includes("already compacted") || text.includes("no real conversation messages");
1419
+ }
1420
+ function formatCompactionReason(reason) {
1421
+ const text = normalizeOptionalString(reason);
1422
+ if (!text) return;
1423
+ const lower = normalizeLowercaseStringOrEmpty(text);
1424
+ if (lower.includes("nothing to compact")) return "nothing compactable in this session yet";
1425
+ if (lower.includes("below threshold")) return "context is below the compaction threshold";
1426
+ if (lower.includes("already compacted")) return "session was already compacted recently";
1427
+ if (lower.includes("no real conversation messages")) return "no real conversation messages yet";
1428
+ return text;
1429
+ }
1430
+ const handleCompactCommand = async (params) => {
1431
+ if (!(params.command.commandBodyNormalized === "/compact" || params.command.commandBodyNormalized.startsWith("/compact "))) return null;
1432
+ if (!params.command.isAuthorizedSender) {
1433
+ logVerbose(`Ignoring /compact from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
1434
+ return { shouldContinue: false };
1435
+ }
1436
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
1437
+ if (!targetSessionEntry?.sessionId) return {
1438
+ shouldContinue: false,
1439
+ reply: { text: "āš™ļø Compaction unavailable (missing session id)." }
1440
+ };
1441
+ const runtime = await loadCompactRuntime();
1442
+ const sessionId = targetSessionEntry.sessionId;
1443
+ if (runtime.isEmbeddedPiRunActive(sessionId)) {
1444
+ runtime.abortEmbeddedPiRun(sessionId);
1445
+ await runtime.waitForEmbeddedPiRunEnd(sessionId, 15e3);
1446
+ }
1447
+ const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
1448
+ sessionKey: params.sessionKey,
1449
+ config: params.cfg
1450
+ }) : params.agentId ?? "main";
1451
+ const sessionAgentDir = sessionAgentId === (params.agentId ?? "main") && params.agentDir ? params.agentDir : resolveAgentDir(params.cfg, sessionAgentId);
1452
+ const customInstructions = extractCompactInstructions({
1453
+ rawBody: params.ctx.CommandBody ?? params.ctx.RawBody ?? params.ctx.Body,
1454
+ ctx: params.ctx,
1455
+ cfg: params.cfg,
1456
+ agentId: sessionAgentId,
1457
+ isGroup: params.isGroup
1458
+ });
1459
+ const result = await runtime.compactEmbeddedPiSession({
1460
+ sessionId,
1461
+ sessionKey: params.sessionKey,
1462
+ allowGatewaySubagentBinding: true,
1463
+ messageChannel: params.command.channel,
1464
+ groupId: targetSessionEntry.groupId,
1465
+ groupChannel: targetSessionEntry.groupChannel,
1466
+ groupSpace: targetSessionEntry.space,
1467
+ spawnedBy: targetSessionEntry.spawnedBy,
1468
+ senderId: params.command.senderId,
1469
+ senderName: params.ctx.SenderName,
1470
+ senderUsername: params.ctx.SenderUsername,
1471
+ senderE164: params.ctx.SenderE164,
1472
+ sessionFile: runtime.resolveSessionFilePath(sessionId, targetSessionEntry, runtime.resolveSessionFilePathOptions({
1473
+ agentId: sessionAgentId,
1474
+ storePath: params.storePath
1475
+ })),
1476
+ workspaceDir: params.workspaceDir,
1477
+ agentDir: sessionAgentDir,
1478
+ config: params.cfg,
1479
+ skillsSnapshot: targetSessionEntry.skillsSnapshot,
1480
+ provider: params.provider,
1481
+ model: params.model,
1482
+ agentHarnessId: targetSessionEntry.sessionId === sessionId ? targetSessionEntry.agentHarnessId : void 0,
1483
+ thinkLevel: params.resolvedThinkLevel ?? await params.resolveDefaultThinkingLevel(),
1484
+ bashElevated: {
1485
+ enabled: false,
1486
+ allowed: false,
1487
+ defaultLevel: "off"
1488
+ },
1489
+ customInstructions,
1490
+ trigger: "manual",
1491
+ senderIsOwner: params.command.senderIsOwner,
1492
+ ownerNumbers: params.command.ownerList.length > 0 ? params.command.ownerList : void 0
1493
+ });
1494
+ 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";
1495
+ if (result.ok && result.compacted) await runtime.incrementCompactionCount({
1496
+ cfg: params.cfg,
1497
+ sessionEntry: targetSessionEntry,
1498
+ sessionStore: params.sessionStore,
1499
+ sessionKey: params.sessionKey,
1500
+ storePath: params.storePath,
1501
+ tokensAfter: result.result?.tokensAfter
1502
+ });
1503
+ const totalTokens = result.result?.tokensAfter ?? runtime.resolveFreshSessionTotalTokens(targetSessionEntry);
1504
+ const contextSummary = runtime.formatContextUsageShort(typeof totalTokens === "number" && totalTokens > 0 ? totalTokens : null, params.contextTokens ?? targetSessionEntry.contextTokens ?? null);
1505
+ const reason = formatCompactionReason(result.reason);
1506
+ const line = reason ? `${compactLabel}: ${reason} • ${contextSummary}` : `${compactLabel} • ${contextSummary}`;
1507
+ runtime.enqueueSystemEvent(line, { sessionKey: params.sessionKey });
1508
+ return {
1509
+ shouldContinue: false,
1510
+ reply: { text: `āš™ļø ${line}` }
1511
+ };
1512
+ };
1513
+ //#endregion
1514
+ //#region src/auto-reply/reply/commands-slash-parse.ts
1515
+ function parseSlashCommandActionArgs(raw, slash) {
1516
+ const trimmed = raw.trim();
1517
+ const slashLower = normalizeLowercaseStringOrEmpty(slash);
1518
+ if (!normalizeLowercaseStringOrEmpty(trimmed).startsWith(slashLower)) return { kind: "no-match" };
1519
+ const rest = trimmed.slice(slash.length).trim();
1520
+ if (!rest) return { kind: "empty" };
1521
+ const match = rest.match(/^(\S+)(?:\s+([\s\S]+))?$/);
1522
+ if (!match) return { kind: "invalid" };
1523
+ return {
1524
+ kind: "parsed",
1525
+ action: normalizeLowercaseStringOrEmpty(match[1]),
1526
+ args: (match[2] ?? "").trim()
1527
+ };
1528
+ }
1529
+ function parseSlashCommandOrNull(raw, slash, opts) {
1530
+ const parsed = parseSlashCommandActionArgs(raw, slash);
1531
+ if (parsed.kind === "no-match") return null;
1532
+ if (parsed.kind === "invalid") return {
1533
+ ok: false,
1534
+ message: opts.invalidMessage
1535
+ };
1536
+ if (parsed.kind === "empty") return {
1537
+ ok: true,
1538
+ action: opts.defaultAction ?? "show",
1539
+ args: ""
1540
+ };
1541
+ return {
1542
+ ok: true,
1543
+ action: parsed.action,
1544
+ args: parsed.args
1545
+ };
1546
+ }
1547
+ //#endregion
1548
+ //#region src/auto-reply/reply/commands-setunset.ts
1549
+ function parseSetUnsetCommand(params) {
1550
+ const action = params.action;
1551
+ const args = params.args.trim();
1552
+ if (action === "unset") {
1553
+ if (!args) return {
1554
+ kind: "error",
1555
+ message: `Usage: ${params.slash} unset path`
1556
+ };
1557
+ return {
1558
+ kind: "unset",
1559
+ path: args
1560
+ };
1561
+ }
1562
+ if (!args) return {
1563
+ kind: "error",
1564
+ message: `Usage: ${params.slash} set path=value`
1565
+ };
1566
+ const eqIndex = args.indexOf("=");
1567
+ if (eqIndex <= 0) return {
1568
+ kind: "error",
1569
+ message: `Usage: ${params.slash} set path=value`
1570
+ };
1571
+ const path = args.slice(0, eqIndex).trim();
1572
+ const rawValue = args.slice(eqIndex + 1);
1573
+ if (!path) return {
1574
+ kind: "error",
1575
+ message: `Usage: ${params.slash} set path=value`
1576
+ };
1577
+ const parsed = parseConfigValue(rawValue);
1578
+ if (parsed.error) return {
1579
+ kind: "error",
1580
+ message: parsed.error
1581
+ };
1582
+ return {
1583
+ kind: "set",
1584
+ path,
1585
+ value: parsed.value
1586
+ };
1587
+ }
1588
+ function parseSetUnsetCommandAction(params) {
1589
+ if (params.action !== "set" && params.action !== "unset") return null;
1590
+ const parsed = parseSetUnsetCommand({
1591
+ slash: params.slash,
1592
+ action: params.action,
1593
+ args: params.args
1594
+ });
1595
+ if (parsed.kind === "error") return params.onError(parsed.message);
1596
+ return parsed.kind === "set" ? params.onSet(parsed.path, parsed.value) : params.onUnset(parsed.path);
1597
+ }
1598
+ function parseSlashCommandWithSetUnset(params) {
1599
+ const parsed = parseSlashCommandOrNull(params.raw, params.slash, { invalidMessage: params.invalidMessage });
1600
+ if (!parsed) return null;
1601
+ if (!parsed.ok) return params.onError(parsed.message);
1602
+ const { action, args } = parsed;
1603
+ const setUnset = parseSetUnsetCommandAction({
1604
+ slash: params.slash,
1605
+ action,
1606
+ args,
1607
+ onSet: params.onSet,
1608
+ onUnset: params.onUnset,
1609
+ onError: params.onError
1610
+ });
1611
+ if (setUnset) return setUnset;
1612
+ const knownAction = params.onKnownAction(action, args);
1613
+ if (knownAction) return knownAction;
1614
+ return params.onError(params.usageMessage);
1615
+ }
1616
+ //#endregion
1617
+ //#region src/auto-reply/reply/commands-setunset-standard.ts
1618
+ function parseStandardSetUnsetSlashCommand(params) {
1619
+ return parseSlashCommandWithSetUnset({
1620
+ raw: params.raw,
1621
+ slash: params.slash,
1622
+ invalidMessage: params.invalidMessage,
1623
+ usageMessage: params.usageMessage,
1624
+ onKnownAction: params.onKnownAction,
1625
+ onSet: params.onSet ?? ((path, value) => ({
1626
+ action: "set",
1627
+ path,
1628
+ value
1629
+ })),
1630
+ onUnset: params.onUnset ?? ((path) => ({
1631
+ action: "unset",
1632
+ path
1633
+ })),
1634
+ onError: params.onError ?? ((message) => ({
1635
+ action: "error",
1636
+ message
1637
+ }))
1638
+ });
1639
+ }
1640
+ //#endregion
1641
+ //#region src/auto-reply/reply/config-commands.ts
1642
+ function parseConfigCommand(raw) {
1643
+ return parseStandardSetUnsetSlashCommand({
1644
+ raw,
1645
+ slash: "/config",
1646
+ invalidMessage: "Invalid /config syntax.",
1647
+ usageMessage: "Usage: /config show|set|unset",
1648
+ onKnownAction: (action, args) => {
1649
+ if (action === "show" || action === "get") return {
1650
+ action: "show",
1651
+ path: args || void 0
1652
+ };
1653
+ }
1654
+ });
1655
+ }
1656
+ //#endregion
1657
+ //#region src/auto-reply/reply/debug-commands.ts
1658
+ function parseDebugCommand(raw) {
1659
+ return parseStandardSetUnsetSlashCommand({
1660
+ raw,
1661
+ slash: "/debug",
1662
+ invalidMessage: "Invalid /debug syntax.",
1663
+ usageMessage: "Usage: /debug show|set|unset|reset",
1664
+ onKnownAction: (action) => {
1665
+ if (action === "show") return { action: "show" };
1666
+ if (action === "reset") return { action: "reset" };
1667
+ }
1668
+ });
1669
+ }
1670
+ //#endregion
1671
+ //#region src/auto-reply/reply/commands-config.ts
1672
+ const handleConfigCommand = async (params, allowTextCommands) => {
1673
+ if (!allowTextCommands) return null;
1674
+ const configCommand = parseConfigCommand(params.command.commandBodyNormalized);
1675
+ if (!configCommand) return null;
1676
+ const unauthorized = rejectUnauthorizedCommand(params, "/config");
1677
+ if (unauthorized) return unauthorized;
1678
+ const nonOwner = configCommand.action === "show" && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/config");
1679
+ if (nonOwner) return nonOwner;
1680
+ const disabled = requireCommandFlagEnabled(params.cfg, {
1681
+ label: "/config",
1682
+ configKey: "config"
1683
+ });
1684
+ if (disabled) return disabled;
1685
+ if (configCommand.action === "error") return {
1686
+ shouldContinue: false,
1687
+ reply: { text: `āš ļø ${configCommand.message}` }
1688
+ };
1689
+ let parsedWritePath;
1690
+ if (configCommand.action === "set" || configCommand.action === "unset") {
1691
+ const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
1692
+ label: "/config write",
1693
+ allowedScopes: ["operator.admin"],
1694
+ missingText: "āŒ /config set|unset requires operator.admin for gateway clients."
1695
+ });
1696
+ if (missingAdminScope) return missingAdminScope;
1697
+ const parsedPath = parseConfigPath(configCommand.path);
1698
+ if (!parsedPath.ok || !parsedPath.path) return {
1699
+ shouldContinue: false,
1700
+ reply: { text: `āš ļø ${parsedPath.error ?? "Invalid path."}` }
1701
+ };
1702
+ parsedWritePath = parsedPath.path;
1703
+ const channelId = params.command.channelId ?? normalizeChannelId(params.command.channel);
1704
+ const deniedText = resolveConfigWriteDeniedText({
1705
+ cfg: params.cfg,
1706
+ channel: params.command.channel,
1707
+ channelId,
1708
+ accountId: resolveChannelAccountId({
1709
+ cfg: params.cfg,
1710
+ ctx: params.ctx,
1711
+ command: params.command
1712
+ }),
1713
+ gatewayClientScopes: params.ctx.GatewayClientScopes,
1714
+ target: resolveConfigWriteTargetFromPath(parsedWritePath)
1715
+ });
1716
+ if (deniedText) return {
1717
+ shouldContinue: false,
1718
+ reply: { text: deniedText }
1719
+ };
1720
+ }
1721
+ const snapshot = await readConfigFileSnapshot();
1722
+ if (!snapshot.valid || !snapshot.parsed || typeof snapshot.parsed !== "object") return {
1723
+ shouldContinue: false,
1724
+ reply: { text: "āš ļø Config file is invalid; fix it before using /config." }
1725
+ };
1726
+ const parsedBase = structuredClone(snapshot.parsed);
1727
+ if (configCommand.action === "show") {
1728
+ const pathRaw = normalizeOptionalString(configCommand.path);
1729
+ if (pathRaw) {
1730
+ const parsedPath = parseConfigPath(pathRaw);
1731
+ if (!parsedPath.ok || !parsedPath.path) return {
1732
+ shouldContinue: false,
1733
+ reply: { text: `āš ļø ${parsedPath.error ?? "Invalid path."}` }
1734
+ };
1735
+ const value = getConfigValueAtPath(parsedBase, parsedPath.path);
1736
+ return {
1737
+ shouldContinue: false,
1738
+ reply: { text: `āš™ļø Config ${pathRaw}:\n\`\`\`json\n${JSON.stringify(value ?? null, null, 2)}\n\`\`\`` }
1739
+ };
1740
+ }
1741
+ return {
1742
+ shouldContinue: false,
1743
+ reply: { text: `āš™ļø Config (raw):\n\`\`\`json\n${JSON.stringify(parsedBase, null, 2)}\n\`\`\`` }
1744
+ };
1745
+ }
1746
+ if (configCommand.action === "unset") {
1747
+ if (!unsetConfigValueAtPath(parsedBase, parsedWritePath ?? [])) return {
1748
+ shouldContinue: false,
1749
+ reply: { text: `āš™ļø No config value found for ${configCommand.path}.` }
1750
+ };
1751
+ const validated = validateConfigObjectWithPlugins(parsedBase);
1752
+ if (!validated.ok) {
1753
+ const issue = validated.issues[0];
1754
+ return {
1755
+ shouldContinue: false,
1756
+ reply: { text: `āš ļø Config invalid after unset (${issue.path}: ${issue.message}).` }
1757
+ };
1758
+ }
1759
+ await writeConfigFile(validated.config);
1760
+ return {
1761
+ shouldContinue: false,
1762
+ reply: { text: `āš™ļø Config updated: ${configCommand.path} removed.` }
1763
+ };
1764
+ }
1765
+ if (configCommand.action === "set") {
1766
+ setConfigValueAtPath(parsedBase, parsedWritePath ?? [], configCommand.value);
1767
+ const validated = validateConfigObjectWithPlugins(parsedBase);
1768
+ if (!validated.ok) {
1769
+ const issue = validated.issues[0];
1770
+ return {
1771
+ shouldContinue: false,
1772
+ reply: { text: `āš ļø Config invalid after set (${issue.path}: ${issue.message}).` }
1773
+ };
1774
+ }
1775
+ await writeConfigFile(validated.config);
1776
+ const valueLabel = typeof configCommand.value === "string" ? `"${configCommand.value}"` : JSON.stringify(configCommand.value);
1777
+ return {
1778
+ shouldContinue: false,
1779
+ reply: { text: `āš™ļø Config updated: ${configCommand.path}=${valueLabel ?? "null"}` }
1780
+ };
1781
+ }
1782
+ return null;
1783
+ };
1784
+ const handleDebugCommand = async (params, allowTextCommands) => {
1785
+ if (!allowTextCommands) return null;
1786
+ const debugCommand = parseDebugCommand(params.command.commandBodyNormalized);
1787
+ if (!debugCommand) return null;
1788
+ const unauthorized = rejectUnauthorizedCommand(params, "/debug");
1789
+ if (unauthorized) return unauthorized;
1790
+ const nonOwner = rejectNonOwnerCommand(params, "/debug");
1791
+ if (nonOwner) return nonOwner;
1792
+ const disabled = requireCommandFlagEnabled(params.cfg, {
1793
+ label: "/debug",
1794
+ configKey: "debug"
1795
+ });
1796
+ if (disabled) return disabled;
1797
+ if (debugCommand.action === "error") return {
1798
+ shouldContinue: false,
1799
+ reply: { text: `āš ļø ${debugCommand.message}` }
1800
+ };
1801
+ if (debugCommand.action === "show") {
1802
+ const overrides = getConfigOverrides();
1803
+ if (!(Object.keys(overrides).length > 0)) return {
1804
+ shouldContinue: false,
1805
+ reply: { text: "āš™ļø Debug overrides: (none)" }
1806
+ };
1807
+ return {
1808
+ shouldContinue: false,
1809
+ reply: { text: `āš™ļø Debug overrides (memory-only):\n\`\`\`json\n${JSON.stringify(overrides, null, 2)}\n\`\`\`` }
1810
+ };
1811
+ }
1812
+ if (debugCommand.action === "reset") {
1813
+ resetConfigOverrides();
1814
+ return {
1815
+ shouldContinue: false,
1816
+ reply: { text: "āš™ļø Debug overrides cleared; using config on disk." }
1817
+ };
1818
+ }
1819
+ if (debugCommand.action === "unset") {
1820
+ const result = unsetConfigOverride(debugCommand.path);
1821
+ if (!result.ok) return {
1822
+ shouldContinue: false,
1823
+ reply: { text: `āš ļø ${result.error ?? "Invalid path."}` }
1824
+ };
1825
+ if (!result.removed) return {
1826
+ shouldContinue: false,
1827
+ reply: { text: `āš™ļø No debug override found for ${debugCommand.path}.` }
1828
+ };
1829
+ return {
1830
+ shouldContinue: false,
1831
+ reply: { text: `āš™ļø Debug override removed for ${debugCommand.path}.` }
1832
+ };
1833
+ }
1834
+ if (debugCommand.action === "set") {
1835
+ const result = setConfigOverride(debugCommand.path, debugCommand.value);
1836
+ if (!result.ok) return {
1837
+ shouldContinue: false,
1838
+ reply: { text: `āš ļø ${result.error ?? "Invalid override."}` }
1839
+ };
1840
+ const valueLabel = typeof debugCommand.value === "string" ? `"${debugCommand.value}"` : JSON.stringify(debugCommand.value);
1841
+ return {
1842
+ shouldContinue: false,
1843
+ reply: { text: `āš™ļø Debug override set: ${debugCommand.path}=${valueLabel ?? "null"}` }
1844
+ };
1845
+ }
1846
+ return null;
1847
+ };
1848
+ //#endregion
1849
+ //#region src/auto-reply/reply/commands-context-report.ts
1850
+ function formatInt(n) {
1851
+ return new Intl.NumberFormat("en-US").format(n);
1852
+ }
1853
+ function formatCharsAndTokens(chars) {
1854
+ return `${formatInt(chars)} chars (~${formatInt(estimateTokensFromChars(chars))} tok)`;
1855
+ }
1856
+ function parseContextArgs(commandBodyNormalized) {
1857
+ if (commandBodyNormalized === "/context") return "";
1858
+ if (commandBodyNormalized.startsWith("/context ")) return commandBodyNormalized.slice(8).trim();
1859
+ return "";
1860
+ }
1861
+ function formatListTop(entries, cap) {
1862
+ const sorted = [...entries].toSorted((a, b) => b.value - a.value);
1863
+ const top = sorted.slice(0, cap);
1864
+ const omitted = Math.max(0, sorted.length - top.length);
1865
+ return {
1866
+ lines: top.map((e) => `- ${e.name}: ${formatCharsAndTokens(e.value)}`),
1867
+ omitted
1868
+ };
1869
+ }
1870
+ async function resolveContextReport(params) {
1871
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
1872
+ const existing = targetSessionEntry?.systemPromptReport;
1873
+ if (existing && existing.source === "run") return existing;
1874
+ const bootstrapMaxChars = resolveBootstrapMaxChars(params.cfg);
1875
+ const bootstrapTotalMaxChars = resolveBootstrapTotalMaxChars(params.cfg);
1876
+ const { resolveCommandsSystemPromptBundle } = await import("./commands-system-prompt-aXNuSW_q.js");
1877
+ const { systemPrompt, tools, skillsPrompt, bootstrapFiles, injectedFiles, sandboxRuntime } = await resolveCommandsSystemPromptBundle(params);
1878
+ return buildSystemPromptReport({
1879
+ source: "estimate",
1880
+ generatedAt: Date.now(),
1881
+ sessionId: targetSessionEntry?.sessionId,
1882
+ sessionKey: params.sessionKey,
1883
+ provider: params.provider,
1884
+ model: params.model,
1885
+ workspaceDir: params.workspaceDir,
1886
+ bootstrapMaxChars,
1887
+ bootstrapTotalMaxChars,
1888
+ sandbox: {
1889
+ mode: sandboxRuntime.mode,
1890
+ sandboxed: sandboxRuntime.sandboxed
1891
+ },
1892
+ systemPrompt,
1893
+ bootstrapFiles,
1894
+ injectedFiles,
1895
+ skillsPrompt,
1896
+ tools
1897
+ });
1898
+ }
1899
+ async function buildContextReply(params) {
1900
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
1901
+ const sub = normalizeLowercaseStringOrEmpty(parseContextArgs(params.command.commandBodyNormalized).split(/\s+/).find(Boolean));
1902
+ if (!sub || sub === "help") return { text: [
1903
+ "🧠 /context",
1904
+ "",
1905
+ "What counts as context (high-level), plus a breakdown mode.",
1906
+ "",
1907
+ "Try:",
1908
+ "- /context list (short breakdown)",
1909
+ "- /context detail (per-file + per-tool + per-skill + system prompt size)",
1910
+ "- /context json (same, machine-readable)",
1911
+ "",
1912
+ "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."
1913
+ ].join("\n") };
1914
+ const report = await resolveContextReport(params);
1915
+ const cachedContextUsageTokens = resolveFreshSessionTotalTokens(targetSessionEntry);
1916
+ const session = {
1917
+ totalTokens: targetSessionEntry?.totalTokens ?? null,
1918
+ totalTokensFresh: targetSessionEntry?.totalTokensFresh ?? null,
1919
+ inputTokens: targetSessionEntry?.inputTokens ?? null,
1920
+ outputTokens: targetSessionEntry?.outputTokens ?? null,
1921
+ contextTokens: params.contextTokens ?? null
1922
+ };
1923
+ if (sub === "json") return { text: JSON.stringify({
1924
+ report,
1925
+ session
1926
+ }, null, 2) };
1927
+ 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") };
1928
+ const fileLines = report.injectedWorkspaceFiles.map((f) => {
1929
+ const status = f.missing ? "MISSING" : f.truncated ? "TRUNCATED" : "OK";
1930
+ const raw = f.missing ? "0" : formatCharsAndTokens(f.rawChars);
1931
+ const injected = f.missing ? "0" : formatCharsAndTokens(f.injectedChars);
1932
+ return `- ${f.name}: ${status} | raw ${raw} | injected ${injected}`;
1933
+ });
1934
+ const sandboxLine = `Sandbox: mode=${report.sandbox?.mode ?? "unknown"} sandboxed=${report.sandbox?.sandboxed ?? false}`;
1935
+ const toolSchemaLine = `Tool schemas (JSON): ${formatCharsAndTokens(report.tools.schemaChars)} (counts toward context; not shown as text)`;
1936
+ const toolListLine = `Tool list (system prompt text): ${formatCharsAndTokens(report.tools.listChars)}`;
1937
+ const skillNameSet = new Set(report.skills.entries.map((s) => s.name));
1938
+ const skillNames = Array.from(skillNameSet);
1939
+ const toolNames = report.tools.entries.map((t) => t.name);
1940
+ const formatNameList = (names, cap) => names.length <= cap ? names.join(", ") : `${names.slice(0, cap).join(", ")}, … (+${names.length - cap} more)`;
1941
+ const skillsLine = `Skills list (system prompt text): ${formatCharsAndTokens(report.skills.promptChars)} (${skillNameSet.size} skills)`;
1942
+ const skillsNamesLine = skillNameSet.size ? `Skills: ${formatNameList(skillNames, 20)}` : "Skills: (none)";
1943
+ const toolsNamesLine = toolNames.length ? `Tools: ${formatNameList(toolNames, 30)}` : "Tools: (none)";
1944
+ const systemPromptLine = `System prompt (${report.source}): ${formatCharsAndTokens(report.systemPrompt.chars)} (Project Context ${formatCharsAndTokens(report.systemPrompt.projectContextChars)})`;
1945
+ const workspaceLabel = report.workspaceDir ?? params.workspaceDir;
1946
+ const bootstrapMaxChars = typeof report.bootstrapMaxChars === "number" && Number.isFinite(report.bootstrapMaxChars) && report.bootstrapMaxChars > 0 ? report.bootstrapMaxChars : resolveBootstrapMaxChars(params.cfg);
1947
+ const bootstrapTotalMaxChars = typeof report.bootstrapTotalMaxChars === "number" && Number.isFinite(report.bootstrapTotalMaxChars) && report.bootstrapTotalMaxChars > 0 ? report.bootstrapTotalMaxChars : resolveBootstrapTotalMaxChars(params.cfg);
1948
+ const bootstrapMaxLabel = `${formatInt(bootstrapMaxChars)} chars`;
1949
+ const bootstrapTotalLabel = `${formatInt(bootstrapTotalMaxChars)} chars`;
1950
+ const bootstrapAnalysis = analyzeBootstrapBudget({
1951
+ files: report.injectedWorkspaceFiles,
1952
+ bootstrapMaxChars,
1953
+ bootstrapTotalMaxChars
1954
+ });
1955
+ const truncatedBootstrapFiles = bootstrapAnalysis.truncatedFiles;
1956
+ const truncationCauseCounts = truncatedBootstrapFiles.reduce((acc, file) => {
1957
+ for (const cause of file.causes) if (cause === "per-file-limit") acc.perFile += 1;
1958
+ else if (cause === "total-limit") acc.total += 1;
1959
+ return acc;
1960
+ }, {
1961
+ perFile: 0,
1962
+ total: 0
1963
+ });
1964
+ 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);
1965
+ const bootstrapWarningLines = truncatedBootstrapFiles.length > 0 ? [
1966
+ `⚠ Bootstrap context is over configured limits: ${truncatedBootstrapFiles.length} file(s) truncated (${formatInt(bootstrapAnalysis.totals.rawChars)} raw chars -> ${formatInt(bootstrapAnalysis.totals.injectedChars)} injected chars).`,
1967
+ ...truncationCauseParts.length ? [`Causes: ${truncationCauseParts.join("; ")}.`] : [],
1968
+ "Tip: increase `agents.defaults.bootstrapMaxChars` and/or `agents.defaults.bootstrapTotalMaxChars` if this truncation is not intentional."
1969
+ ] : [];
1970
+ const contextWindowLabel = session.contextTokens != null ? formatInt(session.contextTokens) : "?";
1971
+ const totalsLine = cachedContextUsageTokens != null ? `Session tokens (cached): ${formatInt(cachedContextUsageTokens)} total / ctx=${contextWindowLabel}` : `Session tokens (cached): unknown / ctx=${contextWindowLabel}`;
1972
+ const sharedContextLines = [
1973
+ `Workspace: ${workspaceLabel}`,
1974
+ `Bootstrap max/file: ${bootstrapMaxLabel}`,
1975
+ `Bootstrap max/total: ${bootstrapTotalLabel}`,
1976
+ sandboxLine,
1977
+ systemPromptLine,
1978
+ ...bootstrapWarningLines.length ? ["", ...bootstrapWarningLines] : [],
1979
+ "",
1980
+ "Injected workspace files:",
1981
+ ...fileLines,
1982
+ "",
1983
+ skillsLine,
1984
+ skillsNamesLine
1985
+ ];
1986
+ if (sub === "detail" || sub === "deep") {
1987
+ const perSkill = formatListTop(report.skills.entries.map((s) => ({
1988
+ name: s.name,
1989
+ value: s.blockChars
1990
+ })), 30);
1991
+ const perToolSchema = formatListTop(report.tools.entries.map((t) => ({
1992
+ name: t.name,
1993
+ value: t.schemaChars
1994
+ })), 30);
1995
+ const perToolSummary = formatListTop(report.tools.entries.map((t) => ({
1996
+ name: t.name,
1997
+ value: t.summaryChars
1998
+ })), 30);
1999
+ 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`);
2000
+ const trackedPromptChars = report.systemPrompt.chars + report.tools.schemaChars;
2001
+ const trackedPromptLine = `Tracked prompt estimate: ${formatCharsAndTokens(trackedPromptChars)}`;
2002
+ const actualContextLine = cachedContextUsageTokens != null ? `Actual context usage (cached): ${formatInt(cachedContextUsageTokens)} tok` : "Actual context usage (cached): unavailable";
2003
+ const overheadTokens = cachedContextUsageTokens != null ? cachedContextUsageTokens - estimateTokensFromChars(trackedPromptChars) : null;
2004
+ const overheadLine = overheadTokens == null ? null : overheadTokens > 0 ? `Untracked provider/runtime overhead: ~${formatInt(overheadTokens)} tok` : "Untracked provider/runtime overhead: not observed in cached usage";
2005
+ return { text: [
2006
+ "🧠 Context breakdown (detailed)",
2007
+ ...sharedContextLines,
2008
+ ...perSkill.lines.length ? ["Top skills (prompt entry size):", ...perSkill.lines] : [],
2009
+ ...perSkill.omitted ? [`… (+${perSkill.omitted} more skills)`] : [],
2010
+ "",
2011
+ toolListLine,
2012
+ toolSchemaLine,
2013
+ toolsNamesLine,
2014
+ "Top tools (schema size):",
2015
+ ...perToolSchema.lines,
2016
+ ...perToolSchema.omitted ? [`… (+${perToolSchema.omitted} more tools)`] : [],
2017
+ "",
2018
+ "Top tools (summary text size):",
2019
+ ...perToolSummary.lines,
2020
+ ...perToolSummary.omitted ? [`… (+${perToolSummary.omitted} more tools)`] : [],
2021
+ ...toolPropsLines.length ? [
2022
+ "",
2023
+ "Tools (param count):",
2024
+ ...toolPropsLines
2025
+ ] : [],
2026
+ "",
2027
+ trackedPromptLine,
2028
+ actualContextLine,
2029
+ ...overheadLine ? [overheadLine] : [],
2030
+ "",
2031
+ totalsLine,
2032
+ "",
2033
+ "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."
2034
+ ].filter(Boolean).join("\n") };
2035
+ }
2036
+ return { text: [
2037
+ "🧠 Context breakdown",
2038
+ ...sharedContextLines,
2039
+ toolListLine,
2040
+ toolSchemaLine,
2041
+ toolsNamesLine,
2042
+ "",
2043
+ totalsLine,
2044
+ "",
2045
+ "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."
2046
+ ].join("\n") };
2047
+ }
2048
+ //#endregion
2049
+ //#region src/auto-reply/reply/commands-context-command.ts
2050
+ const handleContextCommand = async (params, allowTextCommands) => {
2051
+ if (!allowTextCommands) return null;
2052
+ const normalized = params.command.commandBodyNormalized;
2053
+ if (normalized !== "/context" && !normalized.startsWith("/context ")) return null;
2054
+ if (!params.command.isAuthorizedSender) {
2055
+ logVerbose(`Ignoring /context from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2056
+ return { shouldContinue: false };
2057
+ }
2058
+ return {
2059
+ shouldContinue: false,
2060
+ reply: await buildContextReply(params)
2061
+ };
2062
+ };
2063
+ //#endregion
2064
+ //#region src/auto-reply/reply/commands-export-common.ts
2065
+ function escapeRegExp(value) {
2066
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2067
+ }
2068
+ function parseExportCommandOutputPath(commandBodyNormalized, aliases) {
2069
+ const normalized = commandBodyNormalized.trim();
2070
+ if (aliases.some((alias) => normalized === `/${alias}`)) return {};
2071
+ const aliasPattern = aliases.map(escapeRegExp).join("|");
2072
+ return { outputPath: normalized.replace(new RegExp(`^/(${aliasPattern})\\s*`), "").trim().split(/\s+/).find((part) => !part.startsWith("-")) };
2073
+ }
2074
+ function resolveExportCommandSessionTarget(params) {
2075
+ const targetAgentId = resolveAgentIdFromSessionKey(params.sessionKey) || params.agentId;
2076
+ const storePath = params.storePath ?? resolveDefaultSessionStorePath(targetAgentId);
2077
+ const entry = loadSessionStore(storePath, { skipCache: true })[params.sessionKey];
2078
+ if (!entry?.sessionId) return { text: `āŒ Session not found: ${params.sessionKey}` };
2079
+ try {
2080
+ return {
2081
+ entry,
2082
+ sessionFile: resolveSessionFilePath(entry.sessionId, entry, resolveSessionFilePathOptions({
2083
+ agentId: targetAgentId,
2084
+ storePath
2085
+ }))
2086
+ };
2087
+ } catch (err) {
2088
+ return { text: `āŒ Failed to resolve session file: ${formatErrorMessage(err)}` };
2089
+ }
2090
+ }
2091
+ function isReplyPayload(value) {
2092
+ return "text" in value;
2093
+ }
2094
+ //#endregion
2095
+ //#region src/auto-reply/reply/commands-export-session.ts
2096
+ const EXPORT_HTML_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "export-html");
2097
+ function loadTemplate(fileName) {
2098
+ return fs.readFileSync(path.join(EXPORT_HTML_DIR, fileName), "utf-8");
2099
+ }
2100
+ function generateHtml(sessionData) {
2101
+ const template = loadTemplate("template.html");
2102
+ const templateCss = loadTemplate("template.css");
2103
+ const templateJs = loadTemplate("template.js");
2104
+ const markedJs = loadTemplate(path.join("vendor", "marked.min.js"));
2105
+ const hljsJs = loadTemplate(path.join("vendor", "highlight.min.js"));
2106
+ const themeVars = `
2107
+ --cyan: #00d7ff;
2108
+ --blue: #5f87ff;
2109
+ --green: #b5bd68;
2110
+ --red: #cc6666;
2111
+ --yellow: #ffff00;
2112
+ --gray: #808080;
2113
+ --dimGray: #666666;
2114
+ --darkGray: #505050;
2115
+ --accent: #8abeb7;
2116
+ --selectedBg: #3a3a4a;
2117
+ --userMsgBg: #343541;
2118
+ --toolPendingBg: #282832;
2119
+ --toolSuccessBg: #283228;
2120
+ --toolErrorBg: #3c2828;
2121
+ --customMsgBg: #2d2838;
2122
+ --text: #e0e0e0;
2123
+ --dim: #666666;
2124
+ --muted: #808080;
2125
+ --border: #5f87ff;
2126
+ --borderAccent: #00d7ff;
2127
+ --borderMuted: #505050;
2128
+ --success: #b5bd68;
2129
+ --error: #cc6666;
2130
+ --warning: #ffff00;
2131
+ --thinkingText: #808080;
2132
+ --userMessageBg: #343541;
2133
+ --userMessageText: #e0e0e0;
2134
+ --customMessageBg: #2d2838;
2135
+ --customMessageText: #e0e0e0;
2136
+ --customMessageLabel: #9575cd;
2137
+ --toolTitle: #e0e0e0;
2138
+ --toolOutput: #808080;
2139
+ --mdHeading: #f0c674;
2140
+ --mdLink: #81a2be;
2141
+ --mdLinkUrl: #666666;
2142
+ --mdCode: #8abeb7;
2143
+ --mdCodeBlock: #b5bd68;
2144
+ `;
2145
+ const bodyBg = "#1e1e28";
2146
+ const containerBg = "#282832";
2147
+ const infoBg = "#343541";
2148
+ const sessionDataBase64 = Buffer.from(JSON.stringify(sessionData)).toString("base64");
2149
+ 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};`);
2150
+ return template.replace("{{CSS}}", css).replace("{{JS}}", templateJs).replace("{{SESSION_DATA}}", sessionDataBase64).replace("{{MARKED_JS}}", markedJs).replace("{{HIGHLIGHT_JS}}", hljsJs);
2151
+ }
2152
+ async function buildExportSessionReply(params) {
2153
+ const args = parseExportCommandOutputPath(params.command.commandBodyNormalized, ["export-session", "export"]);
2154
+ const sessionTarget = resolveExportCommandSessionTarget(params);
2155
+ if (isReplyPayload(sessionTarget)) return sessionTarget;
2156
+ const { entry, sessionFile } = sessionTarget;
2157
+ if (!fs.existsSync(sessionFile)) return { text: `āŒ Session file not found: ${sessionFile}` };
2158
+ const sessionManager = SessionManager.open(sessionFile);
2159
+ const entries = sessionManager.getEntries();
2160
+ const header = sessionManager.getHeader();
2161
+ const leafId = sessionManager.getLeafId();
2162
+ const { systemPrompt, tools } = await resolveCommandsSystemPromptBundle({
2163
+ ...params,
2164
+ sessionEntry: entry
2165
+ });
2166
+ const html = generateHtml({
2167
+ header,
2168
+ entries,
2169
+ leafId,
2170
+ systemPrompt,
2171
+ tools: tools.map((t) => ({
2172
+ name: t.name,
2173
+ description: t.description,
2174
+ parameters: t.parameters
2175
+ }))
2176
+ });
2177
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
2178
+ const defaultFileName = `genesis-session-${entry.sessionId.slice(0, 8)}-${timestamp}.html`;
2179
+ const outputPath = args.outputPath ? path.resolve(args.outputPath.startsWith("~") ? args.outputPath.replace("~", process.env.HOME ?? "") : args.outputPath) : path.join(params.workspaceDir, defaultFileName);
2180
+ const outputDir = path.dirname(outputPath);
2181
+ if (!fs.existsSync(outputDir)) fs.mkdirSync(outputDir, { recursive: true });
2182
+ fs.writeFileSync(outputPath, html, "utf-8");
2183
+ const relativePath = path.relative(params.workspaceDir, outputPath);
2184
+ return { text: [
2185
+ "āœ… Session exported!",
2186
+ "",
2187
+ `šŸ“„ File: ${relativePath.startsWith("..") ? outputPath : relativePath}`,
2188
+ `šŸ“Š Entries: ${entries.length}`,
2189
+ `🧠 System prompt: ${systemPrompt.length.toLocaleString()} chars`,
2190
+ `šŸ”§ Tools: ${tools.length}`
2191
+ ].join("\n") };
2192
+ }
2193
+ //#endregion
2194
+ //#region src/trajectory/export.ts
2195
+ const MAX_TRAJECTORY_RUNTIME_EVENTS = 2e5;
2196
+ const MAX_TRAJECTORY_TOTAL_EVENTS = 25e4;
2197
+ const MAX_TRAJECTORY_SESSION_FILE_BYTES = 50 * 1024 * 1024;
2198
+ function parseSessionEntries(content) {
2199
+ return content.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean).flatMap((line) => {
2200
+ try {
2201
+ return [JSON.parse(line)];
2202
+ } catch {
2203
+ return [];
2204
+ }
2205
+ });
2206
+ }
2207
+ function migrateLegacySessionEntries(entries) {
2208
+ const version = entries.find((entry) => entry.type === "session")?.version ?? 1;
2209
+ if (version < 2) {
2210
+ let previousId = null;
2211
+ let index = 0;
2212
+ for (const entry of entries) {
2213
+ if (entry.type === "session") {
2214
+ entry.version = 2;
2215
+ continue;
2216
+ }
2217
+ const mutable = entry;
2218
+ if (typeof mutable.id !== "string") mutable.id = `legacy-${index++}`;
2219
+ mutable.parentId = previousId;
2220
+ const entryId = mutable.id;
2221
+ previousId = typeof entryId === "string" ? entryId : null;
2222
+ if (entry.type === "compaction" && typeof mutable.firstKeptEntryIndex === "number") {
2223
+ const target = entries[mutable.firstKeptEntryIndex];
2224
+ if (target && target.type !== "session") mutable.firstKeptEntryId = target.id;
2225
+ delete mutable.firstKeptEntryIndex;
2226
+ }
2227
+ }
2228
+ }
2229
+ if (version < 3) for (const entry of entries) {
2230
+ if (entry.type === "session") {
2231
+ entry.version = 3;
2232
+ continue;
2233
+ }
2234
+ if (entry.type === "message") {
2235
+ const message = entry.message;
2236
+ if (message?.role === "hookMessage") message.role = "custom";
2237
+ }
2238
+ }
2239
+ }
2240
+ function readSessionBranch(filePath) {
2241
+ const fileEntries = parseSessionEntries(fs.readFileSync(filePath, "utf8"));
2242
+ migrateLegacySessionEntries(fileEntries);
2243
+ const header = fileEntries.find((entry) => entry.type === "session") ?? null;
2244
+ const entries = fileEntries.filter((entry) => entry.type !== "session" && typeof entry.id === "string" && (typeof entry.timestamp === "string" || typeof entry.timestamp === "number"));
2245
+ const byId = new Map(entries.map((entry) => [entry.id, entry]));
2246
+ const leafId = entries.at(-1)?.id ?? null;
2247
+ const branchEntries = [];
2248
+ let current = leafId ? byId.get(leafId) : void 0;
2249
+ while (current) {
2250
+ branchEntries.unshift(current);
2251
+ current = current.parentId ? byId.get(current.parentId) : void 0;
2252
+ }
2253
+ return {
2254
+ header,
2255
+ leafId,
2256
+ branchEntries
2257
+ };
2258
+ }
2259
+ function parseJsonlFile(filePath, params) {
2260
+ if (!fs.existsSync(filePath)) return [];
2261
+ const stat = fs.statSync(filePath);
2262
+ if (stat.size > params.maxBytes) throw new Error(`Trajectory runtime file is too large to export (${stat.size} bytes; limit ${params.maxBytes})`);
2263
+ const rows = fs.readFileSync(filePath, "utf8").split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
2264
+ const parsed = [];
2265
+ for (const row of rows) {
2266
+ if (parsed.length >= params.maxEvents) throw new Error(`Trajectory runtime file has too many events to export (limit ${params.maxEvents})`);
2267
+ try {
2268
+ const value = JSON.parse(row);
2269
+ if (!params.validate || params.validate(value)) parsed.push(value);
2270
+ } catch {}
2271
+ }
2272
+ return parsed;
2273
+ }
2274
+ function isFiniteNumber(value) {
2275
+ return typeof value === "number" && Number.isFinite(value);
2276
+ }
2277
+ function isRecord(value) {
2278
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
2279
+ }
2280
+ function isRuntimeTrajectoryEventForSession(value, sessionId) {
2281
+ if (!isRecord(value)) return false;
2282
+ 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));
2283
+ }
2284
+ function isRegularNonSymlinkFile(filePath) {
2285
+ try {
2286
+ const linkStat = fs.lstatSync(filePath);
2287
+ if (linkStat.isSymbolicLink() || !linkStat.isFile()) return false;
2288
+ const stat = fs.statSync(filePath);
2289
+ return stat.isFile() && stat.dev === linkStat.dev && stat.ino === linkStat.ino;
2290
+ } catch {
2291
+ return false;
2292
+ }
2293
+ }
2294
+ function readRuntimePointerFile(sessionFile, sessionId) {
2295
+ const pointerPath = resolveTrajectoryPointerFilePath(sessionFile);
2296
+ if (!isRegularNonSymlinkFile(pointerPath)) return;
2297
+ try {
2298
+ const parsed = JSON.parse(fs.readFileSync(pointerPath, "utf8"));
2299
+ if (!isRecord(parsed)) return;
2300
+ if (parsed.sessionId !== sessionId || typeof parsed.runtimeFile !== "string") return;
2301
+ const runtimeFile = path.resolve(parsed.runtimeFile);
2302
+ const safeRuntimeFileName = `${safeTrajectorySessionFileName(sessionId)}.jsonl`;
2303
+ if (runtimeFile !== path.resolve(resolveTrajectoryFilePath({
2304
+ env: {},
2305
+ sessionFile,
2306
+ sessionId
2307
+ })) && path.basename(runtimeFile) !== safeRuntimeFileName) return;
2308
+ return runtimeFile;
2309
+ } catch {
2310
+ return;
2311
+ }
2312
+ }
2313
+ function resolveTrajectoryRuntimeFile(params) {
2314
+ if (params.runtimeFile) return params.runtimeFile;
2315
+ return [
2316
+ readRuntimePointerFile(params.sessionFile, params.sessionId),
2317
+ resolveTrajectoryFilePath({
2318
+ env: {},
2319
+ sessionFile: params.sessionFile,
2320
+ sessionId: params.sessionId
2321
+ }),
2322
+ resolveTrajectoryFilePath({
2323
+ sessionFile: params.sessionFile,
2324
+ sessionId: params.sessionId
2325
+ })
2326
+ ].filter((candidate) => Boolean(candidate)).find((candidate) => isRegularNonSymlinkFile(candidate));
2327
+ }
2328
+ function normalizeTimestamp(value) {
2329
+ if (typeof value === "number" && Number.isFinite(value)) {
2330
+ const parsed = new Date(value);
2331
+ if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
2332
+ }
2333
+ if (typeof value === "string") {
2334
+ const parsed = new Date(value);
2335
+ if (!Number.isNaN(parsed.getTime())) return parsed.toISOString();
2336
+ }
2337
+ return (/* @__PURE__ */ new Date(0)).toISOString();
2338
+ }
2339
+ function resolveMessageEventType(message) {
2340
+ if (message.role === "user") return "user.message";
2341
+ if (message.role === "assistant") return "assistant.message";
2342
+ if (message.role === "toolResult") return "tool.result";
2343
+ return `message.${message.role}`;
2344
+ }
2345
+ function extractAssistantToolCalls(message) {
2346
+ if (message.role !== "assistant" || !Array.isArray(message.content)) return [];
2347
+ return message.content.flatMap((block, index) => {
2348
+ if (!block || typeof block !== "object") return [];
2349
+ const typedBlock = block;
2350
+ const blockType = typeof typedBlock.type === "string" ? typedBlock.type.trim().toLowerCase() : "";
2351
+ if (blockType !== "toolcall" && blockType !== "tooluse" && blockType !== "functioncall") return [];
2352
+ return [{
2353
+ id: typeof typedBlock.id === "string" ? typedBlock.id : void 0,
2354
+ name: typeof typedBlock.name === "string" ? typedBlock.name : void 0,
2355
+ arguments: typedBlock.arguments ?? typedBlock.input ?? typedBlock.parameters,
2356
+ index
2357
+ }];
2358
+ });
2359
+ }
2360
+ function buildTranscriptEvents(params) {
2361
+ const events = [];
2362
+ let seq = 0;
2363
+ for (const entry of params.entries) {
2364
+ const push = (type, data) => {
2365
+ events.push({
2366
+ traceSchema: "genesis-trajectory",
2367
+ schemaVersion: 1,
2368
+ traceId: params.traceId,
2369
+ source: "transcript",
2370
+ type,
2371
+ ts: normalizeTimestamp(entry.timestamp),
2372
+ seq: 0,
2373
+ sourceSeq: seq += 1,
2374
+ sessionId: params.sessionId,
2375
+ sessionKey: params.sessionKey,
2376
+ workspaceDir: params.workspaceDir,
2377
+ entryId: entry.id,
2378
+ parentEntryId: entry.parentId,
2379
+ data
2380
+ });
2381
+ };
2382
+ switch (entry.type) {
2383
+ case "message":
2384
+ push(resolveMessageEventType(entry.message), { message: sanitizeDiagnosticPayload(entry.message) });
2385
+ for (const toolCall of extractAssistantToolCalls(entry.message)) push("tool.call", {
2386
+ toolCallId: toolCall.id,
2387
+ name: toolCall.name,
2388
+ arguments: sanitizeDiagnosticPayload(toolCall.arguments),
2389
+ assistantEntryId: entry.id,
2390
+ blockIndex: toolCall.index
2391
+ });
2392
+ break;
2393
+ case "compaction":
2394
+ push("session.compaction", {
2395
+ summary: entry.summary,
2396
+ firstKeptEntryId: entry.firstKeptEntryId,
2397
+ tokensBefore: entry.tokensBefore,
2398
+ details: sanitizeDiagnosticPayload(entry.details),
2399
+ fromHook: entry.fromHook ?? false
2400
+ });
2401
+ break;
2402
+ case "branch_summary":
2403
+ push("session.branch_summary", {
2404
+ fromId: entry.fromId,
2405
+ summary: entry.summary,
2406
+ details: sanitizeDiagnosticPayload(entry.details),
2407
+ fromHook: entry.fromHook ?? false
2408
+ });
2409
+ break;
2410
+ case "custom":
2411
+ push("session.custom", {
2412
+ customType: entry.customType,
2413
+ data: sanitizeDiagnosticPayload(entry.data)
2414
+ });
2415
+ break;
2416
+ case "custom_message":
2417
+ push("session.custom_message", {
2418
+ customType: entry.customType,
2419
+ content: sanitizeDiagnosticPayload(entry.content),
2420
+ details: sanitizeDiagnosticPayload(entry.details),
2421
+ display: entry.display
2422
+ });
2423
+ break;
2424
+ case "thinking_level_change":
2425
+ push("session.thinking_level_change", { thinkingLevel: entry.thinkingLevel });
2426
+ break;
2427
+ case "model_change":
2428
+ push("session.model_change", {
2429
+ provider: entry.provider,
2430
+ modelId: entry.modelId
2431
+ });
2432
+ break;
2433
+ case "label":
2434
+ push("session.label", {
2435
+ targetId: entry.targetId,
2436
+ label: entry.label
2437
+ });
2438
+ break;
2439
+ case "session_info":
2440
+ push("session.info", { name: entry.name });
2441
+ break;
2442
+ }
2443
+ }
2444
+ return events;
2445
+ }
2446
+ function sortTrajectoryEvents(events) {
2447
+ const sourceOrder = {
2448
+ runtime: 0,
2449
+ transcript: 1,
2450
+ export: 2
2451
+ };
2452
+ const sorted = events.toSorted((left, right) => {
2453
+ const byTs = left.ts.localeCompare(right.ts);
2454
+ if (byTs !== 0) return byTs;
2455
+ const bySource = sourceOrder[left.source] - sourceOrder[right.source];
2456
+ if (bySource !== 0) return bySource;
2457
+ return (left.sourceSeq ?? left.seq) - (right.sourceSeq ?? right.seq);
2458
+ });
2459
+ for (const [index, event] of sorted.entries()) event.seq = index + 1;
2460
+ return sorted;
2461
+ }
2462
+ function trajectoryJsonlFile(pathName, events) {
2463
+ return jsonlSupportBundleFile(pathName, events.map((event) => safeJsonStringify(event)).filter((line) => Boolean(line)));
2464
+ }
2465
+ function buildTrajectoryExportRedaction(params) {
2466
+ const env = process.env;
2467
+ return {
2468
+ env,
2469
+ stateDir: resolveStateDir(env),
2470
+ workspaceDir: path.resolve(params.workspaceDir)
2471
+ };
2472
+ }
2473
+ function redactWorkspacePathString(value, redaction) {
2474
+ const workspaceDir = redaction.workspaceDir;
2475
+ if (!workspaceDir) return value;
2476
+ const normalizedWorkspaceDir = workspaceDir.replaceAll("\\", "/");
2477
+ let next = value;
2478
+ for (const candidate of new Set([workspaceDir, normalizedWorkspaceDir])) {
2479
+ if (!candidate) continue;
2480
+ const escaped = candidate.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
2481
+ next = next.replace(new RegExp(`${escaped}(?=$|[\\\\/])`, "gu"), "$WORKSPACE_DIR");
2482
+ }
2483
+ return next;
2484
+ }
2485
+ function maybeRedactPathString(value, redaction) {
2486
+ const workspaceRedacted = redactWorkspacePathString(value, redaction);
2487
+ 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);
2488
+ return workspaceRedacted;
2489
+ }
2490
+ function redactLocalPathValues(value, redaction) {
2491
+ if (typeof value === "string") return maybeRedactPathString(value, redaction);
2492
+ if (Array.isArray(value)) return value.map((entry) => redactLocalPathValues(entry, redaction));
2493
+ if (!value || typeof value !== "object") return value;
2494
+ const record = value;
2495
+ const next = {};
2496
+ for (const [key, entry] of Object.entries(record)) next[key] = redactLocalPathValues(entry, redaction);
2497
+ return next;
2498
+ }
2499
+ function redactEventForExport(event, redaction) {
2500
+ return {
2501
+ ...event,
2502
+ workspaceDir: event.workspaceDir ? maybeRedactPathString(event.workspaceDir, redaction) : void 0,
2503
+ data: event.data ? redactLocalPathValues(event.data, redaction) : void 0
2504
+ };
2505
+ }
2506
+ function resolveRuntimeContext(runtimeEvents) {
2507
+ const runtimeData = runtimeEvents.slice().toReversed().find((event) => event.type === "context.compiled")?.data;
2508
+ const toolsValue = Array.isArray(runtimeData?.tools) ? runtimeData.tools : void 0;
2509
+ return {
2510
+ systemPrompt: typeof runtimeData?.systemPrompt === "string" ? runtimeData.systemPrompt : void 0,
2511
+ tools: toolsValue
2512
+ };
2513
+ }
2514
+ function resolveLatestRuntimeEventData(runtimeEvents, type) {
2515
+ return runtimeEvents.slice().toReversed().find((candidate) => candidate.type === type)?.data;
2516
+ }
2517
+ function normalizePathForMatch(value) {
2518
+ return value.replaceAll("\\", "/").trim().toLowerCase();
2519
+ }
2520
+ function collectPotentialPathStrings(value) {
2521
+ const found = /* @__PURE__ */ new Set();
2522
+ const visit = (input) => {
2523
+ if (!input || typeof input !== "object") return;
2524
+ if (Array.isArray(input)) {
2525
+ for (const entry of input) visit(entry);
2526
+ return;
2527
+ }
2528
+ 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);
2529
+ else visit(entry);
2530
+ };
2531
+ visit(value);
2532
+ return [...found];
2533
+ }
2534
+ function markInvokedSkills(params) {
2535
+ if (!params.skills || typeof params.skills !== "object") return params.skills;
2536
+ const skillsRecord = params.skills;
2537
+ if (!Array.isArray(skillsRecord.entries) || skillsRecord.entries.length === 0) return params.skills;
2538
+ const invokedPaths = new Set(params.events.flatMap((event) => {
2539
+ if (event.type !== "tool.call") return [];
2540
+ return collectPotentialPathStrings(event.data?.arguments);
2541
+ }));
2542
+ const normalizedInvokedPaths = new Set([...invokedPaths].map((value) => normalizePathForMatch(value)));
2543
+ const entries = skillsRecord.entries.map((entry) => {
2544
+ const rawPath = typeof entry.filePath === "string" ? entry.filePath : void 0;
2545
+ const normalizedPath = rawPath ? normalizePathForMatch(rawPath) : void 0;
2546
+ const skillDirName = rawPath?.replaceAll("\\", "/").split("/").slice(-2, -1)[0]?.toLowerCase() ?? void 0;
2547
+ const invoked = normalizedPath ? [...normalizedInvokedPaths].some((candidate) => candidate === normalizedPath || candidate.endsWith(normalizedPath) || (skillDirName ? candidate.endsWith(`/${skillDirName}/skill.md`) : false)) : false;
2548
+ return invoked ? {
2549
+ ...entry,
2550
+ invoked,
2551
+ invocationDetectedBy: "tool-call-file-path"
2552
+ } : {
2553
+ ...entry,
2554
+ invoked: false
2555
+ };
2556
+ });
2557
+ return {
2558
+ ...skillsRecord,
2559
+ entries
2560
+ };
2561
+ }
2562
+ function buildMetadataCapture(params) {
2563
+ const runtimeMetadata = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.metadata");
2564
+ if (!runtimeMetadata) return;
2565
+ const modelFallback = (() => {
2566
+ const latest = params.runtimeEvents.slice().toReversed().find((event) => event.provider || event.modelId || event.modelApi);
2567
+ if (!latest?.provider && !latest?.modelId && !latest?.modelApi) return;
2568
+ return {
2569
+ provider: latest.provider,
2570
+ name: latest.modelId,
2571
+ api: latest.modelApi
2572
+ };
2573
+ })();
2574
+ return {
2575
+ traceSchema: "genesis-trajectory",
2576
+ schemaVersion: 1,
2577
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2578
+ traceId: params.manifest.traceId,
2579
+ sessionId: params.manifest.sessionId,
2580
+ sessionKey: params.manifest.sessionKey,
2581
+ harness: runtimeMetadata.harness,
2582
+ model: runtimeMetadata.model ?? modelFallback,
2583
+ config: runtimeMetadata.config,
2584
+ plugins: runtimeMetadata.plugins,
2585
+ skills: markInvokedSkills({
2586
+ skills: runtimeMetadata.skills,
2587
+ events: params.events
2588
+ }),
2589
+ prompting: runtimeMetadata.prompting,
2590
+ redaction: runtimeMetadata.redaction,
2591
+ metadata: runtimeMetadata.metadata
2592
+ };
2593
+ }
2594
+ function buildArtifactsCapture(params) {
2595
+ const runtimeArtifacts = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.artifacts");
2596
+ const runtimeCompletion = resolveLatestRuntimeEventData(params.runtimeEvents, "model.completed");
2597
+ const runtimeEnd = resolveLatestRuntimeEventData(params.runtimeEvents, "session.ended");
2598
+ if (!runtimeArtifacts && !runtimeCompletion && !runtimeEnd) return;
2599
+ return {
2600
+ traceSchema: "genesis-trajectory",
2601
+ schemaVersion: 1,
2602
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2603
+ traceId: params.manifest.traceId,
2604
+ sessionId: params.manifest.sessionId,
2605
+ sessionKey: params.manifest.sessionKey,
2606
+ finalStatus: runtimeArtifacts?.finalStatus ?? runtimeEnd?.status,
2607
+ aborted: runtimeArtifacts?.aborted ?? runtimeEnd?.aborted,
2608
+ externalAbort: runtimeArtifacts?.externalAbort ?? runtimeEnd?.externalAbort,
2609
+ timedOut: runtimeArtifacts?.timedOut ?? runtimeEnd?.timedOut,
2610
+ idleTimedOut: runtimeArtifacts?.idleTimedOut ?? runtimeEnd?.idleTimedOut,
2611
+ timedOutDuringCompaction: runtimeArtifacts?.timedOutDuringCompaction ?? runtimeEnd?.timedOutDuringCompaction,
2612
+ promptError: runtimeArtifacts?.promptError ?? runtimeEnd?.promptError ?? runtimeCompletion?.promptError,
2613
+ promptErrorSource: runtimeArtifacts?.promptErrorSource ?? runtimeCompletion?.promptErrorSource,
2614
+ usage: runtimeArtifacts?.usage ?? runtimeCompletion?.usage,
2615
+ promptCache: runtimeArtifacts?.promptCache ?? runtimeCompletion?.promptCache,
2616
+ compactionCount: runtimeArtifacts?.compactionCount ?? runtimeCompletion?.compactionCount,
2617
+ assistantTexts: runtimeArtifacts?.assistantTexts ?? runtimeCompletion?.assistantTexts,
2618
+ finalPromptText: runtimeArtifacts?.finalPromptText ?? runtimeCompletion?.finalPromptText,
2619
+ itemLifecycle: runtimeArtifacts?.itemLifecycle,
2620
+ toolMetas: runtimeArtifacts?.toolMetas,
2621
+ didSendViaMessagingTool: runtimeArtifacts?.didSendViaMessagingTool,
2622
+ successfulCronAdds: runtimeArtifacts?.successfulCronAdds,
2623
+ messagingToolSentTexts: runtimeArtifacts?.messagingToolSentTexts,
2624
+ messagingToolSentMediaUrls: runtimeArtifacts?.messagingToolSentMediaUrls,
2625
+ messagingToolSentTargets: runtimeArtifacts?.messagingToolSentTargets,
2626
+ lastToolError: runtimeArtifacts?.lastToolError
2627
+ };
2628
+ }
2629
+ function buildPromptsCapture(params) {
2630
+ const runtimeMetadata = resolveLatestRuntimeEventData(params.runtimeEvents, "trace.metadata");
2631
+ const latestCompiled = resolveLatestRuntimeEventData(params.runtimeEvents, "context.compiled");
2632
+ const submittedPrompts = params.runtimeEvents.filter((event) => event.type === "prompt.submitted").map((event) => event.data?.prompt).filter((prompt) => typeof prompt === "string");
2633
+ const systemPrompt = (typeof latestCompiled?.systemPrompt === "string" ? latestCompiled.systemPrompt : void 0) ?? params.runtimeContext.systemPrompt;
2634
+ const skillsPrompt = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.skillsPrompt === "string" ? runtimeMetadata.prompting.skillsPrompt : void 0;
2635
+ const userPromptPrefixText = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.userPromptPrefixText === "string" ? runtimeMetadata.prompting.userPromptPrefixText : void 0;
2636
+ const promptReport = runtimeMetadata?.prompting && typeof runtimeMetadata.prompting === "object" && typeof runtimeMetadata.prompting.systemPromptReport === "object" ? runtimeMetadata.prompting.systemPromptReport : void 0;
2637
+ if (!systemPrompt && submittedPrompts.length === 0 && !skillsPrompt && !userPromptPrefixText) return;
2638
+ return {
2639
+ traceSchema: "genesis-trajectory",
2640
+ schemaVersion: 1,
2641
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2642
+ traceId: params.manifest.traceId,
2643
+ sessionId: params.manifest.sessionId,
2644
+ sessionKey: params.manifest.sessionKey,
2645
+ system: systemPrompt,
2646
+ submittedPrompts,
2647
+ latestSubmittedPrompt: submittedPrompts.at(-1),
2648
+ skillsPrompt,
2649
+ userPromptPrefixText,
2650
+ systemPromptReport: promptReport
2651
+ };
2652
+ }
2653
+ function resolveDefaultTrajectoryExportDir(params) {
2654
+ const timestamp = (params.now ?? /* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19);
2655
+ const sessionFileName = safeTrajectorySessionFileName(params.sessionId);
2656
+ return path.join(params.workspaceDir, ".genesis", "trajectory-exports", `genesis-trajectory-${sessionFileName.slice(0, 8)}-${timestamp}`);
2657
+ }
2658
+ function exportTrajectoryBundle(params) {
2659
+ const redaction = buildTrajectoryExportRedaction({ workspaceDir: params.workspaceDir });
2660
+ const sessionStat = fs.statSync(params.sessionFile);
2661
+ 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})`);
2662
+ const { header, leafId, branchEntries } = readSessionBranch(params.sessionFile);
2663
+ const runtimeFile = resolveTrajectoryRuntimeFile({
2664
+ runtimeFile: params.runtimeFile,
2665
+ sessionFile: params.sessionFile,
2666
+ sessionId: params.sessionId
2667
+ });
2668
+ const runtimeEvents = runtimeFile ? parseJsonlFile(runtimeFile, {
2669
+ maxBytes: TRAJECTORY_RUNTIME_FILE_MAX_BYTES,
2670
+ maxEvents: MAX_TRAJECTORY_RUNTIME_EVENTS,
2671
+ validate: (value) => isRuntimeTrajectoryEventForSession(value, params.sessionId)
2672
+ }) : [];
2673
+ const transcriptEvents = buildTranscriptEvents({
2674
+ entries: branchEntries,
2675
+ sessionId: params.sessionId,
2676
+ sessionKey: params.sessionKey,
2677
+ workspaceDir: params.workspaceDir,
2678
+ traceId: params.sessionId
2679
+ });
2680
+ const maxTotalEvents = params.maxTotalEvents ?? MAX_TRAJECTORY_TOTAL_EVENTS;
2681
+ const totalEventCount = runtimeEvents.length + transcriptEvents.length;
2682
+ if (totalEventCount > maxTotalEvents) throw new Error(`Trajectory export has too many events (${totalEventCount}; limit ${maxTotalEvents})`);
2683
+ const rawEvents = sortTrajectoryEvents([...runtimeEvents, ...transcriptEvents]);
2684
+ const events = rawEvents.map((event) => redactEventForExport(event, redaction));
2685
+ const manifest = {
2686
+ traceSchema: "genesis-trajectory",
2687
+ schemaVersion: 1,
2688
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2689
+ traceId: params.sessionId,
2690
+ sessionId: params.sessionId,
2691
+ sessionKey: params.sessionKey,
2692
+ workspaceDir: maybeRedactPathString(params.workspaceDir, redaction),
2693
+ leafId,
2694
+ eventCount: events.length,
2695
+ runtimeEventCount: runtimeEvents.length,
2696
+ transcriptEventCount: transcriptEvents.length,
2697
+ sourceFiles: {
2698
+ session: maybeRedactPathString(params.sessionFile, redaction),
2699
+ runtime: runtimeFile && isRegularNonSymlinkFile(runtimeFile) ? maybeRedactPathString(runtimeFile, redaction) : void 0
2700
+ }
2701
+ };
2702
+ const bundleRuntimeContext = resolveRuntimeContext(runtimeEvents);
2703
+ const files = [];
2704
+ const supplementalFiles = [];
2705
+ const metadataCapture = buildMetadataCapture({
2706
+ manifest,
2707
+ runtimeEvents,
2708
+ events: rawEvents
2709
+ });
2710
+ const artifactsCapture = buildArtifactsCapture({
2711
+ manifest,
2712
+ runtimeEvents
2713
+ });
2714
+ const promptsCapture = buildPromptsCapture({
2715
+ manifest,
2716
+ runtimeEvents,
2717
+ runtimeContext: bundleRuntimeContext
2718
+ });
2719
+ if (metadataCapture) {
2720
+ files.push(jsonSupportBundleFile("metadata.json", redactLocalPathValues(metadataCapture, redaction)));
2721
+ supplementalFiles.push("metadata.json");
2722
+ }
2723
+ if (artifactsCapture) {
2724
+ files.push(jsonSupportBundleFile("artifacts.json", redactLocalPathValues(artifactsCapture, redaction)));
2725
+ supplementalFiles.push("artifacts.json");
2726
+ }
2727
+ if (promptsCapture) {
2728
+ files.push(jsonSupportBundleFile("prompts.json", redactLocalPathValues(promptsCapture, redaction)));
2729
+ supplementalFiles.push("prompts.json");
2730
+ }
2731
+ if (supplementalFiles.length > 0) manifest.supplementalFiles = supplementalFiles;
2732
+ files.push(trajectoryJsonlFile("events.jsonl", events));
2733
+ files.push(jsonSupportBundleFile("session-branch.json", redactLocalPathValues(sanitizeDiagnosticPayload({
2734
+ header,
2735
+ leafId,
2736
+ entries: branchEntries
2737
+ }), redaction)));
2738
+ if (bundleRuntimeContext.systemPrompt) files.push(textSupportBundleFile("system-prompt.txt", redactLocalPathValues(bundleRuntimeContext.systemPrompt, redaction)));
2739
+ if (bundleRuntimeContext.tools) files.push(jsonSupportBundleFile("tools.json", redactLocalPathValues(bundleRuntimeContext.tools, redaction)));
2740
+ manifest.contents = [...supportBundleContents(files)];
2741
+ writeSupportBundleDirectory({
2742
+ outputDir: params.outputDir,
2743
+ files: [jsonSupportBundleFile("manifest.json", manifest), ...files]
2744
+ });
2745
+ return {
2746
+ manifest,
2747
+ outputDir: params.outputDir,
2748
+ events,
2749
+ header,
2750
+ runtimeFile: runtimeFile && isRegularNonSymlinkFile(runtimeFile) ? runtimeFile : void 0,
2751
+ supplementalFiles
2752
+ };
2753
+ }
2754
+ //#endregion
2755
+ //#region src/auto-reply/reply/commands-export-trajectory.ts
2756
+ function isPathInsideOrEqual(baseDir, candidate) {
2757
+ const relative = path.relative(baseDir, candidate);
2758
+ return relative === "" || !relative.startsWith("..") && !path.isAbsolute(relative);
2759
+ }
2760
+ function validateExistingExportDirectory(params) {
2761
+ const linkStat = fs.lstatSync(params.dir);
2762
+ if (linkStat.isSymbolicLink() || !linkStat.isDirectory()) throw new Error(`${params.label} must be a real directory inside the workspace`);
2763
+ const realDir = fs.realpathSync(params.dir);
2764
+ if (!isPathInsideOrEqual(params.realWorkspace, realDir)) throw new Error("Trajectory exports directory must stay inside the workspace");
2765
+ return realDir;
2766
+ }
2767
+ function mkdirIfMissingThenValidate(params) {
2768
+ if (!fs.existsSync(params.dir)) try {
2769
+ fs.mkdirSync(params.dir, { mode: 448 });
2770
+ } catch (error) {
2771
+ if (error.code !== "EEXIST") throw error;
2772
+ }
2773
+ return validateExistingExportDirectory(params);
2774
+ }
2775
+ function resolveTrajectoryExportBaseDir(workspaceDir) {
2776
+ const workspacePath = path.resolve(workspaceDir);
2777
+ const realWorkspace = fs.realpathSync(workspacePath);
2778
+ const stateDir = path.join(workspacePath, ".genesis");
2779
+ mkdirIfMissingThenValidate({
2780
+ dir: stateDir,
2781
+ label: "Genesis state directory",
2782
+ realWorkspace
2783
+ });
2784
+ const baseDir = path.join(stateDir, "trajectory-exports");
2785
+ const realBase = mkdirIfMissingThenValidate({
2786
+ dir: baseDir,
2787
+ label: "Trajectory exports directory",
2788
+ realWorkspace
2789
+ });
2790
+ return {
2791
+ baseDir: path.resolve(baseDir),
2792
+ realBase
2793
+ };
2794
+ }
2795
+ function resolveTrajectoryCommandOutputDir(params) {
2796
+ const { baseDir, realBase } = resolveTrajectoryExportBaseDir(params.workspaceDir);
2797
+ const raw = params.outputPath?.trim();
2798
+ if (!raw) {
2799
+ const defaultDir = resolveDefaultTrajectoryExportDir({
2800
+ workspaceDir: params.workspaceDir,
2801
+ sessionId: params.sessionId
2802
+ });
2803
+ return path.join(baseDir, path.basename(defaultDir));
2804
+ }
2805
+ if (path.isAbsolute(raw) || raw.startsWith("~")) throw new Error("Output path must be relative to the workspace trajectory exports directory");
2806
+ const resolvedBase = path.resolve(baseDir);
2807
+ const outputDir = path.resolve(resolvedBase, raw);
2808
+ const relative = path.relative(resolvedBase, outputDir);
2809
+ if (!relative || relative.startsWith("..") || path.isAbsolute(relative)) throw new Error("Output path must stay inside the workspace trajectory exports directory");
2810
+ let existingParent = outputDir;
2811
+ while (!fs.existsSync(existingParent)) {
2812
+ const next = path.dirname(existingParent);
2813
+ if (next === existingParent) break;
2814
+ existingParent = next;
2815
+ }
2816
+ if (!isPathInsideOrEqual(realBase, fs.realpathSync(existingParent))) throw new Error("Output path must stay inside the real trajectory exports directory");
2817
+ return outputDir;
2818
+ }
2819
+ async function buildExportTrajectoryReply(params) {
2820
+ const args = parseExportCommandOutputPath(params.command.commandBodyNormalized, ["export-trajectory", "trajectory"]);
2821
+ const sessionTarget = resolveExportCommandSessionTarget(params);
2822
+ if (isReplyPayload(sessionTarget)) return sessionTarget;
2823
+ const { entry, sessionFile } = sessionTarget;
2824
+ if (!fs.existsSync(sessionFile)) return { text: "āŒ Session file not found." };
2825
+ let outputDir;
2826
+ try {
2827
+ outputDir = resolveTrajectoryCommandOutputDir({
2828
+ outputPath: args.outputPath,
2829
+ workspaceDir: params.workspaceDir,
2830
+ sessionId: entry.sessionId
2831
+ });
2832
+ } catch (err) {
2833
+ return { text: `āŒ Failed to resolve output path: ${formatErrorMessage(err)}` };
2834
+ }
2835
+ let bundle;
2836
+ try {
2837
+ bundle = exportTrajectoryBundle({
2838
+ outputDir,
2839
+ sessionFile,
2840
+ sessionId: entry.sessionId,
2841
+ sessionKey: params.sessionKey,
2842
+ workspaceDir: params.workspaceDir
2843
+ });
2844
+ } catch (err) {
2845
+ return { text: `āŒ Failed to export trajectory: ${formatErrorMessage(err)}` };
2846
+ }
2847
+ const relativePath = path.relative(params.workspaceDir, bundle.outputDir);
2848
+ const displayPath = relativePath && !relativePath.startsWith("..") && !path.isAbsolute(relativePath) ? relativePath : path.basename(bundle.outputDir);
2849
+ const files = [
2850
+ "manifest.json",
2851
+ "events.jsonl",
2852
+ "session-branch.json"
2853
+ ];
2854
+ if (bundle.events.some((event) => event.type === "context.compiled")) files.push("system-prompt.txt", "tools.json");
2855
+ files.push(...bundle.supplementalFiles);
2856
+ return { text: [
2857
+ "āœ… Trajectory exported!",
2858
+ "",
2859
+ `šŸ“¦ Bundle: ${displayPath}`,
2860
+ `🧵 Session: ${entry.sessionId}`,
2861
+ `šŸ“Š Events: ${bundle.manifest.eventCount}`,
2862
+ `🧪 Runtime events: ${bundle.manifest.runtimeEventCount}`,
2863
+ `šŸ“ Transcript events: ${bundle.manifest.transcriptEventCount}`,
2864
+ `šŸ“ Files: ${files.join(", ")}`
2865
+ ].join("\n") };
2866
+ }
2867
+ //#endregion
2868
+ //#region src/auto-reply/reply/commands-whoami.ts
2869
+ const handleWhoamiCommand = async (params, allowTextCommands) => {
2870
+ if (!allowTextCommands) return null;
2871
+ if (params.command.commandBodyNormalized !== "/whoami") return null;
2872
+ if (!params.command.isAuthorizedSender) {
2873
+ logVerbose(`Ignoring /whoami from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2874
+ return { shouldContinue: false };
2875
+ }
2876
+ const senderId = params.ctx.SenderId ?? "";
2877
+ const senderUsername = params.ctx.SenderUsername ?? "";
2878
+ const lines = ["🧭 Identity", `Channel: ${params.command.channel}`];
2879
+ if (senderId) lines.push(`User id: ${senderId}`);
2880
+ if (senderUsername) {
2881
+ const handle = senderUsername.startsWith("@") ? senderUsername : `@${senderUsername}`;
2882
+ lines.push(`Username: ${handle}`);
2883
+ }
2884
+ if (params.ctx.ChatType === "group" && params.ctx.From) lines.push(`Chat: ${params.ctx.From}`);
2885
+ if (params.ctx.MessageThreadId != null) lines.push(`Thread: ${params.ctx.MessageThreadId}`);
2886
+ const allowFromSender = params.command.senderId ?? "";
2887
+ if (allowFromSender) lines.push(`AllowFrom: ${allowFromSender}`);
2888
+ return {
2889
+ shouldContinue: false,
2890
+ reply: { text: lines.join("\n") }
2891
+ };
2892
+ };
2893
+ //#endregion
2894
+ //#region src/auto-reply/reply/commands-info.ts
2895
+ const handleHelpCommand = async (params, allowTextCommands) => {
2896
+ if (!allowTextCommands) return null;
2897
+ if (params.command.commandBodyNormalized !== "/help") return null;
2898
+ if (!params.command.isAuthorizedSender) {
2899
+ logVerbose(`Ignoring /help from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2900
+ return { shouldContinue: false };
2901
+ }
2902
+ return {
2903
+ shouldContinue: false,
2904
+ reply: { text: buildHelpMessage(params.cfg) }
2905
+ };
2906
+ };
2907
+ const handleCommandsListCommand = async (params, allowTextCommands) => {
2908
+ if (!allowTextCommands) return null;
2909
+ if (params.command.commandBodyNormalized !== "/commands") return null;
2910
+ if (!params.command.isAuthorizedSender) {
2911
+ logVerbose(`Ignoring /commands from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2912
+ return { shouldContinue: false };
2913
+ }
2914
+ const agentId = params.sessionKey ? resolveSessionAgentId({
2915
+ sessionKey: params.sessionKey,
2916
+ config: params.cfg
2917
+ }) : params.agentId;
2918
+ const skillCommands = params.skillCommands ?? listSkillCommandsForAgents({
2919
+ cfg: params.cfg,
2920
+ agentIds: agentId ? [agentId] : void 0
2921
+ });
2922
+ const surface = params.ctx.Surface;
2923
+ const commandPlugin = surface ? getChannelPlugin(surface) : null;
2924
+ const paginated = buildCommandsMessagePaginated(params.cfg, skillCommands, {
2925
+ page: 1,
2926
+ surface
2927
+ });
2928
+ const channelData = commandPlugin?.commands?.buildCommandsListChannelData?.({
2929
+ currentPage: paginated.currentPage,
2930
+ totalPages: paginated.totalPages,
2931
+ agentId
2932
+ });
2933
+ if (channelData) return {
2934
+ shouldContinue: false,
2935
+ reply: {
2936
+ text: paginated.text,
2937
+ channelData
2938
+ }
2939
+ };
2940
+ return {
2941
+ shouldContinue: false,
2942
+ reply: { text: buildCommandsMessage(params.cfg, skillCommands, { surface }) }
2943
+ };
2944
+ };
2945
+ const handleToolsCommand = async (params, allowTextCommands) => {
2946
+ if (!allowTextCommands) return null;
2947
+ const normalized = params.command.commandBodyNormalized;
2948
+ let verbose = false;
2949
+ if (normalized === "/tools" || normalized === "/tools compact") verbose = false;
2950
+ else if (normalized === "/tools verbose") verbose = true;
2951
+ else if (normalized.startsWith("/tools ")) return {
2952
+ shouldContinue: false,
2953
+ reply: { text: "Usage: /tools [compact|verbose]" }
2954
+ };
2955
+ else return null;
2956
+ if (!params.command.isAuthorizedSender) {
2957
+ logVerbose(`Ignoring /tools from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
2958
+ return { shouldContinue: false };
2959
+ }
2960
+ try {
2961
+ const effectiveAccountId = resolveChannelAccountId({
2962
+ cfg: params.cfg,
2963
+ ctx: params.ctx,
2964
+ command: params.command
2965
+ });
2966
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
2967
+ const sessionBound = Boolean(params.sessionKey);
2968
+ const agentId = sessionBound ? resolveSessionAgentId({
2969
+ sessionKey: params.sessionKey,
2970
+ config: params.cfg
2971
+ }) : params.agentId;
2972
+ const threadingContext = buildThreadingToolContext({
2973
+ sessionCtx: params.ctx,
2974
+ config: params.cfg,
2975
+ hasRepliedRef: void 0
2976
+ });
2977
+ return {
2978
+ shouldContinue: false,
2979
+ reply: { text: buildToolsMessage(resolveEffectiveToolInventory({
2980
+ cfg: params.cfg,
2981
+ agentId,
2982
+ sessionKey: params.sessionKey,
2983
+ workspaceDir: params.workspaceDir,
2984
+ agentDir: sessionBound ? void 0 : params.agentDir,
2985
+ modelProvider: params.provider,
2986
+ modelId: params.model,
2987
+ messageProvider: params.command.channel,
2988
+ senderIsOwner: params.command.senderIsOwner,
2989
+ senderId: params.command.senderId,
2990
+ senderName: params.ctx.SenderName,
2991
+ senderUsername: params.ctx.SenderUsername,
2992
+ senderE164: params.ctx.SenderE164,
2993
+ accountId: effectiveAccountId,
2994
+ currentChannelId: threadingContext.currentChannelId,
2995
+ currentThreadTs: typeof params.ctx.MessageThreadId === "string" || typeof params.ctx.MessageThreadId === "number" ? String(params.ctx.MessageThreadId) : void 0,
2996
+ currentMessageId: threadingContext.currentMessageId,
2997
+ groupId: targetSessionEntry?.groupId ?? extractExplicitGroupId(params.ctx.From),
2998
+ groupChannel: targetSessionEntry?.groupChannel ?? params.ctx.GroupChannel ?? params.ctx.GroupSubject,
2999
+ groupSpace: targetSessionEntry?.space ?? params.ctx.GroupSpace,
3000
+ replyToMode: resolveReplyToMode(params.cfg, params.ctx.OriginatingChannel ?? params.ctx.Provider, effectiveAccountId, params.ctx.ChatType)
3001
+ }), { verbose }) }
3002
+ };
3003
+ } catch (err) {
3004
+ return {
3005
+ shouldContinue: false,
3006
+ 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." }
3007
+ };
3008
+ }
3009
+ };
3010
+ const handleStatusCommand = async (params, allowTextCommands) => {
3011
+ if (!allowTextCommands) return null;
3012
+ if (!(params.directives.hasStatusDirective || params.command.commandBodyNormalized === "/status")) return null;
3013
+ if (!params.command.isAuthorizedSender) {
3014
+ logVerbose(`Ignoring /status from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3015
+ return { shouldContinue: false };
3016
+ }
3017
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3018
+ return {
3019
+ shouldContinue: false,
3020
+ reply: await buildStatusReply({
3021
+ cfg: params.cfg,
3022
+ command: params.command,
3023
+ sessionEntry: targetSessionEntry,
3024
+ sessionKey: params.sessionKey,
3025
+ parentSessionKey: targetSessionEntry?.parentSessionKey ?? params.ctx.ParentSessionKey,
3026
+ sessionScope: params.sessionScope,
3027
+ storePath: params.storePath,
3028
+ provider: params.provider,
3029
+ model: params.model,
3030
+ contextTokens: params.contextTokens,
3031
+ resolvedThinkLevel: params.resolvedThinkLevel,
3032
+ resolvedFastMode: params.resolvedFastMode,
3033
+ resolvedVerboseLevel: params.resolvedVerboseLevel,
3034
+ resolvedReasoningLevel: params.resolvedReasoningLevel,
3035
+ resolvedElevatedLevel: params.resolvedElevatedLevel,
3036
+ resolveDefaultThinkingLevel: params.resolveDefaultThinkingLevel,
3037
+ isGroup: params.isGroup,
3038
+ defaultGroupActivation: params.defaultGroupActivation,
3039
+ mediaDecisions: params.ctx.MediaUnderstandingDecisions
3040
+ })
3041
+ };
3042
+ };
3043
+ const handleExportSessionCommand = async (params, allowTextCommands) => {
3044
+ if (!allowTextCommands) return null;
3045
+ const normalized = params.command.commandBodyNormalized;
3046
+ if (normalized !== "/export-session" && !normalized.startsWith("/export-session ") && normalized !== "/export" && !normalized.startsWith("/export ")) return null;
3047
+ if (!params.command.isAuthorizedSender) {
3048
+ logVerbose(`Ignoring /export-session from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3049
+ return { shouldContinue: false };
3050
+ }
3051
+ return {
3052
+ shouldContinue: false,
3053
+ reply: await buildExportSessionReply(params)
3054
+ };
3055
+ };
3056
+ const handleExportTrajectoryCommand = async (params, allowTextCommands) => {
3057
+ if (!allowTextCommands) return null;
3058
+ const normalized = params.command.commandBodyNormalized;
3059
+ if (normalized !== "/export-trajectory" && !normalized.startsWith("/export-trajectory ") && normalized !== "/trajectory" && !normalized.startsWith("/trajectory ")) return null;
3060
+ const unauthorized = rejectUnauthorizedCommand(params, "/export-trajectory");
3061
+ if (unauthorized) return unauthorized;
3062
+ const nonOwner = rejectNonOwnerCommand(params, "/export-trajectory");
3063
+ if (nonOwner) return nonOwner;
3064
+ return {
3065
+ shouldContinue: false,
3066
+ reply: await buildExportTrajectoryReply(params)
3067
+ };
3068
+ };
3069
+ //#endregion
3070
+ //#region src/auto-reply/reply/mcp-commands.ts
3071
+ function parseMcpCommand(raw) {
3072
+ return parseStandardSetUnsetSlashCommand({
3073
+ raw,
3074
+ slash: "/mcp",
3075
+ invalidMessage: "Invalid /mcp syntax.",
3076
+ usageMessage: "Usage: /mcp show|set|unset",
3077
+ onKnownAction: (action, args) => {
3078
+ if (action === "show" || action === "get") return {
3079
+ action: "show",
3080
+ name: args || void 0
3081
+ };
3082
+ },
3083
+ onSet: (name, value) => ({
3084
+ action: "set",
3085
+ name,
3086
+ value
3087
+ }),
3088
+ onUnset: (name) => ({
3089
+ action: "unset",
3090
+ name
3091
+ })
3092
+ });
3093
+ }
3094
+ //#endregion
3095
+ //#region src/auto-reply/reply/commands-mcp.ts
3096
+ function renderJsonBlock$1(label, value) {
3097
+ return `${label}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
3098
+ }
3099
+ const handleMcpCommand = async (params, allowTextCommands) => {
3100
+ if (!allowTextCommands) return null;
3101
+ const mcpCommand = parseMcpCommand(params.command.commandBodyNormalized);
3102
+ if (!mcpCommand) return null;
3103
+ const unauthorized = rejectUnauthorizedCommand(params, "/mcp");
3104
+ if (unauthorized) return unauthorized;
3105
+ const nonOwner = mcpCommand.action === "show" && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/mcp");
3106
+ if (nonOwner) return nonOwner;
3107
+ const disabled = requireCommandFlagEnabled(params.cfg, {
3108
+ label: "/mcp",
3109
+ configKey: "mcp"
3110
+ });
3111
+ if (disabled) return disabled;
3112
+ if (mcpCommand.action === "error") return {
3113
+ shouldContinue: false,
3114
+ reply: { text: `āš ļø ${mcpCommand.message}` }
3115
+ };
3116
+ if (mcpCommand.action === "show") {
3117
+ const loaded = await listConfiguredMcpServers();
3118
+ if (!loaded.ok) return {
3119
+ shouldContinue: false,
3120
+ reply: { text: `āš ļø ${loaded.error}` }
3121
+ };
3122
+ if (mcpCommand.name) {
3123
+ const server = loaded.mcpServers[mcpCommand.name];
3124
+ if (!server) return {
3125
+ shouldContinue: false,
3126
+ reply: { text: `šŸ”Œ No MCP server named "${mcpCommand.name}" in ${loaded.path}.` }
3127
+ };
3128
+ return {
3129
+ shouldContinue: false,
3130
+ reply: { text: renderJsonBlock$1(`šŸ”Œ MCP server "${mcpCommand.name}" (${loaded.path})`, server) }
3131
+ };
3132
+ }
3133
+ if (Object.keys(loaded.mcpServers).length === 0) return {
3134
+ shouldContinue: false,
3135
+ reply: { text: `šŸ”Œ No MCP servers configured in ${loaded.path}.` }
3136
+ };
3137
+ return {
3138
+ shouldContinue: false,
3139
+ reply: { text: renderJsonBlock$1(`šŸ”Œ MCP servers (${loaded.path})`, loaded.mcpServers) }
3140
+ };
3141
+ }
3142
+ const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
3143
+ label: "/mcp write",
3144
+ allowedScopes: ["operator.admin"],
3145
+ missingText: "āŒ /mcp set|unset requires operator.admin for gateway clients."
3146
+ });
3147
+ if (missingAdminScope) return missingAdminScope;
3148
+ if (mcpCommand.action === "set") {
3149
+ const result = await setConfiguredMcpServer({
3150
+ name: mcpCommand.name,
3151
+ server: mcpCommand.value
3152
+ });
3153
+ if (!result.ok) return {
3154
+ shouldContinue: false,
3155
+ reply: { text: `āš ļø ${result.error}` }
3156
+ };
3157
+ return {
3158
+ shouldContinue: false,
3159
+ reply: { text: `šŸ”Œ MCP server "${mcpCommand.name}" saved to ${result.path}.` }
3160
+ };
3161
+ }
3162
+ const result = await unsetConfiguredMcpServer({ name: mcpCommand.name });
3163
+ if (!result.ok) return {
3164
+ shouldContinue: false,
3165
+ reply: { text: `āš ļø ${result.error}` }
3166
+ };
3167
+ if (!result.removed) return {
3168
+ shouldContinue: false,
3169
+ reply: { text: `šŸ”Œ No MCP server named "${mcpCommand.name}" in ${result.path}.` }
3170
+ };
3171
+ return {
3172
+ shouldContinue: false,
3173
+ reply: { text: `šŸ”Œ MCP server "${mcpCommand.name}" removed from ${result.path}.` }
3174
+ };
3175
+ };
3176
+ //#endregion
3177
+ //#region src/auto-reply/reply/commands-plugin.ts
3178
+ /**
3179
+ * Plugin Command Handler
3180
+ *
3181
+ * Handles commands registered by plugins, bypassing the LLM agent.
3182
+ * This handler is called before built-in command handlers.
3183
+ */
3184
+ /**
3185
+ * Handle plugin-registered commands.
3186
+ * Returns a result if a plugin command was matched and executed,
3187
+ * or null to continue to the next handler.
3188
+ */
3189
+ const handlePluginCommand = async (params, allowTextCommands) => {
3190
+ const { command, cfg } = params;
3191
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3192
+ if (!allowTextCommands) return null;
3193
+ const match = matchPluginCommand(command.commandBodyNormalized);
3194
+ if (!match) return null;
3195
+ return {
3196
+ shouldContinue: false,
3197
+ reply: await executePluginCommand({
3198
+ command: match.command,
3199
+ args: match.args,
3200
+ senderId: command.senderId,
3201
+ channel: command.channel,
3202
+ channelId: command.channelId,
3203
+ isAuthorizedSender: command.isAuthorizedSender,
3204
+ gatewayClientScopes: params.ctx.GatewayClientScopes,
3205
+ sessionKey: params.sessionKey,
3206
+ sessionId: targetSessionEntry?.sessionId,
3207
+ sessionFile: targetSessionEntry?.sessionFile,
3208
+ commandBody: command.commandBodyNormalized,
3209
+ config: cfg,
3210
+ from: command.from,
3211
+ to: command.to,
3212
+ accountId: params.ctx.AccountId ?? void 0,
3213
+ messageThreadId: typeof params.ctx.MessageThreadId === "string" || typeof params.ctx.MessageThreadId === "number" ? params.ctx.MessageThreadId : void 0,
3214
+ threadParentId: normalizeOptionalString(params.ctx.ThreadParentId)
3215
+ })
3216
+ };
3217
+ };
3218
+ //#endregion
3219
+ //#region src/auto-reply/reply/plugins-commands.ts
3220
+ function parsePluginsCommand(raw) {
3221
+ const match = raw.match(/^\/plugins?(?:\s+(.*))?$/i);
3222
+ if (!match) return null;
3223
+ const tail = normalizeOptionalString(match?.[1]) ?? "";
3224
+ if (!tail) return { action: "list" };
3225
+ const [rawAction, ...rest] = tail.split(/\s+/);
3226
+ const action = normalizeOptionalLowercaseString(rawAction);
3227
+ const name = rest.join(" ").trim();
3228
+ if (action === "list") return name ? {
3229
+ action: "error",
3230
+ message: "Usage: /plugins list|inspect|show|get|enable|disable [plugin]"
3231
+ } : { action: "list" };
3232
+ if (action === "inspect" || action === "show" || action === "get") return {
3233
+ action: "inspect",
3234
+ name: name || void 0
3235
+ };
3236
+ if (action === "install" || action === "add") {
3237
+ if (!name) return {
3238
+ action: "error",
3239
+ message: "Usage: /plugins install <path|archive|npm-spec|clawhub:pkg>"
3240
+ };
3241
+ return {
3242
+ action: "install",
3243
+ spec: name
3244
+ };
3245
+ }
3246
+ if (action === "enable" || action === "disable") {
3247
+ if (!name) return {
3248
+ action: "error",
3249
+ message: `Usage: /plugins ${action} <plugin-id-or-name>`
3250
+ };
3251
+ return {
3252
+ action,
3253
+ name
3254
+ };
3255
+ }
3256
+ return {
3257
+ action: "error",
3258
+ message: "Usage: /plugins list|inspect|show|get|install|enable|disable [plugin]"
3259
+ };
3260
+ }
3261
+ //#endregion
3262
+ //#region src/auto-reply/reply/commands-plugins.ts
3263
+ function renderJsonBlock(label, value) {
3264
+ return `${label}\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
3265
+ }
3266
+ function buildPluginInspectJson(params) {
3267
+ const inspect = buildPluginInspectReport({
3268
+ id: params.id,
3269
+ config: params.config,
3270
+ report: params.report
3271
+ });
3272
+ if (!inspect) return null;
3273
+ return {
3274
+ inspect,
3275
+ compatibilityWarnings: inspect.compatibility.map((warning) => ({
3276
+ code: warning.code,
3277
+ severity: warning.severity,
3278
+ message: formatPluginCompatibilityNotice(warning)
3279
+ })),
3280
+ install: params.config.plugins?.installs?.[inspect.plugin.id] ?? null
3281
+ };
3282
+ }
3283
+ function buildAllPluginInspectJson(params) {
3284
+ return buildAllPluginInspectReports({
3285
+ config: params.config,
3286
+ report: params.report
3287
+ }).map((inspect) => ({
3288
+ inspect,
3289
+ compatibilityWarnings: inspect.compatibility.map((warning) => ({
3290
+ code: warning.code,
3291
+ severity: warning.severity,
3292
+ message: formatPluginCompatibilityNotice(warning)
3293
+ })),
3294
+ install: params.config.plugins?.installs?.[inspect.plugin.id] ?? null
3295
+ }));
3296
+ }
3297
+ function formatPluginLabel(plugin) {
3298
+ if (!plugin.name || plugin.name === plugin.id) return plugin.id;
3299
+ return `${plugin.name} (${plugin.id})`;
3300
+ }
3301
+ function formatPluginsList(report) {
3302
+ if (report.plugins.length === 0) return `šŸ”Œ No plugins found for workspace ${report.workspaceDir ?? "(unknown workspace)"}.`;
3303
+ return [`šŸ”Œ Plugins (${report.plugins.filter((plugin) => plugin.status === "loaded").length}/${report.plugins.length} loaded)`, ...report.plugins.map((plugin) => {
3304
+ const format = plugin.bundleFormat ? `${plugin.format ?? "genesis"}/${plugin.bundleFormat}` : plugin.format ?? "genesis";
3305
+ return `- ${formatPluginLabel(plugin)} [${plugin.status}] ${format}`;
3306
+ })].join("\n");
3307
+ }
3308
+ function findPlugin(report, rawName) {
3309
+ const target = normalizeOptionalLowercaseString(rawName);
3310
+ if (!target) return;
3311
+ return report.plugins.find((plugin) => normalizeOptionalLowercaseString(plugin.id) === target || normalizeOptionalLowercaseString(plugin.name) === target);
3312
+ }
3313
+ function looksLikeLocalPluginInstallSpec(raw) {
3314
+ 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");
3315
+ }
3316
+ async function installPluginFromPluginsCommand(params) {
3317
+ const fileSpec = resolveFileNpmSpecToLocalPath(params.raw);
3318
+ if (fileSpec && !fileSpec.ok) return {
3319
+ ok: false,
3320
+ error: fileSpec.error
3321
+ };
3322
+ const resolved = resolveUserPath(fileSpec && fileSpec.ok ? fileSpec.path : params.raw);
3323
+ if (fs.existsSync(resolved)) {
3324
+ const result = await installPluginFromPath({
3325
+ path: resolved,
3326
+ logger: createPluginInstallLogger()
3327
+ });
3328
+ if (!result.ok) return {
3329
+ ok: false,
3330
+ error: result.error
3331
+ };
3332
+ clearPluginManifestRegistryCache();
3333
+ const source = resolveArchiveKind(resolved) ? "archive" : "path";
3334
+ await persistPluginInstall({
3335
+ config: params.config,
3336
+ pluginId: result.pluginId,
3337
+ install: {
3338
+ source,
3339
+ sourcePath: resolved,
3340
+ installPath: result.targetDir,
3341
+ version: result.version
3342
+ }
3343
+ });
3344
+ return {
3345
+ ok: true,
3346
+ pluginId: result.pluginId
3347
+ };
3348
+ }
3349
+ if (looksLikeLocalPluginInstallSpec(params.raw)) return {
3350
+ ok: false,
3351
+ error: `Path not found: ${resolved}`
3352
+ };
3353
+ if (parseClawHubPluginSpec(params.raw)) {
3354
+ const result = await installPluginFromClawHub({
3355
+ spec: params.raw,
3356
+ logger: createPluginInstallLogger()
3357
+ });
3358
+ if (!result.ok) return {
3359
+ ok: false,
3360
+ error: result.error
3361
+ };
3362
+ clearPluginManifestRegistryCache();
3363
+ await persistPluginInstall({
3364
+ config: params.config,
3365
+ pluginId: result.pluginId,
3366
+ install: {
3367
+ source: "clawhub",
3368
+ spec: params.raw,
3369
+ installPath: result.targetDir,
3370
+ version: result.version,
3371
+ integrity: result.clawhub.integrity,
3372
+ resolvedAt: result.clawhub.resolvedAt,
3373
+ clawhubUrl: result.clawhub.clawhubUrl,
3374
+ clawhubPackage: result.clawhub.clawhubPackage,
3375
+ clawhubFamily: result.clawhub.clawhubFamily,
3376
+ clawhubChannel: result.clawhub.clawhubChannel
3377
+ }
3378
+ });
3379
+ return {
3380
+ ok: true,
3381
+ pluginId: result.pluginId
3382
+ };
3383
+ }
3384
+ const preferredClawHubSpec = buildPreferredClawHubSpec(params.raw);
3385
+ if (preferredClawHubSpec) {
3386
+ const clawhubResult = await installPluginFromClawHub({
3387
+ spec: preferredClawHubSpec,
3388
+ logger: createPluginInstallLogger()
3389
+ });
3390
+ if (clawhubResult.ok) {
3391
+ clearPluginManifestRegistryCache();
3392
+ await persistPluginInstall({
3393
+ config: params.config,
3394
+ pluginId: clawhubResult.pluginId,
3395
+ install: {
3396
+ source: "clawhub",
3397
+ spec: preferredClawHubSpec,
3398
+ installPath: clawhubResult.targetDir,
3399
+ version: clawhubResult.version,
3400
+ integrity: clawhubResult.clawhub.integrity,
3401
+ resolvedAt: clawhubResult.clawhub.resolvedAt,
3402
+ clawhubUrl: clawhubResult.clawhub.clawhubUrl,
3403
+ clawhubPackage: clawhubResult.clawhub.clawhubPackage,
3404
+ clawhubFamily: clawhubResult.clawhub.clawhubFamily,
3405
+ clawhubChannel: clawhubResult.clawhub.clawhubChannel
3406
+ }
3407
+ });
3408
+ return {
3409
+ ok: true,
3410
+ pluginId: clawhubResult.pluginId
3411
+ };
3412
+ }
3413
+ if (decidePreferredClawHubFallback(clawhubResult) !== "fallback_to_npm") return {
3414
+ ok: false,
3415
+ error: clawhubResult.error
3416
+ };
3417
+ }
3418
+ const result = await installPluginFromNpmSpec({
3419
+ spec: params.raw,
3420
+ logger: createPluginInstallLogger()
3421
+ });
3422
+ if (!result.ok) return {
3423
+ ok: false,
3424
+ error: result.error
3425
+ };
3426
+ clearPluginManifestRegistryCache();
3427
+ const installRecord = buildNpmInstallRecordFields({
3428
+ spec: params.raw,
3429
+ installPath: result.targetDir,
3430
+ version: result.version,
3431
+ resolution: result.npmResolution
3432
+ });
3433
+ await persistPluginInstall({
3434
+ config: params.config,
3435
+ pluginId: result.pluginId,
3436
+ install: installRecord
3437
+ });
3438
+ return {
3439
+ ok: true,
3440
+ pluginId: result.pluginId
3441
+ };
3442
+ }
3443
+ async function loadPluginCommandState(workspaceDir, options) {
3444
+ const snapshot = await readConfigFileSnapshot();
3445
+ if (!snapshot.valid) return {
3446
+ ok: false,
3447
+ path: snapshot.path,
3448
+ error: "Config file is invalid; fix it before using /plugins."
3449
+ };
3450
+ const config = structuredClone(snapshot.resolved);
3451
+ return {
3452
+ ok: true,
3453
+ path: snapshot.path,
3454
+ config,
3455
+ report: options?.loadModules === true ? buildPluginDiagnosticsReport({
3456
+ config,
3457
+ workspaceDir
3458
+ }) : buildPluginSnapshotReport({
3459
+ config,
3460
+ workspaceDir
3461
+ })
3462
+ };
3463
+ }
3464
+ async function loadPluginCommandConfig() {
3465
+ const snapshot = await readConfigFileSnapshot();
3466
+ if (!snapshot.valid) return {
3467
+ ok: false,
3468
+ path: snapshot.path,
3469
+ error: "Config file is invalid; fix it before using /plugins."
3470
+ };
3471
+ return {
3472
+ ok: true,
3473
+ path: snapshot.path,
3474
+ config: structuredClone(snapshot.resolved)
3475
+ };
3476
+ }
3477
+ const handlePluginsCommand = async (params, allowTextCommands) => {
3478
+ if (!allowTextCommands) return null;
3479
+ const pluginsCommand = parsePluginsCommand(params.command.commandBodyNormalized);
3480
+ if (!pluginsCommand) return null;
3481
+ const unauthorized = rejectUnauthorizedCommand(params, "/plugins");
3482
+ if (unauthorized) return unauthorized;
3483
+ const nonOwner = (pluginsCommand.action === "list" || pluginsCommand.action === "inspect") && isInternalMessageChannel(params.command.channel) ? null : rejectNonOwnerCommand(params, "/plugins");
3484
+ if (nonOwner) return nonOwner;
3485
+ const disabled = requireCommandFlagEnabled(params.cfg, {
3486
+ label: "/plugins",
3487
+ configKey: "plugins"
3488
+ });
3489
+ if (disabled) return disabled;
3490
+ if (pluginsCommand.action === "error") return {
3491
+ shouldContinue: false,
3492
+ reply: { text: `āš ļø ${pluginsCommand.message}` }
3493
+ };
3494
+ const missingAdminScope = requireGatewayClientScopeForInternalChannel(params, {
3495
+ label: "/plugins write",
3496
+ allowedScopes: ["operator.admin"],
3497
+ missingText: "āŒ /plugins install|enable|disable requires operator.admin for gateway clients."
3498
+ });
3499
+ if (missingAdminScope) return missingAdminScope;
3500
+ if (pluginsCommand.action === "install") {
3501
+ const loadedConfig = await loadPluginCommandConfig();
3502
+ if (!loadedConfig.ok) return {
3503
+ shouldContinue: false,
3504
+ reply: { text: `āš ļø ${loadedConfig.error}` }
3505
+ };
3506
+ const installed = await installPluginFromPluginsCommand({
3507
+ raw: pluginsCommand.spec,
3508
+ config: loadedConfig.config
3509
+ });
3510
+ if (!installed.ok) return {
3511
+ shouldContinue: false,
3512
+ reply: { text: `āš ļø ${installed.error}` }
3513
+ };
3514
+ return {
3515
+ shouldContinue: false,
3516
+ reply: { text: `šŸ”Œ Installed plugin "${installed.pluginId}". Restart the gateway to load plugins.` }
3517
+ };
3518
+ }
3519
+ const loaded = await loadPluginCommandState(params.workspaceDir, { loadModules: pluginsCommand.action !== "list" });
3520
+ if (!loaded.ok) return {
3521
+ shouldContinue: false,
3522
+ reply: { text: `āš ļø ${loaded.error}` }
3523
+ };
3524
+ if (pluginsCommand.action === "list") return {
3525
+ shouldContinue: false,
3526
+ reply: { text: formatPluginsList(loaded.report) }
3527
+ };
3528
+ if (pluginsCommand.action === "inspect") {
3529
+ if (!pluginsCommand.name) return {
3530
+ shouldContinue: false,
3531
+ reply: { text: formatPluginsList(loaded.report) }
3532
+ };
3533
+ if (normalizeOptionalLowercaseString(pluginsCommand.name) === "all") return {
3534
+ shouldContinue: false,
3535
+ reply: { text: renderJsonBlock("šŸ”Œ Plugins", buildAllPluginInspectJson(loaded)) }
3536
+ };
3537
+ const payload = buildPluginInspectJson({
3538
+ id: pluginsCommand.name,
3539
+ config: loaded.config,
3540
+ report: loaded.report
3541
+ });
3542
+ if (!payload) return {
3543
+ shouldContinue: false,
3544
+ reply: { text: `šŸ”Œ No plugin named "${pluginsCommand.name}" found.` }
3545
+ };
3546
+ return {
3547
+ shouldContinue: false,
3548
+ reply: { text: renderJsonBlock(`šŸ”Œ Plugin "${payload.inspect.plugin.id}"`, {
3549
+ ...payload.inspect,
3550
+ compatibilityWarnings: payload.compatibilityWarnings,
3551
+ install: payload.install
3552
+ }) }
3553
+ };
3554
+ }
3555
+ const plugin = findPlugin(loaded.report, pluginsCommand.name);
3556
+ if (!plugin) return {
3557
+ shouldContinue: false,
3558
+ reply: { text: `šŸ”Œ No plugin named "${pluginsCommand.name}" found.` }
3559
+ };
3560
+ const validated = validateConfigObjectWithPlugins(setPluginEnabledInConfig(structuredClone(loaded.config), plugin.id, pluginsCommand.action === "enable"));
3561
+ if (!validated.ok) {
3562
+ const issue = validated.issues[0];
3563
+ return {
3564
+ shouldContinue: false,
3565
+ reply: { text: `āš ļø Config invalid after /plugins ${pluginsCommand.action} (${issue.path}: ${issue.message}).` }
3566
+ };
3567
+ }
3568
+ await writeConfigFile(validated.config);
3569
+ return {
3570
+ shouldContinue: false,
3571
+ reply: { text: `šŸ”Œ Plugin "${plugin.id}" ${pluginsCommand.action}d in ${loaded.path}. Restart the gateway to apply.` }
3572
+ };
3573
+ };
3574
+ //#endregion
3575
+ //#region src/auto-reply/send-policy.ts
3576
+ function normalizeSendPolicyOverride(raw) {
3577
+ const value = normalizeOptionalLowercaseString(raw);
3578
+ if (!value) return;
3579
+ if (value === "allow" || value === "on") return "allow";
3580
+ if (value === "deny" || value === "off") return "deny";
3581
+ }
3582
+ function parseSendPolicyCommand(raw) {
3583
+ if (!raw) return { hasCommand: false };
3584
+ const trimmed = raw.trim();
3585
+ if (!trimmed) return { hasCommand: false };
3586
+ const match = normalizeCommandBody(stripInboundMetadata(trimmed)).match(/^\/send(?:\s+([a-zA-Z]+))?\s*$/i);
3587
+ if (!match) return { hasCommand: false };
3588
+ const token = normalizeOptionalLowercaseString(match[1]);
3589
+ if (!token) return { hasCommand: true };
3590
+ if (token === "inherit" || token === "default" || token === "reset") return {
3591
+ hasCommand: true,
3592
+ mode: "inherit"
3593
+ };
3594
+ return {
3595
+ hasCommand: true,
3596
+ mode: normalizeSendPolicyOverride(token)
3597
+ };
3598
+ }
3599
+ //#endregion
3600
+ //#region src/auto-reply/reply/commands-session-store.ts
3601
+ async function persistSessionEntry(params) {
3602
+ if (!params.sessionEntry || !params.sessionStore || !params.sessionKey) return false;
3603
+ params.sessionEntry.updatedAt = Date.now();
3604
+ params.sessionStore[params.sessionKey] = params.sessionEntry;
3605
+ if (params.storePath) await updateSessionStore(params.storePath, (store) => {
3606
+ store[params.sessionKey] = params.sessionEntry;
3607
+ });
3608
+ return true;
3609
+ }
3610
+ async function persistAbortTargetEntry(params) {
3611
+ const { entry, key, sessionStore, storePath, abortCutoff } = params;
3612
+ if (!entry || !key || !sessionStore) return false;
3613
+ entry.abortedLastRun = true;
3614
+ applyAbortCutoffToSessionEntry(entry, abortCutoff);
3615
+ entry.updatedAt = Date.now();
3616
+ sessionStore[key] = entry;
3617
+ if (storePath) await updateSessionStore(storePath, (store) => {
3618
+ const nextEntry = store[key] ?? entry;
3619
+ if (!nextEntry) return;
3620
+ nextEntry.abortedLastRun = true;
3621
+ applyAbortCutoffToSessionEntry(nextEntry, abortCutoff);
3622
+ nextEntry.updatedAt = Date.now();
3623
+ store[key] = nextEntry;
3624
+ });
3625
+ return true;
3626
+ }
3627
+ //#endregion
3628
+ //#region src/auto-reply/reply/commands-session-abort.ts
3629
+ async function abortEmbeddedPiRunForSession(sessionId) {
3630
+ const { abortEmbeddedPiRun } = await import("./runs-DR3Fr0Np.js");
3631
+ abortEmbeddedPiRun(sessionId);
3632
+ }
3633
+ function resolveAbortTarget(params) {
3634
+ const targetSessionKey = normalizeOptionalString(params.ctx.CommandTargetSessionKey) || params.sessionKey;
3635
+ const { entry, key } = resolveSessionEntryForKey(params.sessionStore, targetSessionKey);
3636
+ if (entry && key) return {
3637
+ entry,
3638
+ key,
3639
+ sessionId: replyRunRegistry.resolveSessionId(key) ?? entry.sessionId
3640
+ };
3641
+ if (params.sessionEntry && params.sessionKey && (!targetSessionKey || targetSessionKey === params.sessionKey)) return {
3642
+ entry: params.sessionEntry,
3643
+ key: params.sessionKey,
3644
+ sessionId: replyRunRegistry.resolveSessionId(params.sessionKey) ?? params.sessionEntry.sessionId
3645
+ };
3646
+ return {
3647
+ entry: void 0,
3648
+ key: targetSessionKey,
3649
+ sessionId: targetSessionKey ? replyRunRegistry.resolveSessionId(targetSessionKey) : void 0
3650
+ };
3651
+ }
3652
+ function resolveAbortCutoffForTarget(params) {
3653
+ if (!shouldPersistAbortCutoff({
3654
+ commandSessionKey: params.commandSessionKey,
3655
+ targetSessionKey: params.targetSessionKey
3656
+ })) return;
3657
+ return resolveAbortCutoffFromContext(params.ctx);
3658
+ }
3659
+ async function applyAbortTarget(params) {
3660
+ const { abortTarget } = params;
3661
+ if (abortTarget.key) replyRunRegistry.abort(abortTarget.key);
3662
+ if (abortTarget.sessionId) await abortEmbeddedPiRunForSession(abortTarget.sessionId);
3663
+ if (!await persistAbortTargetEntry({
3664
+ entry: abortTarget.entry,
3665
+ key: abortTarget.key,
3666
+ sessionStore: params.sessionStore,
3667
+ storePath: params.storePath,
3668
+ abortCutoff: params.abortCutoff
3669
+ }) && params.abortKey) setAbortMemory(params.abortKey, true);
3670
+ }
3671
+ function buildAbortTargetApplyParams(params, abortTarget) {
3672
+ return {
3673
+ abortTarget,
3674
+ sessionStore: params.sessionStore,
3675
+ storePath: params.storePath,
3676
+ abortKey: params.command.abortKey,
3677
+ abortCutoff: resolveAbortCutoffForTarget({
3678
+ ctx: params.ctx,
3679
+ commandSessionKey: params.sessionKey,
3680
+ targetSessionKey: abortTarget.key
3681
+ })
3682
+ };
3683
+ }
3684
+ const handleStopCommand = async (params, allowTextCommands) => {
3685
+ if (!allowTextCommands) return null;
3686
+ if (params.command.commandBodyNormalized !== "/stop") return null;
3687
+ const unauthorizedStop = rejectUnauthorizedCommand(params, "/stop");
3688
+ if (unauthorizedStop) return unauthorizedStop;
3689
+ const abortTarget = resolveAbortTarget({
3690
+ ctx: params.ctx,
3691
+ sessionKey: params.sessionKey,
3692
+ sessionEntry: params.sessionEntry,
3693
+ sessionStore: params.sessionStore
3694
+ });
3695
+ const cleared = clearSessionQueues([abortTarget.key, abortTarget.sessionId]);
3696
+ if (cleared.followupCleared > 0 || cleared.laneCleared > 0) logVerbose(`stop: cleared followups=${cleared.followupCleared} lane=${cleared.laneCleared} keys=${cleared.keys.join(",")}`);
3697
+ await applyAbortTarget(buildAbortTargetApplyParams(params, abortTarget));
3698
+ await triggerInternalHook(createInternalHookEvent("command", "stop", abortTarget.key ?? params.sessionKey ?? "", {
3699
+ sessionEntry: abortTarget.entry,
3700
+ sessionId: abortTarget.sessionId,
3701
+ commandSource: params.command.surface,
3702
+ senderId: params.command.senderId
3703
+ }));
3704
+ const { stopped } = stopSubagentsForRequester({
3705
+ cfg: params.cfg,
3706
+ requesterSessionKey: abortTarget.key ?? params.sessionKey
3707
+ });
3708
+ return {
3709
+ shouldContinue: false,
3710
+ reply: { text: formatAbortReplyText(stopped) }
3711
+ };
3712
+ };
3713
+ const handleAbortTrigger = async (params, allowTextCommands) => {
3714
+ if (!allowTextCommands) return null;
3715
+ if (!isAbortTrigger(params.command.rawBodyNormalized)) return null;
3716
+ const unauthorizedAbortTrigger = rejectUnauthorizedCommand(params, "abort trigger");
3717
+ if (unauthorizedAbortTrigger) return unauthorizedAbortTrigger;
3718
+ await applyAbortTarget(buildAbortTargetApplyParams(params, resolveAbortTarget({
3719
+ ctx: params.ctx,
3720
+ sessionKey: params.sessionKey,
3721
+ sessionEntry: params.sessionEntry,
3722
+ sessionStore: params.sessionStore
3723
+ })));
3724
+ return {
3725
+ shouldContinue: false,
3726
+ reply: { text: "āš™ļø Agent was aborted." }
3727
+ };
3728
+ };
3729
+ //#endregion
3730
+ //#region src/auto-reply/reply/commands-session.ts
3731
+ const SESSION_DURATION_OFF_VALUES = new Set([
3732
+ "off",
3733
+ "disable",
3734
+ "disabled",
3735
+ "none",
3736
+ "0"
3737
+ ]);
3738
+ const SESSION_ACTION_IDLE = "idle";
3739
+ const SESSION_ACTION_MAX_AGE = "max-age";
3740
+ function buildRestartCommandSentinel(params) {
3741
+ const sessionKey = normalizeOptionalString(params.sessionKey);
3742
+ if (!sessionKey) return null;
3743
+ const { deliveryContext, threadId } = extractDeliveryInfo(sessionKey);
3744
+ return {
3745
+ kind: "restart",
3746
+ status: "ok",
3747
+ ts: Date.now(),
3748
+ sessionKey,
3749
+ deliveryContext,
3750
+ threadId,
3751
+ message: "/restart",
3752
+ continuation: buildRestartSuccessContinuation({ sessionKey }),
3753
+ doctorHint: formatDoctorNonInteractiveHint(),
3754
+ stats: {
3755
+ mode: "gateway.restart",
3756
+ reason: "/restart"
3757
+ }
3758
+ };
3759
+ }
3760
+ function resolveSessionCommandUsage() {
3761
+ return "Usage: /session idle <duration|off> | /session max-age <duration|off> (example: /session idle 24h)";
3762
+ }
3763
+ function parseSessionDurationMs(raw) {
3764
+ const normalized = normalizeOptionalLowercaseString(raw);
3765
+ if (!normalized) throw new Error("missing duration");
3766
+ if (SESSION_DURATION_OFF_VALUES.has(normalized)) return 0;
3767
+ if (/^\d+(?:\.\d+)?$/.test(normalized)) {
3768
+ const hours = Number(normalized);
3769
+ if (!Number.isFinite(hours) || hours < 0) throw new Error("invalid duration");
3770
+ return Math.round(hours * 60 * 60 * 1e3);
3771
+ }
3772
+ return parseDurationMs(normalized, { defaultUnit: "h" });
3773
+ }
3774
+ function formatSessionExpiry(expiresAt) {
3775
+ return new Date(expiresAt).toISOString();
3776
+ }
3777
+ function resolveSessionBindingDurationMs(binding, key, fallbackMs) {
3778
+ const raw = binding.metadata?.[key];
3779
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return fallbackMs;
3780
+ return Math.max(0, Math.floor(raw));
3781
+ }
3782
+ function resolveSessionBindingLastActivityAt(binding) {
3783
+ const raw = binding.metadata?.lastActivityAt;
3784
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return binding.boundAt;
3785
+ return Math.max(Math.floor(raw), binding.boundAt);
3786
+ }
3787
+ function resolveSessionBindingBoundBy(binding) {
3788
+ const raw = binding.metadata?.boundBy;
3789
+ return normalizeOptionalString(raw) ?? "";
3790
+ }
3791
+ function isSessionBindingRecord(binding) {
3792
+ return "bindingId" in binding;
3793
+ }
3794
+ function resolveUpdatedLifecycleDurationMs(binding, key) {
3795
+ if (!isSessionBindingRecord(binding)) {
3796
+ const raw = binding[key];
3797
+ if (typeof raw === "number" && Number.isFinite(raw)) return Math.max(0, Math.floor(raw));
3798
+ }
3799
+ if (!isSessionBindingRecord(binding)) return;
3800
+ const raw = binding.metadata?.[key];
3801
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return;
3802
+ return Math.max(0, Math.floor(raw));
3803
+ }
3804
+ function toUpdatedLifecycleBinding(binding) {
3805
+ const lastActivityAt = isSessionBindingRecord(binding) ? resolveSessionBindingLastActivityAt(binding) : Math.max(Math.floor(binding.lastActivityAt), binding.boundAt);
3806
+ return {
3807
+ boundAt: binding.boundAt,
3808
+ lastActivityAt,
3809
+ idleTimeoutMs: resolveUpdatedLifecycleDurationMs(binding, "idleTimeoutMs"),
3810
+ maxAgeMs: resolveUpdatedLifecycleDurationMs(binding, "maxAgeMs")
3811
+ };
3812
+ }
3813
+ function resolveUpdatedBindingExpiry(params) {
3814
+ const expiries = params.bindings.map((binding) => {
3815
+ if (params.action === SESSION_ACTION_IDLE) {
3816
+ const idleTimeoutMs = typeof binding.idleTimeoutMs === "number" && Number.isFinite(binding.idleTimeoutMs) ? Math.max(0, Math.floor(binding.idleTimeoutMs)) : 0;
3817
+ if (idleTimeoutMs <= 0) return;
3818
+ return Math.max(binding.lastActivityAt, binding.boundAt) + idleTimeoutMs;
3819
+ }
3820
+ const maxAgeMs = typeof binding.maxAgeMs === "number" && Number.isFinite(binding.maxAgeMs) ? Math.max(0, Math.floor(binding.maxAgeMs)) : 0;
3821
+ if (maxAgeMs <= 0) return;
3822
+ return binding.boundAt + maxAgeMs;
3823
+ }).filter((expiresAt) => typeof expiresAt === "number");
3824
+ if (expiries.length === 0) return;
3825
+ return Math.min(...expiries);
3826
+ }
3827
+ const handleActivationCommand = async (params, allowTextCommands) => {
3828
+ if (!allowTextCommands) return null;
3829
+ const activationCommand = parseActivationCommand(params.command.commandBodyNormalized);
3830
+ if (!activationCommand.hasCommand) return null;
3831
+ if (!params.isGroup) return {
3832
+ shouldContinue: false,
3833
+ reply: { text: "āš™ļø Group activation only applies to group chats." }
3834
+ };
3835
+ if (!params.command.isAuthorizedSender) {
3836
+ logVerbose(`Ignoring /activation from unauthorized sender in group: ${params.command.senderId || "<unknown>"}`);
3837
+ return { shouldContinue: false };
3838
+ }
3839
+ if (!activationCommand.mode) return {
3840
+ shouldContinue: false,
3841
+ reply: { text: "āš™ļø Usage: /activation mention|always" }
3842
+ };
3843
+ if (params.sessionEntry && params.sessionStore && params.sessionKey) {
3844
+ params.sessionEntry.groupActivation = activationCommand.mode;
3845
+ params.sessionEntry.groupActivationNeedsSystemIntro = true;
3846
+ await persistSessionEntry(params);
3847
+ }
3848
+ return {
3849
+ shouldContinue: false,
3850
+ reply: { text: `āš™ļø Group activation set to ${activationCommand.mode}.` }
3851
+ };
3852
+ };
3853
+ const handleSendPolicyCommand = async (params, allowTextCommands) => {
3854
+ if (!allowTextCommands) return null;
3855
+ const sendPolicyCommand = parseSendPolicyCommand(params.command.commandBodyNormalized);
3856
+ if (!sendPolicyCommand.hasCommand) return null;
3857
+ const unauthorizedResult = rejectUnauthorizedCommand(params, "/send");
3858
+ if (unauthorizedResult) return unauthorizedResult;
3859
+ const nonOwnerResult = rejectNonOwnerCommand(params, "/send");
3860
+ if (nonOwnerResult) return nonOwnerResult;
3861
+ if (!sendPolicyCommand.mode) return {
3862
+ shouldContinue: false,
3863
+ reply: { text: "āš™ļø Usage: /send on|off|inherit" }
3864
+ };
3865
+ if (params.sessionEntry && params.sessionStore && params.sessionKey) {
3866
+ if (sendPolicyCommand.mode === "inherit") delete params.sessionEntry.sendPolicy;
3867
+ else params.sessionEntry.sendPolicy = sendPolicyCommand.mode;
3868
+ await persistSessionEntry(params);
3869
+ }
3870
+ return {
3871
+ shouldContinue: false,
3872
+ reply: { text: `āš™ļø Send policy set to ${sendPolicyCommand.mode === "inherit" ? "inherit" : sendPolicyCommand.mode === "allow" ? "on" : "off"}.` }
3873
+ };
3874
+ };
3875
+ const handleUsageCommand = async (params, allowTextCommands) => {
3876
+ if (!allowTextCommands) return null;
3877
+ const normalized = params.command.commandBodyNormalized;
3878
+ if (normalized !== "/usage" && !normalized.startsWith("/usage ")) return null;
3879
+ if (!params.command.isAuthorizedSender) {
3880
+ logVerbose(`Ignoring /usage from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3881
+ return { shouldContinue: false };
3882
+ }
3883
+ const rawArgs = normalized === "/usage" ? "" : normalized.slice(6).trim();
3884
+ const requested = rawArgs ? normalizeUsageDisplay(rawArgs) : void 0;
3885
+ if (normalizeLowercaseStringOrEmpty(rawArgs).startsWith("cost")) {
3886
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3887
+ const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
3888
+ sessionKey: params.sessionKey,
3889
+ config: params.cfg
3890
+ }) : params.agentId;
3891
+ const sessionSummary = await loadSessionCostSummary({
3892
+ sessionId: targetSessionEntry?.sessionId,
3893
+ sessionEntry: targetSessionEntry,
3894
+ sessionFile: targetSessionEntry?.sessionFile,
3895
+ config: params.cfg,
3896
+ agentId: sessionAgentId
3897
+ });
3898
+ const summary = await loadCostUsageSummary({
3899
+ days: 30,
3900
+ config: params.cfg
3901
+ });
3902
+ const sessionCost = formatUsd(sessionSummary?.totalCost);
3903
+ const sessionTokens = sessionSummary?.totalTokens ? formatTokenCount(sessionSummary.totalTokens) : void 0;
3904
+ const sessionSuffix = (sessionSummary?.missingCostEntries ?? 0) > 0 ? " (partial)" : "";
3905
+ const sessionLine = sessionCost || sessionTokens ? `Session ${sessionCost ?? "n/a"}${sessionSuffix}${sessionTokens ? ` Ā· ${sessionTokens} tokens` : ""}` : "Session n/a";
3906
+ const todayKey = (/* @__PURE__ */ new Date()).toLocaleDateString("en-CA");
3907
+ const todayEntry = summary.daily.find((entry) => entry.date === todayKey);
3908
+ const todayCost = formatUsd(todayEntry?.totalCost);
3909
+ const todaySuffix = (todayEntry?.missingCostEntries ?? 0) > 0 ? " (partial)" : "";
3910
+ const todayLine = `Today ${todayCost ?? "n/a"}${todaySuffix}`;
3911
+ const last30Cost = formatUsd(summary.totals.totalCost);
3912
+ const last30Suffix = summary.totals.missingCostEntries > 0 ? " (partial)" : "";
3913
+ return {
3914
+ shouldContinue: false,
3915
+ reply: { text: `šŸ’ø Usage cost\n${sessionLine}\n${todayLine}\n${`Last 30d ${last30Cost ?? "n/a"}${last30Suffix}`}` }
3916
+ };
3917
+ }
3918
+ if (rawArgs && !requested) return {
3919
+ shouldContinue: false,
3920
+ reply: { text: "āš™ļø Usage: /usage off|tokens|full|cost" }
3921
+ };
3922
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3923
+ const currentRaw = targetSessionEntry?.responseUsage;
3924
+ const current = resolveResponseUsageMode(currentRaw);
3925
+ const next = requested ?? (current === "off" ? "tokens" : current === "tokens" ? "full" : "off");
3926
+ if (targetSessionEntry && params.sessionStore && params.sessionKey) {
3927
+ if (next === "off") delete targetSessionEntry.responseUsage;
3928
+ else targetSessionEntry.responseUsage = next;
3929
+ params.sessionStore[params.sessionKey] = targetSessionEntry;
3930
+ await persistSessionEntry({
3931
+ ...params,
3932
+ sessionEntry: targetSessionEntry
3933
+ });
3934
+ }
3935
+ return {
3936
+ shouldContinue: false,
3937
+ reply: { text: `āš™ļø Usage footer: ${next}.` }
3938
+ };
3939
+ };
3940
+ const handleFastCommand = async (params, allowTextCommands) => {
3941
+ if (!allowTextCommands) return null;
3942
+ const normalized = params.command.commandBodyNormalized;
3943
+ if (normalized !== "/fast" && !normalized.startsWith("/fast ")) return null;
3944
+ if (!params.command.isAuthorizedSender) {
3945
+ logVerbose(`Ignoring /fast from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3946
+ return { shouldContinue: false };
3947
+ }
3948
+ const rawMode = normalizeLowercaseStringOrEmpty(normalized === "/fast" ? "" : normalized.slice(5).trim());
3949
+ if (!rawMode || rawMode === "status") {
3950
+ const targetSessionEntry = params.sessionStore?.[params.sessionKey] ?? params.sessionEntry;
3951
+ const sessionAgentId = params.sessionKey ? resolveSessionAgentId({
3952
+ sessionKey: params.sessionKey,
3953
+ config: params.cfg
3954
+ }) : params.agentId;
3955
+ const state = resolveFastModeState({
3956
+ cfg: params.cfg,
3957
+ provider: params.provider,
3958
+ model: params.model,
3959
+ agentId: sessionAgentId,
3960
+ sessionEntry: targetSessionEntry
3961
+ });
3962
+ const suffix = state.source === "agent" ? " (agent)" : state.source === "config" ? " (config)" : state.source === "default" ? " (default)" : "";
3963
+ return {
3964
+ shouldContinue: false,
3965
+ reply: { text: `āš™ļø Current fast mode: ${state.enabled ? "on" : "off"}${suffix}.` }
3966
+ };
3967
+ }
3968
+ const nextMode = normalizeFastMode(rawMode);
3969
+ if (nextMode === void 0) return {
3970
+ shouldContinue: false,
3971
+ reply: { text: "āš™ļø Usage: /fast status|on|off" }
3972
+ };
3973
+ if (params.sessionEntry && params.sessionStore && params.sessionKey) {
3974
+ params.sessionEntry.fastMode = nextMode;
3975
+ await persistSessionEntry(params);
3976
+ }
3977
+ return {
3978
+ shouldContinue: false,
3979
+ reply: { text: `āš™ļø Fast mode ${nextMode ? "enabled" : "disabled"}.` }
3980
+ };
3981
+ };
3982
+ const handleSessionCommand = async (params, allowTextCommands) => {
3983
+ if (!allowTextCommands) return null;
3984
+ const normalized = params.command.commandBodyNormalized;
3985
+ if (!/^\/session(?:\s|$)/.test(normalized)) return null;
3986
+ if (!params.command.isAuthorizedSender) {
3987
+ logVerbose(`Ignoring /session from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
3988
+ return { shouldContinue: false };
3989
+ }
3990
+ const tokens = normalized.slice(8).trim().split(/\s+/).filter(Boolean);
3991
+ const action = normalizeOptionalLowercaseString(tokens[0]);
3992
+ if (action !== SESSION_ACTION_IDLE && action !== SESSION_ACTION_MAX_AGE) return {
3993
+ shouldContinue: false,
3994
+ reply: { text: resolveSessionCommandUsage() }
3995
+ };
3996
+ const channelId = params.command.channelId ?? normalizeChannelId$1(resolveCommandSurfaceChannel(params)) ?? void 0;
3997
+ const commandConversationBindings = channelId ? getChannelPlugin(channelId)?.conversationBindings : void 0;
3998
+ const commandSupportsCurrentConversationBinding = Boolean(commandConversationBindings?.supportsCurrentConversationBinding);
3999
+ const commandSupportsLifecycleUpdate = action === SESSION_ACTION_IDLE ? typeof commandConversationBindings?.setIdleTimeoutBySessionKey === "function" : typeof commandConversationBindings?.setMaxAgeBySessionKey === "function";
4000
+ const bindingContext = resolveConversationBindingContextFromAcpCommand(params);
4001
+ if (!bindingContext) {
4002
+ if (!channelId || !commandSupportsCurrentConversationBinding || !commandSupportsLifecycleUpdate) return {
4003
+ shouldContinue: false,
4004
+ reply: { text: "āš ļø /session idle and /session max-age are currently available only on channels that support focused conversation bindings." }
4005
+ };
4006
+ return {
4007
+ shouldContinue: false,
4008
+ reply: { text: "āš ļø /session idle and /session max-age must be run inside a focused conversation." }
4009
+ };
4010
+ }
4011
+ const resolvedChannelId = bindingContext.channel || channelId;
4012
+ const conversationBindings = resolvedChannelId ? getChannelPlugin(resolvedChannelId)?.conversationBindings : void 0;
4013
+ const supportsCurrentConversationBinding = Boolean(conversationBindings?.supportsCurrentConversationBinding);
4014
+ const supportsLifecycleUpdate = action === SESSION_ACTION_IDLE ? typeof conversationBindings?.setIdleTimeoutBySessionKey === "function" : typeof conversationBindings?.setMaxAgeBySessionKey === "function";
4015
+ if (!resolvedChannelId || !supportsCurrentConversationBinding || !supportsLifecycleUpdate) return {
4016
+ shouldContinue: false,
4017
+ reply: { text: "āš ļø /session idle and /session max-age are currently available only on channels that support focused conversation bindings." }
4018
+ };
4019
+ const activeBinding = getSessionBindingService().resolveByConversation(bindingContext);
4020
+ if (!activeBinding) return {
4021
+ shouldContinue: false,
4022
+ reply: { text: "ā„¹ļø This conversation is not currently focused." }
4023
+ };
4024
+ const idleTimeoutMs = resolveSessionBindingDurationMs(activeBinding, "idleTimeoutMs", 1440 * 60 * 1e3);
4025
+ const idleExpiresAt = idleTimeoutMs > 0 ? resolveSessionBindingLastActivityAt(activeBinding) + idleTimeoutMs : void 0;
4026
+ const maxAgeMs = resolveSessionBindingDurationMs(activeBinding, "maxAgeMs", 0);
4027
+ const maxAgeExpiresAt = maxAgeMs > 0 ? activeBinding.boundAt + maxAgeMs : void 0;
4028
+ const durationArgRaw = tokens.slice(1).join("");
4029
+ if (!durationArgRaw) {
4030
+ if (action === SESSION_ACTION_IDLE) {
4031
+ if (typeof idleExpiresAt === "number" && Number.isFinite(idleExpiresAt) && idleExpiresAt > Date.now()) return {
4032
+ shouldContinue: false,
4033
+ reply: { text: `ā„¹ļø Idle timeout active (${formatThreadBindingDurationLabel(idleTimeoutMs)}, next auto-unfocus at ${formatSessionExpiry(idleExpiresAt)}).` }
4034
+ };
4035
+ return {
4036
+ shouldContinue: false,
4037
+ reply: { text: "ā„¹ļø Idle timeout is currently disabled for this focused session." }
4038
+ };
4039
+ }
4040
+ if (typeof maxAgeExpiresAt === "number" && Number.isFinite(maxAgeExpiresAt) && maxAgeExpiresAt > Date.now()) return {
4041
+ shouldContinue: false,
4042
+ reply: { text: `ā„¹ļø Max age active (${formatThreadBindingDurationLabel(maxAgeMs)}, hard auto-unfocus at ${formatSessionExpiry(maxAgeExpiresAt)}).` }
4043
+ };
4044
+ return {
4045
+ shouldContinue: false,
4046
+ reply: { text: "ā„¹ļø Max age is currently disabled for this focused session." }
4047
+ };
4048
+ }
4049
+ const senderId = normalizeOptionalString(params.command.senderId) ?? "";
4050
+ const boundBy = resolveSessionBindingBoundBy(activeBinding);
4051
+ if (boundBy && boundBy !== "system" && senderId && senderId !== boundBy) return {
4052
+ shouldContinue: false,
4053
+ reply: { text: `āš ļø Only ${boundBy} can update session lifecycle settings for this conversation.` }
4054
+ };
4055
+ let durationMs;
4056
+ try {
4057
+ durationMs = parseSessionDurationMs(durationArgRaw);
4058
+ } catch {
4059
+ return {
4060
+ shouldContinue: false,
4061
+ reply: { text: resolveSessionCommandUsage() }
4062
+ };
4063
+ }
4064
+ const updatedBindings = action === SESSION_ACTION_IDLE ? setChannelConversationBindingIdleTimeoutBySessionKey({
4065
+ channelId: bindingContext.channel,
4066
+ targetSessionKey: activeBinding.targetSessionKey,
4067
+ accountId: bindingContext.accountId,
4068
+ idleTimeoutMs: durationMs
4069
+ }) : setChannelConversationBindingMaxAgeBySessionKey({
4070
+ channelId: bindingContext.channel,
4071
+ targetSessionKey: activeBinding.targetSessionKey,
4072
+ accountId: bindingContext.accountId,
4073
+ maxAgeMs: durationMs
4074
+ });
4075
+ if (updatedBindings.length === 0) return {
4076
+ shouldContinue: false,
4077
+ reply: { text: action === SESSION_ACTION_IDLE ? "āš ļø Failed to update idle timeout for the current binding." : "āš ļø Failed to update max age for the current binding." }
4078
+ };
4079
+ if (durationMs <= 0) return {
4080
+ shouldContinue: false,
4081
+ 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"}.` }
4082
+ };
4083
+ const nextExpiry = resolveUpdatedBindingExpiry({
4084
+ action,
4085
+ bindings: updatedBindings.map((binding) => toUpdatedLifecycleBinding(binding))
4086
+ });
4087
+ const expiryLabel = typeof nextExpiry === "number" && Number.isFinite(nextExpiry) ? formatSessionExpiry(nextExpiry) : "n/a";
4088
+ return {
4089
+ shouldContinue: false,
4090
+ 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}).` }
4091
+ };
4092
+ };
4093
+ const handleRestartCommand = async (params, allowTextCommands) => {
4094
+ if (!allowTextCommands) return null;
4095
+ if (params.command.commandBodyNormalized !== "/restart") return null;
4096
+ if (!params.command.isAuthorizedSender) {
4097
+ logVerbose(`Ignoring /restart from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
4098
+ return { shouldContinue: false };
4099
+ }
4100
+ const nonOwner = rejectNonOwnerCommand(params, "/restart");
4101
+ if (nonOwner) return nonOwner;
4102
+ if (!isRestartEnabled(params.cfg)) return {
4103
+ shouldContinue: false,
4104
+ reply: { text: "āš ļø /restart is disabled (commands.restart=false)." }
4105
+ };
4106
+ const hasSigusr1Listener = process.listenerCount("SIGUSR1") > 0;
4107
+ const sentinelPayload = buildRestartCommandSentinel(params);
4108
+ if (hasSigusr1Listener) {
4109
+ let sentinelPath = null;
4110
+ scheduleGatewaySigusr1Restart({
4111
+ reason: "/restart",
4112
+ emitHooks: sentinelPayload ? {
4113
+ beforeEmit: async () => {
4114
+ sentinelPath = await writeRestartSentinel(sentinelPayload);
4115
+ },
4116
+ afterEmitRejected: async () => {
4117
+ await removeRestartSentinelFile(sentinelPath);
4118
+ }
4119
+ } : void 0
4120
+ });
4121
+ return {
4122
+ shouldContinue: false,
4123
+ reply: { text: "āš™ļø Restarting Genesis in-process (SIGUSR1); back in a few seconds." }
4124
+ };
4125
+ }
4126
+ let sentinelPath = null;
4127
+ try {
4128
+ if (sentinelPayload) sentinelPath = await writeRestartSentinel(sentinelPayload);
4129
+ } catch (err) {
4130
+ logVerbose(`failed to write /restart sentinel: ${String(err)}`);
4131
+ return {
4132
+ shouldContinue: false,
4133
+ reply: { text: "āš ļø Restart failed: could not persist the post-restart acknowledgement." }
4134
+ };
4135
+ }
4136
+ const restartMethod = triggerGenesisRestart();
4137
+ if (!restartMethod.ok) {
4138
+ await removeRestartSentinelFile(sentinelPath);
4139
+ const detail = restartMethod.detail ? ` Details: ${restartMethod.detail}` : "";
4140
+ return {
4141
+ shouldContinue: false,
4142
+ reply: { text: `āš ļø Restart failed (${restartMethod.method}).${detail}` }
4143
+ };
4144
+ }
4145
+ return {
4146
+ shouldContinue: false,
4147
+ reply: { text: `āš™ļø Restarting Genesis via ${restartMethod.method}; give me a few seconds to come back online.` }
4148
+ };
4149
+ };
4150
+ //#endregion
4151
+ //#region src/auto-reply/reply/commands-subagents.ts
4152
+ let actionAgentsPromise = null;
4153
+ let actionFocusPromise = null;
4154
+ let actionHelpPromise = null;
4155
+ let actionInfoPromise = null;
4156
+ let actionKillPromise = null;
4157
+ let actionListPromise = null;
4158
+ let actionLogPromise = null;
4159
+ let actionSendPromise = null;
4160
+ let actionSpawnPromise = null;
4161
+ let actionUnfocusPromise = null;
4162
+ let controlRuntimePromise = null;
4163
+ function loadAgentsAction() {
4164
+ actionAgentsPromise ??= import("./action-agents-6PpsUM02.js");
4165
+ return actionAgentsPromise;
4166
+ }
4167
+ function loadFocusAction() {
4168
+ actionFocusPromise ??= import("./action-focus-B4kHRvRY.js");
4169
+ return actionFocusPromise;
4170
+ }
4171
+ function loadHelpAction() {
4172
+ actionHelpPromise ??= import("./action-help-C5lxx1KX.js");
4173
+ return actionHelpPromise;
4174
+ }
4175
+ function loadInfoAction() {
4176
+ actionInfoPromise ??= import("./action-info-oy2vw7kF.js");
4177
+ return actionInfoPromise;
4178
+ }
4179
+ function loadKillAction() {
4180
+ actionKillPromise ??= import("./action-kill-CD139kh2.js");
4181
+ return actionKillPromise;
4182
+ }
4183
+ function loadListAction() {
4184
+ actionListPromise ??= import("./action-list-DZ9teqOY.js");
4185
+ return actionListPromise;
4186
+ }
4187
+ function loadLogAction() {
4188
+ actionLogPromise ??= import("./action-log-gxlq_2Rp.js");
4189
+ return actionLogPromise;
4190
+ }
4191
+ function loadSendAction() {
4192
+ actionSendPromise ??= import("./action-send-BurQ0zyV.js");
4193
+ return actionSendPromise;
4194
+ }
4195
+ function loadSpawnAction() {
4196
+ actionSpawnPromise ??= import("./action-spawn-DxOHnNm7.js");
4197
+ return actionSpawnPromise;
4198
+ }
4199
+ function loadUnfocusAction() {
4200
+ actionUnfocusPromise ??= import("./action-unfocus-CugM3XlM.js");
4201
+ return actionUnfocusPromise;
4202
+ }
4203
+ function loadControlRuntime() {
4204
+ controlRuntimePromise ??= import("./commands-subagents-control.runtime-RvrJJSNg.js");
4205
+ return controlRuntimePromise;
4206
+ }
4207
+ const handleSubagentsCommand = async (params, allowTextCommands) => {
4208
+ if (!allowTextCommands) return null;
4209
+ const normalized = params.command.commandBodyNormalized;
4210
+ const handledPrefix = resolveHandledPrefix(normalized);
4211
+ if (!handledPrefix) return null;
4212
+ if (!params.command.isAuthorizedSender) {
4213
+ logVerbose(`Ignoring ${handledPrefix} from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
4214
+ return { shouldContinue: false };
4215
+ }
4216
+ const restTokens = normalized.slice(handledPrefix.length).trim().split(/\s+/).filter(Boolean);
4217
+ const action = resolveSubagentsAction({
4218
+ handledPrefix,
4219
+ restTokens
4220
+ });
4221
+ if (!action) return (await loadHelpAction()).handleSubagentsHelpAction();
4222
+ const requesterKey = action === "spawn" ? resolveRequesterSessionKey(params, { preferCommandTarget: true }) : resolveRequesterSessionKey(params);
4223
+ if (!requesterKey) return stopWithText("āš ļø Missing session key.");
4224
+ const ctx = {
4225
+ params,
4226
+ handledPrefix,
4227
+ requesterKey,
4228
+ runs: (await loadControlRuntime()).listControlledSubagentRuns(requesterKey),
4229
+ restTokens
4230
+ };
4231
+ switch (action) {
4232
+ case "help": return (await loadHelpAction()).handleSubagentsHelpAction();
4233
+ case "agents": return (await loadAgentsAction()).handleSubagentsAgentsAction(ctx);
4234
+ case "focus": return await (await loadFocusAction()).handleSubagentsFocusAction(ctx);
4235
+ case "unfocus": return await (await loadUnfocusAction()).handleSubagentsUnfocusAction(ctx);
4236
+ case "list": return (await loadListAction()).handleSubagentsListAction(ctx);
4237
+ case "kill": return await (await loadKillAction()).handleSubagentsKillAction(ctx);
4238
+ case "info": return (await loadInfoAction()).handleSubagentsInfoAction(ctx);
4239
+ case "log": return await (await loadLogAction()).handleSubagentsLogAction(ctx);
4240
+ case "send": return await (await loadSendAction()).handleSubagentsSendAction(ctx, false);
4241
+ case "steer": return await (await loadSendAction()).handleSubagentsSendAction(ctx, true);
4242
+ case "spawn": return await (await loadSpawnAction()).handleSubagentsSpawnAction(ctx);
4243
+ default: return (await loadHelpAction()).handleSubagentsHelpAction();
4244
+ }
4245
+ };
4246
+ //#endregion
4247
+ //#region src/auto-reply/reply/commands-tasks.ts
4248
+ const MAX_VISIBLE_TASKS = 5;
4249
+ const TASK_STATUS_ICONS = {
4250
+ queued: "🟔",
4251
+ running: "🟢",
4252
+ succeeded: "āœ…",
4253
+ failed: "šŸ”“",
4254
+ timed_out: "ā±ļø",
4255
+ cancelled: "āšŖļø",
4256
+ lost: "āš ļø"
4257
+ };
4258
+ const TASK_RUNTIME_LABELS = {
4259
+ subagent: "Subagent",
4260
+ acp: "ACP",
4261
+ cli: "CLI",
4262
+ cron: "Cron"
4263
+ };
4264
+ function formatTaskHeadline(snapshot) {
4265
+ if (snapshot.totalCount === 0) return "All clear - nothing linked to this session right now.";
4266
+ return `Current session: ${snapshot.activeCount} active Ā· ${snapshot.totalCount} total`;
4267
+ }
4268
+ function formatAgentFallbackLine(agentId) {
4269
+ const snapshot = buildTaskStatusSnapshot(listTasksForAgentIdForStatus(agentId));
4270
+ if (snapshot.totalCount === 0) return;
4271
+ return `Agent-local: ${snapshot.activeCount} active Ā· ${snapshot.totalCount} total`;
4272
+ }
4273
+ function formatTaskTiming(task) {
4274
+ if (task.status === "running") {
4275
+ const startedAt = task.startedAt ?? task.createdAt;
4276
+ return `elapsed ${formatDurationCompact(Date.now() - startedAt, { spaced: true }) ?? "0s"}`;
4277
+ }
4278
+ if (task.status === "queued") return `queued ${formatTimeAgo(Date.now() - task.createdAt)}`;
4279
+ const endedAt = task.endedAt ?? task.lastEventAt ?? task.createdAt;
4280
+ return `finished ${formatTimeAgo(Date.now() - endedAt)}`;
4281
+ }
4282
+ function formatTaskDetail(task) {
4283
+ return formatTaskStatusDetail(task);
4284
+ }
4285
+ function formatVisibleTask(task, index) {
4286
+ const title = formatTaskStatusTitle(task);
4287
+ const status = task.status.replaceAll("_", " ");
4288
+ const timing = formatTaskTiming(task);
4289
+ const detail = formatTaskDetail(task);
4290
+ const meta = [
4291
+ TASK_RUNTIME_LABELS[task.runtime],
4292
+ status,
4293
+ timing
4294
+ ].filter(Boolean).join(" Ā· ");
4295
+ const lines = [`${index + 1}. ${TASK_STATUS_ICONS[task.status]} ${title}`, ` ${meta}`];
4296
+ if (detail) lines.push(` ${detail}`);
4297
+ return lines.join("\n");
4298
+ }
4299
+ function buildTasksText(params) {
4300
+ const sessionSnapshot = buildTaskStatusSnapshot(listTasksForSessionKeyForStatus(params.sessionKey));
4301
+ const lines = ["šŸ“‹ Tasks", formatTaskHeadline(sessionSnapshot)];
4302
+ if (sessionSnapshot.totalCount > 0) {
4303
+ const visible = sessionSnapshot.visible.slice(0, MAX_VISIBLE_TASKS);
4304
+ lines.push("");
4305
+ for (const [index, task] of visible.entries()) {
4306
+ lines.push(formatVisibleTask(task, index));
4307
+ if (index < visible.length - 1) lines.push("");
4308
+ }
4309
+ const hiddenCount = sessionSnapshot.visible.length - visible.length;
4310
+ if (hiddenCount > 0) lines.push("", `+${hiddenCount} more recent task${hiddenCount === 1 ? "" : "s"}`);
4311
+ return lines.join("\n");
4312
+ }
4313
+ const agentFallback = formatAgentFallbackLine(params.agentId);
4314
+ if (agentFallback) lines.push(agentFallback);
4315
+ return lines.join("\n");
4316
+ }
4317
+ async function buildTasksReply(params) {
4318
+ const agentId = resolveSessionAgentId({
4319
+ sessionKey: params.sessionKey,
4320
+ config: params.cfg
4321
+ });
4322
+ return { text: buildTasksText({
4323
+ sessionKey: params.sessionKey,
4324
+ agentId
4325
+ }) };
4326
+ }
4327
+ const handleTasksCommand = async (params, allowTextCommands) => {
4328
+ if (!allowTextCommands) return null;
4329
+ const normalized = params.command.commandBodyNormalized;
4330
+ if (normalized !== "/tasks" && !normalized.startsWith("/tasks ")) return null;
4331
+ if (!params.command.isAuthorizedSender) {
4332
+ logVerbose(`Ignoring /tasks from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
4333
+ return { shouldContinue: false };
4334
+ }
4335
+ if (normalized !== "/tasks") return {
4336
+ shouldContinue: false,
4337
+ reply: { text: "Usage: /tasks" }
4338
+ };
4339
+ return {
4340
+ shouldContinue: false,
4341
+ reply: await buildTasksReply(params)
4342
+ };
4343
+ };
4344
+ //#endregion
4345
+ //#region src/auto-reply/reply/commands-tts.ts
4346
+ function parseTtsCommand(normalized) {
4347
+ if (normalized === "/tts") return {
4348
+ action: "status",
4349
+ args: ""
4350
+ };
4351
+ if (!normalized.startsWith("/tts ")) return null;
4352
+ const rest = normalized.slice(5).trim();
4353
+ if (!rest) return {
4354
+ action: "status",
4355
+ args: ""
4356
+ };
4357
+ const [action, ...tail] = rest.split(/\s+/);
4358
+ return {
4359
+ action: normalizeOptionalLowercaseString(action) ?? "",
4360
+ args: normalizeOptionalString(tail.join(" ")) ?? ""
4361
+ };
4362
+ }
4363
+ function formatAttemptDetails(attempts) {
4364
+ if (!attempts || attempts.length === 0) return;
4365
+ return attempts.map((attempt) => {
4366
+ const reason = attempt.reasonCode === "success" ? "ok" : attempt.reasonCode;
4367
+ const latency = Number.isFinite(attempt.latencyMs) ? ` ${attempt.latencyMs}ms` : "";
4368
+ return `${attempt.provider}:${attempt.outcome}(${reason})${latency}`;
4369
+ }).join(", ");
4370
+ }
4371
+ function ttsUsage() {
4372
+ 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!" };
4373
+ }
4374
+ const handleTtsCommands = async (params, allowTextCommands) => {
4375
+ if (!allowTextCommands) return null;
4376
+ const parsed = parseTtsCommand(params.command.commandBodyNormalized);
4377
+ if (!parsed) return null;
4378
+ if (!params.command.isAuthorizedSender) {
4379
+ logVerbose(`Ignoring TTS command from unauthorized sender: ${params.command.senderId || "<unknown>"}`);
4380
+ return { shouldContinue: false };
4381
+ }
4382
+ const config = resolveTtsConfig(params.cfg);
4383
+ const prefsPath = resolveTtsPrefsPath(config);
4384
+ const action = parsed.action;
4385
+ const args = parsed.args;
4386
+ if (action === "help") return {
4387
+ shouldContinue: false,
4388
+ reply: ttsUsage()
4389
+ };
4390
+ if (action === "on") {
4391
+ setTtsEnabled(prefsPath, true);
4392
+ return {
4393
+ shouldContinue: false,
4394
+ reply: { text: "šŸ”Š TTS enabled." }
4395
+ };
4396
+ }
4397
+ if (action === "off") {
4398
+ setTtsEnabled(prefsPath, false);
4399
+ return {
4400
+ shouldContinue: false,
4401
+ reply: { text: "šŸ”‡ TTS disabled." }
4402
+ };
4403
+ }
4404
+ if (action === "audio") {
4405
+ if (!args.trim()) return {
4406
+ shouldContinue: false,
4407
+ reply: { text: "šŸŽ¤ Generate audio from text.\n\nUsage: /tts audio <text>\nExample: /tts audio Hello, this is a test!" }
4408
+ };
4409
+ const start = Date.now();
4410
+ const result = await textToSpeech({
4411
+ text: args,
4412
+ cfg: params.cfg,
4413
+ channel: params.command.channel,
4414
+ prefsPath
4415
+ });
4416
+ if (result.success && result.audioPath) {
4417
+ setLastTtsAttempt({
4418
+ timestamp: Date.now(),
4419
+ success: true,
4420
+ textLength: args.length,
4421
+ summarized: false,
4422
+ provider: result.provider,
4423
+ fallbackFrom: result.fallbackFrom,
4424
+ attemptedProviders: result.attemptedProviders,
4425
+ attempts: result.attempts,
4426
+ latencyMs: result.latencyMs
4427
+ });
4428
+ return {
4429
+ shouldContinue: false,
4430
+ reply: {
4431
+ mediaUrl: result.audioPath,
4432
+ audioAsVoice: result.voiceCompatible === true,
4433
+ trustedLocalMedia: true,
4434
+ spokenText: args
4435
+ }
4436
+ };
4437
+ }
4438
+ setLastTtsAttempt({
4439
+ timestamp: Date.now(),
4440
+ success: false,
4441
+ textLength: args.length,
4442
+ summarized: false,
4443
+ attemptedProviders: result.attemptedProviders,
4444
+ attempts: result.attempts,
4445
+ error: result.error,
4446
+ latencyMs: Date.now() - start
4447
+ });
4448
+ return {
4449
+ shouldContinue: false,
4450
+ reply: { text: `āŒ Error generating audio: ${result.error ?? "unknown error"}` }
4451
+ };
4452
+ }
4453
+ if (action === "provider") {
4454
+ const currentProvider = getTtsProvider(config, prefsPath);
4455
+ if (!args.trim()) {
4456
+ const providers = listSpeechProviders(params.cfg);
4457
+ return {
4458
+ shouldContinue: false,
4459
+ reply: { text: `šŸŽ™ļø TTS provider\nPrimary: ${currentProvider}\n` + providers.map((provider) => `${provider.label}: ${provider.isConfigured({
4460
+ cfg: params.cfg,
4461
+ providerConfig: getResolvedSpeechProviderConfig(config, provider.id, params.cfg),
4462
+ timeoutMs: config.timeoutMs
4463
+ }) ? "āœ…" : "āŒ"}`).join("\n") + `\nUsage: /tts provider <id>` }
4464
+ };
4465
+ }
4466
+ const requested = normalizeOptionalLowercaseString(args) ?? "";
4467
+ const resolvedProvider = getSpeechProvider(requested, params.cfg);
4468
+ if (!resolvedProvider) return {
4469
+ shouldContinue: false,
4470
+ reply: ttsUsage()
4471
+ };
4472
+ const nextProvider = canonicalizeSpeechProviderId(requested, params.cfg) ?? resolvedProvider.id;
4473
+ setTtsProvider(prefsPath, nextProvider);
4474
+ return {
4475
+ shouldContinue: false,
4476
+ reply: { text: `āœ… TTS provider set to ${nextProvider}.` }
4477
+ };
4478
+ }
4479
+ if (action === "limit") {
4480
+ if (!args.trim()) return {
4481
+ shouldContinue: false,
4482
+ 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` }
4483
+ };
4484
+ const next = Number.parseInt(args.trim(), 10);
4485
+ if (!Number.isFinite(next) || next < 100 || next > 4096) return {
4486
+ shouldContinue: false,
4487
+ reply: { text: "āŒ Limit must be between 100 and 4096 characters." }
4488
+ };
4489
+ setTtsMaxLength(prefsPath, next);
4490
+ return {
4491
+ shouldContinue: false,
4492
+ reply: { text: `āœ… TTS limit set to ${next} characters.` }
4493
+ };
4494
+ }
4495
+ if (action === "summary") {
4496
+ if (!args.trim()) {
4497
+ const enabled = isSummarizationEnabled(prefsPath);
4498
+ const maxLen = getTtsMaxLength(prefsPath);
4499
+ return {
4500
+ shouldContinue: false,
4501
+ 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` }
4502
+ };
4503
+ }
4504
+ const requested = normalizeOptionalLowercaseString(args) ?? "";
4505
+ if (requested !== "on" && requested !== "off") return {
4506
+ shouldContinue: false,
4507
+ reply: ttsUsage()
4508
+ };
4509
+ setSummarizationEnabled(prefsPath, requested === "on");
4510
+ return {
4511
+ shouldContinue: false,
4512
+ reply: { text: requested === "on" ? "āœ… TTS auto-summary enabled." : "āŒ TTS auto-summary disabled." }
4513
+ };
4514
+ }
4515
+ if (action === "status") {
4516
+ const enabled = isTtsEnabled(config, prefsPath);
4517
+ const provider = getTtsProvider(config, prefsPath);
4518
+ const hasKey = isTtsProviderConfigured(config, provider, params.cfg);
4519
+ const maxLength = getTtsMaxLength(prefsPath);
4520
+ const summarize = isSummarizationEnabled(prefsPath);
4521
+ const last = getLastTtsAttempt();
4522
+ const lines = [
4523
+ "šŸ“Š TTS status",
4524
+ `State: ${enabled ? "āœ… enabled" : "āŒ disabled"}`,
4525
+ `Provider: ${provider} (${hasKey ? "āœ… configured" : "āŒ not configured"})`,
4526
+ `Text limit: ${maxLength} chars`,
4527
+ `Auto-summary: ${summarize ? "on" : "off"}`
4528
+ ];
4529
+ if (last) {
4530
+ const timeAgo = Math.round((Date.now() - last.timestamp) / 1e3);
4531
+ lines.push("");
4532
+ lines.push(`Last attempt (${timeAgo}s ago): ${last.success ? "āœ…" : "āŒ"}`);
4533
+ lines.push(`Text: ${last.textLength} chars${last.summarized ? " (summarized)" : ""}`);
4534
+ if (last.success) {
4535
+ lines.push(`Provider: ${last.provider ?? "unknown"}`);
4536
+ if (last.fallbackFrom && last.provider && last.fallbackFrom !== last.provider) lines.push(`Fallback: ${last.fallbackFrom} -> ${last.provider}`);
4537
+ if (last.attemptedProviders && last.attemptedProviders.length > 1) lines.push(`Attempts: ${last.attemptedProviders.join(" -> ")}`);
4538
+ const details = formatAttemptDetails(last.attempts);
4539
+ if (details) lines.push(`Attempt details: ${details}`);
4540
+ lines.push(`Latency: ${last.latencyMs ?? 0}ms`);
4541
+ } else if (last.error) {
4542
+ lines.push(`Error: ${last.error}`);
4543
+ if (last.attemptedProviders && last.attemptedProviders.length > 0) lines.push(`Attempts: ${last.attemptedProviders.join(" -> ")}`);
4544
+ const details = formatAttemptDetails(last.attempts);
4545
+ if (details) lines.push(`Attempt details: ${details}`);
4546
+ }
4547
+ }
4548
+ return {
4549
+ shouldContinue: false,
4550
+ reply: { text: lines.join("\n") }
4551
+ };
4552
+ }
4553
+ return {
4554
+ shouldContinue: false,
4555
+ reply: ttsUsage()
4556
+ };
4557
+ };
4558
+ //#endregion
4559
+ //#region src/auto-reply/reply/commands-handlers.runtime.ts
4560
+ function loadCommandHandlers() {
4561
+ return [
4562
+ handlePluginCommand,
4563
+ handleBtwCommand,
4564
+ handleBashCommand,
4565
+ handleActivationCommand,
4566
+ handleSendPolicyCommand,
4567
+ handleFastCommand,
4568
+ handleUsageCommand,
4569
+ handleSessionCommand,
4570
+ handleRestartCommand,
4571
+ handleTtsCommands,
4572
+ handleHelpCommand,
4573
+ handleCommandsListCommand,
4574
+ handleToolsCommand,
4575
+ handleStatusCommand,
4576
+ handleTasksCommand,
4577
+ handleAllowlistCommand,
4578
+ handleApproveCommand,
4579
+ handleContextCommand,
4580
+ handleExportSessionCommand,
4581
+ handleExportTrajectoryCommand,
4582
+ handleWhoamiCommand,
4583
+ handleSubagentsCommand,
4584
+ handleAcpCommand,
4585
+ handleMcpCommand,
4586
+ handlePluginsCommand,
4587
+ handleConfigCommand,
4588
+ handleDebugCommand,
4589
+ handleModelsCommand,
4590
+ handleStopCommand,
4591
+ handleCompactCommand,
4592
+ handleAbortTrigger
4593
+ ];
4594
+ }
4595
+ //#endregion
4596
+ export { loadCommandHandlers };