@pixelzx/genesis 2026.7.8 → 2026.7.9

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