@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
@@ -1,4573 +0,0 @@
1
- import { i as formatErrorMessage } from "./errors-Jbvi20TW.js";
2
- import { a as normalizeLowercaseStringOrEmpty, c as normalizeOptionalString, s as normalizeOptionalLowercaseString } from "./string-coerce-C1IzJjqi.js";
3
- import { h as loggingState } from "./logger-QwLssHIf.js";
4
- import { n as defaultRuntime } from "./runtime-CQ7eH0le.js";
5
- import { i as visibleWidth, r as stripAnsi$1 } from "./ansi-BZHMLcUk.js";
6
- import { u as setConsoleSubsystemFilter } from "./subsystem-DTMy5YmO.js";
7
- import { t as formatDocsLink } from "./links-DmsJCU7L.js";
8
- import { r as theme$1 } from "./theme-BrRleVfL.js";
9
- import { n as VERSION } from "./version-BoqlEm3e.js";
10
- import { n as assertExplicitGatewayAuthModeWhenBothConfigured } from "./auth-mode-policy-BM9E_-zc.js";
11
- import { a as isLoopbackHost } from "./net-AycWGi8-.js";
12
- import { a as loadConfig } from "./io-CRPT2IUI.js";
13
- import { o as parseAgentSessionKey } from "./session-key-utils-BT0y7mVK.js";
14
- import { c as normalizeAgentId, l as normalizeMainKey, r as buildAgentMainSessionKey } from "./session-key-EpIbK3Oz.js";
15
- import { r as DEFAULT_PROVIDER } from "./defaults-DM8yIn8C.js";
16
- import { a as resolveAgentIdByWorkspacePath, p as resolveSessionAgentId, x as resolveDefaultAgentId } from "./agent-scope-CDjZLqNk.js";
17
- import "./config-DcheqK7J.js";
18
- import { n as GatewayClientRequestError, t as GatewayClient } from "./client-D1dJTyU7.js";
19
- import { g as GATEWAY_CLIENT_NAMES, h as GATEWAY_CLIENT_MODES, p as GATEWAY_CLIENT_CAPS } from "./message-channel-D2Y7UhTM.js";
20
- import { r as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-core-CtbksRwN.js";
21
- import { g as resolveResponseUsageMode, m as normalizeUsageDisplay, r as listThinkingLevelLabels, t as formatThinkingLevels } from "./thinking-B2FO5LMN.js";
22
- import { p as resolveThinkingDefault, t as buildAllowedModelSet } from "./model-selection-CKrtE2-6.js";
23
- import { t as loadCombinedSessionStoreForGateway } from "./combined-store-gateway-HyzDURpi.js";
24
- import { o as updateSessionStore } from "./store-Cxyeks39.js";
25
- import "./sessions-BGtpdShC.js";
26
- import { l as onAgentEvent } from "./agent-events-DpcKIBpp.js";
27
- import { r as formatTokenCount } from "./usage-format-DV4f3qrf.js";
28
- import { c as stripEnvelopeFromMessages, i as readSessionMessages, n as capArrayByJsonBytes } from "./session-utils.fs-DK1dJtSj.js";
29
- import { r as extractAssistantVisibleText } from "./chat-message-content-BMWW7Uy3.js";
30
- import { i as stripInlineDirectiveTagsForDisplay } from "./directive-tags-DUaKI8c-.js";
31
- import { r as stripLeadingInboundMetadata } from "./strip-inbound-meta-BAmHhTY1.js";
32
- import { a as loadSessionEntry, d as resolveGatewaySessionStoreTarget, n as listAgentsForGateway, o as migrateAndPruneGatewaySessionStoreKey, p as resolveSessionModelRef, r as listSessionsFromStore } from "./session-utils-BRO58_d4.js";
33
- import { a as isSilentReplyText, n as SILENT_REPLY_TOKEN } from "./tokens-oGSgdkSq.js";
34
- import { v as setEmbeddedMode } from "./genesis-tools-DkQyKJJH.js";
35
- import "./pi-embedded-helpers-CdvDVhim.js";
36
- import { D as formatRawAssistantErrorForUi, m as isAuthErrorMessage } from "./sanitize-user-facing-text-BMntd_9L.js";
37
- import { r as resolveToolDisplay, t as formatToolDetail } from "./tool-display-Bi6Q9vXz.js";
38
- import { l as resolveExplicitGatewayAuth, n as buildGatewayConnectionDetails, s as ensureExplicitGatewayAuth } from "./call-DMoCOQgN.js";
39
- import { t as parseTimeoutMs } from "./parse-timeout-CHQvQw9J.js";
40
- import { r as resolveSessionInfoModelSelection } from "./model-selection-display-BInPDh4b.js";
41
- import { n as listChatCommands, r as listChatCommandsForConfig } from "./commands-registry-list-BjEQSlzn.js";
42
- import "./commands-registry-aHwimQdh.js";
43
- import { n as formatTimeAgo, t as formatRelativeTimestamp } from "./format-relative-DBI0ON8M.js";
44
- import { t as normalizeGroupActivation } from "./group-activation-DBUyCcKk.js";
45
- import { r as agentCommandFromIngress } from "./agent-command-DpCldQUr.js";
46
- import { t as createDefaultDeps } from "./deps-Cc7P1Am8.js";
47
- import { _ as loadGatewayModelCatalog } from "./http-utils-CSMhLOmU.js";
48
- import { T as augmentChatHistoryWithCliSessionImports, a as enforceChatHistoryFinalBudget, c as sanitizeChatHistoryMessages, o as replaceOversizedChatHistoryMessages, r as augmentChatHistoryWithCanvasBlocks, s as resolveEffectiveChatHistoryMaxChars, t as CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES, w as getMaxChatHistoryMessagesBytes } from "./chat-CjH9IZPG.js";
49
- import { n as timestampOptsFromConfig, t as injectTimestamp } from "./agent-timestamp-CZWew-lY.js";
50
- import { a as performGatewaySessionReset } from "./session-reset-service-0D6xi-ak.js";
51
- import { t as applySessionsPatchToStore } from "./sessions-patch-DIqqzD_r.js";
52
- import { t as resolveGatewayInteractiveSurfaceAuth } from "./auth-surface-resolution-BtcYJDJ9.js";
53
- import { n as TUI_SETUP_AUTH_SOURCE_ENV, t as TUI_SETUP_AUTH_SOURCE_CONFIG } from "./setup-launch-env-DG2dGYnk.js";
54
- import { fileURLToPath } from "node:url";
55
- import { existsSync } from "node:fs";
56
- import path from "node:path";
57
- import { execFileSync, spawn } from "node:child_process";
58
- import chalk from "chalk";
59
- import { randomUUID } from "node:crypto";
60
- import { Box, CombinedAutocompleteProvider, Container, Editor, Input, Key, Loader, Markdown, ProcessTerminal, SelectList, SettingsList, Spacer, TUI, Text, isKeyRelease, matchesKey, truncateToWidth } from "@mariozechner/pi-tui";
61
- //#region src/tui/commands.ts
62
- const VERBOSE_LEVELS = ["on", "off"];
63
- const TRACE_LEVELS = ["on", "off"];
64
- const FAST_LEVELS = [
65
- "status",
66
- "on",
67
- "off"
68
- ];
69
- const REASONING_LEVELS = ["on", "off"];
70
- const ELEVATED_LEVELS = [
71
- "on",
72
- "off",
73
- "ask",
74
- "full"
75
- ];
76
- const ACTIVATION_LEVELS = ["mention", "always"];
77
- const USAGE_FOOTER_LEVELS = [
78
- "off",
79
- "tokens",
80
- "full"
81
- ];
82
- const COMMAND_ALIASES = {
83
- elev: "elevated",
84
- gwstatus: "gateway-status"
85
- };
86
- function createLevelCompletion(levels) {
87
- return (prefix) => levels.filter((value) => value.startsWith(normalizeLowercaseStringOrEmpty(prefix))).map((value) => ({
88
- value,
89
- label: value
90
- }));
91
- }
92
- function parseCommand(input) {
93
- const trimmed = input.replace(/^\//, "").trim();
94
- if (!trimmed) return {
95
- name: "",
96
- args: ""
97
- };
98
- const [name, ...rest] = trimmed.split(/\s+/);
99
- const normalized = normalizeLowercaseStringOrEmpty(name);
100
- return {
101
- name: COMMAND_ALIASES[normalized] ?? normalized,
102
- args: rest.join(" ").trim()
103
- };
104
- }
105
- function getSlashCommands(options = {}) {
106
- const thinkLevels = listThinkingLevelLabels(options.provider, options.model);
107
- const verboseCompletions = createLevelCompletion(VERBOSE_LEVELS);
108
- const traceCompletions = createLevelCompletion(TRACE_LEVELS);
109
- const fastCompletions = createLevelCompletion(FAST_LEVELS);
110
- const reasoningCompletions = createLevelCompletion(REASONING_LEVELS);
111
- const usageCompletions = createLevelCompletion(USAGE_FOOTER_LEVELS);
112
- const elevatedCompletions = createLevelCompletion(ELEVATED_LEVELS);
113
- const activationCompletions = createLevelCompletion(ACTIVATION_LEVELS);
114
- const commands = [
115
- {
116
- name: "help",
117
- description: "Show slash command help"
118
- },
119
- {
120
- name: "gateway-status",
121
- description: "Show gateway status summary"
122
- },
123
- {
124
- name: "gwstatus",
125
- description: "Alias for /gateway-status"
126
- },
127
- ...options.local ? [{
128
- name: "auth",
129
- description: "Run provider auth/login flow"
130
- }] : [],
131
- {
132
- name: "agent",
133
- description: "Switch agent (or open picker)"
134
- },
135
- {
136
- name: "agents",
137
- description: "Open agent picker"
138
- },
139
- {
140
- name: "session",
141
- description: "Switch session (or open picker)"
142
- },
143
- {
144
- name: "sessions",
145
- description: "Open session picker"
146
- },
147
- {
148
- name: "model",
149
- description: "Set model (or open picker)"
150
- },
151
- {
152
- name: "models",
153
- description: "Open model picker"
154
- },
155
- {
156
- name: "think",
157
- description: "Set thinking level",
158
- getArgumentCompletions: (prefix) => thinkLevels.filter((v) => v.startsWith(normalizeLowercaseStringOrEmpty(prefix))).map((value) => ({
159
- value,
160
- label: value
161
- }))
162
- },
163
- {
164
- name: "fast",
165
- description: "Set fast mode on/off",
166
- getArgumentCompletions: fastCompletions
167
- },
168
- {
169
- name: "verbose",
170
- description: "Set verbose on/off",
171
- getArgumentCompletions: verboseCompletions
172
- },
173
- {
174
- name: "trace",
175
- description: "Set trace on/off",
176
- getArgumentCompletions: traceCompletions
177
- },
178
- {
179
- name: "reasoning",
180
- description: "Set reasoning on/off",
181
- getArgumentCompletions: reasoningCompletions
182
- },
183
- {
184
- name: "usage",
185
- description: "Toggle per-response usage line",
186
- getArgumentCompletions: usageCompletions
187
- },
188
- {
189
- name: "elevated",
190
- description: "Set elevated on/off/ask/full",
191
- getArgumentCompletions: elevatedCompletions
192
- },
193
- {
194
- name: "elev",
195
- description: "Alias for /elevated",
196
- getArgumentCompletions: elevatedCompletions
197
- },
198
- {
199
- name: "activation",
200
- description: "Set group activation",
201
- getArgumentCompletions: activationCompletions
202
- },
203
- {
204
- name: "abort",
205
- description: "Abort active run"
206
- },
207
- {
208
- name: "new",
209
- description: "Reset the session"
210
- },
211
- {
212
- name: "reset",
213
- description: "Reset the session"
214
- },
215
- {
216
- name: "settings",
217
- description: "Open settings"
218
- },
219
- {
220
- name: "exit",
221
- description: "Exit the TUI"
222
- },
223
- {
224
- name: "quit",
225
- description: "Exit the TUI"
226
- }
227
- ];
228
- const seen = new Set(commands.map((command) => command.name));
229
- const gatewayCommands = options.cfg ? listChatCommandsForConfig(options.cfg) : listChatCommands();
230
- for (const command of gatewayCommands) {
231
- const aliases = command.textAliases.length > 0 ? command.textAliases : [`/${command.key}`];
232
- for (const alias of aliases) {
233
- const name = alias.replace(/^\//, "").trim();
234
- if (!name || seen.has(name)) continue;
235
- seen.add(name);
236
- commands.push({
237
- name,
238
- description: command.description
239
- });
240
- }
241
- }
242
- return commands;
243
- }
244
- function helpText(options = {}) {
245
- const thinkLevels = formatThinkingLevels(options.provider, options.model, "|");
246
- return [
247
- "Slash commands:",
248
- "/help",
249
- "/commands",
250
- "/status",
251
- "/gateway-status",
252
- "/gwstatus",
253
- ...options.local ? ["/auth [provider]"] : [],
254
- "/agent <id> (or /agents)",
255
- "/session <key> (or /sessions)",
256
- "/model <provider/model> (or /models)",
257
- `/think <${thinkLevels}>`,
258
- "/fast <status|on|off>",
259
- "/verbose <on|off>",
260
- "/trace <on|off>",
261
- "/reasoning <on|off>",
262
- "/usage <off|tokens|full>",
263
- "/elevated <on|off|ask|full>",
264
- "/elev <on|off|ask|full>",
265
- "/activation <mention|always>",
266
- "/new or /reset",
267
- "/abort",
268
- "/settings",
269
- "/exit"
270
- ].join("\n");
271
- }
272
- //#endregion
273
- //#region src/tui/theme/theme.ts
274
- const DARK_TEXT = "#E8E3D5";
275
- const LIGHT_TEXT = "#1E1E1E";
276
- const XTERM_LEVELS = [
277
- 0,
278
- 95,
279
- 135,
280
- 175,
281
- 215,
282
- 255
283
- ];
284
- function channelToSrgb(value) {
285
- const normalized = value / 255;
286
- return normalized <= .03928 ? normalized / 12.92 : ((normalized + .055) / 1.055) ** 2.4;
287
- }
288
- function relativeLuminanceRgb(r, g, b) {
289
- const red = channelToSrgb(r);
290
- const green = channelToSrgb(g);
291
- const blue = channelToSrgb(b);
292
- return .2126 * red + .7152 * green + .0722 * blue;
293
- }
294
- function relativeLuminanceHex(hex) {
295
- return relativeLuminanceRgb(Number.parseInt(hex.slice(1, 3), 16), Number.parseInt(hex.slice(3, 5), 16), Number.parseInt(hex.slice(5, 7), 16));
296
- }
297
- function contrastRatio(background, foregroundHex) {
298
- const foreground = relativeLuminanceHex(foregroundHex);
299
- const lighter = Math.max(background, foreground);
300
- const darker = Math.min(background, foreground);
301
- return (lighter + .05) / (darker + .05);
302
- }
303
- function pickHigherContrastText(r, g, b) {
304
- const background = relativeLuminanceRgb(r, g, b);
305
- return contrastRatio(background, LIGHT_TEXT) >= contrastRatio(background, DARK_TEXT);
306
- }
307
- function isLightBackground() {
308
- const explicit = normalizeOptionalLowercaseString(process.env.GENESIS_THEME);
309
- if (explicit === "light") return true;
310
- if (explicit === "dark") return false;
311
- const colorfgbg = process.env.COLORFGBG;
312
- if (colorfgbg && colorfgbg.length <= 64) {
313
- const sep = colorfgbg.lastIndexOf(";");
314
- const bg = Number.parseInt(sep >= 0 ? colorfgbg.slice(sep + 1) : colorfgbg, 10);
315
- if (bg >= 0 && bg <= 255) {
316
- if (bg <= 15) return bg === 7 || bg === 15;
317
- if (bg >= 232) return bg >= 244;
318
- const cubeIndex = bg - 16;
319
- const bVal = XTERM_LEVELS[cubeIndex % 6];
320
- const gVal = XTERM_LEVELS[Math.floor(cubeIndex / 6) % 6];
321
- const rVal = XTERM_LEVELS[Math.floor(cubeIndex / 36)];
322
- return pickHigherContrastText(rVal, gVal, bVal);
323
- }
324
- }
325
- return false;
326
- }
327
- const palette = isLightBackground() ? {
328
- text: "#1E1E1E",
329
- dim: "#5B6472",
330
- accent: "#B45309",
331
- accentSoft: "#C2410C",
332
- border: "#5B6472",
333
- userBg: "#F3F0E8",
334
- userText: "#1E1E1E",
335
- systemText: "#4B5563",
336
- toolPendingBg: "#EFF6FF",
337
- toolSuccessBg: "#ECFDF5",
338
- toolErrorBg: "#FEF2F2",
339
- toolTitle: "#B45309",
340
- toolOutput: "#374151",
341
- quote: "#1D4ED8",
342
- quoteBorder: "#2563EB",
343
- code: "#92400E",
344
- codeBlock: "#F9FAFB",
345
- codeBorder: "#92400E",
346
- link: "#047857",
347
- error: "#DC2626",
348
- success: "#047857"
349
- } : {
350
- text: "#E8E3D5",
351
- dim: "#7B7F87",
352
- accent: "#F6C453",
353
- accentSoft: "#F2A65A",
354
- border: "#3C414B",
355
- userBg: "#2B2F36",
356
- userText: "#F3EEE0",
357
- systemText: "#9BA3B2",
358
- toolPendingBg: "#1F2A2F",
359
- toolSuccessBg: "#1E2D23",
360
- toolErrorBg: "#2F1F1F",
361
- toolTitle: "#F6C453",
362
- toolOutput: "#E1DACB",
363
- quote: "#8CC8FF",
364
- quoteBorder: "#3B4D6B",
365
- code: "#F0C987",
366
- codeBlock: "#1E232A",
367
- codeBorder: "#343A45",
368
- link: "#7DD3A5",
369
- error: "#F97066",
370
- success: "#7DD3A5"
371
- };
372
- const fg = (hex) => (text) => chalk.hex(hex)(text);
373
- const bg = (hex) => (text) => chalk.bgHex(hex)(text);
374
- /**
375
- * Render code blocks with the theme code color without pulling a parser into the base TUI path.
376
- * Returns an array of lines with ANSI escape codes.
377
- */
378
- function highlightCode(code) {
379
- return code.split("\n").map((line) => fg(palette.code)(line));
380
- }
381
- const theme = {
382
- fg: fg(palette.text),
383
- assistantText: (text) => text,
384
- dim: fg(palette.dim),
385
- accent: fg(palette.accent),
386
- accentSoft: fg(palette.accentSoft),
387
- success: fg(palette.success),
388
- error: fg(palette.error),
389
- header: (text) => chalk.bold(fg(palette.accent)(text)),
390
- system: fg(palette.systemText),
391
- userBg: bg(palette.userBg),
392
- userText: fg(palette.userText),
393
- toolTitle: fg(palette.toolTitle),
394
- toolOutput: fg(palette.toolOutput),
395
- toolPendingBg: bg(palette.toolPendingBg),
396
- toolSuccessBg: bg(palette.toolSuccessBg),
397
- toolErrorBg: bg(palette.toolErrorBg),
398
- border: fg(palette.border),
399
- bold: (text) => chalk.bold(text),
400
- italic: (text) => chalk.italic(text)
401
- };
402
- const markdownTheme = {
403
- heading: (text) => chalk.bold(fg(palette.accent)(text)),
404
- link: (text) => fg(palette.link)(text),
405
- linkUrl: (text) => chalk.dim(text),
406
- code: (text) => fg(palette.code)(text),
407
- codeBlock: (text) => fg(palette.code)(text),
408
- codeBlockBorder: (text) => fg(palette.codeBorder)(text),
409
- quote: (text) => fg(palette.quote)(text),
410
- quoteBorder: (text) => fg(palette.quoteBorder)(text),
411
- hr: (text) => fg(palette.border)(text),
412
- listBullet: (text) => fg(palette.accentSoft)(text),
413
- bold: (text) => chalk.bold(text),
414
- italic: (text) => chalk.italic(text),
415
- strikethrough: (text) => chalk.strikethrough(text),
416
- underline: (text) => chalk.underline(text),
417
- highlightCode
418
- };
419
- const baseSelectListTheme = {
420
- selectedPrefix: (text) => fg(palette.accent)(text),
421
- selectedText: (text) => chalk.bold(fg(palette.accent)(text)),
422
- description: (text) => fg(palette.dim)(text),
423
- scrollInfo: (text) => fg(palette.dim)(text),
424
- noMatch: (text) => fg(palette.dim)(text)
425
- };
426
- const selectListTheme = baseSelectListTheme;
427
- const filterableSelectListTheme = {
428
- ...baseSelectListTheme,
429
- filterLabel: (text) => fg(palette.dim)(text)
430
- };
431
- const settingsListTheme = {
432
- label: (text, selected) => selected ? chalk.bold(fg(palette.accent)(text)) : fg(palette.text)(text),
433
- value: (text, selected) => selected ? fg(palette.accentSoft)(text) : fg(palette.dim)(text),
434
- description: (text) => fg(palette.systemText)(text),
435
- cursor: fg(palette.accent)("→ "),
436
- hint: (text) => fg(palette.dim)(text)
437
- };
438
- const editorTheme = {
439
- borderColor: (text) => fg(palette.border)(text),
440
- selectList: selectListTheme
441
- };
442
- const searchableSelectListTheme = {
443
- ...baseSelectListTheme,
444
- searchPrompt: (text) => fg(palette.accentSoft)(text),
445
- searchInput: (text) => fg(palette.text)(text),
446
- matchHighlight: (text) => chalk.bold(fg(palette.accent)(text))
447
- };
448
- //#endregion
449
- //#region src/tui/osc8-hyperlinks.ts
450
- const SGR_PATTERN = "\\x1b\\[[0-9;]*m";
451
- const OSC8_PATTERN = "\\x1b\\]8;;.*?(?:\\x07|\\x1b\\\\)";
452
- const ANSI_RE = new RegExp(`${SGR_PATTERN}|${OSC8_PATTERN}`, "g");
453
- const SGR_START_RE = new RegExp(`^${SGR_PATTERN}`);
454
- const OSC8_START_RE = new RegExp(`^${OSC8_PATTERN}`);
455
- /**
456
- * Extract all unique URLs from raw markdown text.
457
- * Finds both bare URLs and markdown link hrefs [text](url).
458
- */
459
- function extractUrls(markdown) {
460
- const urls = /* @__PURE__ */ new Set();
461
- const mdLinkRe = /\[(?:[^\]]*)\]\(\s*<?(https?:\/\/[^)\s>]+)>?(?:\s+["'][^"']*["'])?\s*\)/g;
462
- let m;
463
- while ((m = mdLinkRe.exec(markdown)) !== null) urls.add(m[1]);
464
- const stripped = markdown.replace(/\[(?:[^\]]*)\]\(\s*<?https?:\/\/[^)\s>]+>?(?:\s+["'][^"']*["'])?\s*\)/g, "");
465
- const bareRe = /https?:\/\/[^\s)\]>]+/g;
466
- while ((m = bareRe.exec(stripped)) !== null) urls.add(m[0]);
467
- return [...urls];
468
- }
469
- /** Strip ANSI SGR and OSC 8 sequences to get visible text. */
470
- function stripAnsi(input) {
471
- return input.replace(ANSI_RE, "");
472
- }
473
- /**
474
- * Find URL ranges in a line's visible text, handling cross-line URL splits.
475
- */
476
- function findUrlRanges(visibleText, knownUrls, pending) {
477
- const ranges = [];
478
- let newPending = null;
479
- let searchFrom = 0;
480
- if (pending) {
481
- const remaining = pending.url.slice(pending.consumed);
482
- const trimmed = visibleText.trimStart();
483
- const leadingSpaces = visibleText.length - trimmed.length;
484
- let matchLen = 0;
485
- for (let j = 0; j < remaining.length && j < trimmed.length; j++) if (remaining[j] === trimmed[j]) matchLen++;
486
- else break;
487
- if (matchLen > 0) {
488
- ranges.push({
489
- start: leadingSpaces,
490
- end: leadingSpaces + matchLen,
491
- url: pending.url
492
- });
493
- searchFrom = leadingSpaces + matchLen;
494
- if (pending.consumed + matchLen < pending.url.length) newPending = {
495
- url: pending.url,
496
- consumed: pending.consumed + matchLen
497
- };
498
- }
499
- }
500
- const urlRe = /https?:\/\/[^\s)\]>]+/g;
501
- urlRe.lastIndex = searchFrom;
502
- let match;
503
- while ((match = urlRe.exec(visibleText)) !== null) {
504
- const fragment = match[0];
505
- const start = match.index;
506
- let resolvedUrl = fragment;
507
- let found = false;
508
- for (const known of knownUrls) if (known === fragment) {
509
- resolvedUrl = known;
510
- found = true;
511
- break;
512
- }
513
- if (!found) {
514
- let bestLen = 0;
515
- for (const known of knownUrls) if (known.startsWith(fragment) && known.length > bestLen) {
516
- resolvedUrl = known;
517
- bestLen = known.length;
518
- found = true;
519
- }
520
- }
521
- if (!found) {
522
- let bestLen = 0;
523
- for (const known of knownUrls) if (fragment.startsWith(known) && known.length > bestLen) {
524
- resolvedUrl = known;
525
- bestLen = known.length;
526
- }
527
- }
528
- ranges.push({
529
- start,
530
- end: start + fragment.length,
531
- url: resolvedUrl
532
- });
533
- if (resolvedUrl.length > fragment.length && resolvedUrl.startsWith(fragment)) newPending = {
534
- url: resolvedUrl,
535
- consumed: fragment.length
536
- };
537
- }
538
- return {
539
- ranges,
540
- pending: newPending
541
- };
542
- }
543
- /**
544
- * Apply OSC 8 hyperlink sequences to a line based on visible-text URL ranges.
545
- * Walks through the raw string character by character, inserting OSC 8
546
- * open/close sequences at URL range boundaries while preserving ANSI codes.
547
- */
548
- function applyOsc8Ranges(line, ranges) {
549
- if (ranges.length === 0) return line;
550
- const urlAt = /* @__PURE__ */ new Map();
551
- for (const r of ranges) for (let p = r.start; p < r.end; p++) urlAt.set(p, r.url);
552
- let result = "";
553
- let visiblePos = 0;
554
- let activeUrl = null;
555
- let i = 0;
556
- while (i < line.length) {
557
- if (line.charCodeAt(i) === 27) {
558
- const sgr = line.slice(i).match(SGR_START_RE);
559
- if (sgr) {
560
- result += sgr[0];
561
- i += sgr[0].length;
562
- continue;
563
- }
564
- const osc = line.slice(i).match(OSC8_START_RE);
565
- if (osc) {
566
- result += osc[0];
567
- i += osc[0].length;
568
- continue;
569
- }
570
- }
571
- const targetUrl = urlAt.get(visiblePos) ?? null;
572
- if (targetUrl !== activeUrl) {
573
- if (activeUrl !== null) result += "\x1B]8;;\x07";
574
- if (targetUrl !== null) result += `\x1b]8;;${targetUrl}\x07`;
575
- activeUrl = targetUrl;
576
- }
577
- result += line[i];
578
- visiblePos++;
579
- i++;
580
- }
581
- if (activeUrl !== null) result += "\x1B]8;;\x07";
582
- return result;
583
- }
584
- /**
585
- * Add OSC 8 hyperlinks to rendered lines using a pre-extracted URL list.
586
- *
587
- * For each line, finds URL-like substrings in the visible text, matches them
588
- * against known URLs, and wraps each fragment with OSC 8 escape sequences.
589
- * Handles URLs broken across multiple lines by pi-tui's word wrapping.
590
- */
591
- function addOsc8Hyperlinks(lines, urls) {
592
- if (urls.length === 0) return lines;
593
- let pending = null;
594
- return lines.map((line) => {
595
- const result = findUrlRanges(stripAnsi(line), urls, pending);
596
- pending = result.pending;
597
- return applyOsc8Ranges(line, result.ranges);
598
- });
599
- }
600
- //#endregion
601
- //#region src/tui/components/hyperlink-markdown.ts
602
- /**
603
- * Wrapper around pi-tui's Markdown component that adds OSC 8 terminal
604
- * hyperlinks to rendered output, making URLs clickable even when broken
605
- * across multiple lines by word wrapping.
606
- */
607
- var HyperlinkMarkdown = class {
608
- constructor(text, paddingX, paddingY, theme, options) {
609
- this.inner = new Markdown(text, paddingX, paddingY, theme, options);
610
- this.urls = extractUrls(text);
611
- }
612
- render(width) {
613
- return addOsc8Hyperlinks(this.inner.render(width), this.urls);
614
- }
615
- setText(text) {
616
- this.inner.setText(text);
617
- this.urls = extractUrls(text);
618
- }
619
- invalidate() {
620
- this.inner.invalidate();
621
- }
622
- };
623
- //#endregion
624
- //#region src/tui/components/assistant-message.ts
625
- var AssistantMessageComponent = class extends Container {
626
- constructor(text) {
627
- super();
628
- this.body = new HyperlinkMarkdown(text, 0, 0, markdownTheme, { color: (line) => theme.assistantText(line) });
629
- this.addChild(new Spacer(1));
630
- this.addChild(this.body);
631
- }
632
- setText(text) {
633
- this.body.setText(text);
634
- }
635
- };
636
- //#endregion
637
- //#region src/tui/components/btw-inline-message.ts
638
- var BtwInlineMessage = class extends Container {
639
- constructor(params) {
640
- super();
641
- this.setResult(params);
642
- }
643
- setResult(params) {
644
- this.clear();
645
- this.addChild(new Spacer(1));
646
- this.addChild(new Text(theme.header(`BTW: ${params.question}`), 1, 0));
647
- if (params.isError) this.addChild(new Text(theme.error(params.text), 1, 0));
648
- else this.addChild(new AssistantMessageComponent(params.text));
649
- this.addChild(new Text(theme.dim("Press Enter or Esc to dismiss"), 1, 0));
650
- }
651
- };
652
- //#endregion
653
- //#region src/tui/tui-formatters.ts
654
- const REPLACEMENT_CHAR_RE = /\uFFFD/g;
655
- const MAX_TOKEN_CHARS = 32;
656
- const LONG_TOKEN_RE = /\S{33,}/g;
657
- const LONG_TOKEN_TEST_RE = /\S{33,}/;
658
- const BINARY_LINE_REPLACEMENT_THRESHOLD = 12;
659
- const URL_PREFIX_RE = /^(https?:\/\/|file:\/\/)/i;
660
- const WINDOWS_DRIVE_RE = /^[a-zA-Z]:[\\/]/;
661
- const FILE_LIKE_RE = /^[a-zA-Z0-9._-]+$/;
662
- const EDGE_PUNCTUATION_RE = /^[`"'([{<]+|[`"')\]}>.,:;!?]+$/g;
663
- const TOKENISH_MIN_LENGTH = 24;
664
- const RTL_SCRIPT_RE = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc]/;
665
- const BIDI_CONTROL_RE = /[\u202a-\u202e\u2066-\u2069]/;
666
- const RTL_ISOLATE_START = "⁧";
667
- const RTL_ISOLATE_END = "⁩";
668
- function hasControlChars(text) {
669
- for (const char of text) {
670
- const code = char.charCodeAt(0);
671
- if (code <= 31 && code !== 9 && code !== 10 && code !== 13 || code >= 127 && code <= 159) return true;
672
- }
673
- return false;
674
- }
675
- function stripControlChars(text) {
676
- if (!hasControlChars(text)) return text;
677
- let sanitized = "";
678
- for (const char of text) {
679
- const code = char.charCodeAt(0);
680
- if (!(code <= 31 && code !== 9 && code !== 10 && code !== 13) && !(code >= 127 && code <= 159)) sanitized += char;
681
- }
682
- return sanitized;
683
- }
684
- function chunkToken(token, maxChars) {
685
- if (token.length <= maxChars) return [token];
686
- const chunks = [];
687
- for (let i = 0; i < token.length; i += maxChars) chunks.push(token.slice(i, i + maxChars));
688
- return chunks;
689
- }
690
- function isCopySensitiveToken(token) {
691
- const candidate = token.replace(EDGE_PUNCTUATION_RE, "") || token;
692
- if (URL_PREFIX_RE.test(token)) return true;
693
- if (token.startsWith("/") || token.startsWith("~/") || token.startsWith("./") || token.startsWith("../")) return true;
694
- if (WINDOWS_DRIVE_RE.test(token) || token.startsWith("\\\\")) return true;
695
- if (token.includes("/") || token.includes("\\")) return true;
696
- if (token.includes("_") && FILE_LIKE_RE.test(token)) return true;
697
- if (candidate.length >= TOKENISH_MIN_LENGTH && /[a-z]/i.test(candidate) && /\d/.test(candidate)) return true;
698
- return false;
699
- }
700
- function normalizeLongTokenForDisplay(token) {
701
- if (isCopySensitiveToken(token)) return token;
702
- return chunkToken(token, MAX_TOKEN_CHARS).join(" ");
703
- }
704
- function redactBinaryLikeLine(line) {
705
- const replacementCount = (line.match(REPLACEMENT_CHAR_RE) || []).length;
706
- if (replacementCount >= BINARY_LINE_REPLACEMENT_THRESHOLD && replacementCount * 2 >= line.length) return "[binary data omitted]";
707
- return line;
708
- }
709
- function isolateRtlLine(line) {
710
- if (!RTL_SCRIPT_RE.test(line) || BIDI_CONTROL_RE.test(line)) return line;
711
- return `${RTL_ISOLATE_START}${line}${RTL_ISOLATE_END}`;
712
- }
713
- function applyRtlIsolation(text) {
714
- if (!RTL_SCRIPT_RE.test(text)) return text;
715
- return text.split("\n").map((line) => isolateRtlLine(line)).join("\n");
716
- }
717
- function sanitizeRenderableText(text) {
718
- if (!text) return text;
719
- const hasAnsi = text.includes("\x1B");
720
- const hasReplacementChars = text.includes("�");
721
- const hasLongTokens = LONG_TOKEN_TEST_RE.test(text);
722
- const hasControls = hasControlChars(text);
723
- if (!hasAnsi && !hasReplacementChars && !hasLongTokens && !hasControls) return applyRtlIsolation(text);
724
- const withoutAnsi = hasAnsi ? stripAnsi$1(text) : text;
725
- const withoutControlChars = hasControls ? stripControlChars(withoutAnsi) : withoutAnsi;
726
- const redacted = hasReplacementChars ? withoutControlChars.split("\n").map((line) => redactBinaryLikeLine(line)).join("\n") : withoutControlChars;
727
- return applyRtlIsolation(LONG_TOKEN_TEST_RE.test(redacted) ? redacted.replace(LONG_TOKEN_RE, normalizeLongTokenForDisplay) : redacted);
728
- }
729
- function resolveFinalAssistantText(params) {
730
- const finalText = params.finalText ?? "";
731
- if (finalText.trim()) return finalText;
732
- const streamedText = params.streamedText ?? "";
733
- if (streamedText.trim()) return streamedText;
734
- const errorMessage = params.errorMessage ?? "";
735
- if (errorMessage.trim()) return formatRawAssistantErrorForUi(errorMessage);
736
- return "(no output)";
737
- }
738
- function composeThinkingAndContent(params) {
739
- const thinkingText = params.thinkingText?.trim() ?? "";
740
- const contentText = params.contentText?.trim() ?? "";
741
- const parts = [];
742
- if (params.showThinking && thinkingText) parts.push(`[thinking]\n${thinkingText}`);
743
- if (contentText) parts.push(contentText);
744
- return parts.join("\n\n").trim();
745
- }
746
- function asMessageRecord(message) {
747
- if (!message || typeof message !== "object") return;
748
- return message;
749
- }
750
- function resolveMessageRecord(message) {
751
- const record = asMessageRecord(message);
752
- if (!record) return;
753
- return {
754
- record,
755
- content: record.content
756
- };
757
- }
758
- function formatAssistantErrorFromRecord(record) {
759
- if ((typeof record.stopReason === "string" ? record.stopReason : "") !== "error") return "";
760
- return formatRawAssistantErrorForUi(typeof record.errorMessage === "string" ? record.errorMessage : "");
761
- }
762
- function collectSanitizedBlockStrings(params) {
763
- if (!Array.isArray(params.content)) return [];
764
- const parts = [];
765
- for (const block of params.content) {
766
- if (!block || typeof block !== "object") continue;
767
- const rec = block;
768
- if (rec.type === params.blockType && typeof rec[params.valueKey] === "string") parts.push(sanitizeRenderableText(rec[params.valueKey]));
769
- }
770
- return parts;
771
- }
772
- /**
773
- * Extract ONLY thinking blocks from message content.
774
- * Model-agnostic: returns empty string if no thinking blocks exist.
775
- */
776
- function extractThinkingFromMessage(message) {
777
- const resolved = resolveMessageRecord(message);
778
- if (!resolved) return "";
779
- const { content } = resolved;
780
- if (typeof content === "string") return "";
781
- return collectSanitizedBlockStrings({
782
- content,
783
- blockType: "thinking",
784
- valueKey: "thinking"
785
- }).join("\n").trim();
786
- }
787
- /**
788
- * Extract ONLY text content blocks from message (excludes thinking).
789
- * Model-agnostic: works for any model with text content blocks.
790
- */
791
- function extractContentFromMessage(message) {
792
- const resolved = resolveMessageRecord(message);
793
- if (!resolved) return "";
794
- const { record, content } = resolved;
795
- if (record.role === "assistant") {
796
- if (typeof content === "string") return sanitizeRenderableText(content).trim();
797
- if (Array.isArray(content)) return extractAssistantRenderableContent(record);
798
- }
799
- if (typeof content === "string") return sanitizeRenderableText(content).trim();
800
- const parts = collectSanitizedBlockStrings({
801
- content,
802
- blockType: "text",
803
- valueKey: "text"
804
- });
805
- if (parts.length > 0) return parts.join("\n").trim();
806
- return formatAssistantErrorFromRecord(record);
807
- }
808
- function extractAssistantRenderableContent(record) {
809
- const visible = sanitizeRenderableText(extractAssistantVisibleText(record) ?? "").trim();
810
- if (visible) return visible;
811
- return formatAssistantErrorFromRecord(record);
812
- }
813
- function extractTextBlocks(content, opts) {
814
- if (typeof content === "string") return sanitizeRenderableText(content).trim();
815
- if (!Array.isArray(content)) return "";
816
- const textParts = collectSanitizedBlockStrings({
817
- content,
818
- blockType: "text",
819
- valueKey: "text"
820
- });
821
- return composeThinkingAndContent({
822
- thinkingText: (opts?.includeThinking === true ? collectSanitizedBlockStrings({
823
- content,
824
- blockType: "thinking",
825
- valueKey: "thinking"
826
- }) : []).join("\n").trim(),
827
- contentText: textParts.join("\n").trim(),
828
- showThinking: opts?.includeThinking ?? false
829
- });
830
- }
831
- function extractTextFromMessage(message, opts) {
832
- const record = asMessageRecord(message);
833
- if (!record) return "";
834
- if (record.role === "assistant") return composeThinkingAndContent({
835
- thinkingText: extractThinkingFromMessage(record),
836
- contentText: extractAssistantRenderableContent(record),
837
- showThinking: opts?.includeThinking ?? false
838
- });
839
- const text = extractTextBlocks(record.content, opts);
840
- if (text) {
841
- if (record.role === "user" || record.command === true) return stripLeadingInboundMetadata(text);
842
- return text;
843
- }
844
- const errorText = formatAssistantErrorFromRecord(record);
845
- if (!errorText) return "";
846
- return errorText;
847
- }
848
- function isCommandMessage(message) {
849
- if (!message || typeof message !== "object") return false;
850
- return message.command === true;
851
- }
852
- function formatTokens(total, context) {
853
- if (total == null && context == null) return "tokens ?";
854
- const totalLabel = total == null ? "?" : formatTokenCount(total);
855
- if (context == null) return `tokens ${totalLabel}`;
856
- const pct = typeof total === "number" && context > 0 ? Math.min(999, Math.round(total / context * 100)) : null;
857
- return `tokens ${totalLabel}/${formatTokenCount(context)}${pct !== null ? ` (${pct}%)` : ""}`;
858
- }
859
- function formatContextUsageLine(params) {
860
- const totalLabel = typeof params.total === "number" ? formatTokenCount(params.total) : "?";
861
- const ctxLabel = typeof params.context === "number" ? formatTokenCount(params.context) : "?";
862
- const pct = typeof params.percent === "number" ? Math.min(999, Math.round(params.percent)) : null;
863
- const extra = [typeof params.remaining === "number" ? `${formatTokenCount(params.remaining)} left` : null, pct !== null ? `${pct}%` : null].filter(Boolean).join(", ");
864
- return `tokens ${totalLabel}/${ctxLabel}${extra ? ` (${extra})` : ""}`;
865
- }
866
- function asString(value, fallback = "") {
867
- if (typeof value === "string") return value;
868
- if (typeof value === "number" || typeof value === "boolean") return String(value);
869
- return fallback;
870
- }
871
- //#endregion
872
- //#region src/tui/components/tool-execution.ts
873
- const PREVIEW_LINES = 12;
874
- function formatArgs(toolName, args) {
875
- const detail = formatToolDetail(resolveToolDisplay({
876
- name: toolName,
877
- args
878
- }));
879
- if (detail) return sanitizeRenderableText(detail);
880
- if (!args || typeof args !== "object") return "";
881
- try {
882
- return sanitizeRenderableText(JSON.stringify(args));
883
- } catch {
884
- return "";
885
- }
886
- }
887
- function extractText(result) {
888
- if (!result?.content) return "";
889
- const lines = [];
890
- for (const entry of result.content) if (entry.type === "text" && entry.text) lines.push(sanitizeRenderableText(entry.text));
891
- else if (entry.type === "image") {
892
- const mime = entry.mimeType ?? "image";
893
- const size = entry.bytes ? ` ${Math.round(entry.bytes / 1024)}kb` : "";
894
- const omitted = entry.omitted ? " (omitted)" : "";
895
- lines.push(`[${mime}${size}${omitted}]`);
896
- }
897
- return lines.join("\n").trim();
898
- }
899
- var ToolExecutionComponent = class extends Container {
900
- constructor(toolName, args) {
901
- super();
902
- this.expanded = false;
903
- this.isError = false;
904
- this.isPartial = true;
905
- this.toolName = toolName;
906
- this.args = args;
907
- this.box = new Box(1, 1, (line) => theme.toolPendingBg(line));
908
- this.header = new Text("", 0, 0);
909
- this.argsLine = new Text("", 0, 0);
910
- this.output = new Markdown("", 0, 0, markdownTheme, { color: (line) => theme.toolOutput(line) });
911
- this.addChild(new Spacer(1));
912
- this.addChild(this.box);
913
- this.box.addChild(this.header);
914
- this.box.addChild(this.argsLine);
915
- this.box.addChild(this.output);
916
- this.refresh();
917
- }
918
- setArgs(args) {
919
- this.args = args;
920
- this.refresh();
921
- }
922
- setExpanded(expanded) {
923
- this.expanded = expanded;
924
- this.refresh();
925
- }
926
- setResult(result, opts) {
927
- this.result = result;
928
- this.isPartial = false;
929
- this.isError = Boolean(opts?.isError);
930
- this.refresh();
931
- }
932
- setPartialResult(result) {
933
- this.result = result;
934
- this.isPartial = true;
935
- this.refresh();
936
- }
937
- refresh() {
938
- const bg = this.isPartial ? theme.toolPendingBg : this.isError ? theme.toolErrorBg : theme.toolSuccessBg;
939
- this.box.setBgFn((line) => bg(line));
940
- const display = resolveToolDisplay({
941
- name: this.toolName,
942
- args: this.args
943
- });
944
- const title = `${display.emoji} ${display.label}${this.isPartial ? " (running)" : ""}`;
945
- this.header.setText(theme.toolTitle(theme.bold(title)));
946
- const argLine = formatArgs(this.toolName, this.args);
947
- this.argsLine.setText(argLine ? theme.dim(argLine) : theme.dim(" "));
948
- const text = extractText(this.result) || (this.isPartial ? "…" : "");
949
- if (!this.expanded && text) {
950
- const lines = text.split("\n");
951
- const preview = lines.length > PREVIEW_LINES ? `${lines.slice(0, PREVIEW_LINES).join("\n")}\n…` : text;
952
- this.output.setText(preview);
953
- } else this.output.setText(text);
954
- }
955
- };
956
- //#endregion
957
- //#region src/tui/components/markdown-message.ts
958
- var MarkdownMessageComponent = class extends Container {
959
- constructor(text, y, options) {
960
- super();
961
- this.body = new HyperlinkMarkdown(text, 0, y, markdownTheme, options);
962
- this.addChild(new Spacer(1));
963
- this.addChild(this.body);
964
- }
965
- setText(text) {
966
- this.body.setText(text);
967
- }
968
- };
969
- //#endregion
970
- //#region src/tui/components/user-message.ts
971
- var UserMessageComponent = class extends MarkdownMessageComponent {
972
- constructor(text) {
973
- super(text, 1, {
974
- bgColor: (line) => theme.userBg(line),
975
- color: (line) => theme.userText(line)
976
- });
977
- }
978
- };
979
- //#endregion
980
- //#region src/tui/components/chat-log.ts
981
- const PENDING_HISTORY_CLOCK_SKEW_TOLERANCE_MS = 6e4;
982
- var ChatLog = class extends Container {
983
- constructor(maxComponents = 180) {
984
- super();
985
- this.toolById = /* @__PURE__ */ new Map();
986
- this.streamingRuns = /* @__PURE__ */ new Map();
987
- this.pendingUsers = /* @__PURE__ */ new Map();
988
- this.btwMessage = null;
989
- this.toolsExpanded = false;
990
- this.maxComponents = Math.max(20, Math.floor(maxComponents));
991
- }
992
- dropComponentReferences(component) {
993
- for (const [toolId, tool] of this.toolById.entries()) if (tool === component) this.toolById.delete(toolId);
994
- for (const [runId, message] of this.streamingRuns.entries()) if (message === component) this.streamingRuns.delete(runId);
995
- for (const [runId, entry] of this.pendingUsers.entries()) if (entry.component === component) this.pendingUsers.delete(runId);
996
- if (this.btwMessage === component) this.btwMessage = null;
997
- }
998
- pruneOverflow() {
999
- while (this.children.length > this.maxComponents) {
1000
- const oldest = this.children[0];
1001
- if (!oldest) return;
1002
- this.removeChild(oldest);
1003
- this.dropComponentReferences(oldest);
1004
- }
1005
- }
1006
- append(component) {
1007
- this.addChild(component);
1008
- this.pruneOverflow();
1009
- }
1010
- clearAll(opts) {
1011
- this.clear();
1012
- this.toolById.clear();
1013
- this.streamingRuns.clear();
1014
- this.btwMessage = null;
1015
- if (!opts?.preservePendingUsers) this.pendingUsers.clear();
1016
- }
1017
- restorePendingUsers() {
1018
- for (const entry of this.pendingUsers.values()) {
1019
- if (this.children.includes(entry.component)) continue;
1020
- this.append(entry.component);
1021
- }
1022
- }
1023
- clearPendingUsers() {
1024
- for (const entry of this.pendingUsers.values()) this.removeChild(entry.component);
1025
- this.pendingUsers.clear();
1026
- }
1027
- createSystemMessage(text) {
1028
- const entry = new Container();
1029
- entry.addChild(new Spacer(1));
1030
- entry.addChild(new Text(theme.system(text), 1, 0));
1031
- return entry;
1032
- }
1033
- addSystem(text) {
1034
- this.append(this.createSystemMessage(text));
1035
- }
1036
- addUser(text) {
1037
- this.append(new UserMessageComponent(text));
1038
- }
1039
- addPendingUser(runId, text, createdAt = Date.now()) {
1040
- const existing = this.pendingUsers.get(runId);
1041
- if (existing) {
1042
- existing.text = text;
1043
- existing.createdAt = createdAt;
1044
- existing.component.setText(text);
1045
- return existing.component;
1046
- }
1047
- const component = new UserMessageComponent(text);
1048
- this.pendingUsers.set(runId, {
1049
- component,
1050
- text,
1051
- createdAt
1052
- });
1053
- this.append(component);
1054
- return component;
1055
- }
1056
- commitPendingUser(runId) {
1057
- return this.pendingUsers.delete(runId);
1058
- }
1059
- dropPendingUser(runId) {
1060
- const existing = this.pendingUsers.get(runId);
1061
- if (!existing) return false;
1062
- this.removeChild(existing.component);
1063
- this.pendingUsers.delete(runId);
1064
- return true;
1065
- }
1066
- hasPendingUser(runId) {
1067
- return this.pendingUsers.has(runId);
1068
- }
1069
- reconcilePendingUsers(historyUsers) {
1070
- const normalizedHistory = historyUsers.map((entry) => ({
1071
- text: entry.text.trim(),
1072
- timestamp: typeof entry.timestamp === "number" ? entry.timestamp : null
1073
- })).filter((entry) => entry.text.length > 0 && entry.timestamp !== null);
1074
- const clearedRunIds = [];
1075
- for (const [runId, entry] of this.pendingUsers.entries()) {
1076
- const pendingText = entry.text.trim();
1077
- if (!pendingText) continue;
1078
- const matchIndex = normalizedHistory.findIndex((historyEntry) => historyEntry.text === pendingText && (historyEntry.timestamp ?? 0) >= entry.createdAt - PENDING_HISTORY_CLOCK_SKEW_TOLERANCE_MS);
1079
- if (matchIndex === -1) continue;
1080
- if (this.children.includes(entry.component)) this.removeChild(entry.component);
1081
- this.pendingUsers.delete(runId);
1082
- clearedRunIds.push(runId);
1083
- normalizedHistory.splice(matchIndex, 1);
1084
- }
1085
- return clearedRunIds;
1086
- }
1087
- countPendingUsers() {
1088
- return this.pendingUsers.size;
1089
- }
1090
- resolveRunId(runId) {
1091
- return runId ?? "default";
1092
- }
1093
- startAssistant(text, runId) {
1094
- const effectiveRunId = this.resolveRunId(runId);
1095
- const existing = this.streamingRuns.get(effectiveRunId);
1096
- if (existing) {
1097
- existing.setText(text);
1098
- return existing;
1099
- }
1100
- const component = new AssistantMessageComponent(text);
1101
- this.streamingRuns.set(effectiveRunId, component);
1102
- this.append(component);
1103
- return component;
1104
- }
1105
- updateAssistant(text, runId) {
1106
- const effectiveRunId = this.resolveRunId(runId);
1107
- const existing = this.streamingRuns.get(effectiveRunId);
1108
- if (!existing) {
1109
- this.startAssistant(text, runId);
1110
- return;
1111
- }
1112
- existing.setText(text);
1113
- }
1114
- finalizeAssistant(text, runId) {
1115
- const effectiveRunId = this.resolveRunId(runId);
1116
- const existing = this.streamingRuns.get(effectiveRunId);
1117
- if (existing) {
1118
- existing.setText(text);
1119
- this.streamingRuns.delete(effectiveRunId);
1120
- return;
1121
- }
1122
- this.append(new AssistantMessageComponent(text));
1123
- }
1124
- dropAssistant(runId) {
1125
- const effectiveRunId = this.resolveRunId(runId);
1126
- const existing = this.streamingRuns.get(effectiveRunId);
1127
- if (!existing) return;
1128
- this.removeChild(existing);
1129
- this.streamingRuns.delete(effectiveRunId);
1130
- }
1131
- showBtw(params) {
1132
- if (this.btwMessage) {
1133
- this.btwMessage.setResult(params);
1134
- if (this.children[this.children.length - 1] !== this.btwMessage) {
1135
- this.removeChild(this.btwMessage);
1136
- this.append(this.btwMessage);
1137
- }
1138
- return this.btwMessage;
1139
- }
1140
- const component = new BtwInlineMessage(params);
1141
- this.btwMessage = component;
1142
- this.append(component);
1143
- return component;
1144
- }
1145
- dismissBtw() {
1146
- if (!this.btwMessage) return;
1147
- this.removeChild(this.btwMessage);
1148
- this.btwMessage = null;
1149
- }
1150
- hasVisibleBtw() {
1151
- return this.btwMessage !== null;
1152
- }
1153
- startTool(toolCallId, toolName, args) {
1154
- const existing = this.toolById.get(toolCallId);
1155
- if (existing) {
1156
- existing.setArgs(args);
1157
- return existing;
1158
- }
1159
- const component = new ToolExecutionComponent(toolName, args);
1160
- component.setExpanded(this.toolsExpanded);
1161
- this.toolById.set(toolCallId, component);
1162
- this.append(component);
1163
- return component;
1164
- }
1165
- updateToolArgs(toolCallId, args) {
1166
- const existing = this.toolById.get(toolCallId);
1167
- if (!existing) return;
1168
- existing.setArgs(args);
1169
- }
1170
- updateToolResult(toolCallId, result, opts) {
1171
- const existing = this.toolById.get(toolCallId);
1172
- if (!existing) return;
1173
- if (opts?.partial) {
1174
- existing.setPartialResult(result);
1175
- return;
1176
- }
1177
- existing.setResult(result, { isError: opts?.isError });
1178
- }
1179
- setToolsExpanded(expanded) {
1180
- this.toolsExpanded = expanded;
1181
- for (const tool of this.toolById.values()) tool.setExpanded(expanded);
1182
- }
1183
- };
1184
- //#endregion
1185
- //#region src/tui/components/custom-editor.ts
1186
- var CustomEditor = class extends Editor {
1187
- handleInput(data) {
1188
- if (matchesKey(data, Key.alt("enter")) && this.onAltEnter) {
1189
- this.onAltEnter();
1190
- return;
1191
- }
1192
- if (matchesKey(data, Key.alt("up")) && this.onAltUp) {
1193
- this.onAltUp();
1194
- return;
1195
- }
1196
- if (matchesKey(data, Key.ctrl("l")) && this.onCtrlL) {
1197
- this.onCtrlL();
1198
- return;
1199
- }
1200
- if (matchesKey(data, Key.ctrl("o")) && this.onCtrlO) {
1201
- this.onCtrlO();
1202
- return;
1203
- }
1204
- if (matchesKey(data, Key.ctrl("p")) && this.onCtrlP) {
1205
- this.onCtrlP();
1206
- return;
1207
- }
1208
- if (matchesKey(data, Key.ctrl("g")) && this.onCtrlG) {
1209
- this.onCtrlG();
1210
- return;
1211
- }
1212
- if (matchesKey(data, Key.ctrl("t")) && this.onCtrlT) {
1213
- this.onCtrlT();
1214
- return;
1215
- }
1216
- if (matchesKey(data, Key.shift("tab")) && this.onShiftTab) {
1217
- this.onShiftTab();
1218
- return;
1219
- }
1220
- if (matchesKey(data, Key.escape) && this.onEscape && !this.isShowingAutocomplete()) {
1221
- this.onEscape();
1222
- return;
1223
- }
1224
- if (matchesKey(data, Key.ctrl("c")) && this.onCtrlC) {
1225
- this.onCtrlC();
1226
- return;
1227
- }
1228
- if (matchesKey(data, Key.ctrl("d"))) {
1229
- if (this.getText().length === 0 && this.onCtrlD) this.onCtrlD();
1230
- return;
1231
- }
1232
- super.handleInput(data);
1233
- }
1234
- };
1235
- //#endregion
1236
- //#region src/tui/embedded-backend.ts
1237
- const silentRuntime = {
1238
- log: (..._args) => void 0,
1239
- error: (..._args) => void 0,
1240
- exit: (code) => {
1241
- throw new Error(`embedded tui runtime exit ${String(code)}`);
1242
- }
1243
- };
1244
- function isSilentReplyLeadFragment(text) {
1245
- const normalized = text.trim().toUpperCase();
1246
- if (!normalized) return false;
1247
- if (!/^[A-Z_]+$/.test(normalized)) return false;
1248
- if (normalized === "NO_REPLY") return false;
1249
- return SILENT_REPLY_TOKEN.startsWith(normalized);
1250
- }
1251
- function appendUniqueSuffix(base, suffix) {
1252
- if (!suffix) return base;
1253
- if (!base) return suffix;
1254
- if (base.endsWith(suffix)) return base;
1255
- const maxOverlap = Math.min(base.length, suffix.length);
1256
- for (let overlap = maxOverlap; overlap > 0; overlap -= 1) if (base.slice(-overlap) === suffix.slice(0, overlap)) return base + suffix.slice(overlap);
1257
- return base + suffix;
1258
- }
1259
- function resolveMergedAssistantText(params) {
1260
- const previous = params.previousText;
1261
- const next = params.nextText;
1262
- const delta = params.nextDelta;
1263
- if (!previous) return next || delta;
1264
- if (next && next.startsWith(previous)) return next;
1265
- if (delta) return appendUniqueSuffix(previous, delta);
1266
- return appendUniqueSuffix(previous, next);
1267
- }
1268
- function resolveBtwQuestion(message) {
1269
- const question = /^\/btw(?::|\s)+(.*)$/i.exec(message.trim())?.[1]?.trim();
1270
- return question ? question : void 0;
1271
- }
1272
- function payloadText(parts) {
1273
- if (!Array.isArray(parts)) return "";
1274
- return parts.map((part) => {
1275
- if (!part || typeof part !== "object") return "";
1276
- const payload = part;
1277
- return typeof payload.text === "string" ? payload.text.trim() : "";
1278
- }).filter(Boolean).join("\n\n").trim();
1279
- }
1280
- function timeoutSecondsFromMs(timeoutMs) {
1281
- if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs < 0) return;
1282
- return String(Math.max(0, Math.ceil(timeoutMs / 1e3)));
1283
- }
1284
- var EmbeddedTuiBackend = class {
1285
- constructor() {
1286
- this.connection = { url: "local embedded" };
1287
- this.deps = createDefaultDeps();
1288
- this.runs = /* @__PURE__ */ new Map();
1289
- this.seq = 0;
1290
- }
1291
- start() {
1292
- if (this.unsubscribe) return;
1293
- setEmbeddedMode(true);
1294
- this.previousRuntimeLog = defaultRuntime.log;
1295
- this.previousRuntimeError = defaultRuntime.error;
1296
- defaultRuntime.log = silentRuntime.log;
1297
- defaultRuntime.error = silentRuntime.error;
1298
- this.unsubscribe = onAgentEvent((evt) => {
1299
- this.handleAgentEvent(evt);
1300
- });
1301
- queueMicrotask(() => {
1302
- this.onConnected?.();
1303
- });
1304
- }
1305
- stop() {
1306
- this.unsubscribe?.();
1307
- this.unsubscribe = void 0;
1308
- for (const run of this.runs.values()) run.controller.abort();
1309
- this.runs.clear();
1310
- defaultRuntime.log = this.previousRuntimeLog ?? defaultRuntime.log;
1311
- defaultRuntime.error = this.previousRuntimeError ?? defaultRuntime.error;
1312
- this.previousRuntimeLog = void 0;
1313
- this.previousRuntimeError = void 0;
1314
- setEmbeddedMode(false);
1315
- }
1316
- async sendChat(opts) {
1317
- const runId = opts.runId ?? randomUUID();
1318
- const question = resolveBtwQuestion(opts.message);
1319
- if (!question) this.abortSessionRuns(opts.sessionKey);
1320
- const controller = new AbortController();
1321
- this.runs.set(runId, {
1322
- sessionKey: opts.sessionKey,
1323
- controller,
1324
- buffer: "",
1325
- isBtw: Boolean(question),
1326
- question,
1327
- finalSent: false,
1328
- registered: false
1329
- });
1330
- this.runTurn({
1331
- runId,
1332
- sessionKey: opts.sessionKey,
1333
- message: opts.message,
1334
- thinking: opts.thinking,
1335
- deliver: opts.deliver,
1336
- timeoutMs: opts.timeoutMs,
1337
- controller
1338
- });
1339
- return { runId };
1340
- }
1341
- async abortChat(opts) {
1342
- const run = this.runs.get(opts.runId);
1343
- if (!run || run.sessionKey !== opts.sessionKey) return {
1344
- ok: true,
1345
- aborted: false
1346
- };
1347
- run.controller.abort();
1348
- return {
1349
- ok: true,
1350
- aborted: true
1351
- };
1352
- }
1353
- async loadHistory(opts) {
1354
- const { cfg, storePath, entry } = loadSessionEntry(opts.sessionKey);
1355
- const sessionId = entry?.sessionId;
1356
- const resolvedSessionModel = resolveSessionModelRef(cfg, entry, resolveSessionAgentId({
1357
- sessionKey: opts.sessionKey,
1358
- config: cfg
1359
- }));
1360
- const localMessages = sessionId && storePath ? readSessionMessages(sessionId, storePath, entry?.sessionFile) : [];
1361
- const rawMessages = augmentChatHistoryWithCliSessionImports({
1362
- entry,
1363
- provider: resolvedSessionModel.provider,
1364
- localMessages
1365
- });
1366
- const max = Math.min(1e3, typeof opts.limit === "number" ? opts.limit : 200);
1367
- const sliced = rawMessages.length > max ? rawMessages.slice(-max) : rawMessages;
1368
- const effectiveMaxChars = resolveEffectiveChatHistoryMaxChars(cfg);
1369
- const normalized = augmentChatHistoryWithCanvasBlocks(sanitizeChatHistoryMessages(stripEnvelopeFromMessages(sliced), effectiveMaxChars));
1370
- const maxHistoryBytes = getMaxChatHistoryMessagesBytes();
1371
- const capped = capArrayByJsonBytes(replaceOversizedChatHistoryMessages({
1372
- messages: normalized,
1373
- maxSingleMessageBytes: Math.min(CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES, maxHistoryBytes)
1374
- }).messages, maxHistoryBytes).items;
1375
- const messages = enforceChatHistoryFinalBudget({
1376
- messages: capped,
1377
- maxBytes: maxHistoryBytes
1378
- }).messages;
1379
- let thinkingLevel = entry?.thinkingLevel;
1380
- if (!thinkingLevel) {
1381
- const catalog = await loadGatewayModelCatalog();
1382
- thinkingLevel = resolveThinkingDefault({
1383
- cfg,
1384
- provider: resolvedSessionModel.provider,
1385
- model: resolvedSessionModel.model,
1386
- catalog
1387
- });
1388
- }
1389
- return {
1390
- sessionKey: opts.sessionKey,
1391
- sessionId,
1392
- messages,
1393
- thinkingLevel,
1394
- fastMode: entry?.fastMode,
1395
- verboseLevel: entry?.verboseLevel ?? cfg.agents?.defaults?.verboseDefault
1396
- };
1397
- }
1398
- async listSessions(opts) {
1399
- const cfg = loadConfig();
1400
- const { storePath, store } = loadCombinedSessionStoreForGateway(cfg);
1401
- return listSessionsFromStore({
1402
- cfg,
1403
- storePath,
1404
- store,
1405
- opts: opts ?? {}
1406
- });
1407
- }
1408
- async listAgents() {
1409
- return listAgentsForGateway(loadConfig());
1410
- }
1411
- async patchSession(opts) {
1412
- const cfg = loadConfig();
1413
- const target = resolveGatewaySessionStoreTarget({
1414
- cfg,
1415
- key: opts.key
1416
- });
1417
- const applied = await updateSessionStore(target.storePath, async (store) => {
1418
- const { primaryKey } = migrateAndPruneGatewaySessionStoreKey({
1419
- cfg,
1420
- key: opts.key,
1421
- store
1422
- });
1423
- return await applySessionsPatchToStore({
1424
- cfg,
1425
- store,
1426
- storeKey: primaryKey,
1427
- patch: opts,
1428
- loadGatewayModelCatalog
1429
- });
1430
- });
1431
- if (!applied.ok) throw new Error(applied.error.message);
1432
- const agentId = resolveSessionAgentId({
1433
- sessionKey: target.canonicalKey ?? opts.key,
1434
- config: cfg
1435
- });
1436
- const resolved = resolveSessionModelRef(cfg, applied.entry, agentId);
1437
- return {
1438
- ok: true,
1439
- path: target.storePath,
1440
- key: target.canonicalKey ?? opts.key,
1441
- entry: applied.entry,
1442
- resolved: {
1443
- modelProvider: resolved.provider,
1444
- model: resolved.model
1445
- }
1446
- };
1447
- }
1448
- async resetSession(key, reason) {
1449
- const result = await performGatewaySessionReset({
1450
- key,
1451
- reason: reason === "new" ? "new" : "reset",
1452
- commandSource: "tui:embedded"
1453
- });
1454
- if (!result.ok) throw new Error(result.error.message);
1455
- return {
1456
- ok: true,
1457
- key: result.key,
1458
- entry: result.entry
1459
- };
1460
- }
1461
- async getGatewayStatus() {
1462
- return `local embedded mode${this.runs.size > 0 ? ` (${String(this.runs.size)} active run${this.runs.size === 1 ? "" : "s"})` : ""}`;
1463
- }
1464
- async listModels() {
1465
- const catalog = await loadGatewayModelCatalog();
1466
- const { allowedCatalog } = buildAllowedModelSet({
1467
- cfg: loadConfig(),
1468
- catalog,
1469
- defaultProvider: DEFAULT_PROVIDER
1470
- });
1471
- return (allowedCatalog.length > 0 ? allowedCatalog : catalog).map((entry) => ({
1472
- id: entry.id,
1473
- name: entry.name ?? entry.id,
1474
- provider: entry.provider,
1475
- contextWindow: entry.contextWindow,
1476
- reasoning: entry.reasoning
1477
- }));
1478
- }
1479
- abortSessionRuns(sessionKey) {
1480
- for (const run of this.runs.values()) if (run.sessionKey === sessionKey && !run.isBtw) run.controller.abort();
1481
- }
1482
- nextSeq() {
1483
- this.seq += 1;
1484
- return this.seq;
1485
- }
1486
- emit(event, payload) {
1487
- this.onEvent?.({
1488
- event,
1489
- payload,
1490
- seq: this.nextSeq()
1491
- });
1492
- }
1493
- emitChatDelta(runId, run) {
1494
- const text = run.buffer.trim();
1495
- if (!text || isSilentReplyText(text, "NO_REPLY") || isSilentReplyLeadFragment(text)) return;
1496
- run.registered = true;
1497
- this.emit("chat", {
1498
- runId,
1499
- sessionKey: run.sessionKey,
1500
- state: "delta",
1501
- message: {
1502
- role: "assistant",
1503
- content: [{
1504
- type: "text",
1505
- text
1506
- }],
1507
- timestamp: Date.now()
1508
- }
1509
- });
1510
- }
1511
- emitChatFinal(runId, run, stopReason) {
1512
- if (run.finalSent) return;
1513
- run.finalSent = true;
1514
- run.registered = true;
1515
- const text = run.buffer.trim();
1516
- const shouldIncludeMessage = Boolean(text) && !isSilentReplyText(text, "NO_REPLY") && !isSilentReplyLeadFragment(text);
1517
- this.emit("chat", {
1518
- runId,
1519
- sessionKey: run.sessionKey,
1520
- state: "final",
1521
- ...stopReason ? { stopReason } : {},
1522
- ...shouldIncludeMessage ? { message: {
1523
- role: "assistant",
1524
- content: [{
1525
- type: "text",
1526
- text
1527
- }],
1528
- timestamp: Date.now()
1529
- } } : {}
1530
- });
1531
- }
1532
- emitChatAborted(runId, run) {
1533
- if (run.finalSent) return;
1534
- run.finalSent = true;
1535
- run.registered = true;
1536
- this.emit("chat", {
1537
- runId,
1538
- sessionKey: run.sessionKey,
1539
- state: "aborted"
1540
- });
1541
- }
1542
- emitChatError(runId, run, errorMessage) {
1543
- if (run.finalSent) return;
1544
- run.finalSent = true;
1545
- run.registered = true;
1546
- this.emit("chat", {
1547
- runId,
1548
- sessionKey: run.sessionKey,
1549
- state: "error",
1550
- ...errorMessage ? { errorMessage } : {}
1551
- });
1552
- }
1553
- ensureRunRegistered(runId, run) {
1554
- if (run.registered || run.isBtw) return;
1555
- run.registered = true;
1556
- this.emit("chat", {
1557
- runId,
1558
- sessionKey: run.sessionKey,
1559
- state: "delta",
1560
- message: {
1561
- role: "assistant",
1562
- content: [{
1563
- type: "text",
1564
- text: ""
1565
- }],
1566
- timestamp: Date.now()
1567
- }
1568
- });
1569
- }
1570
- async handleAgentEvent(evt) {
1571
- const run = this.runs.get(evt.runId);
1572
- if (!run) return;
1573
- if (evt.stream !== "assistant") this.ensureRunRegistered(evt.runId, run);
1574
- this.emit("agent", {
1575
- runId: evt.runId,
1576
- stream: evt.stream,
1577
- data: evt.data
1578
- });
1579
- if (evt.stream === "assistant" && !run.isBtw && typeof evt.data?.text === "string") {
1580
- const nextText = stripInlineDirectiveTagsForDisplay(evt.data.text).text;
1581
- const nextDelta = typeof evt.data?.delta === "string" ? stripInlineDirectiveTagsForDisplay(evt.data.delta).text : "";
1582
- run.buffer = resolveMergedAssistantText({
1583
- previousText: run.buffer,
1584
- nextText,
1585
- nextDelta
1586
- });
1587
- this.emitChatDelta(evt.runId, run);
1588
- return;
1589
- }
1590
- if (evt.stream !== "lifecycle") return;
1591
- const phase = typeof evt.data?.phase === "string" ? evt.data.phase : "";
1592
- const aborted = evt.data?.aborted === true || run.controller.signal.aborted;
1593
- if (phase === "end") {
1594
- if (aborted) {
1595
- this.emitChatAborted(evt.runId, run);
1596
- return;
1597
- }
1598
- if (!run.isBtw) {
1599
- const stopReason = typeof evt.data?.stopReason === "string" ? evt.data.stopReason : void 0;
1600
- this.emitChatFinal(evt.runId, run, stopReason);
1601
- }
1602
- return;
1603
- }
1604
- if (phase === "error") {
1605
- if (aborted) {
1606
- this.emitChatAborted(evt.runId, run);
1607
- return;
1608
- }
1609
- const errorMessage = typeof evt.data?.error === "string" ? evt.data.error : void 0;
1610
- this.emitChatError(evt.runId, run, errorMessage);
1611
- }
1612
- }
1613
- async runTurn(params) {
1614
- try {
1615
- const { cfg, canonicalKey, entry } = loadSessionEntry(params.sessionKey);
1616
- const result = await agentCommandFromIngress({
1617
- message: injectTimestamp(params.message, timestampOptsFromConfig(cfg)),
1618
- sessionKey: canonicalKey,
1619
- ...entry?.sessionId ? { sessionId: entry.sessionId } : {},
1620
- thinking: params.thinking,
1621
- deliver: params.deliver,
1622
- channel: INTERNAL_MESSAGE_CHANNEL,
1623
- runContext: { messageChannel: INTERNAL_MESSAGE_CHANNEL },
1624
- timeout: timeoutSecondsFromMs(params.timeoutMs),
1625
- runId: params.runId,
1626
- abortSignal: params.controller.signal,
1627
- senderIsOwner: true,
1628
- allowModelOverride: false
1629
- }, silentRuntime, this.deps);
1630
- const run = this.runs.get(params.runId);
1631
- if (!run) return;
1632
- if (run.isBtw) {
1633
- const text = payloadText(result?.payloads);
1634
- if (run.question && text) this.emit("chat.side_result", {
1635
- kind: "btw",
1636
- runId: params.runId,
1637
- sessionKey: run.sessionKey,
1638
- question: run.question,
1639
- text
1640
- });
1641
- this.emitChatFinal(params.runId, run);
1642
- return;
1643
- }
1644
- if (!run.finalSent) {
1645
- const normalizedText = payloadText(result?.payloads);
1646
- if (normalizedText && !run.buffer) run.buffer = normalizedText;
1647
- this.emitChatFinal(params.runId, run);
1648
- }
1649
- } catch (error) {
1650
- const run = this.runs.get(params.runId);
1651
- if (!run) return;
1652
- if (params.controller.signal.aborted) {
1653
- this.emitChatAborted(params.runId, run);
1654
- return;
1655
- }
1656
- const errorMessage = error instanceof Error ? error.message : String(error);
1657
- this.emitChatError(params.runId, run, errorMessage);
1658
- } finally {
1659
- this.runs.delete(params.runId);
1660
- }
1661
- }
1662
- };
1663
- //#endregion
1664
- //#region src/tui/gateway-chat.ts
1665
- const STARTUP_CHAT_HISTORY_RETRY_TIMEOUT_MS = 6e4;
1666
- const STARTUP_CHAT_HISTORY_DEFAULT_RETRY_MS = 500;
1667
- const STARTUP_CHAT_HISTORY_MAX_RETRY_MS = 5e3;
1668
- function throwGatewayAuthResolutionError(reason) {
1669
- throw new Error([
1670
- reason,
1671
- "Fix: set GENESIS_GATEWAY_TOKEN/GENESIS_GATEWAY_PASSWORD, pass --token/--password,",
1672
- "or resolve the configured secret provider for this credential."
1673
- ].join("\n"));
1674
- }
1675
- function isRetryableStartupUnavailable(err, method) {
1676
- if (!(err instanceof GatewayClientRequestError)) return false;
1677
- if (err.gatewayCode !== "UNAVAILABLE" || !err.retryable) return false;
1678
- const details = err.details;
1679
- if (!details || typeof details !== "object") return true;
1680
- const detailMethod = details.method;
1681
- return typeof detailMethod !== "string" || detailMethod === method;
1682
- }
1683
- function resolveStartupRetryDelayMs(err) {
1684
- const retryAfterMs = typeof err.retryAfterMs === "number" ? err.retryAfterMs : STARTUP_CHAT_HISTORY_DEFAULT_RETRY_MS;
1685
- return Math.min(Math.max(retryAfterMs, 100), STARTUP_CHAT_HISTORY_MAX_RETRY_MS);
1686
- }
1687
- function sleep(ms) {
1688
- return new Promise((resolve) => setTimeout(resolve, ms));
1689
- }
1690
- var GatewayChatClient = class GatewayChatClient {
1691
- constructor(connection) {
1692
- this.connection = connection;
1693
- this.readyPromise = new Promise((resolve) => {
1694
- this.resolveReady = resolve;
1695
- });
1696
- this.client = new GatewayClient({
1697
- url: connection.url,
1698
- token: connection.token,
1699
- password: connection.password,
1700
- clientName: GATEWAY_CLIENT_NAMES.TUI,
1701
- clientDisplayName: "genesis-tui",
1702
- clientVersion: VERSION,
1703
- platform: process.platform,
1704
- mode: GATEWAY_CLIENT_MODES.UI,
1705
- deviceIdentity: connection.allowInsecureLocalOperatorUi ? null : void 0,
1706
- caps: [GATEWAY_CLIENT_CAPS.TOOL_EVENTS],
1707
- instanceId: randomUUID(),
1708
- minProtocol: 4,
1709
- maxProtocol: 4,
1710
- onHelloOk: (hello) => {
1711
- this.hello = hello;
1712
- this.resolveReady?.();
1713
- this.onConnected?.();
1714
- },
1715
- onEvent: (evt) => {
1716
- this.onEvent?.({
1717
- event: evt.event,
1718
- payload: evt.payload,
1719
- seq: evt.seq
1720
- });
1721
- },
1722
- onClose: (_code, reason) => {
1723
- this.readyPromise = new Promise((resolve) => {
1724
- this.resolveReady = resolve;
1725
- });
1726
- this.onDisconnected?.(reason);
1727
- },
1728
- onGap: (info) => {
1729
- this.onGap?.(info);
1730
- }
1731
- });
1732
- }
1733
- static async connect(opts) {
1734
- return new GatewayChatClient(await resolveGatewayConnection(opts));
1735
- }
1736
- start() {
1737
- this.client.start();
1738
- }
1739
- stop() {
1740
- this.client.stop();
1741
- }
1742
- async waitForReady() {
1743
- await this.readyPromise;
1744
- }
1745
- async sendChat(opts) {
1746
- const runId = opts.runId ?? randomUUID();
1747
- await this.client.request("chat.send", {
1748
- sessionKey: opts.sessionKey,
1749
- message: opts.message,
1750
- thinking: opts.thinking,
1751
- deliver: opts.deliver,
1752
- timeoutMs: opts.timeoutMs,
1753
- idempotencyKey: runId
1754
- });
1755
- return { runId };
1756
- }
1757
- async abortChat(opts) {
1758
- return await this.client.request("chat.abort", {
1759
- sessionKey: opts.sessionKey,
1760
- runId: opts.runId
1761
- });
1762
- }
1763
- async loadHistory(opts) {
1764
- const startedAt = Date.now();
1765
- for (;;) try {
1766
- return await this.client.request("chat.history", {
1767
- sessionKey: opts.sessionKey,
1768
- limit: opts.limit
1769
- });
1770
- } catch (err) {
1771
- if (Date.now() - startedAt < STARTUP_CHAT_HISTORY_RETRY_TIMEOUT_MS && isRetryableStartupUnavailable(err, "chat.history")) {
1772
- await sleep(resolveStartupRetryDelayMs(err));
1773
- continue;
1774
- }
1775
- throw err;
1776
- }
1777
- }
1778
- async listSessions(opts) {
1779
- return await this.client.request("sessions.list", {
1780
- limit: opts?.limit,
1781
- activeMinutes: opts?.activeMinutes,
1782
- includeGlobal: opts?.includeGlobal,
1783
- includeUnknown: opts?.includeUnknown,
1784
- includeDerivedTitles: opts?.includeDerivedTitles,
1785
- includeLastMessage: opts?.includeLastMessage,
1786
- agentId: opts?.agentId
1787
- });
1788
- }
1789
- async listAgents() {
1790
- return await this.client.request("agents.list", {});
1791
- }
1792
- async patchSession(opts) {
1793
- return await this.client.request("sessions.patch", opts);
1794
- }
1795
- async resetSession(key, reason) {
1796
- return await this.client.request("sessions.reset", {
1797
- key,
1798
- ...reason ? { reason } : {}
1799
- });
1800
- }
1801
- async getGatewayStatus() {
1802
- return await this.client.request("status");
1803
- }
1804
- async listModels() {
1805
- const res = await this.client.request("models.list");
1806
- return Array.isArray(res?.models) ? res.models : [];
1807
- }
1808
- };
1809
- async function resolveGatewayConnection(opts) {
1810
- const config = loadConfig();
1811
- const env = process.env;
1812
- const gatewayAuthMode = config.gateway?.auth?.mode;
1813
- const isRemoteMode = config.gateway?.mode === "remote";
1814
- const preferConfiguredAuth = env[TUI_SETUP_AUTH_SOURCE_ENV] === TUI_SETUP_AUTH_SOURCE_CONFIG;
1815
- const urlOverride = typeof opts.url === "string" && opts.url.trim().length > 0 ? opts.url.trim() : void 0;
1816
- const explicitAuth = resolveExplicitGatewayAuth({
1817
- token: opts.token,
1818
- password: opts.password
1819
- });
1820
- ensureExplicitGatewayAuth({
1821
- urlOverride,
1822
- urlOverrideSource: "cli",
1823
- explicitAuth,
1824
- errorHint: "Fix: pass --token or --password when using --url."
1825
- });
1826
- const url = buildGatewayConnectionDetails({
1827
- config,
1828
- ...urlOverride ? { url: urlOverride } : {}
1829
- }).url;
1830
- const allowInsecureLocalOperatorUi = (() => {
1831
- if (config.gateway?.controlUi?.allowInsecureAuth !== true) return false;
1832
- try {
1833
- return isLoopbackHost(new URL(url).hostname);
1834
- } catch {
1835
- return false;
1836
- }
1837
- })();
1838
- if (urlOverride) return {
1839
- url,
1840
- token: explicitAuth.token,
1841
- password: explicitAuth.password,
1842
- allowInsecureLocalOperatorUi
1843
- };
1844
- if (isRemoteMode) {
1845
- const resolved = await resolveGatewayInteractiveSurfaceAuth({
1846
- config,
1847
- env,
1848
- explicitAuth,
1849
- surface: "remote"
1850
- });
1851
- if (resolved.failureReason) throwGatewayAuthResolutionError(resolved.failureReason);
1852
- return {
1853
- url,
1854
- token: resolved.token,
1855
- password: resolved.password,
1856
- allowInsecureLocalOperatorUi: false
1857
- };
1858
- }
1859
- if (gatewayAuthMode === "none" || gatewayAuthMode === "trusted-proxy") {
1860
- const resolved = await resolveGatewayInteractiveSurfaceAuth({
1861
- config,
1862
- env,
1863
- explicitAuth,
1864
- surface: "local"
1865
- });
1866
- return {
1867
- url,
1868
- token: resolved.token,
1869
- password: resolved.password,
1870
- allowInsecureLocalOperatorUi
1871
- };
1872
- }
1873
- try {
1874
- assertExplicitGatewayAuthModeWhenBothConfigured(config);
1875
- } catch (err) {
1876
- throwGatewayAuthResolutionError(formatErrorMessage(err));
1877
- }
1878
- const resolved = await resolveGatewayInteractiveSurfaceAuth({
1879
- config,
1880
- env,
1881
- explicitAuth,
1882
- suppressEnvAuthFallback: preferConfiguredAuth,
1883
- surface: "local"
1884
- });
1885
- if (resolved.failureReason) throwGatewayAuthResolutionError(resolved.failureReason);
1886
- return {
1887
- url,
1888
- token: resolved.token,
1889
- password: resolved.password,
1890
- allowInsecureLocalOperatorUi
1891
- };
1892
- }
1893
- //#endregion
1894
- //#region src/tui/components/fuzzy-filter.ts
1895
- /**
1896
- * Shared fuzzy filtering utilities for select list components.
1897
- */
1898
- /**
1899
- * Word boundary characters for matching.
1900
- */
1901
- const WORD_BOUNDARY_CHARS = /[\s\-_./:#@]/;
1902
- /**
1903
- * Check if position is at a word boundary.
1904
- */
1905
- function isWordBoundary(text, index) {
1906
- return index === 0 || WORD_BOUNDARY_CHARS.test(text[index - 1] ?? "");
1907
- }
1908
- /**
1909
- * Find index where query matches at a word boundary in text.
1910
- * Returns null if no match.
1911
- */
1912
- function findWordBoundaryIndex(text, query) {
1913
- if (!query) return null;
1914
- const textLower = normalizeLowercaseStringOrEmpty(text);
1915
- const queryLower = normalizeLowercaseStringOrEmpty(query);
1916
- const maxIndex = textLower.length - queryLower.length;
1917
- if (maxIndex < 0) return null;
1918
- for (let i = 0; i <= maxIndex; i++) if (textLower.startsWith(queryLower, i) && isWordBoundary(textLower, i)) return i;
1919
- return null;
1920
- }
1921
- /**
1922
- * Fuzzy match with pre-lowercased inputs (avoids toLowerCase on every keystroke).
1923
- * Returns score (lower = better) or null if no match.
1924
- */
1925
- function fuzzyMatchLower(queryLower, textLower) {
1926
- if (queryLower.length === 0) return 0;
1927
- if (queryLower.length > textLower.length) return null;
1928
- let queryIndex = 0;
1929
- let score = 0;
1930
- let lastMatchIndex = -1;
1931
- let consecutiveMatches = 0;
1932
- for (let i = 0; i < textLower.length && queryIndex < queryLower.length; i++) if (textLower[i] === queryLower[queryIndex]) {
1933
- const isAtWordBoundary = isWordBoundary(textLower, i);
1934
- if (lastMatchIndex === i - 1) {
1935
- consecutiveMatches++;
1936
- score -= consecutiveMatches * 5;
1937
- } else {
1938
- consecutiveMatches = 0;
1939
- if (lastMatchIndex >= 0) score += (i - lastMatchIndex - 1) * 2;
1940
- }
1941
- if (isAtWordBoundary) score -= 10;
1942
- score += i * .1;
1943
- lastMatchIndex = i;
1944
- queryIndex++;
1945
- }
1946
- return queryIndex < queryLower.length ? null : score;
1947
- }
1948
- /**
1949
- * Filter items using pre-lowercased searchTextLower field.
1950
- * Supports space-separated tokens (all must match).
1951
- */
1952
- function fuzzyFilterLower(items, queryLower) {
1953
- const trimmed = queryLower.trim();
1954
- if (!trimmed) return items;
1955
- const tokens = trimmed.split(/\s+/).filter((t) => t.length > 0);
1956
- if (tokens.length === 0) return items;
1957
- const results = [];
1958
- for (const item of items) {
1959
- const text = item.searchTextLower ?? "";
1960
- let totalScore = 0;
1961
- let allMatch = true;
1962
- for (const token of tokens) {
1963
- const score = fuzzyMatchLower(token, text);
1964
- if (score !== null) totalScore += score;
1965
- else {
1966
- allMatch = false;
1967
- break;
1968
- }
1969
- }
1970
- if (allMatch) results.push({
1971
- item,
1972
- score: totalScore
1973
- });
1974
- }
1975
- results.sort((a, b) => a.score - b.score);
1976
- return results.map((r) => r.item);
1977
- }
1978
- /**
1979
- * Prepare items for fuzzy filtering by pre-computing lowercase search text.
1980
- */
1981
- function prepareSearchItems(items) {
1982
- return items.map((item) => {
1983
- const parts = [];
1984
- if (item.label) parts.push(item.label);
1985
- if (item.description) parts.push(item.description);
1986
- if (item.searchText) parts.push(item.searchText);
1987
- return {
1988
- ...item,
1989
- searchTextLower: normalizeLowercaseStringOrEmpty(parts.join(" "))
1990
- };
1991
- });
1992
- }
1993
- //#endregion
1994
- //#region src/tui/components/filterable-select-list.ts
1995
- /**
1996
- * Combines text input filtering with a select list.
1997
- * User types to filter, arrows/j/k to navigate, Enter to select, Escape to clear/cancel.
1998
- */
1999
- var FilterableSelectList = class {
2000
- constructor(items, maxVisible, theme) {
2001
- this.filterText = "";
2002
- this.allItems = prepareSearchItems(items);
2003
- this.maxVisible = maxVisible;
2004
- this.theme = theme;
2005
- this.input = new Input();
2006
- this.selectList = new SelectList(this.allItems, maxVisible, theme);
2007
- }
2008
- applyFilter() {
2009
- const queryLower = normalizeLowercaseStringOrEmpty(this.filterText);
2010
- if (!queryLower.trim()) {
2011
- this.selectList = new SelectList(this.allItems, this.maxVisible, this.theme);
2012
- return;
2013
- }
2014
- const filtered = fuzzyFilterLower(this.allItems, queryLower);
2015
- this.selectList = new SelectList(filtered, this.maxVisible, this.theme);
2016
- }
2017
- invalidate() {
2018
- this.input.invalidate();
2019
- this.selectList.invalidate();
2020
- }
2021
- render(width) {
2022
- const lines = [];
2023
- const filterLabel = this.theme.filterLabel("Filter: ");
2024
- const inputText = this.input.render(width - 8)[0] ?? "";
2025
- lines.push(filterLabel + inputText);
2026
- lines.push(chalk.dim("─".repeat(Math.max(0, width))));
2027
- const listLines = this.selectList.render(width);
2028
- lines.push(...listLines);
2029
- return lines;
2030
- }
2031
- handleInput(keyData) {
2032
- const allowVimNav = !this.filterText.trim();
2033
- if (matchesKey(keyData, "up") || matchesKey(keyData, "ctrl+p") || allowVimNav && keyData === "k") {
2034
- this.selectList.handleInput("\x1B[A");
2035
- return;
2036
- }
2037
- if (matchesKey(keyData, "down") || matchesKey(keyData, "ctrl+n") || allowVimNav && keyData === "j") {
2038
- this.selectList.handleInput("\x1B[B");
2039
- return;
2040
- }
2041
- if (matchesKey(keyData, "enter")) {
2042
- const selected = this.selectList.getSelectedItem();
2043
- if (selected) this.onSelect?.(selected);
2044
- return;
2045
- }
2046
- if (matchesKey(keyData, "escape") || keyData === "") {
2047
- if (this.filterText) {
2048
- this.filterText = "";
2049
- this.input.setValue("");
2050
- this.applyFilter();
2051
- } else this.onCancel?.();
2052
- return;
2053
- }
2054
- const prevValue = this.input.getValue();
2055
- this.input.handleInput(keyData);
2056
- const newValue = this.input.getValue();
2057
- if (newValue !== prevValue) {
2058
- this.filterText = newValue;
2059
- this.applyFilter();
2060
- }
2061
- }
2062
- getSelectedItem() {
2063
- return this.selectList.getSelectedItem();
2064
- }
2065
- getFilterText() {
2066
- return this.filterText;
2067
- }
2068
- };
2069
- //#endregion
2070
- //#region src/tui/components/searchable-select-list.ts
2071
- const ANSI_SGR_REGEX = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g");
2072
- /**
2073
- * A select list with a search input at the top for fuzzy filtering.
2074
- */
2075
- var SearchableSelectList = class SearchableSelectList {
2076
- static {
2077
- this.DESCRIPTION_LAYOUT_MIN_WIDTH = 40;
2078
- }
2079
- static {
2080
- this.DESCRIPTION_MIN_WIDTH = 12;
2081
- }
2082
- static {
2083
- this.DESCRIPTION_SPACING_WIDTH = 2;
2084
- }
2085
- static {
2086
- this.RIGHT_MARGIN_WIDTH = 2;
2087
- }
2088
- constructor(items, maxVisible, theme) {
2089
- this.selectedIndex = 0;
2090
- this.regexCache = /* @__PURE__ */ new Map();
2091
- this.compareByScore = (a, b) => {
2092
- if (a.tier !== b.tier) return a.tier - b.tier;
2093
- if (a.score !== b.score) return a.score - b.score;
2094
- return this.getItemLabel(a.item).localeCompare(this.getItemLabel(b.item));
2095
- };
2096
- this.items = items;
2097
- this.filteredItems = items;
2098
- this.maxVisible = maxVisible;
2099
- this.theme = theme;
2100
- this.searchInput = new Input();
2101
- }
2102
- getCachedRegex(pattern) {
2103
- let regex = this.regexCache.get(pattern);
2104
- if (!regex) {
2105
- regex = new RegExp(this.escapeRegex(pattern), "gi");
2106
- this.regexCache.set(pattern, regex);
2107
- }
2108
- return regex;
2109
- }
2110
- updateFilter() {
2111
- const query = this.searchInput.getValue().trim();
2112
- if (!query) this.filteredItems = this.items;
2113
- else this.filteredItems = this.smartFilter(query);
2114
- this.selectedIndex = 0;
2115
- this.notifySelectionChange();
2116
- }
2117
- /**
2118
- * Smart filtering that prioritizes:
2119
- * 1. Exact substring match in label (highest priority)
2120
- * 2. Word-boundary prefix match in label
2121
- * 3. Exact substring in description
2122
- * 4. Fuzzy match (lowest priority)
2123
- */
2124
- smartFilter(query) {
2125
- const q = normalizeLowercaseStringOrEmpty(query);
2126
- const scoredItems = [];
2127
- const fuzzyCandidates = [];
2128
- for (const item of this.items) {
2129
- const rawLabel = this.getItemLabel(item);
2130
- const rawDesc = item.description ?? "";
2131
- const label = normalizeLowercaseStringOrEmpty(stripAnsi$1(rawLabel));
2132
- const desc = normalizeLowercaseStringOrEmpty(stripAnsi$1(rawDesc));
2133
- const labelIndex = label.indexOf(q);
2134
- if (labelIndex !== -1) {
2135
- scoredItems.push({
2136
- item,
2137
- tier: 0,
2138
- score: labelIndex
2139
- });
2140
- continue;
2141
- }
2142
- const wordBoundaryIndex = findWordBoundaryIndex(label, q);
2143
- if (wordBoundaryIndex !== null) {
2144
- scoredItems.push({
2145
- item,
2146
- tier: 1,
2147
- score: wordBoundaryIndex
2148
- });
2149
- continue;
2150
- }
2151
- const descIndex = desc.indexOf(q);
2152
- if (descIndex !== -1) {
2153
- scoredItems.push({
2154
- item,
2155
- tier: 2,
2156
- score: descIndex
2157
- });
2158
- continue;
2159
- }
2160
- const searchText = item.searchText ?? "";
2161
- fuzzyCandidates.push({
2162
- item,
2163
- searchTextLower: normalizeLowercaseStringOrEmpty([
2164
- rawLabel,
2165
- rawDesc,
2166
- searchText
2167
- ].map((value) => stripAnsi$1(value)).filter(Boolean).join(" "))
2168
- });
2169
- }
2170
- scoredItems.sort(this.compareByScore);
2171
- const fuzzyMatches = fuzzyFilterLower(fuzzyCandidates, q);
2172
- return [...scoredItems.map((s) => s.item), ...fuzzyMatches.map((entry) => entry.item)];
2173
- }
2174
- escapeRegex(str) {
2175
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2176
- }
2177
- getItemLabel(item) {
2178
- return item.label || item.value;
2179
- }
2180
- splitAnsiParts(text) {
2181
- const parts = [];
2182
- ANSI_SGR_REGEX.lastIndex = 0;
2183
- let lastIndex = 0;
2184
- let match;
2185
- while ((match = ANSI_SGR_REGEX.exec(text)) !== null) {
2186
- if (match.index > lastIndex) parts.push({
2187
- text: text.slice(lastIndex, match.index),
2188
- isAnsi: false
2189
- });
2190
- parts.push({
2191
- text: match[0],
2192
- isAnsi: true
2193
- });
2194
- lastIndex = match.index + match[0].length;
2195
- }
2196
- if (lastIndex < text.length) parts.push({
2197
- text: text.slice(lastIndex),
2198
- isAnsi: false
2199
- });
2200
- return parts;
2201
- }
2202
- highlightMatch(text, query) {
2203
- const tokens = query.trim().split(/\s+/).map((token) => normalizeLowercaseStringOrEmpty(token)).filter((token) => token.length > 0);
2204
- if (tokens.length === 0) return text;
2205
- const uniqueTokens = Array.from(new Set(tokens)).toSorted((a, b) => b.length - a.length);
2206
- let parts = this.splitAnsiParts(text);
2207
- for (const token of uniqueTokens) {
2208
- const regex = this.getCachedRegex(token);
2209
- const nextParts = [];
2210
- for (const part of parts) {
2211
- if (part.isAnsi) {
2212
- nextParts.push(part);
2213
- continue;
2214
- }
2215
- regex.lastIndex = 0;
2216
- const replaced = part.text.replace(regex, (match) => this.theme.matchHighlight(match));
2217
- if (replaced === part.text) {
2218
- nextParts.push(part);
2219
- continue;
2220
- }
2221
- nextParts.push(...this.splitAnsiParts(replaced));
2222
- }
2223
- parts = nextParts;
2224
- }
2225
- return parts.map((part) => part.text).join("");
2226
- }
2227
- setSelectedIndex(index) {
2228
- this.selectedIndex = Math.max(0, Math.min(index, this.filteredItems.length - 1));
2229
- }
2230
- invalidate() {
2231
- this.searchInput.invalidate();
2232
- }
2233
- render(width) {
2234
- const lines = [];
2235
- const prompt = this.theme.searchPrompt("search: ");
2236
- const inputWidth = Math.max(1, width - visibleWidth(prompt));
2237
- const inputText = this.searchInput.render(inputWidth)[0] ?? "";
2238
- lines.push(`${prompt}${this.theme.searchInput(inputText)}`);
2239
- lines.push("");
2240
- const query = this.searchInput.getValue().trim();
2241
- if (this.filteredItems.length === 0) {
2242
- lines.push(this.theme.noMatch(" No matches"));
2243
- return lines;
2244
- }
2245
- const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible));
2246
- const endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);
2247
- for (let i = startIndex; i < endIndex; i++) {
2248
- const item = this.filteredItems[i];
2249
- if (!item) continue;
2250
- const isSelected = i === this.selectedIndex;
2251
- lines.push(this.renderItemLine(item, isSelected, width, query));
2252
- }
2253
- if (this.filteredItems.length > this.maxVisible) {
2254
- const scrollInfo = `${this.selectedIndex + 1}/${this.filteredItems.length}`;
2255
- lines.push(this.theme.scrollInfo(` ${scrollInfo}`));
2256
- }
2257
- return lines;
2258
- }
2259
- renderItemLine(item, isSelected, width, query) {
2260
- const prefix = isSelected ? "→ " : " ";
2261
- const prefixWidth = prefix.length;
2262
- const displayValue = this.getItemLabel(item);
2263
- const description = item.description;
2264
- if (description) {
2265
- const descriptionLayout = this.getDescriptionLayout(width, prefixWidth);
2266
- if (descriptionLayout) {
2267
- const truncatedValue = truncateToWidth(displayValue, descriptionLayout.maxValueWidth, "");
2268
- const valueText = this.highlightMatch(truncatedValue, query);
2269
- const usedByValue = visibleWidth(valueText);
2270
- const descriptionWidth = descriptionLayout.availableWidth - usedByValue - descriptionLayout.spacingWidth;
2271
- if (descriptionWidth >= SearchableSelectList.DESCRIPTION_MIN_WIDTH) {
2272
- const spacing = " ".repeat(descriptionLayout.spacingWidth);
2273
- const truncatedDesc = truncateToWidth(description, descriptionWidth, "");
2274
- const highlightedDesc = this.highlightMatch(truncatedDesc, query);
2275
- const line = `${prefix}${valueText}${spacing}${isSelected ? highlightedDesc : this.theme.description(highlightedDesc)}`;
2276
- return isSelected ? this.theme.selectedText(line) : line;
2277
- }
2278
- }
2279
- }
2280
- const truncatedValue = truncateToWidth(displayValue, width - prefixWidth - 2, "");
2281
- const line = `${prefix}${this.highlightMatch(truncatedValue, query)}`;
2282
- return isSelected ? this.theme.selectedText(line) : line;
2283
- }
2284
- getDescriptionLayout(width, prefixWidth) {
2285
- if (width <= SearchableSelectList.DESCRIPTION_LAYOUT_MIN_WIDTH) return null;
2286
- const availableWidth = Math.max(1, width - prefixWidth - SearchableSelectList.RIGHT_MARGIN_WIDTH);
2287
- const maxValueWidth = availableWidth - SearchableSelectList.DESCRIPTION_MIN_WIDTH - SearchableSelectList.DESCRIPTION_SPACING_WIDTH;
2288
- if (maxValueWidth < 1) return null;
2289
- return {
2290
- availableWidth,
2291
- maxValueWidth,
2292
- spacingWidth: SearchableSelectList.DESCRIPTION_SPACING_WIDTH
2293
- };
2294
- }
2295
- handleInput(keyData) {
2296
- if (isKeyRelease(keyData)) return;
2297
- if (matchesKey(keyData, "up") || matchesKey(keyData, "ctrl+p")) {
2298
- this.selectedIndex = Math.max(0, this.selectedIndex - 1);
2299
- this.notifySelectionChange();
2300
- return;
2301
- }
2302
- if (matchesKey(keyData, "down") || matchesKey(keyData, "ctrl+n")) {
2303
- this.selectedIndex = Math.min(this.filteredItems.length - 1, this.selectedIndex + 1);
2304
- this.notifySelectionChange();
2305
- return;
2306
- }
2307
- if (matchesKey(keyData, "enter")) {
2308
- const item = this.filteredItems[this.selectedIndex];
2309
- if (item && this.onSelect) this.onSelect(item);
2310
- return;
2311
- }
2312
- if (matchesKey(keyData, "escape") || keyData === "") {
2313
- if (this.onCancel) this.onCancel();
2314
- return;
2315
- }
2316
- const prevValue = this.searchInput.getValue();
2317
- this.searchInput.handleInput(keyData);
2318
- if (prevValue !== this.searchInput.getValue()) this.updateFilter();
2319
- }
2320
- notifySelectionChange() {
2321
- const item = this.filteredItems[this.selectedIndex];
2322
- if (item && this.onSelectionChange) this.onSelectionChange(item);
2323
- }
2324
- getSelectedItem() {
2325
- return this.filteredItems[this.selectedIndex] ?? null;
2326
- }
2327
- };
2328
- //#endregion
2329
- //#region src/tui/components/selectors.ts
2330
- function createSearchableSelectList(items, maxVisible = 7) {
2331
- return new SearchableSelectList(items, maxVisible, searchableSelectListTheme);
2332
- }
2333
- function createFilterableSelectList(items, maxVisible = 7) {
2334
- return new FilterableSelectList(items, maxVisible, filterableSelectListTheme);
2335
- }
2336
- function createSettingsList(items, onChange, onCancel, maxVisible = 7) {
2337
- return new SettingsList(items, maxVisible, settingsListTheme, onChange, onCancel);
2338
- }
2339
- //#endregion
2340
- //#region src/tui/tui-status-summary.ts
2341
- function formatStatusSummary(summary) {
2342
- const lines = [];
2343
- lines.push("Gateway status");
2344
- if (summary.runtimeVersion) lines.push(`Version: ${summary.runtimeVersion}`);
2345
- if (!summary.linkChannel) lines.push("Link channel: unknown");
2346
- else {
2347
- const linkLabel = summary.linkChannel.label ?? "Link channel";
2348
- const linked = summary.linkChannel.linked === true;
2349
- const authAge = linked && typeof summary.linkChannel.authAgeMs === "number" ? ` (last refreshed ${formatTimeAgo(summary.linkChannel.authAgeMs)})` : "";
2350
- lines.push(`${linkLabel}: ${linked ? "linked" : "not linked"}${authAge}`);
2351
- }
2352
- const providerSummary = Array.isArray(summary.providerSummary) ? summary.providerSummary : [];
2353
- if (providerSummary.length > 0) {
2354
- lines.push("");
2355
- lines.push("System:");
2356
- for (const line of providerSummary) lines.push(` ${line}`);
2357
- }
2358
- const heartbeatAgents = summary.heartbeat?.agents ?? [];
2359
- if (heartbeatAgents.length > 0) {
2360
- const heartbeatParts = heartbeatAgents.map((agent) => {
2361
- const agentId = agent.agentId ?? "unknown";
2362
- if (!agent.enabled || !agent.everyMs) return `disabled (${agentId})`;
2363
- return `${agent.every ?? "unknown"} (${agentId})`;
2364
- });
2365
- lines.push("");
2366
- lines.push(`Heartbeat: ${heartbeatParts.join(", ")}`);
2367
- }
2368
- const sessionPaths = summary.sessions?.paths ?? [];
2369
- if (sessionPaths.length === 1) lines.push(`Session store: ${sessionPaths[0]}`);
2370
- else if (sessionPaths.length > 1) lines.push(`Session stores: ${sessionPaths.length}`);
2371
- const defaults = summary.sessions?.defaults;
2372
- const defaultModel = defaults?.model ?? "unknown";
2373
- const defaultCtx = typeof defaults?.contextTokens === "number" ? ` (${formatTokenCount(defaults.contextTokens)} ctx)` : "";
2374
- lines.push(`Default model: ${defaultModel}${defaultCtx}`);
2375
- const sessionCount = summary.sessions?.count ?? 0;
2376
- lines.push(`Active sessions: ${sessionCount}`);
2377
- const recent = Array.isArray(summary.sessions?.recent) ? summary.sessions?.recent : [];
2378
- if (recent.length > 0) {
2379
- lines.push("Recent sessions:");
2380
- for (const entry of recent) {
2381
- const ageLabel = typeof entry.age === "number" ? formatTimeAgo(entry.age) : "no activity";
2382
- const model = entry.model ?? "unknown";
2383
- const usage = formatContextUsageLine({
2384
- total: entry.totalTokens ?? null,
2385
- context: entry.contextTokens ?? null,
2386
- remaining: entry.remainingTokens ?? null,
2387
- percent: entry.percentUsed ?? null
2388
- });
2389
- const flags = entry.flags?.length ? ` | flags: ${entry.flags.join(", ")}` : "";
2390
- lines.push(`- ${entry.key}${entry.kind ? ` [${entry.kind}]` : ""} | ${ageLabel} | model ${model} | ${usage}${flags}`);
2391
- }
2392
- }
2393
- const queued = Array.isArray(summary.queuedSystemEvents) ? summary.queuedSystemEvents : [];
2394
- if (queued.length > 0) {
2395
- const preview = queued.slice(0, 3).join(" | ");
2396
- lines.push(`Queued system events (${queued.length}): ${preview}`);
2397
- }
2398
- return lines;
2399
- }
2400
- //#endregion
2401
- //#region src/tui/tui-command-handlers.ts
2402
- function isBtwCommand(text) {
2403
- return /^\/btw(?::|\s|$)/i.test(text.trim());
2404
- }
2405
- function createCommandHandlers(context) {
2406
- const { client, chatLog, tui, opts, state, deliverDefault, openOverlay, closeOverlay, refreshSessionInfo, loadHistory, setSession, refreshAgents, abortActive, setActivityStatus, formatSessionKey, applySessionInfoFromPatch, noteLocalBtwRunId, forgetLocalRunId, forgetLocalBtwRunId, runAuthFlow, requestExit } = context;
2407
- const setAgent = async (id) => {
2408
- state.currentAgentId = normalizeAgentId(id);
2409
- await setSession("");
2410
- };
2411
- const closeOverlayAndRender = () => {
2412
- closeOverlay();
2413
- tui.requestRender();
2414
- };
2415
- const openSelector = (selector, onSelect) => {
2416
- selector.onSelect = (item) => {
2417
- (async () => {
2418
- await onSelect(item.value);
2419
- closeOverlayAndRender();
2420
- })();
2421
- };
2422
- selector.onCancel = closeOverlayAndRender;
2423
- openOverlay(selector);
2424
- tui.requestRender();
2425
- };
2426
- const openModelSelector = async () => {
2427
- try {
2428
- const models = await client.listModels();
2429
- if (models.length === 0) {
2430
- chatLog.addSystem("no models available");
2431
- tui.requestRender();
2432
- return;
2433
- }
2434
- openSelector(createSearchableSelectList(models.map((model) => ({
2435
- value: `${model.provider}/${model.id}`,
2436
- label: `${model.provider}/${model.id}`,
2437
- description: model.name && model.name !== model.id ? model.name : ""
2438
- })), 9), async (value) => {
2439
- try {
2440
- const result = await client.patchSession({
2441
- key: state.currentSessionKey,
2442
- model: value
2443
- });
2444
- chatLog.addSystem(`model set to ${value}`);
2445
- applySessionInfoFromPatch(result);
2446
- await refreshSessionInfo();
2447
- } catch (err) {
2448
- chatLog.addSystem(`model set failed: ${String(err)}`);
2449
- }
2450
- });
2451
- } catch (err) {
2452
- chatLog.addSystem(`model list failed: ${String(err)}`);
2453
- tui.requestRender();
2454
- }
2455
- };
2456
- const openAgentSelector = async () => {
2457
- await refreshAgents();
2458
- if (state.agents.length === 0) {
2459
- chatLog.addSystem("no agents found");
2460
- tui.requestRender();
2461
- return;
2462
- }
2463
- openSelector(createSearchableSelectList(state.agents.map((agent) => ({
2464
- value: agent.id,
2465
- label: agent.name ? `${agent.id} (${agent.name})` : agent.id,
2466
- description: agent.id === state.agentDefaultId ? "default" : ""
2467
- })), 9), async (value) => {
2468
- await setAgent(value);
2469
- });
2470
- };
2471
- const openSessionSelector = async () => {
2472
- try {
2473
- openSelector(createFilterableSelectList((await client.listSessions({
2474
- includeGlobal: false,
2475
- includeUnknown: false,
2476
- includeDerivedTitles: true,
2477
- includeLastMessage: true,
2478
- agentId: state.currentAgentId
2479
- })).sessions.map((session) => {
2480
- const title = session.derivedTitle ?? session.displayName;
2481
- const formattedKey = formatSessionKey(session.key);
2482
- const label = title && title !== formattedKey ? `${title} (${formattedKey})` : formattedKey;
2483
- const timePart = session.updatedAt ? formatRelativeTimestamp(session.updatedAt, {
2484
- dateFallback: true,
2485
- fallback: ""
2486
- }) : "";
2487
- const preview = session.lastMessagePreview?.replace(/\s+/g, " ").trim();
2488
- const description = timePart && preview ? `${timePart} · ${preview}` : preview ?? timePart;
2489
- return {
2490
- value: session.key,
2491
- label,
2492
- description,
2493
- searchText: [
2494
- session.displayName,
2495
- session.label,
2496
- session.subject,
2497
- session.sessionId,
2498
- session.key,
2499
- session.lastMessagePreview
2500
- ].filter(Boolean).join(" ")
2501
- };
2502
- }), 9), async (value) => {
2503
- await setSession(value);
2504
- });
2505
- } catch (err) {
2506
- chatLog.addSystem(`sessions list failed: ${String(err)}`);
2507
- tui.requestRender();
2508
- }
2509
- };
2510
- const openSettings = () => {
2511
- openOverlay(createSettingsList([{
2512
- id: "tools",
2513
- label: "Tool output",
2514
- currentValue: state.toolsExpanded ? "expanded" : "collapsed",
2515
- values: ["collapsed", "expanded"]
2516
- }, {
2517
- id: "thinking",
2518
- label: "Show thinking",
2519
- currentValue: state.showThinking ? "on" : "off",
2520
- values: ["off", "on"]
2521
- }], (id, value) => {
2522
- if (id === "tools") {
2523
- state.toolsExpanded = value === "expanded";
2524
- chatLog.setToolsExpanded(state.toolsExpanded);
2525
- }
2526
- if (id === "thinking") {
2527
- state.showThinking = value === "on";
2528
- loadHistory();
2529
- }
2530
- tui.requestRender();
2531
- }, () => {
2532
- closeOverlay();
2533
- tui.requestRender();
2534
- }));
2535
- tui.requestRender();
2536
- };
2537
- const handleCommand = async (raw) => {
2538
- const { name, args } = parseCommand(raw);
2539
- if (!name) return;
2540
- switch (name) {
2541
- case "help":
2542
- chatLog.addSystem(helpText({
2543
- local: opts.local,
2544
- provider: state.sessionInfo.modelProvider,
2545
- model: state.sessionInfo.model
2546
- }));
2547
- break;
2548
- case "auth": {
2549
- if (!runAuthFlow) {
2550
- chatLog.addSystem("auth login is only available in local embedded mode");
2551
- break;
2552
- }
2553
- if (state.activeChatRunId || state.pendingOptimisticUserMessage) {
2554
- chatLog.addSystem("abort the current run before /auth");
2555
- break;
2556
- }
2557
- const provider = args.trim() || state.sessionInfo.modelProvider || void 0;
2558
- chatLog.addSystem(provider ? `opening auth flow for ${provider}; TUI will resume when it exits` : "opening auth flow; TUI will resume when it exits");
2559
- tui.requestRender();
2560
- setActivityStatus("auth");
2561
- try {
2562
- const result = await runAuthFlow({ provider });
2563
- await refreshSessionInfo();
2564
- if (result.exitCode === 0 && !result.signal) {
2565
- chatLog.addSystem(provider ? `auth flow finished for ${provider}` : "auth flow finished");
2566
- setActivityStatus("idle");
2567
- } else {
2568
- const failureSuffix = result.signal ? ` (signal ${result.signal})` : typeof result.exitCode === "number" ? ` (exit ${String(result.exitCode)})` : "";
2569
- chatLog.addSystem(`auth flow failed${failureSuffix}`);
2570
- setActivityStatus("error");
2571
- }
2572
- } catch (err) {
2573
- chatLog.addSystem(`auth flow failed: ${sanitizeRenderableText(String(err))}`);
2574
- setActivityStatus("error");
2575
- }
2576
- break;
2577
- }
2578
- case "gateway-status":
2579
- try {
2580
- const status = await client.getGatewayStatus();
2581
- if (typeof status === "string") {
2582
- chatLog.addSystem(status);
2583
- break;
2584
- }
2585
- if (status && typeof status === "object") {
2586
- const lines = formatStatusSummary(status);
2587
- for (const line of lines) chatLog.addSystem(line);
2588
- break;
2589
- }
2590
- chatLog.addSystem("status: unknown response");
2591
- } catch (err) {
2592
- chatLog.addSystem(`status failed: ${String(err)}`);
2593
- }
2594
- break;
2595
- case "agent":
2596
- if (!args) await openAgentSelector();
2597
- else await setAgent(args);
2598
- break;
2599
- case "agents":
2600
- await openAgentSelector();
2601
- break;
2602
- case "session":
2603
- if (!args) await openSessionSelector();
2604
- else await setSession(args);
2605
- break;
2606
- case "sessions":
2607
- await openSessionSelector();
2608
- break;
2609
- case "model":
2610
- if (!args) await openModelSelector();
2611
- else try {
2612
- const result = await client.patchSession({
2613
- key: state.currentSessionKey,
2614
- model: args
2615
- });
2616
- chatLog.addSystem(`model set to ${args}`);
2617
- applySessionInfoFromPatch(result);
2618
- await refreshSessionInfo();
2619
- } catch (err) {
2620
- chatLog.addSystem(`model set failed: ${String(err)}`);
2621
- }
2622
- break;
2623
- case "models":
2624
- await openModelSelector();
2625
- break;
2626
- case "think":
2627
- if (!args) {
2628
- const levels = formatThinkingLevels(state.sessionInfo.modelProvider, state.sessionInfo.model, "|");
2629
- chatLog.addSystem(`usage: /think <${levels}>`);
2630
- break;
2631
- }
2632
- try {
2633
- const result = await client.patchSession({
2634
- key: state.currentSessionKey,
2635
- thinkingLevel: args
2636
- });
2637
- chatLog.addSystem(`thinking set to ${args}`);
2638
- applySessionInfoFromPatch(result);
2639
- await refreshSessionInfo();
2640
- } catch (err) {
2641
- chatLog.addSystem(`think failed: ${String(err)}`);
2642
- }
2643
- break;
2644
- case "verbose":
2645
- if (!args) {
2646
- chatLog.addSystem("usage: /verbose <on|off>");
2647
- break;
2648
- }
2649
- try {
2650
- const result = await client.patchSession({
2651
- key: state.currentSessionKey,
2652
- verboseLevel: args
2653
- });
2654
- chatLog.addSystem(`verbose set to ${args}`);
2655
- applySessionInfoFromPatch(result);
2656
- await loadHistory();
2657
- } catch (err) {
2658
- chatLog.addSystem(`verbose failed: ${String(err)}`);
2659
- }
2660
- break;
2661
- case "trace":
2662
- if (!args) {
2663
- chatLog.addSystem("usage: /trace <on|off>");
2664
- break;
2665
- }
2666
- try {
2667
- const result = await client.patchSession({
2668
- key: state.currentSessionKey,
2669
- traceLevel: args
2670
- });
2671
- chatLog.addSystem(`trace set to ${args}`);
2672
- applySessionInfoFromPatch(result);
2673
- await loadHistory();
2674
- } catch (err) {
2675
- chatLog.addSystem(`trace failed: ${String(err)}`);
2676
- }
2677
- break;
2678
- case "fast":
2679
- if (!args || args === "status") {
2680
- chatLog.addSystem(`fast mode: ${state.sessionInfo.fastMode ? "on" : "off"}`);
2681
- break;
2682
- }
2683
- if (args !== "on" && args !== "off") {
2684
- chatLog.addSystem("usage: /fast <status|on|off>");
2685
- break;
2686
- }
2687
- try {
2688
- const result = await client.patchSession({
2689
- key: state.currentSessionKey,
2690
- fastMode: args === "on"
2691
- });
2692
- chatLog.addSystem(`fast mode ${args === "on" ? "enabled" : "disabled"}`);
2693
- applySessionInfoFromPatch(result);
2694
- await refreshSessionInfo();
2695
- } catch (err) {
2696
- chatLog.addSystem(`fast failed: ${String(err)}`);
2697
- }
2698
- break;
2699
- case "reasoning":
2700
- if (!args) {
2701
- chatLog.addSystem("usage: /reasoning <on|off>");
2702
- break;
2703
- }
2704
- try {
2705
- const result = await client.patchSession({
2706
- key: state.currentSessionKey,
2707
- reasoningLevel: args
2708
- });
2709
- chatLog.addSystem(`reasoning set to ${args}`);
2710
- applySessionInfoFromPatch(result);
2711
- await refreshSessionInfo();
2712
- } catch (err) {
2713
- chatLog.addSystem(`reasoning failed: ${String(err)}`);
2714
- }
2715
- break;
2716
- case "usage": {
2717
- const normalized = args ? normalizeUsageDisplay(args) : void 0;
2718
- if (args && !normalized) {
2719
- chatLog.addSystem("usage: /usage <off|tokens|full>");
2720
- break;
2721
- }
2722
- const currentRaw = state.sessionInfo.responseUsage;
2723
- const current = resolveResponseUsageMode(currentRaw);
2724
- const next = normalized ?? (current === "off" ? "tokens" : current === "tokens" ? "full" : "off");
2725
- try {
2726
- const result = await client.patchSession({
2727
- key: state.currentSessionKey,
2728
- responseUsage: next === "off" ? null : next
2729
- });
2730
- chatLog.addSystem(`usage footer: ${next}`);
2731
- applySessionInfoFromPatch(result);
2732
- await refreshSessionInfo();
2733
- } catch (err) {
2734
- chatLog.addSystem(`usage failed: ${String(err)}`);
2735
- }
2736
- break;
2737
- }
2738
- case "elevated":
2739
- if (!args) {
2740
- chatLog.addSystem("usage: /elevated <on|off|ask|full>");
2741
- break;
2742
- }
2743
- if (![
2744
- "on",
2745
- "off",
2746
- "ask",
2747
- "full"
2748
- ].includes(args)) {
2749
- chatLog.addSystem("usage: /elevated <on|off|ask|full>");
2750
- break;
2751
- }
2752
- try {
2753
- const result = await client.patchSession({
2754
- key: state.currentSessionKey,
2755
- elevatedLevel: args
2756
- });
2757
- chatLog.addSystem(`elevated set to ${args}`);
2758
- applySessionInfoFromPatch(result);
2759
- await refreshSessionInfo();
2760
- } catch (err) {
2761
- chatLog.addSystem(`elevated failed: ${String(err)}`);
2762
- }
2763
- break;
2764
- case "activation": {
2765
- if (!args) {
2766
- chatLog.addSystem("usage: /activation <mention|always>");
2767
- break;
2768
- }
2769
- const activation = normalizeGroupActivation(args);
2770
- if (!activation) {
2771
- chatLog.addSystem("usage: /activation <mention|always>");
2772
- break;
2773
- }
2774
- try {
2775
- const result = await client.patchSession({
2776
- key: state.currentSessionKey,
2777
- groupActivation: activation
2778
- });
2779
- chatLog.addSystem(`activation set to ${activation}`);
2780
- applySessionInfoFromPatch(result);
2781
- await refreshSessionInfo();
2782
- } catch (err) {
2783
- chatLog.addSystem(`activation failed: ${String(err)}`);
2784
- }
2785
- break;
2786
- }
2787
- case "new":
2788
- try {
2789
- state.sessionInfo.inputTokens = null;
2790
- state.sessionInfo.outputTokens = null;
2791
- state.sessionInfo.totalTokens = null;
2792
- tui.requestRender();
2793
- const uniqueKey = `tui-${randomUUID()}`;
2794
- await setSession(uniqueKey);
2795
- chatLog.addSystem(`new session: ${uniqueKey}`);
2796
- } catch (err) {
2797
- chatLog.addSystem(`new session failed: ${sanitizeRenderableText(String(err))}`);
2798
- }
2799
- break;
2800
- case "reset":
2801
- try {
2802
- state.sessionInfo.inputTokens = null;
2803
- state.sessionInfo.outputTokens = null;
2804
- state.sessionInfo.totalTokens = null;
2805
- tui.requestRender();
2806
- await client.resetSession(state.currentSessionKey, name);
2807
- chatLog.addSystem(`session ${state.currentSessionKey} reset`);
2808
- await loadHistory();
2809
- } catch (err) {
2810
- chatLog.addSystem(`reset failed: ${sanitizeRenderableText(String(err))}`);
2811
- }
2812
- break;
2813
- case "abort":
2814
- await abortActive();
2815
- break;
2816
- case "settings":
2817
- openSettings();
2818
- break;
2819
- case "exit":
2820
- case "quit":
2821
- requestExit();
2822
- break;
2823
- default:
2824
- await sendMessage(raw);
2825
- break;
2826
- }
2827
- tui.requestRender();
2828
- };
2829
- const sendMessage = async (text) => {
2830
- if (!state.isConnected) {
2831
- chatLog.addSystem(opts.local ? "local runtime not ready — message not sent" : "not connected to gateway — message not sent");
2832
- setActivityStatus("disconnected");
2833
- tui.requestRender();
2834
- return;
2835
- }
2836
- const isBtw = isBtwCommand(text);
2837
- const runId = randomUUID();
2838
- try {
2839
- if (!isBtw) {
2840
- chatLog.addUser(text);
2841
- state.pendingOptimisticUserMessage = true;
2842
- setActivityStatus("sending");
2843
- } else noteLocalBtwRunId?.(runId);
2844
- tui.requestRender();
2845
- await client.sendChat({
2846
- sessionKey: state.currentSessionKey,
2847
- message: text,
2848
- thinking: opts.thinking,
2849
- deliver: deliverDefault,
2850
- timeoutMs: opts.timeoutMs,
2851
- runId
2852
- });
2853
- if (!isBtw) {
2854
- setActivityStatus("waiting");
2855
- tui.requestRender();
2856
- }
2857
- } catch (err) {
2858
- if (isBtw) forgetLocalBtwRunId?.(runId);
2859
- if (!isBtw && state.activeChatRunId) forgetLocalRunId?.(state.activeChatRunId);
2860
- if (!isBtw) {
2861
- state.pendingOptimisticUserMessage = false;
2862
- state.activeChatRunId = null;
2863
- }
2864
- chatLog.addSystem(`${isBtw ? "btw failed" : "send failed"}: ${String(err)}`);
2865
- if (!isBtw) setActivityStatus("error");
2866
- tui.requestRender();
2867
- }
2868
- };
2869
- return {
2870
- handleCommand,
2871
- sendMessage,
2872
- openModelSelector,
2873
- openAgentSelector,
2874
- openSessionSelector,
2875
- openSettings,
2876
- setAgent
2877
- };
2878
- }
2879
- //#endregion
2880
- //#region src/tui/tui-stream-assembler.ts
2881
- function extractTextBlocksAndSignals(message) {
2882
- if (!message || typeof message !== "object") return {
2883
- textBlocks: [],
2884
- sawNonTextContentBlocks: false
2885
- };
2886
- const content = message.content;
2887
- if (typeof content === "string") {
2888
- const text = content.trim();
2889
- return {
2890
- textBlocks: text ? [text] : [],
2891
- sawNonTextContentBlocks: false
2892
- };
2893
- }
2894
- if (!Array.isArray(content)) return {
2895
- textBlocks: [],
2896
- sawNonTextContentBlocks: false
2897
- };
2898
- const textBlocks = [];
2899
- let sawNonTextContentBlocks = false;
2900
- for (const block of content) {
2901
- if (!block || typeof block !== "object") continue;
2902
- const rec = block;
2903
- if (rec.type === "text" && typeof rec.text === "string") {
2904
- const text = rec.text.trim();
2905
- if (text) textBlocks.push(text);
2906
- continue;
2907
- }
2908
- if (typeof rec.type === "string" && rec.type !== "thinking") sawNonTextContentBlocks = true;
2909
- }
2910
- return {
2911
- textBlocks,
2912
- sawNonTextContentBlocks
2913
- };
2914
- }
2915
- function isDroppedBoundaryTextBlockSubset(params) {
2916
- const { streamedTextBlocks, finalTextBlocks } = params;
2917
- if (finalTextBlocks.length === 0 || finalTextBlocks.length >= streamedTextBlocks.length) return false;
2918
- if (finalTextBlocks.every((block, index) => streamedTextBlocks[index] === block)) return true;
2919
- const suffixStart = streamedTextBlocks.length - finalTextBlocks.length;
2920
- return finalTextBlocks.every((block, index) => streamedTextBlocks[suffixStart + index] === block);
2921
- }
2922
- function shouldPreserveBoundaryDroppedText(params) {
2923
- if (params.boundaryDropMode === "off") return false;
2924
- if (!(params.boundaryDropMode === "streamed-or-incoming" ? params.streamedSawNonTextContentBlocks || params.incomingSawNonTextContentBlocks : params.streamedSawNonTextContentBlocks)) return false;
2925
- return isDroppedBoundaryTextBlockSubset({
2926
- streamedTextBlocks: params.streamedTextBlocks,
2927
- finalTextBlocks: params.nextContentBlocks
2928
- });
2929
- }
2930
- var TuiStreamAssembler = class {
2931
- constructor() {
2932
- this.runs = /* @__PURE__ */ new Map();
2933
- }
2934
- getOrCreateRun(runId) {
2935
- let state = this.runs.get(runId);
2936
- if (!state) {
2937
- state = {
2938
- thinkingText: "",
2939
- contentText: "",
2940
- contentBlocks: [],
2941
- sawNonTextContentBlocks: false,
2942
- displayText: ""
2943
- };
2944
- this.runs.set(runId, state);
2945
- }
2946
- return state;
2947
- }
2948
- updateRunState(state, message, showThinking, opts) {
2949
- const thinkingText = extractThinkingFromMessage(message);
2950
- const contentText = extractContentFromMessage(message);
2951
- const { textBlocks, sawNonTextContentBlocks } = extractTextBlocksAndSignals(message);
2952
- if (thinkingText) state.thinkingText = thinkingText;
2953
- if (contentText) {
2954
- const nextContentBlocks = textBlocks.length > 0 ? textBlocks : [contentText];
2955
- if (!shouldPreserveBoundaryDroppedText({
2956
- boundaryDropMode: opts?.boundaryDropMode ?? "off",
2957
- streamedSawNonTextContentBlocks: state.sawNonTextContentBlocks,
2958
- incomingSawNonTextContentBlocks: sawNonTextContentBlocks,
2959
- streamedTextBlocks: state.contentBlocks,
2960
- nextContentBlocks
2961
- })) {
2962
- state.contentText = contentText;
2963
- state.contentBlocks = nextContentBlocks;
2964
- }
2965
- }
2966
- if (sawNonTextContentBlocks) state.sawNonTextContentBlocks = true;
2967
- state.displayText = composeThinkingAndContent({
2968
- thinkingText: state.thinkingText,
2969
- contentText: state.contentText,
2970
- showThinking
2971
- });
2972
- }
2973
- ingestDelta(runId, message, showThinking) {
2974
- const state = this.getOrCreateRun(runId);
2975
- const previousDisplayText = state.displayText;
2976
- this.updateRunState(state, message, showThinking, { boundaryDropMode: "streamed-or-incoming" });
2977
- if (!state.displayText || state.displayText === previousDisplayText) return null;
2978
- return state.displayText;
2979
- }
2980
- finalize(runId, message, showThinking, errorMessage) {
2981
- const state = this.getOrCreateRun(runId);
2982
- const streamedDisplayText = state.displayText;
2983
- const streamedTextBlocks = [...state.contentBlocks];
2984
- const streamedSawNonTextContentBlocks = state.sawNonTextContentBlocks;
2985
- this.updateRunState(state, message, showThinking, { boundaryDropMode: "streamed-only" });
2986
- const finalComposed = state.displayText;
2987
- const finalText = resolveFinalAssistantText({
2988
- finalText: streamedSawNonTextContentBlocks && isDroppedBoundaryTextBlockSubset({
2989
- streamedTextBlocks,
2990
- finalTextBlocks: state.contentBlocks
2991
- }) ? streamedDisplayText : finalComposed,
2992
- streamedText: streamedDisplayText,
2993
- errorMessage
2994
- });
2995
- this.runs.delete(runId);
2996
- return finalText;
2997
- }
2998
- drop(runId) {
2999
- this.runs.delete(runId);
3000
- }
3001
- };
3002
- //#endregion
3003
- //#region src/tui/tui-event-handlers.ts
3004
- const DEFAULT_STREAMING_WATCHDOG_MS = 3e4;
3005
- function createEventHandlers(context) {
3006
- const { chatLog, btw, tui, state, setActivityStatus, refreshSessionInfo, loadHistory, noteLocalRunId, isLocalRunId, forgetLocalRunId, clearLocalRunIds, isLocalBtwRunId, forgetLocalBtwRunId, clearLocalBtwRunIds, localMode } = context;
3007
- const finalizedRuns = /* @__PURE__ */ new Map();
3008
- const sessionRuns = /* @__PURE__ */ new Map();
3009
- let streamAssembler = new TuiStreamAssembler();
3010
- let lastSessionKey = state.currentSessionKey;
3011
- let pendingHistoryRefresh = false;
3012
- const streamingWatchdogMs = typeof context.streamingWatchdogMs === "number" && Number.isFinite(context.streamingWatchdogMs) && context.streamingWatchdogMs >= 0 ? Math.floor(context.streamingWatchdogMs) : DEFAULT_STREAMING_WATCHDOG_MS;
3013
- let streamingWatchdogTimer = null;
3014
- let streamingWatchdogRunId = null;
3015
- const clearStreamingWatchdog = () => {
3016
- if (streamingWatchdogTimer) {
3017
- clearTimeout(streamingWatchdogTimer);
3018
- streamingWatchdogTimer = null;
3019
- }
3020
- streamingWatchdogRunId = null;
3021
- };
3022
- const armStreamingWatchdog = (runId) => {
3023
- if (streamingWatchdogMs <= 0) return;
3024
- if (streamingWatchdogTimer) clearTimeout(streamingWatchdogTimer);
3025
- streamingWatchdogRunId = runId;
3026
- streamingWatchdogTimer = setTimeout(() => {
3027
- streamingWatchdogTimer = null;
3028
- if (streamingWatchdogRunId !== runId || state.activeChatRunId !== runId) return;
3029
- streamingWatchdogRunId = null;
3030
- state.activeChatRunId = null;
3031
- setActivityStatus("idle");
3032
- chatLog.addSystem(`streaming watchdog: no stream updates for ${Math.round(streamingWatchdogMs / 1e3)}s; resetting status. The backend may have dropped this run silently — send a new message to resync.`);
3033
- tui.requestRender();
3034
- }, streamingWatchdogMs);
3035
- const maybeUnref = streamingWatchdogTimer.unref;
3036
- if (typeof maybeUnref === "function") maybeUnref.call(streamingWatchdogTimer);
3037
- };
3038
- const pruneRunMap = (runs) => {
3039
- if (runs.size <= 200) return;
3040
- const keepUntil = Date.now() - 600 * 1e3;
3041
- for (const [key, ts] of runs) {
3042
- if (runs.size <= 150) break;
3043
- if (ts < keepUntil) runs.delete(key);
3044
- }
3045
- if (runs.size > 200) for (const key of runs.keys()) {
3046
- runs.delete(key);
3047
- if (runs.size <= 150) break;
3048
- }
3049
- };
3050
- const syncSessionKey = () => {
3051
- if (state.currentSessionKey === lastSessionKey) return;
3052
- lastSessionKey = state.currentSessionKey;
3053
- finalizedRuns.clear();
3054
- sessionRuns.clear();
3055
- streamAssembler = new TuiStreamAssembler();
3056
- pendingHistoryRefresh = false;
3057
- state.pendingOptimisticUserMessage = false;
3058
- clearLocalRunIds?.();
3059
- clearLocalBtwRunIds?.();
3060
- btw.clear();
3061
- clearStreamingWatchdog();
3062
- };
3063
- const flushPendingHistoryRefreshIfIdle = () => {
3064
- if (!pendingHistoryRefresh || state.activeChatRunId) return;
3065
- pendingHistoryRefresh = false;
3066
- loadHistory?.();
3067
- };
3068
- const resolveAuthErrorHint = (errorMessage) => {
3069
- if (!localMode || !isAuthErrorMessage(errorMessage)) return;
3070
- const provider = state.sessionInfo.modelProvider?.trim();
3071
- return provider ? `auth or provider access failed for ${provider}. Run /auth ${provider} to refresh credentials; if you already re-authed, switch models/providers because this account may still be blocked for inference.` : "auth or provider access failed for the current provider. Run /auth to refresh credentials; if you already re-authed, switch models/providers because this account may still be blocked for inference.";
3072
- };
3073
- const noteSessionRun = (runId) => {
3074
- sessionRuns.set(runId, Date.now());
3075
- pruneRunMap(sessionRuns);
3076
- };
3077
- const noteFinalizedRun = (runId) => {
3078
- finalizedRuns.set(runId, Date.now());
3079
- sessionRuns.delete(runId);
3080
- streamAssembler.drop(runId);
3081
- pruneRunMap(finalizedRuns);
3082
- };
3083
- const clearActiveRunIfMatch = (runId) => {
3084
- if (state.activeChatRunId === runId) state.activeChatRunId = null;
3085
- };
3086
- const finalizeRun = (params) => {
3087
- noteFinalizedRun(params.runId);
3088
- clearActiveRunIfMatch(params.runId);
3089
- flushPendingHistoryRefreshIfIdle();
3090
- if (params.wasActiveRun) {
3091
- setActivityStatus(params.status);
3092
- clearStreamingWatchdog();
3093
- } else if (streamingWatchdogRunId === params.runId) clearStreamingWatchdog();
3094
- refreshSessionInfo?.();
3095
- };
3096
- const terminateRun = (params) => {
3097
- streamAssembler.drop(params.runId);
3098
- sessionRuns.delete(params.runId);
3099
- clearActiveRunIfMatch(params.runId);
3100
- flushPendingHistoryRefreshIfIdle();
3101
- if (params.wasActiveRun) {
3102
- setActivityStatus(params.status);
3103
- clearStreamingWatchdog();
3104
- } else if (streamingWatchdogRunId === params.runId) clearStreamingWatchdog();
3105
- refreshSessionInfo?.();
3106
- };
3107
- const hasConcurrentActiveRun = (runId) => {
3108
- const activeRunId = state.activeChatRunId;
3109
- if (!activeRunId || activeRunId === runId) return false;
3110
- return sessionRuns.has(activeRunId);
3111
- };
3112
- const maybeRefreshHistoryForRun = (runId, opts) => {
3113
- if (isLocalRunId?.(runId) ?? false) {
3114
- forgetLocalRunId?.(runId);
3115
- if (!opts?.allowLocalWithoutDisplayableFinal) return;
3116
- if (state.activeChatRunId && state.activeChatRunId !== runId) {
3117
- pendingHistoryRefresh = true;
3118
- return;
3119
- }
3120
- }
3121
- if (hasConcurrentActiveRun(runId)) return;
3122
- pendingHistoryRefresh = false;
3123
- loadHistory?.();
3124
- };
3125
- const isSameSessionKey = (left, right) => {
3126
- const normalizedLeft = normalizeLowercaseStringOrEmpty(left);
3127
- const normalizedRight = normalizeLowercaseStringOrEmpty(right);
3128
- if (!normalizedLeft || !normalizedRight) return false;
3129
- if (normalizedLeft === normalizedRight) return true;
3130
- const parsedLeft = parseAgentSessionKey(normalizedLeft);
3131
- const parsedRight = parseAgentSessionKey(normalizedRight);
3132
- if (parsedLeft && parsedRight) return parsedLeft.agentId === parsedRight.agentId && parsedLeft.rest === parsedRight.rest;
3133
- if (parsedLeft) return parsedLeft.rest === normalizedRight;
3134
- if (parsedRight) return normalizedLeft === parsedRight.rest;
3135
- return false;
3136
- };
3137
- const handleChatEvent = (payload) => {
3138
- if (!payload || typeof payload !== "object") return;
3139
- const evt = payload;
3140
- syncSessionKey();
3141
- if (!isSameSessionKey(evt.sessionKey, state.currentSessionKey)) return;
3142
- if (finalizedRuns.has(evt.runId)) {
3143
- if (evt.state === "delta") return;
3144
- if (evt.state === "final") return;
3145
- }
3146
- noteSessionRun(evt.runId);
3147
- if (!state.activeChatRunId && !isLocalBtwRunId?.(evt.runId)) {
3148
- state.activeChatRunId = evt.runId;
3149
- if (state.pendingOptimisticUserMessage) {
3150
- noteLocalRunId?.(evt.runId);
3151
- state.pendingOptimisticUserMessage = false;
3152
- }
3153
- }
3154
- if (evt.state === "delta") {
3155
- setActivityStatus("streaming");
3156
- if (state.activeChatRunId === evt.runId) armStreamingWatchdog(evt.runId);
3157
- const displayText = streamAssembler.ingestDelta(evt.runId, evt.message, state.showThinking);
3158
- if (!displayText) return;
3159
- chatLog.updateAssistant(displayText, evt.runId);
3160
- }
3161
- if (evt.state === "final") {
3162
- const isLocalBtwRun = isLocalBtwRunId?.(evt.runId) ?? false;
3163
- const wasActiveRun = state.activeChatRunId === evt.runId;
3164
- if (!evt.message && isLocalBtwRun) {
3165
- forgetLocalBtwRunId?.(evt.runId);
3166
- noteFinalizedRun(evt.runId);
3167
- tui.requestRender();
3168
- return;
3169
- }
3170
- if (!evt.message) {
3171
- maybeRefreshHistoryForRun(evt.runId, { allowLocalWithoutDisplayableFinal: true });
3172
- chatLog.dropAssistant(evt.runId);
3173
- finalizeRun({
3174
- runId: evt.runId,
3175
- wasActiveRun,
3176
- status: "idle"
3177
- });
3178
- tui.requestRender();
3179
- return;
3180
- }
3181
- if (isCommandMessage(evt.message)) {
3182
- maybeRefreshHistoryForRun(evt.runId);
3183
- const text = extractTextFromMessage(evt.message);
3184
- if (text) chatLog.addSystem(text);
3185
- finalizeRun({
3186
- runId: evt.runId,
3187
- wasActiveRun,
3188
- status: "idle"
3189
- });
3190
- tui.requestRender();
3191
- return;
3192
- }
3193
- maybeRefreshHistoryForRun(evt.runId);
3194
- const stopReason = evt.message && typeof evt.message === "object" && !Array.isArray(evt.message) ? typeof evt.message.stopReason === "string" ? evt.message.stopReason : "" : "";
3195
- const finalText = streamAssembler.finalize(evt.runId, evt.message, state.showThinking, evt.errorMessage);
3196
- if (finalText === "(no output)" && !isLocalRunId?.(evt.runId)) chatLog.dropAssistant(evt.runId);
3197
- else chatLog.finalizeAssistant(finalText, evt.runId);
3198
- finalizeRun({
3199
- runId: evt.runId,
3200
- wasActiveRun,
3201
- status: stopReason === "error" ? "error" : "idle"
3202
- });
3203
- }
3204
- if (evt.state === "aborted") {
3205
- forgetLocalBtwRunId?.(evt.runId);
3206
- const wasActiveRun = state.activeChatRunId === evt.runId;
3207
- chatLog.addSystem("run aborted");
3208
- terminateRun({
3209
- runId: evt.runId,
3210
- wasActiveRun,
3211
- status: "aborted"
3212
- });
3213
- maybeRefreshHistoryForRun(evt.runId);
3214
- }
3215
- if (evt.state === "error") {
3216
- forgetLocalBtwRunId?.(evt.runId);
3217
- const wasActiveRun = state.activeChatRunId === evt.runId;
3218
- const errorMessage = evt.errorMessage ?? "unknown";
3219
- chatLog.addSystem(resolveAuthErrorHint(errorMessage) ?? `run error: ${errorMessage}`);
3220
- terminateRun({
3221
- runId: evt.runId,
3222
- wasActiveRun,
3223
- status: "error"
3224
- });
3225
- maybeRefreshHistoryForRun(evt.runId);
3226
- }
3227
- tui.requestRender();
3228
- };
3229
- const handleAgentEvent = (payload) => {
3230
- if (!payload || typeof payload !== "object") return;
3231
- const evt = payload;
3232
- syncSessionKey();
3233
- const isActiveRun = evt.runId === state.activeChatRunId;
3234
- if (!(isActiveRun || sessionRuns.has(evt.runId) || finalizedRuns.has(evt.runId))) return;
3235
- if (evt.stream === "tool") {
3236
- const verbose = state.sessionInfo.verboseLevel ?? "off";
3237
- const allowToolEvents = verbose !== "off";
3238
- const allowToolOutput = verbose === "full";
3239
- if (!allowToolEvents) return;
3240
- const data = evt.data ?? {};
3241
- const phase = asString(data.phase, "");
3242
- const toolCallId = asString(data.toolCallId, "");
3243
- const toolName = asString(data.name, "tool");
3244
- if (!toolCallId) return;
3245
- if (phase === "start") chatLog.startTool(toolCallId, toolName, data.args);
3246
- else if (phase === "update") {
3247
- if (!allowToolOutput) return;
3248
- chatLog.updateToolResult(toolCallId, data.partialResult, { partial: true });
3249
- } else if (phase === "result") if (allowToolOutput) chatLog.updateToolResult(toolCallId, data.result, { isError: Boolean(data.isError) });
3250
- else chatLog.updateToolResult(toolCallId, { content: [] }, { isError: Boolean(data.isError) });
3251
- tui.requestRender();
3252
- return;
3253
- }
3254
- if (evt.stream === "lifecycle") {
3255
- if (!isActiveRun) return;
3256
- const phase = typeof evt.data?.phase === "string" ? evt.data.phase : "";
3257
- if (phase === "start") setActivityStatus("running");
3258
- if (phase === "end") setActivityStatus("idle");
3259
- if (phase === "error") setActivityStatus("error");
3260
- tui.requestRender();
3261
- }
3262
- };
3263
- const handleBtwEvent = (payload) => {
3264
- if (!payload || typeof payload !== "object") return;
3265
- const evt = payload;
3266
- syncSessionKey();
3267
- if (!isSameSessionKey(evt.sessionKey, state.currentSessionKey)) return;
3268
- if (evt.kind !== "btw") return;
3269
- const question = evt.question.trim();
3270
- const text = evt.text.trim();
3271
- if (!question || !text) return;
3272
- btw.showResult({
3273
- question,
3274
- text,
3275
- isError: evt.isError
3276
- });
3277
- tui.requestRender();
3278
- };
3279
- const dispose = () => {
3280
- clearStreamingWatchdog();
3281
- };
3282
- return {
3283
- handleChatEvent,
3284
- handleAgentEvent,
3285
- handleBtwEvent,
3286
- dispose
3287
- };
3288
- }
3289
- //#endregion
3290
- //#region src/tui/tui-local-shell.ts
3291
- function createLocalShellRunner(deps) {
3292
- let localExecAsked = false;
3293
- let localExecAllowed = false;
3294
- const createSelector = deps.createSelector ?? createSearchableSelectList;
3295
- const spawnCommand = deps.spawnCommand ?? spawn;
3296
- const getCwd = deps.getCwd ?? (() => process.cwd());
3297
- const env = deps.env ?? process.env;
3298
- const maxChars = deps.maxOutputChars ?? 4e4;
3299
- const ensureLocalExecAllowed = async () => {
3300
- if (localExecAllowed) return true;
3301
- if (localExecAsked) return false;
3302
- localExecAsked = true;
3303
- return await new Promise((resolve) => {
3304
- deps.chatLog.addSystem("Allow local shell commands for this session?");
3305
- deps.chatLog.addSystem("This runs commands on YOUR machine (not the gateway) and may delete files or reveal secrets.");
3306
- deps.chatLog.addSystem("Select Yes/No (arrows + Enter), Esc to cancel.");
3307
- const selector = createSelector([{
3308
- value: "no",
3309
- label: "No"
3310
- }, {
3311
- value: "yes",
3312
- label: "Yes"
3313
- }], 2);
3314
- selector.onSelect = (item) => {
3315
- deps.closeOverlay();
3316
- if (item.value === "yes") {
3317
- localExecAllowed = true;
3318
- deps.chatLog.addSystem("local shell: enabled for this session");
3319
- resolve(true);
3320
- } else {
3321
- deps.chatLog.addSystem("local shell: not enabled");
3322
- resolve(false);
3323
- }
3324
- deps.tui.requestRender();
3325
- };
3326
- selector.onCancel = () => {
3327
- deps.closeOverlay();
3328
- deps.chatLog.addSystem("local shell: cancelled");
3329
- deps.tui.requestRender();
3330
- resolve(false);
3331
- };
3332
- deps.openOverlay(selector);
3333
- deps.tui.requestRender();
3334
- });
3335
- };
3336
- const runLocalShellLine = async (line) => {
3337
- const cmd = line.slice(1);
3338
- if (cmd === "") return;
3339
- if (localExecAsked && !localExecAllowed) {
3340
- deps.chatLog.addSystem("local shell: not enabled for this session");
3341
- deps.tui.requestRender();
3342
- return;
3343
- }
3344
- if (!await ensureLocalExecAllowed()) return;
3345
- deps.chatLog.addSystem(`[local] $ ${cmd}`);
3346
- deps.tui.requestRender();
3347
- const appendWithCap = (text, chunk) => {
3348
- const combined = text + chunk;
3349
- return combined.length > maxChars ? combined.slice(-maxChars) : combined;
3350
- };
3351
- await new Promise((resolve) => {
3352
- const child = spawnCommand(cmd, {
3353
- shell: true,
3354
- cwd: getCwd(),
3355
- env: {
3356
- ...env,
3357
- GENESIS_SHELL: "tui-local"
3358
- }
3359
- });
3360
- let stdout = "";
3361
- let stderr = "";
3362
- child.stdout.on("data", (buf) => {
3363
- stdout = appendWithCap(stdout, buf.toString("utf8"));
3364
- });
3365
- child.stderr.on("data", (buf) => {
3366
- stderr = appendWithCap(stderr, buf.toString("utf8"));
3367
- });
3368
- child.on("close", (code, signal) => {
3369
- const combined = (stdout + (stderr ? (stdout ? "\n" : "") + stderr : "")).slice(0, maxChars).trimEnd();
3370
- if (combined) for (const line of combined.split("\n")) deps.chatLog.addSystem(`[local] ${line}`);
3371
- deps.chatLog.addSystem(`[local] exit ${code ?? "?"}${signal ? ` (signal ${signal})` : ""}`);
3372
- deps.tui.requestRender();
3373
- resolve();
3374
- });
3375
- child.on("error", (err) => {
3376
- deps.chatLog.addSystem(`[local] error: ${String(err)}`);
3377
- deps.tui.requestRender();
3378
- resolve();
3379
- });
3380
- });
3381
- };
3382
- return { runLocalShellLine };
3383
- }
3384
- //#endregion
3385
- //#region src/tui/tui-overlays.ts
3386
- function createOverlayHandlers(host, fallbackFocus) {
3387
- const openOverlay = (component) => {
3388
- host.showOverlay(component);
3389
- };
3390
- const closeOverlay = () => {
3391
- if (host.hasOverlay()) {
3392
- host.hideOverlay();
3393
- return;
3394
- }
3395
- host.setFocus(fallbackFocus);
3396
- };
3397
- return {
3398
- openOverlay,
3399
- closeOverlay
3400
- };
3401
- }
3402
- //#endregion
3403
- //#region src/tui/tui-session-actions.ts
3404
- function createSessionActions(context) {
3405
- const { client, chatLog, btw, tui, opts, state, agentNames, initialSessionInput, initialSessionAgentId, resolveSessionKey, updateHeader, updateFooter, updateAutocompleteProvider, setActivityStatus, clearLocalRunIds } = context;
3406
- let refreshSessionInfoPromise = Promise.resolve();
3407
- let lastSessionDefaults = null;
3408
- const applyAgentsResult = (result) => {
3409
- state.agentDefaultId = normalizeAgentId(result.defaultId);
3410
- state.sessionMainKey = normalizeMainKey(result.mainKey);
3411
- state.sessionScope = result.scope ?? state.sessionScope;
3412
- state.agents = result.agents.map((agent) => ({
3413
- id: normalizeAgentId(agent.id),
3414
- name: normalizeOptionalString(agent.name)
3415
- }));
3416
- agentNames.clear();
3417
- for (const agent of state.agents) if (agent.name) agentNames.set(agent.id, agent.name);
3418
- if (!state.initialSessionApplied) {
3419
- if (initialSessionAgentId) {
3420
- if (state.agents.some((agent) => agent.id === initialSessionAgentId)) state.currentAgentId = initialSessionAgentId;
3421
- } else if (!state.agents.some((agent) => agent.id === state.currentAgentId)) state.currentAgentId = state.agents[0]?.id ?? normalizeAgentId(result.defaultId ?? state.currentAgentId);
3422
- const nextSessionKey = resolveSessionKey(initialSessionInput);
3423
- if (nextSessionKey !== state.currentSessionKey) state.currentSessionKey = nextSessionKey;
3424
- state.initialSessionApplied = true;
3425
- } else if (!state.agents.some((agent) => agent.id === state.currentAgentId)) state.currentAgentId = state.agents[0]?.id ?? normalizeAgentId(result.defaultId ?? state.currentAgentId);
3426
- updateHeader();
3427
- updateFooter();
3428
- };
3429
- const refreshAgents = async () => {
3430
- try {
3431
- applyAgentsResult(await client.listAgents());
3432
- } catch (err) {
3433
- chatLog.addSystem(`agents list failed: ${String(err)}`);
3434
- }
3435
- };
3436
- const updateAgentFromSessionKey = (key) => {
3437
- const parsed = parseAgentSessionKey(key);
3438
- if (!parsed) return;
3439
- const next = normalizeAgentId(parsed.agentId);
3440
- if (next !== state.currentAgentId) state.currentAgentId = next;
3441
- };
3442
- const resolveModelSelection = (entry) => {
3443
- return resolveSessionInfoModelSelection({
3444
- currentProvider: state.sessionInfo.modelProvider,
3445
- currentModel: state.sessionInfo.model,
3446
- defaultProvider: lastSessionDefaults?.modelProvider,
3447
- defaultModel: lastSessionDefaults?.model,
3448
- entryProvider: entry?.modelProvider,
3449
- entryModel: entry?.model,
3450
- overrideProvider: entry?.providerOverride,
3451
- overrideModel: entry?.modelOverride
3452
- });
3453
- };
3454
- const applySessionInfo = (params) => {
3455
- const entry = params.entry ?? void 0;
3456
- const defaults = params.defaults ?? lastSessionDefaults ?? void 0;
3457
- const previousDefaults = lastSessionDefaults;
3458
- const defaultsChanged = params.defaults ? previousDefaults?.model !== params.defaults.model || previousDefaults?.modelProvider !== params.defaults.modelProvider || previousDefaults?.contextTokens !== params.defaults.contextTokens : false;
3459
- if (params.defaults) lastSessionDefaults = params.defaults;
3460
- const entryUpdatedAt = entry?.updatedAt ?? null;
3461
- const currentUpdatedAt = state.sessionInfo.updatedAt ?? null;
3462
- if (!params.force && entryUpdatedAt !== null && currentUpdatedAt !== null && entryUpdatedAt < currentUpdatedAt && !defaultsChanged) return;
3463
- const next = { ...state.sessionInfo };
3464
- if (entry?.thinkingLevel !== void 0) next.thinkingLevel = entry.thinkingLevel;
3465
- if (entry?.fastMode !== void 0) next.fastMode = entry.fastMode;
3466
- if (entry?.verboseLevel !== void 0) next.verboseLevel = entry.verboseLevel;
3467
- if (entry?.traceLevel !== void 0) next.traceLevel = entry.traceLevel;
3468
- if (entry?.reasoningLevel !== void 0) next.reasoningLevel = entry.reasoningLevel;
3469
- if (entry?.responseUsage !== void 0) next.responseUsage = entry.responseUsage;
3470
- if (entry?.inputTokens !== void 0) next.inputTokens = entry.inputTokens;
3471
- if (entry?.outputTokens !== void 0) next.outputTokens = entry.outputTokens;
3472
- if (entry?.totalTokens !== void 0) next.totalTokens = entry.totalTokens;
3473
- if (entry?.contextTokens !== void 0 || defaults?.contextTokens !== void 0) next.contextTokens = entry?.contextTokens ?? defaults?.contextTokens ?? state.sessionInfo.contextTokens;
3474
- if (entry?.displayName !== void 0) next.displayName = entry.displayName;
3475
- if (entry?.updatedAt !== void 0) next.updatedAt = entry.updatedAt;
3476
- const selection = resolveModelSelection(entry);
3477
- if (selection.modelProvider !== void 0) next.modelProvider = selection.modelProvider;
3478
- if (selection.model !== void 0) next.model = selection.model;
3479
- state.sessionInfo = next;
3480
- updateAutocompleteProvider();
3481
- updateFooter();
3482
- tui.requestRender();
3483
- };
3484
- const runRefreshSessionInfo = async () => {
3485
- try {
3486
- const resolveListAgentId = () => {
3487
- if (state.currentSessionKey === "global" || state.currentSessionKey === "unknown") return;
3488
- const parsed = parseAgentSessionKey(state.currentSessionKey);
3489
- return parsed?.agentId ? normalizeAgentId(parsed.agentId) : state.currentAgentId;
3490
- };
3491
- const listAgentId = resolveListAgentId();
3492
- const result = await client.listSessions({
3493
- includeGlobal: false,
3494
- includeUnknown: false,
3495
- agentId: listAgentId
3496
- });
3497
- const normalizeMatchKey = (key) => parseAgentSessionKey(key)?.rest ?? key;
3498
- const currentMatchKey = normalizeMatchKey(state.currentSessionKey);
3499
- const entry = result.sessions.find((row) => {
3500
- if (row.key === state.currentSessionKey) return true;
3501
- return normalizeMatchKey(row.key) === currentMatchKey;
3502
- });
3503
- if (entry?.key && entry.key !== state.currentSessionKey) {
3504
- updateAgentFromSessionKey(entry.key);
3505
- state.currentSessionKey = entry.key;
3506
- updateHeader();
3507
- }
3508
- applySessionInfo({
3509
- entry,
3510
- defaults: result.defaults
3511
- });
3512
- } catch (err) {
3513
- chatLog.addSystem(`sessions list failed: ${String(err)}`);
3514
- }
3515
- };
3516
- const refreshSessionInfo = async () => {
3517
- refreshSessionInfoPromise = refreshSessionInfoPromise.then(runRefreshSessionInfo, runRefreshSessionInfo);
3518
- await refreshSessionInfoPromise;
3519
- };
3520
- const applySessionInfoFromPatch = (result) => {
3521
- if (!result?.entry) return;
3522
- if (result.key && result.key !== state.currentSessionKey) {
3523
- updateAgentFromSessionKey(result.key);
3524
- state.currentSessionKey = result.key;
3525
- updateHeader();
3526
- }
3527
- const resolved = result.resolved;
3528
- applySessionInfo({
3529
- entry: resolved && (resolved.modelProvider || resolved.model) ? {
3530
- ...result.entry,
3531
- modelProvider: resolved.modelProvider ?? result.entry.modelProvider,
3532
- model: resolved.model ?? result.entry.model
3533
- } : result.entry,
3534
- force: true
3535
- });
3536
- };
3537
- const loadHistory = async () => {
3538
- try {
3539
- const record = await client.loadHistory({
3540
- sessionKey: state.currentSessionKey,
3541
- limit: opts.historyLimit ?? 200
3542
- });
3543
- state.currentSessionId = typeof record.sessionId === "string" ? record.sessionId : null;
3544
- state.sessionInfo.thinkingLevel = record.thinkingLevel ?? state.sessionInfo.thinkingLevel;
3545
- state.sessionInfo.fastMode = record.fastMode ?? state.sessionInfo.fastMode;
3546
- state.sessionInfo.verboseLevel = record.verboseLevel ?? state.sessionInfo.verboseLevel;
3547
- state.sessionInfo.traceLevel = record.traceLevel ?? state.sessionInfo.traceLevel;
3548
- const showTools = (state.sessionInfo.verboseLevel ?? "off") !== "off";
3549
- chatLog.clearAll();
3550
- btw.clear();
3551
- chatLog.addSystem(`session ${state.currentSessionKey}`);
3552
- for (const entry of record.messages ?? []) {
3553
- if (!entry || typeof entry !== "object") continue;
3554
- const message = entry;
3555
- if (isCommandMessage(message)) {
3556
- const text = extractTextFromMessage(message);
3557
- if (text) chatLog.addSystem(text);
3558
- continue;
3559
- }
3560
- if (message.role === "user") {
3561
- const text = extractTextFromMessage(message);
3562
- if (text) chatLog.addUser(text);
3563
- continue;
3564
- }
3565
- if (message.role === "assistant") {
3566
- const text = extractTextFromMessage(message, { includeThinking: state.showThinking });
3567
- if (text) chatLog.finalizeAssistant(text);
3568
- continue;
3569
- }
3570
- if (message.role === "toolResult") {
3571
- if (!showTools) continue;
3572
- const toolCallId = asString(message.toolCallId, "");
3573
- const toolName = asString(message.toolName, "tool");
3574
- chatLog.startTool(toolCallId, toolName, {}).setResult({
3575
- content: Array.isArray(message.content) ? message.content : [],
3576
- details: typeof message.details === "object" && message.details ? message.details : void 0
3577
- }, { isError: Boolean(message.isError) });
3578
- }
3579
- }
3580
- state.historyLoaded = true;
3581
- } catch (err) {
3582
- chatLog.addSystem(`history failed: ${String(err)}`);
3583
- }
3584
- await refreshSessionInfo();
3585
- tui.requestRender();
3586
- };
3587
- const setSession = async (rawKey) => {
3588
- const nextKey = resolveSessionKey(rawKey);
3589
- updateAgentFromSessionKey(nextKey);
3590
- state.currentSessionKey = nextKey;
3591
- state.activeChatRunId = null;
3592
- setActivityStatus("idle");
3593
- state.currentSessionId = null;
3594
- state.sessionInfo.updatedAt = null;
3595
- state.historyLoaded = false;
3596
- clearLocalRunIds?.();
3597
- btw.clear();
3598
- updateHeader();
3599
- updateFooter();
3600
- await loadHistory();
3601
- };
3602
- const abortActive = async () => {
3603
- if (!state.activeChatRunId) {
3604
- chatLog.addSystem("no active run");
3605
- tui.requestRender();
3606
- return;
3607
- }
3608
- try {
3609
- await client.abortChat({
3610
- sessionKey: state.currentSessionKey,
3611
- runId: state.activeChatRunId
3612
- });
3613
- setActivityStatus("aborted");
3614
- } catch (err) {
3615
- chatLog.addSystem(`abort failed: ${String(err)}`);
3616
- setActivityStatus("abort failed");
3617
- }
3618
- tui.requestRender();
3619
- };
3620
- return {
3621
- applyAgentsResult,
3622
- refreshAgents,
3623
- refreshSessionInfo,
3624
- applySessionInfoFromPatch,
3625
- loadHistory,
3626
- setSession,
3627
- abortActive
3628
- };
3629
- }
3630
- //#endregion
3631
- //#region src/tui/tui-submit.ts
3632
- function createEditorSubmitHandler(params) {
3633
- return (text) => {
3634
- const raw = text;
3635
- const value = raw.trim();
3636
- params.editor.setText("");
3637
- if (!value) return;
3638
- if (raw.startsWith("!") && raw !== "!") {
3639
- params.editor.addToHistory(raw);
3640
- params.handleBangLine(raw);
3641
- return;
3642
- }
3643
- params.editor.addToHistory(value);
3644
- if (value.startsWith("/")) {
3645
- params.handleCommand(value);
3646
- return;
3647
- }
3648
- params.sendMessage(value);
3649
- };
3650
- }
3651
- function shouldEnableWindowsGitBashPasteFallback(params) {
3652
- const platform = params?.platform ?? process.platform;
3653
- const env = params?.env ?? process.env;
3654
- const termProgram = normalizeLowercaseStringOrEmpty(env.TERM_PROGRAM);
3655
- if (platform === "darwin") {
3656
- if (termProgram.includes("iterm") || termProgram.includes("apple_terminal")) return true;
3657
- return false;
3658
- }
3659
- if (platform !== "win32") return false;
3660
- const msystem = (env.MSYSTEM ?? "").toUpperCase();
3661
- const shell = env.SHELL ?? "";
3662
- if (msystem.startsWith("MINGW") || msystem.startsWith("MSYS")) return true;
3663
- if (normalizeLowercaseStringOrEmpty(shell).includes("bash")) return true;
3664
- return termProgram.includes("mintty");
3665
- }
3666
- function createSubmitBurstCoalescer(params) {
3667
- const windowMs = Math.max(1, params.burstWindowMs ?? 50);
3668
- const now = params.now ?? (() => Date.now());
3669
- const setTimer = params.setTimer ?? setTimeout;
3670
- const clearTimer = params.clearTimer ?? clearTimeout;
3671
- let pending = null;
3672
- let pendingAt = 0;
3673
- let flushTimer = null;
3674
- const clearFlushTimer = () => {
3675
- if (!flushTimer) return;
3676
- clearTimer(flushTimer);
3677
- flushTimer = null;
3678
- };
3679
- const flushPending = () => {
3680
- if (pending === null) return;
3681
- const value = pending;
3682
- pending = null;
3683
- pendingAt = 0;
3684
- clearFlushTimer();
3685
- params.submit(value);
3686
- };
3687
- const scheduleFlush = () => {
3688
- clearFlushTimer();
3689
- flushTimer = setTimer(() => {
3690
- flushPending();
3691
- }, windowMs);
3692
- };
3693
- return (value) => {
3694
- if (!params.enabled) {
3695
- params.submit(value);
3696
- return;
3697
- }
3698
- if (value.includes("\n")) {
3699
- flushPending();
3700
- params.submit(value);
3701
- return;
3702
- }
3703
- const ts = now();
3704
- if (pending === null) {
3705
- pending = value;
3706
- pendingAt = ts;
3707
- scheduleFlush();
3708
- return;
3709
- }
3710
- if (ts - pendingAt <= windowMs) {
3711
- pending = `${pending}\n${value}`;
3712
- pendingAt = ts;
3713
- scheduleFlush();
3714
- return;
3715
- }
3716
- flushPending();
3717
- pending = value;
3718
- pendingAt = ts;
3719
- scheduleFlush();
3720
- };
3721
- }
3722
- //#endregion
3723
- //#region src/tui/tui-waiting.ts
3724
- const defaultWaitingPhrases = [
3725
- "flibbertigibbeting",
3726
- "kerfuffling",
3727
- "dillydallying",
3728
- "twiddling thumbs",
3729
- "noodling",
3730
- "bamboozling",
3731
- "moseying",
3732
- "hobnobbing",
3733
- "pondering",
3734
- "conjuring"
3735
- ];
3736
- function pickWaitingPhrase(tick, phrases = defaultWaitingPhrases) {
3737
- return phrases[Math.floor(tick / 10) % phrases.length] ?? phrases[0] ?? "waiting";
3738
- }
3739
- function shimmerText(theme, text, tick) {
3740
- const width = 6;
3741
- const hi = (ch) => theme.bold(theme.accentSoft(ch));
3742
- const pos = tick % (text.length + width);
3743
- const start = Math.max(0, pos - width);
3744
- const end = Math.min(text.length - 1, pos);
3745
- let out = "";
3746
- for (let i = 0; i < text.length; i++) {
3747
- const ch = text[i];
3748
- out += i >= start && i <= end ? hi(ch) : theme.dim(ch);
3749
- }
3750
- return out;
3751
- }
3752
- function buildWaitingStatusMessage(params) {
3753
- const phrase = pickWaitingPhrase(params.tick, params.phrases);
3754
- return `${shimmerText(params.theme, `${phrase}…`, params.tick)} • ${params.elapsed} | ${params.connectionStatus}`;
3755
- }
3756
- //#endregion
3757
- //#region src/tui/tui.ts
3758
- const GENESIS_CLI_WRAPPER_PATH = fileURLToPath(new URL("../../genesis.mjs", import.meta.url));
3759
- const GENESIS_RUN_NODE_SCRIPT_PATH = fileURLToPath(new URL("../../scripts/run-node.mjs", import.meta.url));
3760
- const GENESIS_DIST_ENTRY_JS_PATH = fileURLToPath(new URL("../../dist/entry.js", import.meta.url));
3761
- const GENESIS_DIST_ENTRY_MJS_PATH = fileURLToPath(new URL("../../dist/entry.mjs", import.meta.url));
3762
- const OPENAI_CODEX_PROVIDER = "openai-codex";
3763
- /** Resolve the absolute path to the `codex` CLI binary, or `null` if not installed. */
3764
- function resolveCodexCliBin() {
3765
- try {
3766
- return execFileSync(process.platform === "win32" ? "where" : "which", ["codex"], { encoding: "utf8" }).trim().split(/\r?\n/)[0] || null;
3767
- } catch {
3768
- return null;
3769
- }
3770
- }
3771
- function resolveLocalAuthCliInvocation(params) {
3772
- const hasDistEntry = params?.hasDistEntry ?? (existsSync(GENESIS_DIST_ENTRY_JS_PATH) || existsSync(GENESIS_DIST_ENTRY_MJS_PATH));
3773
- const hasRunNodeScript = params?.hasRunNodeScript ?? existsSync(GENESIS_RUN_NODE_SCRIPT_PATH);
3774
- const command = params?.execPath ?? process.execPath;
3775
- const wrapperPath = params?.wrapperPath ?? GENESIS_CLI_WRAPPER_PATH;
3776
- const runNodePath = params?.runNodePath ?? GENESIS_RUN_NODE_SCRIPT_PATH;
3777
- return hasDistEntry || !hasRunNodeScript ? {
3778
- command,
3779
- args: [
3780
- wrapperPath,
3781
- "models",
3782
- "auth",
3783
- "login"
3784
- ]
3785
- } : {
3786
- command,
3787
- args: [
3788
- runNodePath,
3789
- "models",
3790
- "auth",
3791
- "login"
3792
- ]
3793
- };
3794
- }
3795
- function resolveLocalAuthSpawnOptions(params) {
3796
- return (params.platform ?? process.platform) === "win32" && /\.(cmd|bat)$/iu.test(params.command.trim()) ? { shell: true } : {};
3797
- }
3798
- function resolveLocalAuthSpawnCwd(params) {
3799
- const defaultCwd = params.defaultCwd ?? process.cwd();
3800
- const entryArg = params.args[0]?.trim();
3801
- if (!entryArg) return defaultCwd;
3802
- const entryBase = path.basename(entryArg).toLowerCase();
3803
- if (entryBase === "genesis.mjs") return path.dirname(entryArg);
3804
- if (entryBase === "run-node.mjs") return path.dirname(path.dirname(entryArg));
3805
- return defaultCwd;
3806
- }
3807
- function resolveTuiSessionKey(params) {
3808
- const trimmed = (params.raw ?? "").trim();
3809
- if (!trimmed) {
3810
- if (params.sessionScope === "global") return "global";
3811
- return buildAgentMainSessionKey({
3812
- agentId: params.currentAgentId,
3813
- mainKey: params.sessionMainKey
3814
- });
3815
- }
3816
- if (trimmed === "global" || trimmed === "unknown") return trimmed;
3817
- if (trimmed.startsWith("agent:")) return normalizeLowercaseStringOrEmpty(trimmed);
3818
- return `agent:${params.currentAgentId}:${normalizeLowercaseStringOrEmpty(trimmed)}`;
3819
- }
3820
- function resolveInitialTuiAgentId(params) {
3821
- const parsed = parseAgentSessionKey((params.initialSessionInput ?? "").trim());
3822
- if (parsed?.agentId) return normalizeAgentId(parsed.agentId);
3823
- const inferredFromWorkspace = resolveAgentIdByWorkspacePath(params.cfg, params.cwd ?? process.cwd());
3824
- if (inferredFromWorkspace) return inferredFromWorkspace;
3825
- return normalizeAgentId(params.fallbackAgentId);
3826
- }
3827
- function resolveGatewayDisconnectState(reason) {
3828
- const reasonLabel = reason?.trim() ? reason.trim() : "closed";
3829
- if (/pairing required/i.test(reasonLabel)) return {
3830
- connectionStatus: `gateway disconnected: ${reasonLabel}`,
3831
- activityStatus: "pairing required: run genesis devices list",
3832
- pairingHint: "Pairing required. Run `genesis devices list`, approve your request ID, then reconnect."
3833
- };
3834
- return {
3835
- connectionStatus: `gateway disconnected: ${reasonLabel}`,
3836
- activityStatus: "idle"
3837
- };
3838
- }
3839
- function createBackspaceDeduper(params) {
3840
- const dedupeWindowMs = Math.max(0, Math.floor(params?.dedupeWindowMs ?? 8));
3841
- const now = params?.now ?? (() => Date.now());
3842
- let lastBackspaceAt = -1;
3843
- return (data) => {
3844
- if (!matchesKey(data, Key.backspace)) return data;
3845
- const ts = now();
3846
- if (lastBackspaceAt >= 0 && ts - lastBackspaceAt <= dedupeWindowMs) return "";
3847
- lastBackspaceAt = ts;
3848
- return data;
3849
- };
3850
- }
3851
- function isIgnorableTuiStopError(error) {
3852
- if (!error || typeof error !== "object") return false;
3853
- const err = error;
3854
- const code = typeof err.code === "string" ? err.code : "";
3855
- const syscall = typeof err.syscall === "string" ? err.syscall : "";
3856
- const message = typeof err.message === "string" ? err.message : "";
3857
- if (code === "EBADF" && syscall === "setRawMode") return true;
3858
- return /setRawMode/i.test(message) && /EBADF/i.test(message);
3859
- }
3860
- function stopTuiSafely(stop) {
3861
- try {
3862
- stop();
3863
- } catch (error) {
3864
- if (!isIgnorableTuiStopError(error)) throw error;
3865
- }
3866
- }
3867
- async function drainAndStopTuiSafely(tui) {
3868
- if (typeof tui.terminal?.drainInput === "function") try {
3869
- await tui.terminal.drainInput();
3870
- } catch {}
3871
- stopTuiSafely(() => tui.stop());
3872
- }
3873
- function resolveCtrlCAction(params) {
3874
- const exitWindowMs = Math.max(1, Math.floor(params.exitWindowMs ?? 1e3));
3875
- if (params.hasInput) return {
3876
- action: "clear",
3877
- nextLastCtrlCAt: params.now
3878
- };
3879
- if (params.now - params.lastCtrlCAt <= exitWindowMs) return {
3880
- action: "exit",
3881
- nextLastCtrlCAt: params.lastCtrlCAt
3882
- };
3883
- return {
3884
- action: "warn",
3885
- nextLastCtrlCAt: params.now
3886
- };
3887
- }
3888
- async function runTui(opts) {
3889
- const isLocalMode = opts.local === true;
3890
- const config = loadConfig();
3891
- const initialSessionInput = (opts.session ?? "").trim();
3892
- let sessionScope = config.session?.scope ?? "per-sender";
3893
- let sessionMainKey = normalizeMainKey(config.session?.mainKey);
3894
- let agentDefaultId = resolveDefaultAgentId(config);
3895
- let currentAgentId = resolveInitialTuiAgentId({
3896
- cfg: config,
3897
- fallbackAgentId: agentDefaultId,
3898
- initialSessionInput,
3899
- cwd: process.cwd()
3900
- });
3901
- let agents = [];
3902
- const agentNames = /* @__PURE__ */ new Map();
3903
- let currentSessionKey = "";
3904
- let initialSessionApplied = false;
3905
- let currentSessionId = null;
3906
- let activeChatRunId = null;
3907
- let pendingOptimisticUserMessage = false;
3908
- let historyLoaded = false;
3909
- let isConnected = false;
3910
- let wasDisconnected = false;
3911
- let toolsExpanded = false;
3912
- let showThinking = false;
3913
- let pairingHintShown = false;
3914
- const localRunIds = /* @__PURE__ */ new Set();
3915
- const localBtwRunIds = /* @__PURE__ */ new Set();
3916
- const deliverDefault = opts.deliver ?? false;
3917
- const autoMessage = opts.message?.trim();
3918
- let autoMessageSent = false;
3919
- let sessionInfo = {};
3920
- let lastCtrlCAt = 0;
3921
- let exitRequested = false;
3922
- let activityStatus = "idle";
3923
- let connectionStatus = isLocalMode ? "starting local runtime" : "connecting";
3924
- let statusTimeout = null;
3925
- let statusTimer = null;
3926
- let statusStartedAt = null;
3927
- let lastActivityStatus = activityStatus;
3928
- const state = {
3929
- get agentDefaultId() {
3930
- return agentDefaultId;
3931
- },
3932
- set agentDefaultId(value) {
3933
- agentDefaultId = value;
3934
- },
3935
- get sessionMainKey() {
3936
- return sessionMainKey;
3937
- },
3938
- set sessionMainKey(value) {
3939
- sessionMainKey = value;
3940
- },
3941
- get sessionScope() {
3942
- return sessionScope;
3943
- },
3944
- set sessionScope(value) {
3945
- sessionScope = value;
3946
- },
3947
- get agents() {
3948
- return agents;
3949
- },
3950
- set agents(value) {
3951
- agents = value;
3952
- },
3953
- get currentAgentId() {
3954
- return currentAgentId;
3955
- },
3956
- set currentAgentId(value) {
3957
- currentAgentId = value;
3958
- },
3959
- get currentSessionKey() {
3960
- return currentSessionKey;
3961
- },
3962
- set currentSessionKey(value) {
3963
- currentSessionKey = value;
3964
- },
3965
- get currentSessionId() {
3966
- return currentSessionId;
3967
- },
3968
- set currentSessionId(value) {
3969
- currentSessionId = value;
3970
- },
3971
- get activeChatRunId() {
3972
- return activeChatRunId;
3973
- },
3974
- set activeChatRunId(value) {
3975
- activeChatRunId = value;
3976
- },
3977
- get pendingOptimisticUserMessage() {
3978
- return pendingOptimisticUserMessage;
3979
- },
3980
- set pendingOptimisticUserMessage(value) {
3981
- pendingOptimisticUserMessage = value;
3982
- },
3983
- get historyLoaded() {
3984
- return historyLoaded;
3985
- },
3986
- set historyLoaded(value) {
3987
- historyLoaded = value;
3988
- },
3989
- get sessionInfo() {
3990
- return sessionInfo;
3991
- },
3992
- set sessionInfo(value) {
3993
- sessionInfo = value;
3994
- },
3995
- get initialSessionApplied() {
3996
- return initialSessionApplied;
3997
- },
3998
- set initialSessionApplied(value) {
3999
- initialSessionApplied = value;
4000
- },
4001
- get isConnected() {
4002
- return isConnected;
4003
- },
4004
- set isConnected(value) {
4005
- isConnected = value;
4006
- },
4007
- get autoMessageSent() {
4008
- return autoMessageSent;
4009
- },
4010
- set autoMessageSent(value) {
4011
- autoMessageSent = value;
4012
- },
4013
- get toolsExpanded() {
4014
- return toolsExpanded;
4015
- },
4016
- set toolsExpanded(value) {
4017
- toolsExpanded = value;
4018
- },
4019
- get showThinking() {
4020
- return showThinking;
4021
- },
4022
- set showThinking(value) {
4023
- showThinking = value;
4024
- },
4025
- get connectionStatus() {
4026
- return connectionStatus;
4027
- },
4028
- set connectionStatus(value) {
4029
- connectionStatus = value;
4030
- },
4031
- get activityStatus() {
4032
- return activityStatus;
4033
- },
4034
- set activityStatus(value) {
4035
- activityStatus = value;
4036
- },
4037
- get statusTimeout() {
4038
- return statusTimeout;
4039
- },
4040
- set statusTimeout(value) {
4041
- statusTimeout = value;
4042
- },
4043
- get lastCtrlCAt() {
4044
- return lastCtrlCAt;
4045
- },
4046
- set lastCtrlCAt(value) {
4047
- lastCtrlCAt = value;
4048
- }
4049
- };
4050
- const noteLocalRunId = (runId) => {
4051
- if (!runId) return;
4052
- localRunIds.add(runId);
4053
- if (localRunIds.size > 200) {
4054
- const [first] = localRunIds;
4055
- if (first) localRunIds.delete(first);
4056
- }
4057
- };
4058
- const forgetLocalRunId = (runId) => {
4059
- localRunIds.delete(runId);
4060
- };
4061
- const isLocalRunId = (runId) => localRunIds.has(runId);
4062
- const clearLocalRunIds = () => {
4063
- localRunIds.clear();
4064
- };
4065
- const noteLocalBtwRunId = (runId) => {
4066
- if (!runId) return;
4067
- localBtwRunIds.add(runId);
4068
- if (localBtwRunIds.size > 200) {
4069
- const [first] = localBtwRunIds;
4070
- if (first) localBtwRunIds.delete(first);
4071
- }
4072
- };
4073
- const forgetLocalBtwRunId = (runId) => {
4074
- localBtwRunIds.delete(runId);
4075
- };
4076
- const isLocalBtwRunId = (runId) => localBtwRunIds.has(runId);
4077
- const clearLocalBtwRunIds = () => {
4078
- localBtwRunIds.clear();
4079
- };
4080
- const client = opts.local ? new EmbeddedTuiBackend() : await GatewayChatClient.connect({
4081
- url: opts.url,
4082
- token: opts.token,
4083
- password: opts.password
4084
- });
4085
- const previousConsoleSubsystemFilter = isLocalMode ? loggingState.consoleSubsystemFilter ? [...loggingState.consoleSubsystemFilter] : null : null;
4086
- if (isLocalMode) setConsoleSubsystemFilter(["__genesis_tui_quiet__"]);
4087
- const tui = new TUI(new ProcessTerminal());
4088
- const dedupeBackspace = createBackspaceDeduper();
4089
- tui.addInputListener((data) => {
4090
- const next = dedupeBackspace(data);
4091
- if (next.length === 0) return { consume: true };
4092
- return { data: next };
4093
- });
4094
- const header = new Text("", 1, 0);
4095
- const statusContainer = new Container();
4096
- const footer = new Text("", 1, 0);
4097
- const chatLog = new ChatLog();
4098
- const editor = new CustomEditor(tui, editorTheme);
4099
- const root = new Container();
4100
- root.addChild(header);
4101
- root.addChild(chatLog);
4102
- root.addChild(statusContainer);
4103
- root.addChild(footer);
4104
- root.addChild(editor);
4105
- const updateAutocompleteProvider = () => {
4106
- editor.setAutocompleteProvider(new CombinedAutocompleteProvider(getSlashCommands({
4107
- cfg: config,
4108
- local: isLocalMode,
4109
- provider: sessionInfo.modelProvider,
4110
- model: sessionInfo.model
4111
- }), process.cwd()));
4112
- };
4113
- tui.addChild(root);
4114
- tui.setFocus(editor);
4115
- const formatSessionKey = (key) => {
4116
- if (key === "global" || key === "unknown") return key;
4117
- return parseAgentSessionKey(key)?.rest ?? key;
4118
- };
4119
- const formatAgentLabel = (id) => {
4120
- const name = agentNames.get(id);
4121
- return name ? `${id} (${name})` : id;
4122
- };
4123
- const resolveSessionKey = (raw) => {
4124
- return resolveTuiSessionKey({
4125
- raw,
4126
- sessionScope,
4127
- currentAgentId,
4128
- sessionMainKey
4129
- });
4130
- };
4131
- currentSessionKey = resolveSessionKey(initialSessionInput);
4132
- const updateHeader = () => {
4133
- const sessionLabel = formatSessionKey(currentSessionKey);
4134
- const agentLabel = formatAgentLabel(currentAgentId);
4135
- header.setText(theme.header(`genesis tui - ${client.connection.url} - agent ${agentLabel} - session ${sessionLabel}`));
4136
- };
4137
- const busyStates = new Set([
4138
- "sending",
4139
- "waiting",
4140
- "streaming",
4141
- "running"
4142
- ]);
4143
- let statusText = null;
4144
- let statusLoader = null;
4145
- const formatElapsed = (startMs) => {
4146
- const totalSeconds = Math.max(0, Math.floor((Date.now() - startMs) / 1e3));
4147
- if (totalSeconds < 60) return `${totalSeconds}s`;
4148
- return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`;
4149
- };
4150
- const ensureStatusText = () => {
4151
- if (statusText) return;
4152
- statusContainer.clear();
4153
- statusLoader?.stop();
4154
- statusLoader = null;
4155
- statusText = new Text("", 1, 0);
4156
- statusContainer.addChild(statusText);
4157
- };
4158
- const ensureStatusLoader = () => {
4159
- if (statusLoader) return;
4160
- statusContainer.clear();
4161
- statusText = null;
4162
- statusLoader = new Loader(tui, (spinner) => theme.accent(spinner), (text) => theme.bold(theme.accentSoft(text)), "");
4163
- statusContainer.addChild(statusLoader);
4164
- };
4165
- let waitingTick = 0;
4166
- let waitingTimer = null;
4167
- let waitingPhrase = null;
4168
- const updateBusyStatusMessage = () => {
4169
- if (!statusLoader || !statusStartedAt) return;
4170
- const elapsed = formatElapsed(statusStartedAt);
4171
- if (activityStatus === "waiting") {
4172
- waitingTick++;
4173
- statusLoader.setMessage(buildWaitingStatusMessage({
4174
- theme,
4175
- tick: waitingTick,
4176
- elapsed,
4177
- connectionStatus,
4178
- phrases: waitingPhrase ? [waitingPhrase] : void 0
4179
- }));
4180
- return;
4181
- }
4182
- statusLoader.setMessage(`${activityStatus} • ${elapsed} | ${connectionStatus}`);
4183
- };
4184
- const startStatusTimer = () => {
4185
- if (statusTimer) return;
4186
- statusTimer = setInterval(() => {
4187
- if (!busyStates.has(activityStatus)) return;
4188
- updateBusyStatusMessage();
4189
- }, 1e3);
4190
- };
4191
- const stopStatusTimer = () => {
4192
- if (!statusTimer) return;
4193
- clearInterval(statusTimer);
4194
- statusTimer = null;
4195
- };
4196
- const startWaitingTimer = () => {
4197
- if (waitingTimer) return;
4198
- if (!waitingPhrase) waitingPhrase = defaultWaitingPhrases[Math.floor(Math.random() * defaultWaitingPhrases.length)] ?? defaultWaitingPhrases[0] ?? "waiting";
4199
- waitingTick = 0;
4200
- waitingTimer = setInterval(() => {
4201
- if (activityStatus !== "waiting") return;
4202
- updateBusyStatusMessage();
4203
- }, 120);
4204
- };
4205
- const stopWaitingTimer = () => {
4206
- if (!waitingTimer) return;
4207
- clearInterval(waitingTimer);
4208
- waitingTimer = null;
4209
- waitingPhrase = null;
4210
- };
4211
- const renderStatus = () => {
4212
- if (busyStates.has(activityStatus)) {
4213
- if (!statusStartedAt || lastActivityStatus !== activityStatus) statusStartedAt = Date.now();
4214
- ensureStatusLoader();
4215
- if (activityStatus === "waiting") {
4216
- stopStatusTimer();
4217
- startWaitingTimer();
4218
- } else {
4219
- stopWaitingTimer();
4220
- startStatusTimer();
4221
- }
4222
- updateBusyStatusMessage();
4223
- } else {
4224
- statusStartedAt = null;
4225
- stopStatusTimer();
4226
- stopWaitingTimer();
4227
- statusLoader?.stop();
4228
- statusLoader = null;
4229
- ensureStatusText();
4230
- const text = activityStatus ? `${connectionStatus} | ${activityStatus}` : connectionStatus;
4231
- statusText?.setText(theme.dim(text));
4232
- }
4233
- lastActivityStatus = activityStatus;
4234
- };
4235
- const setConnectionStatus = (text, ttlMs) => {
4236
- connectionStatus = text;
4237
- renderStatus();
4238
- if (statusTimeout) clearTimeout(statusTimeout);
4239
- if (ttlMs && ttlMs > 0) statusTimeout = setTimeout(() => {
4240
- connectionStatus = isConnected ? isLocalMode ? "local ready" : "connected" : isLocalMode ? "local stopped" : "disconnected";
4241
- renderStatus();
4242
- }, ttlMs);
4243
- };
4244
- const setActivityStatus = (text) => {
4245
- activityStatus = text;
4246
- renderStatus();
4247
- };
4248
- const withTuiSuspended = async (work) => {
4249
- await drainAndStopTuiSafely(tui);
4250
- if (isLocalMode) setConsoleSubsystemFilter(previousConsoleSubsystemFilter);
4251
- try {
4252
- return await work();
4253
- } finally {
4254
- if (isLocalMode) setConsoleSubsystemFilter(["__genesis_tui_quiet__"]);
4255
- tui.start();
4256
- tui.setFocus(editor);
4257
- updateHeader();
4258
- updateFooter();
4259
- tui.requestRender(true);
4260
- }
4261
- };
4262
- const runAuthFlow = isLocalMode ? async (params) => await withTuiSuspended(async () => await new Promise((resolve, reject) => {
4263
- const provider = params.provider?.trim() || void 0;
4264
- const codexBin = provider === OPENAI_CODEX_PROVIDER || !provider && sessionInfo.modelProvider === OPENAI_CODEX_PROVIDER ? resolveCodexCliBin() : null;
4265
- let command;
4266
- let args;
4267
- if (codexBin) {
4268
- command = codexBin;
4269
- args = ["login"];
4270
- } else {
4271
- ({command, args} = resolveLocalAuthCliInvocation());
4272
- if (provider) args.push("--provider", provider);
4273
- }
4274
- const child = spawn(command, args, {
4275
- cwd: resolveLocalAuthSpawnCwd({
4276
- args,
4277
- defaultCwd: process.cwd()
4278
- }),
4279
- env: process.env,
4280
- stdio: "inherit",
4281
- ...resolveLocalAuthSpawnOptions({ command })
4282
- });
4283
- child.once("error", reject);
4284
- child.once("exit", (exitCode, signal) => {
4285
- resolve({
4286
- exitCode,
4287
- signal
4288
- });
4289
- });
4290
- })) : void 0;
4291
- const updateFooter = () => {
4292
- const sessionKeyLabel = formatSessionKey(currentSessionKey);
4293
- const sessionLabel = sessionInfo.displayName ? `${sessionKeyLabel} (${sessionInfo.displayName})` : sessionKeyLabel;
4294
- const agentLabel = formatAgentLabel(currentAgentId);
4295
- const modelLabel = sessionInfo.model ? sessionInfo.modelProvider ? `${sessionInfo.modelProvider}/${sessionInfo.model}` : sessionInfo.model : "unknown";
4296
- const tokens = formatTokens(sessionInfo.totalTokens ?? null, sessionInfo.contextTokens ?? null);
4297
- const think = sessionInfo.thinkingLevel ?? "off";
4298
- const fast = sessionInfo.fastMode === true;
4299
- const verbose = sessionInfo.verboseLevel ?? "off";
4300
- const reasoning = sessionInfo.reasoningLevel ?? "off";
4301
- const reasoningLabel = reasoning === "on" ? "reasoning" : reasoning === "stream" ? "reasoning:stream" : null;
4302
- const footerParts = [
4303
- `agent ${agentLabel}`,
4304
- `session ${sessionLabel}`,
4305
- modelLabel,
4306
- think !== "off" ? `think ${think}` : null,
4307
- fast ? "fast" : null,
4308
- verbose !== "off" ? `verbose ${verbose}` : null,
4309
- reasoningLabel,
4310
- tokens
4311
- ].filter(Boolean);
4312
- footer.setText(theme.dim(footerParts.join(" | ")));
4313
- };
4314
- const { openOverlay, closeOverlay } = createOverlayHandlers(tui, editor);
4315
- const btw = {
4316
- showResult: (params) => {
4317
- chatLog.showBtw(params);
4318
- },
4319
- clear: () => {
4320
- chatLog.dismissBtw();
4321
- }
4322
- };
4323
- const { refreshAgents, refreshSessionInfo, applySessionInfoFromPatch, loadHistory, setSession, abortActive } = createSessionActions({
4324
- client,
4325
- chatLog,
4326
- btw,
4327
- tui,
4328
- opts,
4329
- state,
4330
- agentNames,
4331
- initialSessionInput,
4332
- initialSessionAgentId: (() => {
4333
- if (!initialSessionInput) return null;
4334
- const parsed = parseAgentSessionKey(initialSessionInput);
4335
- return parsed ? normalizeAgentId(parsed.agentId) : null;
4336
- })(),
4337
- resolveSessionKey,
4338
- updateHeader,
4339
- updateFooter,
4340
- updateAutocompleteProvider,
4341
- setActivityStatus,
4342
- clearLocalRunIds
4343
- });
4344
- const { handleChatEvent, handleAgentEvent, handleBtwEvent } = createEventHandlers({
4345
- chatLog,
4346
- btw,
4347
- tui,
4348
- state,
4349
- localMode: isLocalMode,
4350
- setActivityStatus,
4351
- refreshSessionInfo,
4352
- loadHistory,
4353
- noteLocalRunId,
4354
- isLocalRunId,
4355
- forgetLocalRunId,
4356
- clearLocalRunIds,
4357
- isLocalBtwRunId,
4358
- forgetLocalBtwRunId,
4359
- clearLocalBtwRunIds
4360
- });
4361
- const requestExit = () => {
4362
- if (exitRequested) return;
4363
- exitRequested = true;
4364
- client.stop();
4365
- drainAndStopTuiSafely(tui).then(() => {
4366
- process.exit(0);
4367
- });
4368
- };
4369
- const { handleCommand, sendMessage, openModelSelector, openAgentSelector, openSessionSelector } = createCommandHandlers({
4370
- client,
4371
- chatLog,
4372
- tui,
4373
- opts,
4374
- state,
4375
- deliverDefault,
4376
- openOverlay,
4377
- closeOverlay,
4378
- refreshSessionInfo,
4379
- applySessionInfoFromPatch,
4380
- loadHistory,
4381
- setSession,
4382
- refreshAgents,
4383
- abortActive,
4384
- setActivityStatus,
4385
- formatSessionKey,
4386
- noteLocalRunId,
4387
- noteLocalBtwRunId,
4388
- forgetLocalRunId,
4389
- forgetLocalBtwRunId,
4390
- runAuthFlow,
4391
- requestExit
4392
- });
4393
- const { runLocalShellLine } = createLocalShellRunner({
4394
- chatLog,
4395
- tui,
4396
- openOverlay,
4397
- closeOverlay
4398
- });
4399
- updateAutocompleteProvider();
4400
- editor.onSubmit = createSubmitBurstCoalescer({
4401
- submit: createEditorSubmitHandler({
4402
- editor,
4403
- handleCommand,
4404
- sendMessage,
4405
- handleBangLine: runLocalShellLine
4406
- }),
4407
- enabled: shouldEnableWindowsGitBashPasteFallback()
4408
- });
4409
- editor.onEscape = () => {
4410
- if (chatLog.hasVisibleBtw()) {
4411
- chatLog.dismissBtw();
4412
- tui.requestRender();
4413
- return;
4414
- }
4415
- abortActive();
4416
- };
4417
- const handleCtrlC = () => {
4418
- const now = Date.now();
4419
- const decision = resolveCtrlCAction({
4420
- hasInput: editor.getText().trim().length > 0,
4421
- now,
4422
- lastCtrlCAt
4423
- });
4424
- lastCtrlCAt = decision.nextLastCtrlCAt;
4425
- if (decision.action === "clear") {
4426
- editor.setText("");
4427
- setActivityStatus("cleared input; press ctrl+c again to exit");
4428
- tui.requestRender();
4429
- return;
4430
- }
4431
- if (decision.action === "exit") {
4432
- requestExit();
4433
- return;
4434
- }
4435
- setActivityStatus("press ctrl+c again to exit");
4436
- tui.requestRender();
4437
- };
4438
- editor.onCtrlC = () => {
4439
- handleCtrlC();
4440
- };
4441
- editor.onCtrlD = () => {
4442
- requestExit();
4443
- };
4444
- editor.onCtrlO = () => {
4445
- toolsExpanded = !toolsExpanded;
4446
- chatLog.setToolsExpanded(toolsExpanded);
4447
- setActivityStatus(toolsExpanded ? "tools expanded" : "tools collapsed");
4448
- tui.requestRender();
4449
- };
4450
- editor.onCtrlL = () => {
4451
- openModelSelector();
4452
- };
4453
- editor.onCtrlG = () => {
4454
- openAgentSelector();
4455
- };
4456
- editor.onCtrlP = () => {
4457
- openSessionSelector();
4458
- };
4459
- editor.onCtrlT = () => {
4460
- showThinking = !showThinking;
4461
- loadHistory();
4462
- };
4463
- tui.addInputListener((data) => {
4464
- if (!chatLog.hasVisibleBtw()) return;
4465
- if (editor.getText().length > 0) return;
4466
- if (matchesKey(data, "enter")) {
4467
- chatLog.dismissBtw();
4468
- tui.requestRender();
4469
- return { consume: true };
4470
- }
4471
- });
4472
- client.onEvent = (evt) => {
4473
- if (evt.event === "chat") handleChatEvent(evt.payload);
4474
- if (evt.event === "chat.side_result") handleBtwEvent(evt.payload);
4475
- if (evt.event === "agent") handleAgentEvent(evt.payload);
4476
- };
4477
- client.onConnected = () => {
4478
- isConnected = true;
4479
- pairingHintShown = false;
4480
- const reconnected = wasDisconnected;
4481
- wasDisconnected = false;
4482
- setConnectionStatus(isLocalMode ? "local ready" : "connected");
4483
- (async () => {
4484
- await refreshAgents();
4485
- updateHeader();
4486
- await loadHistory();
4487
- setConnectionStatus(isLocalMode ? "local ready" : reconnected ? "gateway reconnected" : "gateway connected", 4e3);
4488
- tui.requestRender();
4489
- if (!autoMessageSent && autoMessage) {
4490
- autoMessageSent = true;
4491
- await sendMessage(autoMessage);
4492
- }
4493
- updateFooter();
4494
- tui.requestRender();
4495
- })();
4496
- };
4497
- client.onDisconnected = (reason) => {
4498
- isConnected = false;
4499
- wasDisconnected = true;
4500
- historyLoaded = false;
4501
- const disconnectState = isLocalMode ? {
4502
- connectionStatus: `local runtime stopped${reason ? `: ${reason}` : ""}`,
4503
- activityStatus: "idle",
4504
- pairingHint: void 0
4505
- } : resolveGatewayDisconnectState(reason);
4506
- setConnectionStatus(disconnectState.connectionStatus, 5e3);
4507
- setActivityStatus(disconnectState.activityStatus);
4508
- if (disconnectState.pairingHint && !pairingHintShown) {
4509
- pairingHintShown = true;
4510
- chatLog.addSystem(disconnectState.pairingHint);
4511
- }
4512
- updateFooter();
4513
- tui.requestRender();
4514
- };
4515
- client.onGap = (info) => {
4516
- setConnectionStatus(`event gap: expected ${info.expected}, got ${info.received}`, 5e3);
4517
- tui.requestRender();
4518
- };
4519
- updateHeader();
4520
- setConnectionStatus(isLocalMode ? "starting local runtime" : "connecting");
4521
- updateFooter();
4522
- const sigintHandler = () => {
4523
- handleCtrlC();
4524
- };
4525
- const sigtermHandler = () => {
4526
- requestExit();
4527
- };
4528
- process.on("SIGINT", sigintHandler);
4529
- process.on("SIGTERM", sigtermHandler);
4530
- tui.start();
4531
- client.start();
4532
- await new Promise((resolve) => {
4533
- const finish = () => {
4534
- if (isLocalMode) setConsoleSubsystemFilter(previousConsoleSubsystemFilter);
4535
- process.removeListener("SIGINT", sigintHandler);
4536
- process.removeListener("SIGTERM", sigtermHandler);
4537
- resolve();
4538
- };
4539
- process.once("exit", finish);
4540
- });
4541
- }
4542
- //#endregion
4543
- //#region src/cli/tui-cli.ts
4544
- function registerTuiCli(program) {
4545
- program.command("tui").alias("terminal").alias("chat").description("Open a terminal UI connected to the Gateway").option("--local", "Run against the local embedded agent runtime", false).option("--url <url>", "Gateway WebSocket URL (defaults to gateway.remote.url when configured)").option("--token <token>", "Gateway token (if required)").option("--password <password>", "Gateway password (if required)").option("--session <key>", "Session key (default: \"main\", or \"global\" when scope is global)").option("--deliver", "Deliver assistant replies", false).option("--thinking <level>", "Thinking level override").option("--message <text>", "Send an initial message after connecting").option("--timeout-ms <ms>", "Agent timeout in ms (defaults to agents.defaults.timeoutSeconds)").option("--history-limit <n>", "History entries to load", "200").addHelpText("after", () => `\n${theme$1.muted("Docs:")} ${formatDocsLink("/cli/tui", "docs.genesis.ai/cli/tui")}\n`).action(async (opts, cmd) => {
4546
- try {
4547
- const invokedSubcommand = cmd.parent?.args[0];
4548
- const invokedAsLocalAlias = invokedSubcommand === "terminal" || invokedSubcommand === "chat";
4549
- const isLocal = Boolean(opts.local) || invokedAsLocalAlias;
4550
- if (isLocal && (opts.url || opts.token || opts.password)) throw new Error("--local cannot be combined with --url, --token, or --password");
4551
- const timeoutMs = parseTimeoutMs(opts.timeoutMs);
4552
- if (opts.timeoutMs !== void 0 && timeoutMs === void 0) defaultRuntime.error(`warning: invalid --timeout-ms "${String(opts.timeoutMs)}"; ignoring`);
4553
- const historyLimit = Number.parseInt(String(opts.historyLimit ?? "200"), 10);
4554
- await runTui({
4555
- local: isLocal,
4556
- url: opts.url,
4557
- token: opts.token,
4558
- password: opts.password,
4559
- session: opts.session,
4560
- deliver: Boolean(opts.deliver),
4561
- thinking: opts.thinking,
4562
- message: opts.message,
4563
- timeoutMs,
4564
- historyLimit: Number.isNaN(historyLimit) ? void 0 : historyLimit
4565
- });
4566
- } catch (err) {
4567
- defaultRuntime.error(String(err));
4568
- defaultRuntime.exit(1);
4569
- }
4570
- });
4571
- }
4572
- //#endregion
4573
- export { registerTuiCli };