@pixelzx/genesis 2026.6.4 → 2026.6.6

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 (1075) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/.buildstamp +1 -1
  3. package/dist/abort-CcNxEsSq.js +201 -0
  4. package/dist/abort.runtime-DZJDSf0d.js +2 -0
  5. package/dist/abort.runtime.js +1 -1
  6. package/dist/accounts-B7M6y8l8.js +107 -0
  7. package/dist/accounts-DddcYo7u.js +2 -0
  8. package/dist/accounts-v0Cqfnse.js +104 -0
  9. package/dist/acp-cli-D_2_Nim8.js +2193 -0
  10. package/dist/acp-spawn-BZPupfsZ.js +2 -0
  11. package/dist/acp-spawn-CWfIrbK7.js +1093 -0
  12. package/dist/acp-stateful-target-driver-DpCTjH5T.js +89 -0
  13. package/dist/action-agents-fjIM4rpc.js +67 -0
  14. package/dist/action-focus-cx1pm1ym.js +132 -0
  15. package/dist/action-help-DtyAnULB.js +7 -0
  16. package/dist/action-info-DF30-xZl.js +101 -0
  17. package/dist/action-kill-rsSdXzvX.js +33 -0
  18. package/dist/action-list-4VN835m2.js +21 -0
  19. package/dist/action-log-L032mq5B.js +30 -0
  20. package/dist/action-send-Dm62UP-n.js +39 -0
  21. package/dist/action-spawn-BuZHKlpL.js +47 -0
  22. package/dist/action-unfocus-CTIWf8WX.js +29 -0
  23. package/dist/actions.runtime-0ezEcm7K.js +18 -0
  24. package/dist/actions.runtime-DKsCTTnH.js +5 -0
  25. package/dist/actions.runtime.js +1 -1
  26. package/dist/agent-BTOBOCIw.js +2 -0
  27. package/dist/agent-command-C-_EFUUu.js +874 -0
  28. package/dist/agent-harness-runtime-Bye6j3EL.js +144 -0
  29. package/dist/agent-runner-utils-CX2vCMkx.js +239 -0
  30. package/dist/agent-runner.runtime-BBqrjZv4.js +3455 -0
  31. package/dist/agent-runner.runtime.js +1 -1
  32. package/dist/agent-runtime-D1LIGcNj.js +18 -0
  33. package/dist/agents-CME2O1l9.js +5 -0
  34. package/dist/agents-DsDQvAPy.js +954 -0
  35. package/dist/aliases-C807OidC.js +2 -0
  36. package/dist/aliases-jq1ap6Dz.js +96 -0
  37. package/dist/api-BbxKoRkD.js +3 -0
  38. package/dist/api-CwJPCW9U.js +139 -0
  39. package/dist/api-N5Kaaq64.js +5 -0
  40. package/dist/approval-gateway-resolver-DIPFgTnx.js +29 -0
  41. package/dist/approval-gateway-runtime-i0yziXk2.js +2 -0
  42. package/dist/approval-handler-runtime-Cdm-10f9.js +439 -0
  43. package/dist/approval-native-runtime-BRjeBoqL.js +729 -0
  44. package/dist/attempt-execution.runtime-NFTF7Cbt.js +509 -0
  45. package/dist/attempt-execution.runtime.js +1 -1
  46. package/dist/attempt.prompt-helpers-DuBXv46v.js +221 -0
  47. package/dist/attempt.tool-run-context-Qf-tbC-C.js +933 -0
  48. package/dist/audit-DsDfRhB8.js +939 -0
  49. package/dist/audit.runtime-ComjcUGJ.js +7 -0
  50. package/dist/audit.runtime.js +1 -1
  51. package/dist/auth-BT_gqC-D.js +2 -0
  52. package/dist/auth-DeUz_8w8.js +383 -0
  53. package/dist/auth-order-DM7UkPDa.js +96 -0
  54. package/dist/auth-order-yS8hXrXh.js +2 -0
  55. package/dist/bash-tools-D0M9gBDu.js +3 -0
  56. package/dist/bash-tools-tnj1gSbO.js +2824 -0
  57. package/dist/binding-routing-C7atXiTD.js +85 -0
  58. package/dist/binding-targets-CCv7agx9.js +121 -0
  59. package/dist/bridge-server-C5O9rTJg.js +113 -0
  60. package/dist/browser-control-auth-GGN_kbqE.js +2 -0
  61. package/dist/browser-node-runtime-B-uTSVqP.js +12 -0
  62. package/dist/browser-profiles-Dex2eaLH.js +2 -0
  63. package/dist/browser-runtime-BPocB6yO.js +387 -0
  64. package/dist/browser-setup-tools-gHfYeDWA.js +13 -0
  65. package/dist/build-BqG7RkBz.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-BI4JvjcR.js +3 -0
  70. package/dist/call-wY43fzOF.js +331 -0
  71. package/dist/call.runtime-Dh61oVeL.js +2 -0
  72. package/dist/call.runtime.js +1 -1
  73. package/dist/capability-cli-BHz-2Stx.js +1401 -0
  74. package/dist/catchup-Be7tHJwK.js +300 -0
  75. package/dist/channel-B-6VmF4-.js +840 -0
  76. package/dist/channel-BCJccV-O.js +226 -0
  77. package/dist/channel-BDZqLbod.js +1100 -0
  78. package/dist/channel-BQDNgTea.js +1174 -0
  79. package/dist/channel-BwjThGwK.js +453 -0
  80. package/dist/channel-CPoThmda.js +595 -0
  81. package/dist/channel-CUT8NJ-B.js +350 -0
  82. package/dist/channel-C_Y7lv8v.js +491 -0
  83. package/dist/channel-Ck7-C-lB.js +297 -0
  84. package/dist/channel-DOpVjq4i.js +1802 -0
  85. package/dist/channel-core-QV9-eAtb.js +5 -0
  86. package/dist/channel-inbound-D_tebgdx.js +31 -0
  87. package/dist/channel-plugin-runtime-DXcBwNNM.js +771 -0
  88. package/dist/channel-runtime-D4ci0o4V.js +425 -0
  89. package/dist/channel-sAdF_zH-.js +1320 -0
  90. package/dist/channel.runtime-1swLIpNV.js +89 -0
  91. package/dist/channel.runtime-B9hljdNF.js +4 -0
  92. package/dist/channel.runtime-CSbR2pni.js +430 -0
  93. package/dist/channel.runtime-CdpqhnLO.js +2364 -0
  94. package/dist/channel.runtime-DOx6WROg.js +40130 -0
  95. package/dist/channel.runtime-H5Kb2LbC.js +109 -0
  96. package/dist/channel.runtime-V7boBc_e.js +576 -0
  97. package/dist/channel.runtime.js +1 -1
  98. package/dist/channel.setup-BXyeNJ2_.js +10 -0
  99. package/dist/channels-KU7bwUUs.js +733 -0
  100. package/dist/channels-cli-CTX6_5z3.js +268 -0
  101. package/dist/chat-C_i6Wp50.js +2830 -0
  102. package/dist/clawbot-cli-CLGPtbt-.js +9 -0
  103. package/dist/cli/daemon-cli.js +3 -3
  104. package/dist/cli-BhwHu1dK.js +72 -0
  105. package/dist/cli-CFsq8f2H.js +2 -0
  106. package/dist/cli-CNVlwurq.js +219 -0
  107. package/dist/cli-DLP8hKbi.js +2 -0
  108. package/dist/cli-runner-BbNBHV6v.js +286 -0
  109. package/dist/cli-runner.runtime-CfPaauuM.js +4 -0
  110. package/dist/cli-runner.runtime-MxBlCOO2.js +3 -0
  111. package/dist/cli-runner.runtime.js +1 -1
  112. package/dist/cli-startup-metadata.json +2 -2
  113. package/dist/cli.runtime-3cD-pSyn.js +1261 -0
  114. package/dist/cli.runtime.js +1 -1
  115. package/dist/client-Bl0d_7ak.js +138 -0
  116. package/dist/client-ClJyHgmq.js +713 -0
  117. package/dist/command-auth-DO32coey.js +76 -0
  118. package/dist/command-config-resolution-CAsa4fGg.js +2 -0
  119. package/dist/command-config-resolution-D6YcwuRh.js +23 -0
  120. package/dist/command-config-resolution.runtime-CSHDu35A.js +2 -0
  121. package/dist/command-config-resolution.runtime.js +1 -1
  122. package/dist/command-registry-CJeDJ6ZQ.js +9 -0
  123. package/dist/command-registry-CLlMvyEH.js +4 -0
  124. package/dist/command-registry-core-BfZgHqmv.js +106 -0
  125. package/dist/command-secret-gateway-DDNHxysD.js +528 -0
  126. package/dist/command-status.runtime-DqYUCcEA.js +87 -0
  127. package/dist/command-status.runtime.js +1 -1
  128. package/dist/commands-acp-C_zCJPvL.js +77 -0
  129. package/dist/commands-compact.runtime-B6e3kwMS.js +10 -0
  130. package/dist/commands-compact.runtime.js +1 -1
  131. package/dist/commands-handlers.runtime-B0gTkAC0.js +4599 -0
  132. package/dist/commands-handlers.runtime.js +1 -1
  133. package/dist/commands-status-BgZ64sA8.js +16 -0
  134. package/dist/commands-status.runtime-JI89gIEU.js +3 -0
  135. package/dist/commands-status.runtime.js +1 -1
  136. package/dist/commands-subagents-control.runtime-B0hdcBxr.js +2 -0
  137. package/dist/commands-subagents-control.runtime-DUeSQ5j4.js +3 -0
  138. package/dist/commands-subagents-control.runtime.js +1 -1
  139. package/dist/commands-system-prompt-B7moUaCI.js +158 -0
  140. package/dist/commands-system-prompt-DTUkp9TH.js +2 -0
  141. package/dist/commands.runtime-BjCVVqol.js +167 -0
  142. package/dist/commands.runtime.js +1 -1
  143. package/dist/compact-BNJH56SX.js +1118 -0
  144. package/dist/compact.runtime-CYI8Yi9d.js +12 -0
  145. package/dist/compact.runtime.js +1 -1
  146. package/dist/completion-cli-BS9GGHM0.js +328 -0
  147. package/dist/config-DxkleHmo.js +252 -0
  148. package/dist/config-cli-B1bF4s1q.js +1078 -0
  149. package/dist/configure-Bp8WFryM.js +1252 -0
  150. package/dist/configure-DQ_X5zyT.js +2 -0
  151. package/dist/connect-options-BkWD0Wvv.js +699 -0
  152. package/dist/control-auth-Iqyldslx.js +125 -0
  153. package/dist/control-service-xIhkqyZE.js +156 -0
  154. package/dist/control-ui/assets/agents-yxLbGWBi.js +1052 -0
  155. package/dist/control-ui/assets/canvas-D2O4KY2F.js +269 -0
  156. package/dist/control-ui/assets/channel-config-extras-CNdHdere.js +2 -0
  157. package/dist/control-ui/assets/channels-MV5mvE13.js +463 -0
  158. package/dist/control-ui/assets/cron-nvHn9HVd.js +933 -0
  159. package/dist/control-ui/assets/de-ona0Q7Bc.js +2 -0
  160. package/dist/control-ui/assets/debug-BDgyL0QB.js +94 -0
  161. package/dist/control-ui/assets/es-Dn-oNRUH.js +2 -0
  162. package/dist/control-ui/assets/format-BvrOTETl.js +9 -0
  163. package/dist/control-ui/assets/fr-DXJ2RnNl.js +2 -0
  164. package/dist/control-ui/assets/i18n-BiXTtoQW.js +3 -0
  165. package/dist/control-ui/assets/id-BWsRmAR3.js +2 -0
  166. package/dist/control-ui/assets/index-BSKZQZqm.css +1 -0
  167. package/dist/control-ui/assets/index-CM19wT50.js +6255 -0
  168. package/dist/control-ui/assets/instances-i9wzFtbu.js +57 -0
  169. package/dist/control-ui/assets/ja-JP-BUkQN13S.js +2 -0
  170. package/dist/control-ui/assets/ko-Q_K13wyH.js +2 -0
  171. package/dist/control-ui/assets/logs-CzRlG5kP.js +74 -0
  172. package/dist/control-ui/assets/mcp-pb4IaSGI.js +373 -0
  173. package/dist/control-ui/assets/nodes-C0846GJV.js +618 -0
  174. package/dist/control-ui/assets/pl-WlhlBCqd.js +2 -0
  175. package/dist/control-ui/assets/plugins-DSCHUDT6.js +273 -0
  176. package/dist/control-ui/assets/pt-BR-CVchspYo.js +2 -0
  177. package/dist/control-ui/assets/sessions-C1ziAwB3.js +306 -0
  178. package/dist/control-ui/assets/skills-BPsn23lW.js +323 -0
  179. package/dist/control-ui/assets/skills-shared-BbxW-wNm.js +11 -0
  180. package/dist/control-ui/assets/th-C4FUN3Mq.js +2 -0
  181. package/dist/control-ui/assets/tr-CoySBXqw.js +2 -0
  182. package/dist/control-ui/assets/uk-C-mkZs9j.js +2 -0
  183. package/dist/control-ui/assets/wallet-BiPoXXEx.js +285 -0
  184. package/dist/control-ui/assets/zh-CN-B7HXiLrY.js +2 -0
  185. package/dist/control-ui/assets/zh-TW-CKLRstBM.js +2 -0
  186. package/dist/control-ui/index.html +22 -36
  187. package/dist/conversation-id-BZtOqHIz.js +38 -0
  188. package/dist/conversation-id-D1Q9qPFH.js +235 -0
  189. package/dist/conversation-runtime-B1QZ-DEM.js +31 -0
  190. package/dist/core-BdVAy0Wv.js +275 -0
  191. package/dist/cron-cli-BWM2kRKU.js +713 -0
  192. package/dist/daemon-cli-MRl5nyuF.js +12 -0
  193. package/dist/dashboard-BkdlJrnf.js +2 -0
  194. package/dist/dashboard-C9m86rHv.js +81 -0
  195. package/dist/delegate-BjUvKQlo.js +64 -0
  196. package/dist/detached-task-runtime-BAEzkNB8.js +73 -0
  197. package/dist/devices-cli-B1n6tl9f.js +498 -0
  198. package/dist/diagnostics-DZxWkW3i.js +154 -0
  199. package/dist/direct-dm-qw-uk31C.js +64 -0
  200. package/dist/dispatch-D0xiJ6Up.js +1131 -0
  201. package/dist/dispatch-acp-DVN58m9G.js +981 -0
  202. package/dist/dispatch-acp-manager.runtime-C8t1i5Wt.js +3 -0
  203. package/dist/dispatch-acp-manager.runtime.js +1 -1
  204. package/dist/dispatch-acp.runtime-FR0DUPpn.js +19 -0
  205. package/dist/dispatch-acp.runtime.js +1 -1
  206. package/dist/doctor-device-pairing-DIbiBPlL.js +307 -0
  207. package/dist/doctor-gateway-daemon-flow-BFjRlXvA.js +250 -0
  208. package/dist/doctor-gateway-health-uZrukX3c.js +63 -0
  209. package/dist/doctor-health-DKpg1bxM.js +59 -0
  210. package/dist/doctor-health-contributions-BoXX8ubw.js +493 -0
  211. package/dist/doctor-prompter-CLf5Uf10.js +56 -0
  212. package/dist/doctor-workspace-status-Cw61BbGy.js +75 -0
  213. package/dist/dreaming-Bk8dVfGi.js +1574 -0
  214. package/dist/dreaming-narrative-DGSQa-0N.js +595 -0
  215. package/dist/embedded-gateway-stub.runtime-sokWrs6B.js +9 -0
  216. package/dist/embedded-gateway-stub.runtime.js +1 -1
  217. package/dist/entry.js +2 -2
  218. package/dist/exec-approvals-cli-CnNETs_u.js +498 -0
  219. package/dist/extensionAPI.js +1 -1
  220. package/dist/extensions/active-memory/index.js +1 -1
  221. package/dist/extensions/bluebubbles/api.js +3 -3
  222. package/dist/extensions/bluebubbles/channel-plugin-api.js +1 -1
  223. package/dist/extensions/browser/browser-bridge.js +1 -1
  224. package/dist/extensions/browser/browser-config.js +4 -4
  225. package/dist/extensions/browser/browser-control-auth.js +2 -2
  226. package/dist/extensions/browser/browser-doctor.js +2 -2
  227. package/dist/extensions/browser/browser-maintenance.js +2 -2
  228. package/dist/extensions/browser/browser-profiles.js +2 -2
  229. package/dist/extensions/browser/browser-runtime-api.js +10 -10
  230. package/dist/extensions/browser/index.js +1 -1
  231. package/dist/extensions/browser/plugin-registration.js +1 -1
  232. package/dist/extensions/browser/register.runtime.js +3 -3
  233. package/dist/extensions/browser/runtime-api.js +11 -11
  234. package/dist/extensions/browser/test-support.js +1 -1
  235. package/dist/extensions/device-pair/api.js +1 -1
  236. package/dist/extensions/device-pair/index.js +3 -3
  237. package/dist/extensions/device-pair/notify.js +1 -1
  238. package/dist/extensions/device-pair/pair-command-approve.js +1 -1
  239. package/dist/extensions/google-meet/index.js +2 -2
  240. package/dist/extensions/imessage/api.js +3 -3
  241. package/dist/extensions/imessage/channel-plugin-api.js +1 -1
  242. package/dist/extensions/imessage/runtime-api.js +3 -3
  243. package/dist/extensions/irc/api.js +2 -2
  244. package/dist/extensions/irc/channel-plugin-api.js +1 -1
  245. package/dist/extensions/line/api.js +2 -2
  246. package/dist/extensions/line/channel-plugin-api.js +1 -1
  247. package/dist/extensions/line/contract-api.js +1 -1
  248. package/dist/extensions/line/runtime-api.js +4 -4
  249. package/dist/extensions/line/setup-api.js +1 -1
  250. package/dist/extensions/llm-task/index.js +2 -2
  251. package/dist/extensions/lobster/index.js +3 -3
  252. package/dist/extensions/lobster/runtime-api.js +1 -1
  253. package/dist/extensions/mattermost/api.js +1 -1
  254. package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
  255. package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
  256. package/dist/extensions/mattermost/policy-api.js +1 -1
  257. package/dist/extensions/mattermost/runtime-api.js +4 -4
  258. package/dist/extensions/mattermost/slash-route-api.js +1 -1
  259. package/dist/extensions/memory-core/api.js +1 -1
  260. package/dist/extensions/memory-core/cli-metadata.js +2 -2
  261. package/dist/extensions/memory-core/index.js +3 -3
  262. package/dist/extensions/memory-lancedb/cli-metadata.js +1 -1
  263. package/dist/extensions/msteams/api.js +1 -1
  264. package/dist/extensions/msteams/channel-plugin-api.js +1 -1
  265. package/dist/extensions/msteams/runtime-api.js +3 -3
  266. package/dist/extensions/msteams/test-api.js +1 -1
  267. package/dist/extensions/nextcloud-talk/api.js +1 -1
  268. package/dist/extensions/nextcloud-talk/channel-plugin-api.js +1 -1
  269. package/dist/extensions/nextcloud-talk/runtime-api.js +2 -2
  270. package/dist/extensions/openshell/index.js +2 -2
  271. package/dist/extensions/signal/api.js +6 -6
  272. package/dist/extensions/signal/channel-plugin-api.js +1 -1
  273. package/dist/extensions/signal/reaction-runtime-api.js +1 -1
  274. package/dist/extensions/signal/runtime-api.js +7 -7
  275. package/dist/extensions/skill-workshop/api.js +1 -1
  276. package/dist/extensions/skill-workshop/index.js +1 -1
  277. package/dist/extensions/synology-chat/api.js +1 -1
  278. package/dist/extensions/synology-chat/channel-plugin-api.js +1 -1
  279. package/dist/extensions/tlon/api.js +2 -2
  280. package/dist/extensions/tlon/channel-plugin-api.js +1 -1
  281. package/dist/extensions/tlon/runtime-api.js +1 -1
  282. package/dist/extensions/tlon/test-api.js +1 -1
  283. package/dist/extensions/twitch/api.js +1 -1
  284. package/dist/extensions/twitch/channel-plugin-api.js +1 -1
  285. package/dist/extensions/twitch/setup-plugin-api.js +1 -1
  286. package/dist/extensions/zalo/api.js +3 -3
  287. package/dist/extensions/zalo/channel-plugin-api.js +1 -1
  288. package/dist/extensions/zalo/runtime-api.js +2 -2
  289. package/dist/extensions/zalo/setup-api.js +2 -2
  290. package/dist/extensions/zalouser/api.js +3 -3
  291. package/dist/extensions/zalouser/channel-plugin-api.js +1 -1
  292. package/dist/extensions/zalouser/runtime-api.js +6 -6
  293. package/dist/extensions/zalouser/setup-plugin-api.js +1 -1
  294. package/dist/extensions/zalouser/test-api.js +1 -1
  295. package/dist/fallbacks-BwNexEVP.js +31 -0
  296. package/dist/fallbacks-GwVAaFt5.js +2 -0
  297. package/dist/fallbacks-shared-DmepG9Mq.js +111 -0
  298. package/dist/gateway-BB4hdlYm.js +115 -0
  299. package/dist/gateway-cli-Bh2bCtNy.js +1283 -0
  300. package/dist/gateway-rpc-dyJV2osv.js +14 -0
  301. package/dist/gateway-rpc.runtime-DYVOEv4W.js +23 -0
  302. package/dist/gateway-rpc.runtime.js +1 -1
  303. package/dist/gateway-runtime-CqSQCYo0.js +15 -0
  304. package/dist/gateway-status-DdCiwrPt.js +584 -0
  305. package/dist/genesis-tools-Bh6dAUhK.js +9166 -0
  306. package/dist/genesis-tools.runtime-CiIUponP.js +2 -0
  307. package/dist/genesis-tools.runtime.js +1 -1
  308. package/dist/get-reply-from-config.runtime-Cu2DcwOW.js +2 -0
  309. package/dist/get-reply-from-config.runtime.js +1 -1
  310. package/dist/get-reply-qVmTjhwr.js +3897 -0
  311. package/dist/graph-users-kkSJYBNX.js +1337 -0
  312. package/dist/health-CFyVDYng.js +469 -0
  313. package/dist/health-Cl371mu8.js +3 -0
  314. package/dist/health-route-D0IspgUK.js +41 -0
  315. package/dist/health-route-D2tFKCLv.js +2 -0
  316. package/dist/heartbeat-runner-Bmi8YsXz.js +5 -0
  317. package/dist/heartbeat-runner-FSCWra2R.js +1292 -0
  318. package/dist/heartbeat-runner.runtime-QF8dg4j-.js +4 -0
  319. package/dist/heartbeat-runner.runtime.js +1 -1
  320. package/dist/hooks-cli-DYoG7Dz1.js +433 -0
  321. package/dist/image-fallbacks-5ckuJ46I.js +31 -0
  322. package/dist/image-fallbacks-DYnqzK01.js +2 -0
  323. package/dist/inbound-reply-dispatch-D5pqDZRa.js +73 -0
  324. package/dist/index.js +2 -2
  325. package/dist/infra-runtime-D08WIqN2.js +39 -0
  326. package/dist/init-BCgwiSZj.js +59 -0
  327. package/dist/library-CP9n_7AP.js +45 -0
  328. package/dist/lifecycle-BYam90xH.js +229 -0
  329. package/dist/lifecycle-DS58sNmu.js +571 -0
  330. package/dist/lifecycle.runtime-DMwss7xM.js +2 -0
  331. package/dist/lifecycle.runtime.js +1 -1
  332. package/dist/list-CASc4IWz.js +131 -0
  333. package/dist/list-CBPrBS2u.js +1212 -0
  334. package/dist/list-Cf7fcqQd.js +2 -0
  335. package/dist/list-Dqd2QyTH.js +2 -0
  336. package/dist/list.probe-BWcMSWDF.js +419 -0
  337. package/dist/llm-slug-generator-4LADFhXT.js +79 -0
  338. package/dist/llm-slug-generator.js +1 -1
  339. package/dist/load-config-DI-LDL6p.js +35 -0
  340. package/dist/local-dispatch.runtime-WDgraH3j.js +8 -0
  341. package/dist/local-dispatch.runtime.js +1 -1
  342. package/dist/logs-cli-zoBIelUH.js +265 -0
  343. package/dist/logs-cli.runtime-DxKNxXAz.js +2 -0
  344. package/dist/logs-cli.runtime.js +1 -1
  345. package/dist/main-session-restart-recovery-DWZfkOzH.js +206 -0
  346. package/dist/managed-image-attachments-DLDa1aE2.js +2 -0
  347. package/dist/managed-image-attachments-a4v60Bk3.js +635 -0
  348. package/dist/manager-CfUcsSI9.js +2057 -0
  349. package/dist/manager-DmBBLCOg.js +2 -0
  350. package/dist/markdown-to-line-B0mPruD_.js +790 -0
  351. package/dist/mcp/plugin-tools-serve.js +1 -1
  352. package/dist/mcp-cli-CLL9nfvE.js +725 -0
  353. package/dist/mcp-http-p7GbtbMx.js +529 -0
  354. package/dist/memory-core-host-runtime-cli-CZNYkDoE.js +9 -0
  355. package/dist/message-CRyNLXch.js +232 -0
  356. package/dist/message-action-runner-5Y4EFpWh.js +1407 -0
  357. package/dist/message-action-runner-Dxv-GXkn.js +2 -0
  358. package/dist/message-actions-DtoR6Mr2.js +143 -0
  359. package/dist/message.gateway.runtime-RI4cvk_E.js +2 -0
  360. package/dist/message.gateway.runtime.js +1 -1
  361. package/dist/models-auth-status-DsheCXaS.js +201 -0
  362. package/dist/models-cli-CQQG1U-p.js +219 -0
  363. package/dist/monitor-BRRSjPQY.js +1459 -0
  364. package/dist/monitor-Ch-cG7Si.js +1661 -0
  365. package/dist/monitor-ChBhfnC-.js +788 -0
  366. package/dist/monitor-CsvCTpjq.js +671 -0
  367. package/dist/monitor-DjemBuVh.js +1237 -0
  368. package/dist/monitor-LyGEO-KI.js +2 -0
  369. package/dist/monitor-auth-DVCdDwlp.js +207 -0
  370. package/dist/monitor-processing-Cib3ZjUe.js +1974 -0
  371. package/dist/monitor.runtime-DLBFALbV.js +2 -0
  372. package/dist/monitor.runtime.js +1 -1
  373. package/dist/monitor.webhook-Dktr8JA-.js +180 -0
  374. package/dist/msteams-G5I2CO13.js +35 -0
  375. package/dist/native-hook-relay-B1ArNeG5.js +519 -0
  376. package/dist/nextcloud-talk-DimOAfaR.js +17 -0
  377. package/dist/node-cli-RIjV0id4.js +2276 -0
  378. package/dist/nodes-cli-Cke-B80I.js +1046 -0
  379. package/dist/nodes-utils-CsTqKwN9.js +84 -0
  380. package/dist/nodes.helpers-DYpGCFer.js +34 -0
  381. package/dist/notify-zBChwf0-.js +315 -0
  382. package/dist/onboard-D6UawRld.js +2 -0
  383. package/dist/onboard-DfoCtk3_.js +70 -0
  384. package/dist/onboard-helpers-BKQMe3RX.js +6 -0
  385. package/dist/onboard-helpers-BLBJlQ50.js +204 -0
  386. package/dist/onboard-interactive-GAbQD437.js +24 -0
  387. package/dist/onboard-non-interactive-Bqi-JXh3.js +635 -0
  388. package/dist/onboard-remote-CNpTyVws.js +193 -0
  389. package/dist/onboard-remote-GFp2lT6Y.js +2 -0
  390. package/dist/onboard-skills-BQneolfo.js +2 -0
  391. package/dist/onboard-skills-BipqJ48b.js +134 -0
  392. package/dist/openai-http-CLDWjSKC.js +500 -0
  393. package/dist/openresponses-http-DNvXNiw_.js +1128 -0
  394. package/dist/operator-approvals-client-gaflvETF.js +68 -0
  395. package/dist/outbound.runtime-ByVsvEri.js +2 -0
  396. package/dist/outbound.runtime.js +1 -1
  397. package/dist/pair-command-approve-Dzkubc-8.js +44 -0
  398. package/dist/persistent-bindings.lifecycle-BhdRK7Lp.js +2 -0
  399. package/dist/persistent-bindings.lifecycle-DQ0AiHuy.js +85 -0
  400. package/dist/pi-embedded-C789hs31.js +4 -0
  401. package/dist/pi-embedded-CXLkrOwv.js +2905 -0
  402. package/dist/pi-embedded.runtime-BaHYLgKa.js +4 -0
  403. package/dist/pi-embedded.runtime.js +1 -1
  404. package/dist/pi-tool-definition-adapter-DFutc0D4.js +229 -0
  405. package/dist/pi-tools-k60jrAVq.js +1057 -0
  406. package/dist/pi-tools.before-tool-call-CFy20GCz.js +2 -0
  407. package/dist/pi-tools.before-tool-call-DJmPOVfQ.js +433 -0
  408. package/dist/plugin-BfFuIgXQ.js +12195 -0
  409. package/dist/plugin-enabled-dXOUnZwX.js +140 -0
  410. package/dist/plugin-registration-CEAozQhV.js +23 -0
  411. package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
  412. package/dist/plugin-sdk/acp-binding-runtime.js +1 -1
  413. package/dist/plugin-sdk/acp-runtime.js +2 -2
  414. package/dist/plugin-sdk/agent-harness-runtime.js +5 -5
  415. package/dist/plugin-sdk/agent-harness.js +6 -6
  416. package/dist/plugin-sdk/agent-runtime.js +2 -2
  417. package/dist/plugin-sdk/approval-gateway-runtime.js +2 -2
  418. package/dist/plugin-sdk/approval-handler-runtime.js +3 -3
  419. package/dist/plugin-sdk/approval-runtime.js +1 -1
  420. package/dist/plugin-sdk/browser-node-runtime.js +4 -4
  421. package/dist/plugin-sdk/browser-setup-tools.js +3 -3
  422. package/dist/plugin-sdk/browser-support.js +7 -7
  423. package/dist/plugin-sdk/channel-core.js +2 -2
  424. package/dist/plugin-sdk/channel-inbound.js +2 -2
  425. package/dist/plugin-sdk/command-auth.js +1 -1
  426. package/dist/plugin-sdk/command-status-runtime.js +1 -1
  427. package/dist/plugin-sdk/compat.js +1 -1
  428. package/dist/plugin-sdk/conversation-binding-runtime.js +1 -1
  429. package/dist/plugin-sdk/conversation-runtime.js +3 -3
  430. package/dist/plugin-sdk/core.js +2 -2
  431. package/dist/plugin-sdk/direct-dm.js +1 -1
  432. package/dist/plugin-sdk/gateway-runtime.js +3 -3
  433. package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
  434. package/dist/plugin-sdk/index.js +1 -1
  435. package/dist/plugin-sdk/infra-runtime.js +2 -2
  436. package/dist/plugin-sdk/irc.js +2 -2
  437. package/dist/plugin-sdk/matrix.js +1 -1
  438. package/dist/plugin-sdk/memory-core-host-runtime-cli.js +2 -2
  439. package/dist/plugin-sdk/memory-core.js +2 -2
  440. package/dist/plugin-sdk/msteams.js +2 -2
  441. package/dist/plugin-sdk/nextcloud-talk.js +2 -2
  442. package/dist/plugin-sdk/nostr.js +1 -1
  443. package/dist/plugin-sdk/reply-dispatch-runtime.js +1 -1
  444. package/dist/plugin-sdk/reply-runtime.js +4 -4
  445. package/dist/plugin-sdk/runtime-secret-resolution.js +1 -1
  446. package/dist/plugin-sdk/runtime.js +2 -2
  447. package/dist/plugin-sdk/session-visibility.js +1 -1
  448. package/dist/plugin-sdk/testing.js +4 -4
  449. package/dist/plugin-sdk/tlon.js +1 -1
  450. package/dist/plugin-sdk/zalo.js +1 -1
  451. package/dist/plugin-sdk/zalouser.js +1 -1
  452. package/dist/plugin-service-BOpLQ8BU.js +2892 -0
  453. package/dist/plugins/runtime/index.js +1 -1
  454. package/dist/policy-DiIlt2yW.js +328 -0
  455. package/dist/postinstall-inventory.json +446 -446
  456. package/dist/prepare.runtime-Bd8adOy3.js +815 -0
  457. package/dist/prepare.runtime.js +1 -1
  458. package/dist/probe-BOlTfbzG.js +2 -0
  459. package/dist/probe-BSRvsN95.js +2205 -0
  460. package/dist/probe-CDfjQSnz.js +74 -0
  461. package/dist/probe-D7gHyiZV.js +241 -0
  462. package/dist/probe-DTNKTWSs.js +2 -0
  463. package/dist/probe-DcryDdZh.js +45 -0
  464. package/dist/probe-nyesoHxj.js +1443 -0
  465. package/dist/program-CaXAMkVs.js +111 -0
  466. package/dist/prompt-select-styled-BhY1zahx.js +20 -0
  467. package/dist/protocol-DxLbSF2J.js +2477 -0
  468. package/dist/provider-dispatcher-C-yy1D7r.js +22 -0
  469. package/dist/provider-dispatcher-ErSjESTP.js +2 -0
  470. package/dist/qr-cli-C1-oy_ho.js +349 -0
  471. package/dist/qr-cli-DmEs63Sb.js +2 -0
  472. package/dist/reaction-runtime-api-gua650a7.js +116 -0
  473. package/dist/reactions-R-rA7cXz.js +998 -0
  474. package/dist/register-service-commands-DkbqNKVB.js +71 -0
  475. package/dist/register.agent-C3nW9wDn.js +248 -0
  476. package/dist/register.configure-BzLHCu95.js +15 -0
  477. package/dist/register.maintenance-BHFQo4gr.js +363 -0
  478. package/dist/register.message-CsYRdfKi.js +329 -0
  479. package/dist/register.onboard-DltySQ6C.js +88 -0
  480. package/dist/register.runtime-6Sk1Njnp.js +81 -0
  481. package/dist/register.runtime.js +1 -1
  482. package/dist/register.setup-CDvVQJuj.js +150 -0
  483. package/dist/register.status-health-sessions-B8lorJ2x.js +1215 -0
  484. package/dist/register.subclis-C4zdCa8t.js +3 -0
  485. package/dist/register.subclis-core-DKMsWmjc.js +249 -0
  486. package/dist/register.subclis-hUizvi2-.js +29 -0
  487. package/dist/reply-dispatch-runtime-DldslKSK.js +13 -0
  488. package/dist/reply-runtime-2EGTfk-1.js +11 -0
  489. package/dist/reply.runtime-OaHntzIS.js +2 -0
  490. package/dist/reply.runtime.js +1 -1
  491. package/dist/restart-health-BjmfJCUM.js +202 -0
  492. package/dist/restart-health-hw909zlD.js +2 -0
  493. package/dist/root-help-_hHiERsR.js +44 -0
  494. package/dist/routes-BxCk7Pue.js +3341 -0
  495. package/dist/routes-C1_6oFmZ.js +2 -0
  496. package/dist/rpc-zRbkEo6W.js +61 -0
  497. package/dist/rpc.runtime-BZSYNDPa.js +21 -0
  498. package/dist/rpc.runtime.js +1 -1
  499. package/dist/run-delivery.runtime-D6YDo67d.js +530 -0
  500. package/dist/run-delivery.runtime.js +1 -1
  501. package/dist/run-embedded.runtime-BsgPrPDa.js +4 -0
  502. package/dist/run-embedded.runtime.js +1 -1
  503. package/dist/run-execution-cli.runtime-CggaHhrJ.js +4 -0
  504. package/dist/run-execution-cli.runtime.js +1 -1
  505. package/dist/run-executor.runtime-CKkLEr_T.js +277 -0
  506. package/dist/run-executor.runtime.js +1 -1
  507. package/dist/run-main-DrO3awL8.js +567 -0
  508. package/dist/run-subagent-registry.runtime-B0sgf_oy.js +2 -0
  509. package/dist/run-subagent-registry.runtime.js +1 -1
  510. package/dist/run-wait-DHizeptL.js +135 -0
  511. package/dist/runtime-EtV_ChXX.js +9 -0
  512. package/dist/runtime-api-6H864Pmt.js +9 -0
  513. package/dist/runtime-api-CbZqRBZQ.js +14 -0
  514. package/dist/runtime-api-ZxEgu8cW.js +4 -0
  515. package/dist/runtime-api-j9A6jYUr.js +9 -0
  516. package/dist/runtime-embedded-pi.runtime-BHjCPnxo.js +2 -0
  517. package/dist/runtime-embedded-pi.runtime.js +1 -1
  518. package/dist/runtime-hvRzTSAZ.js +973 -0
  519. package/dist/runtime-internal-C_KZYzFK.js +2 -0
  520. package/dist/runtime-options-BZEOCnMg.js +275 -0
  521. package/dist/runtime-schema-BaM8e_HG.js +28576 -0
  522. package/dist/scan-BNDE3dSE.js +523 -0
  523. package/dist/scan-TG6lVEQ2.js +2 -0
  524. package/dist/secrets-cli-twD2FWoZ.js +2101 -0
  525. package/dist/security-cli-Cd1A5yhL.js +486 -0
  526. package/dist/selection-CqqmU0Hi.js +7764 -0
  527. package/dist/selection-CsM62vcz.js +2 -0
  528. package/dist/send-D-EgB64m.js +156 -0
  529. package/dist/send-DPk5hW1W.js +102 -0
  530. package/dist/send.runtime-3QDkKN71.js +2 -0
  531. package/dist/send.runtime.js +1 -1
  532. package/dist/server-C94r_Qff.js +77 -0
  533. package/dist/server-CSSVuQzS.js +13 -0
  534. package/dist/server-context-BFJlu5HY.js +2 -0
  535. package/dist/server-context-PNEqhnTM.js +847 -0
  536. package/dist/server-node-events-QOAWLsDC.js +481 -0
  537. package/dist/server-plugin-bootstrap-B5JaynXk.js +12728 -0
  538. package/dist/server-plugin-bootstrap-fIJyUQIz.js +2 -0
  539. package/dist/server-restart-sentinel-BMPqZ7Jw.js +697 -0
  540. package/dist/server.impl-Ch3-ajhz.js +12864 -0
  541. package/dist/session-kill-http-oPi3ajEp.js +110 -0
  542. package/dist/session-reset-service-CzDd6PBK.js +497 -0
  543. package/dist/session-route-DUOQE8-f.js +93 -0
  544. package/dist/session-status.runtime-W5tlGbXw.js +2 -0
  545. package/dist/session-status.runtime.js +1 -1
  546. package/dist/session-subagent-reactivation.runtime-yoYn1awK.js +2 -0
  547. package/dist/session-subagent-reactivation.runtime.js +1 -1
  548. package/dist/session-tab-registry-DkeCaT-2.js +581 -0
  549. package/dist/session-visibility-B4CFjv43.js +147 -0
  550. package/dist/sessions-helpers-CDfOVWe3.js +305 -0
  551. package/dist/sessions-history-http-QXeTdxXM.js +383 -0
  552. package/dist/sessions-patch-xb4bXPwh.js +309 -0
  553. package/dist/sessions-resolve-BPlrW8C3.js +174 -0
  554. package/dist/sessions.runtime-yYJXudA9.js +2 -0
  555. package/dist/sessions.runtime.js +1 -1
  556. package/dist/setup-0Im0LL1d.js +636 -0
  557. package/dist/setup-api-BxwfqXN-.js +29 -0
  558. package/dist/setup-core-BWwXgEuM.js +171 -0
  559. package/dist/setup-core-DzHNbQLG.js +176 -0
  560. package/dist/setup-surface-BVnqDsfU.js +286 -0
  561. package/dist/setup-surface-BajZWmKz2.js +403 -0
  562. package/dist/setup-surface-rDO3YjSb.js +219 -0
  563. package/dist/setup.finalize-BsnPbdwc.js +547 -0
  564. package/dist/setup.gateway-config-BFawSWHL.js +250 -0
  565. package/dist/shared-52tFSlVk.js +121 -0
  566. package/dist/shared-C8ENgtxM.js +198 -0
  567. package/dist/shared-DbXvU7JV.js +76 -0
  568. package/dist/slash-state-CMuPwgKt.js +1911 -0
  569. package/dist/src-IzaHgU6a.js +3974 -0
  570. package/dist/startup-context-xJS8ckSG.js +312 -0
  571. package/dist/status-BO4LMTER.js +2 -0
  572. package/dist/status-BwY1tASe.js +3 -0
  573. package/dist/status-BxG6n-ko.js +397 -0
  574. package/dist/status-Co_cq2vy.js +2 -0
  575. package/dist/status-DKNeRGzW.js +190 -0
  576. package/dist/status-DzlIHiTS.js +209 -0
  577. package/dist/status-all-DF7qaWjo.js +498 -0
  578. package/dist/status-json-CgCilobT.js +14 -0
  579. package/dist/status-json-command-DAa78z3e.js +84 -0
  580. package/dist/status-runtime-shared-CRCuxXn_.js +257 -0
  581. package/dist/status-subagents.runtime-hUsBd4C5.js +18 -0
  582. package/dist/status-subagents.runtime.js +1 -1
  583. package/dist/status-text-BdbRrl1G.js +237 -0
  584. package/dist/status.gateway-connection.runtime-BmSTYFFO.js +2 -0
  585. package/dist/status.gateway-connection.runtime.js +1 -1
  586. package/dist/status.gather-CItmFIHS.js +292 -0
  587. package/dist/status.gather-qB6WOoH7.js +2 -0
  588. package/dist/status.runtime-ClZCgYx1.js +2 -0
  589. package/dist/status.runtime.js +1 -1
  590. package/dist/status.scan-overview-B0b0Mvng.js +379 -0
  591. package/dist/status.scan-xY7nUi9N.js +65 -0
  592. package/dist/status.scan.fast-json-BANGHOys.js +132 -0
  593. package/dist/status.scan.fast-json-M-DmMy2l.js +2 -0
  594. package/dist/status.summary-B3PlFnWw.js +2 -0
  595. package/dist/status.summary-adB75FOM.js +214 -0
  596. package/dist/subagent-announce-B4w7Mcpr.js +351 -0
  597. package/dist/subagent-announce-delivery-Dma0A4gL.js +726 -0
  598. package/dist/subagent-announce-output-sUPLcge-.js +364 -0
  599. package/dist/subagent-control-CxR0WRrx.js +506 -0
  600. package/dist/subagent-followup.runtime-XeFe_LA0.js +68 -0
  601. package/dist/subagent-followup.runtime.js +1 -1
  602. package/dist/subagent-orphan-recovery-CJPHy8JV.js +305 -0
  603. package/dist/subagent-registry-CjMWjRCE.js +1753 -0
  604. package/dist/subagent-registry-H20VxEu0.js +3 -0
  605. package/dist/subagent-registry.runtime.js +1 -1
  606. package/dist/subagent-spawn-CRM5x6cV.js +1005 -0
  607. package/dist/system-cli-BJ5mMirj.js +59 -0
  608. package/dist/targets-CUnlEj96.js +67 -0
  609. package/dist/task-executor-DKnEwQ6v.js +360 -0
  610. package/dist/task-owner-access-CfypP1Yc.js +74 -0
  611. package/dist/task-registry-delivery-runtime-BB6ZzpqH.js +2 -0
  612. package/dist/task-registry-delivery-runtime-CvHa0gv-.js +3 -0
  613. package/dist/task-registry-pQuAfAL9.js +2366 -0
  614. package/dist/task-registry.maintenance-Bfd87wEV.js +416 -0
  615. package/dist/task-registry.maintenance-VgfbW0yt.js +2 -0
  616. package/dist/telegram/token.js +1 -1
  617. package/dist/testing-C_mngO0u.js +575 -0
  618. package/dist/text-report-Ct6t3he6.js +587 -0
  619. package/dist/tool-resolution-C4KGgPH-.js +90 -0
  620. package/dist/tools-effective-inventory-Bo2QC-m8.js +152 -0
  621. package/dist/tools-invoke-http-CBZPFh5L.js +206 -0
  622. package/dist/trash-DhZow3jd.js +24 -0
  623. package/dist/tui-cli-BPdQPozP.js +4575 -0
  624. package/dist/update-cli-BRi3mVAU.js +1759 -0
  625. package/dist/upgrade-D9zejtCk.js +1226 -0
  626. package/dist/video-generation-task-status-BSBQ0_FO.js +163 -0
  627. package/dist/wait-for-idle-before-flush-D1dTT9th.js +5986 -0
  628. package/dist/wizard-models-ysyV_WWR.js +334 -0
  629. package/package.json +1 -1
  630. package/dist/abort-DaihtnYj.js +0 -201
  631. package/dist/abort.runtime-BUT9L_5l.js +0 -2
  632. package/dist/accounts-BY5wsBnV.js +0 -104
  633. package/dist/accounts-DGth1vsM.js +0 -107
  634. package/dist/accounts-Do6Ir-q3.js +0 -2
  635. package/dist/acp-cli-BHgjn8rh.js +0 -2193
  636. package/dist/acp-spawn-BAM_Jrft.js +0 -2
  637. package/dist/acp-spawn-DyBD_Y_t.js +0 -1093
  638. package/dist/acp-stateful-target-driver-DKGnfjWu.js +0 -89
  639. package/dist/action-agents-CzMSNQdc.js +0 -67
  640. package/dist/action-focus-CpjIrZFe.js +0 -132
  641. package/dist/action-help-BhE9UosK.js +0 -7
  642. package/dist/action-info-CH2j6dKT.js +0 -101
  643. package/dist/action-kill-CB4AnLIf.js +0 -33
  644. package/dist/action-list-CQ8LbzvR.js +0 -21
  645. package/dist/action-log-DZblh247.js +0 -30
  646. package/dist/action-send-DMe0B4FG.js +0 -39
  647. package/dist/action-spawn-CkKMESb5.js +0 -47
  648. package/dist/action-unfocus-DjQzPZwU.js +0 -29
  649. package/dist/actions.runtime-CUdRdpLB.js +0 -5
  650. package/dist/actions.runtime-CxRstWdN.js +0 -18
  651. package/dist/agent-command-Nh_kPL3z.js +0 -874
  652. package/dist/agent-harness-runtime-BEb7Wk1m.js +0 -144
  653. package/dist/agent-q6U-cKJn.js +0 -2
  654. package/dist/agent-runner-utils-x_qJ6xYC.js +0 -239
  655. package/dist/agent-runner.runtime-DRvTfUPd.js +0 -3455
  656. package/dist/agent-runtime-jSYYQd6f.js +0 -18
  657. package/dist/agents-BKOpsZXw.js +0 -5
  658. package/dist/agents-BY34ViPX.js +0 -954
  659. package/dist/aliases-CD5YlX7d.js +0 -2
  660. package/dist/aliases-Dq31zANx.js +0 -96
  661. package/dist/api-BhxN9fxJ.js +0 -139
  662. package/dist/api-DjL_3olO.js +0 -5
  663. package/dist/api-jIYND-S5.js +0 -3
  664. package/dist/approval-gateway-resolver-BfvdJW5s.js +0 -29
  665. package/dist/approval-gateway-runtime-BBf976nt.js +0 -2
  666. package/dist/approval-handler-runtime-Bq4p5wvg.js +0 -439
  667. package/dist/approval-native-runtime-IrisOZrU.js +0 -729
  668. package/dist/attempt-execution.runtime-BXGalt-_.js +0 -509
  669. package/dist/attempt.prompt-helpers-A-pc2LfL.js +0 -221
  670. package/dist/attempt.tool-run-context-Ukna4ck-.js +0 -933
  671. package/dist/audit-CVUpfDvE.js +0 -939
  672. package/dist/audit.runtime-CsuGXvud.js +0 -7
  673. package/dist/auth-CjcZyRUW.js +0 -383
  674. package/dist/auth-order-DIkyTpW4.js +0 -2
  675. package/dist/auth-order-Dpt1K1rT.js +0 -96
  676. package/dist/auth-sVuL2xeZ.js +0 -2
  677. package/dist/bash-tools-DDv0zQh9.js +0 -2824
  678. package/dist/bash-tools-s-QSvRmt.js +0 -3
  679. package/dist/binding-routing-Cz5R2kFK.js +0 -85
  680. package/dist/binding-targets-D4j2hdQh.js +0 -121
  681. package/dist/bridge-server-X8SdeAI3.js +0 -113
  682. package/dist/browser-control-auth-BrF3DZxC.js +0 -2
  683. package/dist/browser-node-runtime-BecPmKOx.js +0 -12
  684. package/dist/browser-profiles-BxAKEG3x.js +0 -2
  685. package/dist/browser-runtime-D9fTDscJ.js +0 -387
  686. package/dist/browser-setup-tools--AQGWGvl.js +0 -13
  687. package/dist/build-B0nbyXrw.js +0 -550
  688. package/dist/call-BvqN9kay.js +0 -3
  689. package/dist/call-Dk5rTl-p.js +0 -331
  690. package/dist/call.runtime-Bx1hKDwO.js +0 -2
  691. package/dist/capability-cli-286Z3Bq3.js +0 -1401
  692. package/dist/catchup-DyeQ6GNj.js +0 -300
  693. package/dist/channel-B5m01jSZ.js +0 -1802
  694. package/dist/channel-BE26v3WU.js +0 -840
  695. package/dist/channel-BS7r_Zt1.js +0 -226
  696. package/dist/channel-BUWCqkGh.js +0 -1320
  697. package/dist/channel-BhgKqvZn.js +0 -453
  698. package/dist/channel-Bx703sxQ.js +0 -297
  699. package/dist/channel-CDjlEQAM.js +0 -491
  700. package/dist/channel-ChrqAgRS.js +0 -595
  701. package/dist/channel-Crmp3BHh.js +0 -1100
  702. package/dist/channel-D7GdDfBl.js +0 -1174
  703. package/dist/channel-DqSzRIul.js +0 -350
  704. package/dist/channel-core-DIwclC34.js +0 -5
  705. package/dist/channel-inbound-DPW1gRUU.js +0 -31
  706. package/dist/channel-plugin-runtime-BJhRSlBI.js +0 -771
  707. package/dist/channel-runtime-sV_Sg0EO.js +0 -425
  708. package/dist/channel.runtime-4BaNapRW.js +0 -89
  709. package/dist/channel.runtime-Bk2w0Yzd.js +0 -2364
  710. package/dist/channel.runtime-Bo5_2imz.js +0 -109
  711. package/dist/channel.runtime-CdYWlMyL.js +0 -40130
  712. package/dist/channel.runtime-CrYmCmSw.js +0 -4
  713. package/dist/channel.runtime-D3APPhVs.js +0 -430
  714. package/dist/channel.runtime-DjF1Gg6N.js +0 -576
  715. package/dist/channel.setup-BxXrmAYb.js +0 -10
  716. package/dist/channels-DHcJgMnw.js +0 -733
  717. package/dist/channels-cli-Dnq08u4r.js +0 -268
  718. package/dist/chat-BGU3UVKD.js +0 -2830
  719. package/dist/clawbot-cli-C-rqJUW-.js +0 -9
  720. package/dist/cli-BlnGJbLJ.js +0 -219
  721. package/dist/cli-D0RU1q0-.js +0 -2
  722. package/dist/cli-DBw79G2t.js +0 -72
  723. package/dist/cli-Dul37_xp.js +0 -2
  724. package/dist/cli-runner-DY8BKEmu.js +0 -286
  725. package/dist/cli-runner.runtime-5JMuegF9.js +0 -3
  726. package/dist/cli-runner.runtime-DQROn9Ve.js +0 -4
  727. package/dist/cli.runtime-CGOUREQg.js +0 -1261
  728. package/dist/client-CCBN1ydB.js +0 -138
  729. package/dist/client-PHLyQ8il.js +0 -713
  730. package/dist/command-auth-79QKQZZ3.js +0 -76
  731. package/dist/command-config-resolution-BKAgMItc.js +0 -2
  732. package/dist/command-config-resolution-BUCAmCZ_.js +0 -23
  733. package/dist/command-config-resolution.runtime-BVtfeARM.js +0 -2
  734. package/dist/command-registry-C9axn0de.js +0 -4
  735. package/dist/command-registry-DkcFlIyM.js +0 -9
  736. package/dist/command-registry-core-DEDRtJmS.js +0 -106
  737. package/dist/command-secret-gateway-g0alGmKz.js +0 -528
  738. package/dist/command-status.runtime-Dw6Zj5hL.js +0 -87
  739. package/dist/commands-acp-De-XFc40.js +0 -77
  740. package/dist/commands-compact.runtime-6gixR2a8.js +0 -10
  741. package/dist/commands-handlers.runtime-DCmZAlRN.js +0 -4599
  742. package/dist/commands-status-CION7GYY.js +0 -16
  743. package/dist/commands-status.runtime-FBwoHftv.js +0 -3
  744. package/dist/commands-subagents-control.runtime-C2xgOYKM.js +0 -2
  745. package/dist/commands-subagents-control.runtime-CgIEblx3.js +0 -3
  746. package/dist/commands-system-prompt-B-jC-KV-.js +0 -158
  747. package/dist/commands-system-prompt-DeK5Jhy_.js +0 -2
  748. package/dist/commands.runtime-CHSb1kYa.js +0 -167
  749. package/dist/compact-Dwchggv2.js +0 -1118
  750. package/dist/compact.runtime-jDUYMSjR.js +0 -12
  751. package/dist/completion-cli-DGiZcg4E.js +0 -328
  752. package/dist/config-Bnb9qa1S.js +0 -252
  753. package/dist/config-cli-BuZ5RUhD.js +0 -1078
  754. package/dist/configure-BLNGlWh0.js +0 -1252
  755. package/dist/configure-nPzsEeOb.js +0 -2
  756. package/dist/connect-options-C9cvS-bh.js +0 -699
  757. package/dist/control-auth-D2-P54fW.js +0 -125
  758. package/dist/control-service-CqUPgxlx.js +0 -156
  759. package/dist/control-ui/assets/agents-CA3uz9sP.js +0 -1052
  760. package/dist/control-ui/assets/canvas-D0sLy568.js +0 -269
  761. package/dist/control-ui/assets/channel-config-extras-CWzNTLS-.js +0 -2
  762. package/dist/control-ui/assets/channels-DXgjbWts.js +0 -463
  763. package/dist/control-ui/assets/cron-D-rffMH6.js +0 -933
  764. package/dist/control-ui/assets/de-l9FbKtxt.js +0 -2
  765. package/dist/control-ui/assets/debug-Vf_bLYLB.js +0 -94
  766. package/dist/control-ui/assets/es-CC-t9AUQ.js +0 -2
  767. package/dist/control-ui/assets/format-BL-FisEP.js +0 -9
  768. package/dist/control-ui/assets/fr-DZKceqST.js +0 -2
  769. package/dist/control-ui/assets/i18n-DFH8x0DD.js +0 -3
  770. package/dist/control-ui/assets/id-D93YKkrM.js +0 -2
  771. package/dist/control-ui/assets/index-DrnKQaGF.css +0 -1
  772. package/dist/control-ui/assets/index-lWAwAXYo.js +0 -6366
  773. package/dist/control-ui/assets/instances-BmzzTloa.js +0 -57
  774. package/dist/control-ui/assets/ja-JP-DoPdk5L_.js +0 -2
  775. package/dist/control-ui/assets/ko-8TeOGGHm.js +0 -2
  776. package/dist/control-ui/assets/logs-BjPSImvD.js +0 -74
  777. package/dist/control-ui/assets/mcp-CQGmuKdR.js +0 -281
  778. package/dist/control-ui/assets/nodes-CDhqPGsD.js +0 -618
  779. package/dist/control-ui/assets/pl-BSP1Y3tH.js +0 -2
  780. package/dist/control-ui/assets/plugins-D4fXQx07.js +0 -273
  781. package/dist/control-ui/assets/pt-BR-D4-81_zm.js +0 -2
  782. package/dist/control-ui/assets/sessions-DzjXl7P7.js +0 -306
  783. package/dist/control-ui/assets/skills-BTQrLVPj.js +0 -323
  784. package/dist/control-ui/assets/skills-shared-CX4mwYFK.js +0 -11
  785. package/dist/control-ui/assets/th-DrnubOIu.js +0 -2
  786. package/dist/control-ui/assets/tr-BMyrj0eZ.js +0 -2
  787. package/dist/control-ui/assets/uk-CZhU3bHK.js +0 -2
  788. package/dist/control-ui/assets/wallet-DPb6whuj.js +0 -285
  789. package/dist/control-ui/assets/zh-CN-CH12jxSw.js +0 -2
  790. package/dist/control-ui/assets/zh-TW-CaTySceX.js +0 -2
  791. package/dist/conversation-id-BAzJOKBB.js +0 -235
  792. package/dist/conversation-id-WJLKuyy9.js +0 -38
  793. package/dist/conversation-runtime-D8fK5aI0.js +0 -31
  794. package/dist/core-DywmHt1k.js +0 -275
  795. package/dist/cron-cli-CeEJRkfR.js +0 -713
  796. package/dist/daemon-cli-BZZOjJHx.js +0 -12
  797. package/dist/dashboard-C0NRxmP3.js +0 -81
  798. package/dist/dashboard-DqhPgQv-.js +0 -2
  799. package/dist/delegate-DwVbOeR5.js +0 -64
  800. package/dist/detached-task-runtime-DiDRj-v-.js +0 -73
  801. package/dist/devices-cli-BKVbpwVc.js +0 -498
  802. package/dist/diagnostics-gh3UN_iV.js +0 -154
  803. package/dist/direct-dm-CwHHUkHV.js +0 -64
  804. package/dist/dispatch-B5af8_1v.js +0 -1131
  805. package/dist/dispatch-acp-DgOnUWBl.js +0 -981
  806. package/dist/dispatch-acp-manager.runtime-XWNjVh_M.js +0 -3
  807. package/dist/dispatch-acp.runtime-BdYL_ZqM.js +0 -19
  808. package/dist/doctor-device-pairing-CtGzWmXB.js +0 -307
  809. package/dist/doctor-gateway-daemon-flow-CCBI0jL4.js +0 -250
  810. package/dist/doctor-gateway-health-CkjqPFDl.js +0 -63
  811. package/dist/doctor-health-BOhuy1vP.js +0 -59
  812. package/dist/doctor-health-contributions-ChEuyLAY.js +0 -493
  813. package/dist/doctor-prompter-9nOTFD0Q.js +0 -56
  814. package/dist/doctor-workspace-status-CO5Ocwlt.js +0 -75
  815. package/dist/dreaming-GOPEFPio.js +0 -1574
  816. package/dist/dreaming-narrative-DfxHaxOU.js +0 -595
  817. package/dist/embedded-gateway-stub.runtime-B2OWcbsK.js +0 -9
  818. package/dist/exec-approvals-cli-CGeFtFbB.js +0 -498
  819. package/dist/fallbacks-CdfWAgNP.js +0 -2
  820. package/dist/fallbacks-eXbQ8TBp.js +0 -31
  821. package/dist/fallbacks-shared-akcCu5CD.js +0 -111
  822. package/dist/gateway-D-dDKqwi.js +0 -115
  823. package/dist/gateway-cli-DBS06Da8.js +0 -1283
  824. package/dist/gateway-rpc-Cxa8dVW5.js +0 -14
  825. package/dist/gateway-rpc.runtime-D76s-oxs.js +0 -23
  826. package/dist/gateway-runtime-Dhm_gLh1.js +0 -15
  827. package/dist/gateway-status-C_L_CdOg.js +0 -584
  828. package/dist/genesis-tools-rRJB3JXY.js +0 -9166
  829. package/dist/genesis-tools.runtime-6oKokqaA.js +0 -2
  830. package/dist/get-reply-BkiDsDVY.js +0 -3897
  831. package/dist/get-reply-from-config.runtime-CHKCcj9D.js +0 -2
  832. package/dist/graph-users-BnXIYyC5.js +0 -1337
  833. package/dist/health-ZsJNENSY.js +0 -3
  834. package/dist/health-osa9LOJf.js +0 -469
  835. package/dist/health-route-8TdKOYLp.js +0 -2
  836. package/dist/health-route-BdLtX2Bg.js +0 -41
  837. package/dist/heartbeat-runner-BCbkAprr.js +0 -1292
  838. package/dist/heartbeat-runner-Dc1K8S94.js +0 -5
  839. package/dist/heartbeat-runner.runtime-pJaAsgLY.js +0 -4
  840. package/dist/hooks-cli-C3ggAz0i.js +0 -433
  841. package/dist/image-fallbacks-CiSae-lb.js +0 -2
  842. package/dist/image-fallbacks-vI8KUh6N.js +0 -31
  843. package/dist/inbound-reply-dispatch-DLM60UDh.js +0 -73
  844. package/dist/infra-runtime-CrHVeejV.js +0 -39
  845. package/dist/init-BKeEiV2q.js +0 -59
  846. package/dist/library-CHB7yTo5.js +0 -45
  847. package/dist/lifecycle-CUULToPr.js +0 -229
  848. package/dist/lifecycle-DCMpTRD2.js +0 -571
  849. package/dist/lifecycle.runtime-CP4gRxWv.js +0 -2
  850. package/dist/list-0zDFAWTF.js +0 -2
  851. package/dist/list-BaxVHTAN.js +0 -131
  852. package/dist/list-CMRMgrPs.js +0 -1212
  853. package/dist/list-DSrBtnKI.js +0 -2
  854. package/dist/list.probe-BJYSCsJY.js +0 -419
  855. package/dist/llm-slug-generator-Bn_wrWYw.js +0 -79
  856. package/dist/load-config-qC2BWt8E.js +0 -35
  857. package/dist/local-dispatch.runtime-DyU7urGc.js +0 -8
  858. package/dist/logs-cli-zK71r_PE.js +0 -265
  859. package/dist/logs-cli.runtime-k0UtiaRP.js +0 -2
  860. package/dist/main-session-restart-recovery-DMT0Oj9a.js +0 -206
  861. package/dist/managed-image-attachments-B6XXE4--.js +0 -635
  862. package/dist/managed-image-attachments-BTzWoDWE.js +0 -2
  863. package/dist/manager-BCKuWA67.js +0 -2057
  864. package/dist/manager-rGwNUzMp.js +0 -2
  865. package/dist/markdown-to-line-DmPbXQA1.js +0 -790
  866. package/dist/mcp-cli-CYpPNMcE.js +0 -725
  867. package/dist/mcp-http-wiE81iKg.js +0 -529
  868. package/dist/memory-core-host-runtime-cli-BOSQRX1T.js +0 -9
  869. package/dist/message-CUDzVGD8.js +0 -232
  870. package/dist/message-action-runner-Dy0IpKa4.js +0 -1407
  871. package/dist/message-action-runner-KkBFzZdg.js +0 -2
  872. package/dist/message-actions-Dcdb5aSR.js +0 -143
  873. package/dist/message.gateway.runtime-D86fFO99.js +0 -2
  874. package/dist/models-auth-status-DkiX4s0b.js +0 -201
  875. package/dist/models-cli-CSUot1R3.js +0 -219
  876. package/dist/monitor-BA8ByMKR.js +0 -2
  877. package/dist/monitor-Bv1GIHW5.js +0 -1661
  878. package/dist/monitor-DTFY0ruF.js +0 -788
  879. package/dist/monitor-DXH-vNGn.js +0 -1459
  880. package/dist/monitor-Df5k8NGk.js +0 -671
  881. package/dist/monitor-Dk2YRF26.js +0 -1237
  882. package/dist/monitor-auth-CZOW753A.js +0 -207
  883. package/dist/monitor-processing-Clta8N4C.js +0 -1974
  884. package/dist/monitor.runtime-3ORbPT0X.js +0 -2
  885. package/dist/monitor.webhook-CRyTxENk.js +0 -180
  886. package/dist/msteams-BE0VieXF.js +0 -35
  887. package/dist/native-hook-relay-DAwGGuEx.js +0 -519
  888. package/dist/nextcloud-talk-DfYlTFsm.js +0 -17
  889. package/dist/node-cli-Bzyci_X_.js +0 -2276
  890. package/dist/nodes-cli-Er3OZkuk.js +0 -1046
  891. package/dist/nodes-utils-Cp8QZO8-.js +0 -84
  892. package/dist/nodes.helpers-CwKAAnRA.js +0 -34
  893. package/dist/notify-D_5n_vEJ.js +0 -315
  894. package/dist/onboard-BE82RudQ.js +0 -2
  895. package/dist/onboard-Bk4xL8X7.js +0 -70
  896. package/dist/onboard-helpers-D4WYa-6g.js +0 -204
  897. package/dist/onboard-helpers-MuFxPZg5.js +0 -6
  898. package/dist/onboard-interactive-0zmI-9ia.js +0 -24
  899. package/dist/onboard-non-interactive-DIRB95mT.js +0 -635
  900. package/dist/onboard-remote-7qR1knbU.js +0 -2
  901. package/dist/onboard-remote-CLmoySkk.js +0 -193
  902. package/dist/onboard-skills-C_873OK_.js +0 -134
  903. package/dist/onboard-skills-DrlBYc0t.js +0 -2
  904. package/dist/openai-http-DzCBqW6b.js +0 -500
  905. package/dist/openresponses-http-B2zgO5hQ.js +0 -1128
  906. package/dist/operator-approvals-client-mGBl4ptH.js +0 -68
  907. package/dist/outbound.runtime--HS-MxM_.js +0 -2
  908. package/dist/pair-command-approve-CCTSQKJH.js +0 -44
  909. package/dist/persistent-bindings.lifecycle-CnmqGsQf.js +0 -85
  910. package/dist/persistent-bindings.lifecycle-Dav1TX9E.js +0 -2
  911. package/dist/pi-embedded-BSKL8IgF.js +0 -4
  912. package/dist/pi-embedded-DMM8Pfp7.js +0 -2905
  913. package/dist/pi-embedded.runtime-Bv_roBVx.js +0 -4
  914. package/dist/pi-tool-definition-adapter-OrxjlSIM.js +0 -229
  915. package/dist/pi-tools-DD1YegeL.js +0 -1057
  916. package/dist/pi-tools.before-tool-call-J9ujp9Wp.js +0 -433
  917. package/dist/pi-tools.before-tool-call-hGEgKGZQ.js +0 -2
  918. package/dist/plugin-Cg3pHepG.js +0 -12195
  919. package/dist/plugin-enabled-wEQ8BQNw.js +0 -140
  920. package/dist/plugin-registration-DLcLJgqz.js +0 -23
  921. package/dist/plugin-service-BogBl5qk.js +0 -2892
  922. package/dist/policy-Bkh8Xtnb.js +0 -328
  923. package/dist/prepare.runtime-Cd31ie7u.js +0 -815
  924. package/dist/probe-9IM22Rkf.js +0 -2
  925. package/dist/probe-ButCyV3d.js +0 -1443
  926. package/dist/probe-D7QBUio1.js +0 -45
  927. package/dist/probe-DV6CWm0r.js +0 -74
  928. package/dist/probe-DkfetvwA.js +0 -2
  929. package/dist/probe-Dxo-LQjn.js +0 -2205
  930. package/dist/probe-nil3qQAV.js +0 -241
  931. package/dist/program-AcjZFtZQ.js +0 -111
  932. package/dist/prompt-select-styled-BSf77q2T.js +0 -20
  933. package/dist/protocol-C4I0nfuT.js +0 -2477
  934. package/dist/provider-dispatcher-CkiPxKIr.js +0 -22
  935. package/dist/provider-dispatcher-PmsHJlUO.js +0 -2
  936. package/dist/qr-cli-BHY0TO2W.js +0 -2
  937. package/dist/qr-cli-BbjDJSKp.js +0 -349
  938. package/dist/reaction-runtime-api-DOigJrbq.js +0 -116
  939. package/dist/reactions-CogkrjNr.js +0 -998
  940. package/dist/register-service-commands-IA3Nfza5.js +0 -71
  941. package/dist/register.agent-DD0aSYye.js +0 -248
  942. package/dist/register.configure-BOy4i7Ah.js +0 -15
  943. package/dist/register.maintenance-CUp6FEOF.js +0 -363
  944. package/dist/register.message-DezTIpNI.js +0 -329
  945. package/dist/register.onboard-Brpxl9p3.js +0 -88
  946. package/dist/register.runtime-BfH5rSb_.js +0 -81
  947. package/dist/register.setup-CIt4FVv0.js +0 -150
  948. package/dist/register.status-health-sessions-IbGZwSaG.js +0 -1215
  949. package/dist/register.subclis-B1H4fYxP.js +0 -29
  950. package/dist/register.subclis-D-_xtNVs.js +0 -3
  951. package/dist/register.subclis-core-CkJelRU8.js +0 -249
  952. package/dist/reply-dispatch-runtime-Lu4Metex.js +0 -13
  953. package/dist/reply-runtime-CgPzru94.js +0 -11
  954. package/dist/reply.runtime-sw14BA5F.js +0 -2
  955. package/dist/restart-health-1MNBua3p.js +0 -202
  956. package/dist/restart-health-BWGpwgPv.js +0 -2
  957. package/dist/root-help-B3zoC2OP.js +0 -44
  958. package/dist/routes-BM6fbday.js +0 -3341
  959. package/dist/routes-pVc_QLiP.js +0 -2
  960. package/dist/rpc-BGOWS7nj.js +0 -61
  961. package/dist/rpc.runtime-Ca9K3sx8.js +0 -21
  962. package/dist/run-delivery.runtime-CabntI64.js +0 -530
  963. package/dist/run-embedded.runtime-Q7wrP6Qn.js +0 -4
  964. package/dist/run-execution-cli.runtime-CtRUFc-M.js +0 -4
  965. package/dist/run-executor.runtime-Nm38xsKA.js +0 -277
  966. package/dist/run-main-kE0nFgvK.js +0 -567
  967. package/dist/run-subagent-registry.runtime-D9_scMUr.js +0 -2
  968. package/dist/run-wait-B2K_6JNL.js +0 -135
  969. package/dist/runtime-BZ296jTK.js +0 -9
  970. package/dist/runtime-DnZsw7MB.js +0 -973
  971. package/dist/runtime-api-BL9vpbvb.js +0 -14
  972. package/dist/runtime-api-BbsLJB4C.js +0 -9
  973. package/dist/runtime-api-ChwFrQRw.js +0 -9
  974. package/dist/runtime-api-_fH7M3Qh.js +0 -4
  975. package/dist/runtime-embedded-pi.runtime-TOdW-E-2.js +0 -2
  976. package/dist/runtime-internal-DGwOFi_E.js +0 -2
  977. package/dist/runtime-options-CSPfxkb1.js +0 -275
  978. package/dist/runtime-schema-CMRvOPkk.js +0 -28576
  979. package/dist/scan-D6gkNpKl.js +0 -523
  980. package/dist/scan-_9J5-5L6.js +0 -2
  981. package/dist/secrets-cli-DlVSRQPM.js +0 -2101
  982. package/dist/security-cli-DtzNOYL2.js +0 -486
  983. package/dist/selection-CBJZE_FL.js +0 -7764
  984. package/dist/selection-XsoEF2p2.js +0 -2
  985. package/dist/send-BAaDBRfi.js +0 -156
  986. package/dist/send-BB-M1afy.js +0 -102
  987. package/dist/send.runtime-CI_75KUP.js +0 -2
  988. package/dist/server-B_BiVYFv.js +0 -13
  989. package/dist/server-D58E1Cua.js +0 -77
  990. package/dist/server-context-D5AnCc1E.js +0 -2
  991. package/dist/server-context-bt09wrJu.js +0 -847
  992. package/dist/server-node-events-CUx4-7FL.js +0 -481
  993. package/dist/server-plugin-bootstrap-CU5P500z.js +0 -12708
  994. package/dist/server-plugin-bootstrap-CXm9xWXR.js +0 -2
  995. package/dist/server-restart-sentinel-ByFI_0MB.js +0 -697
  996. package/dist/server.impl-BBBEDK9u.js +0 -12864
  997. package/dist/session-kill-http-9MoO6FXC.js +0 -110
  998. package/dist/session-reset-service-redPsOs-.js +0 -497
  999. package/dist/session-route-C8oB2UYs.js +0 -93
  1000. package/dist/session-status.runtime-D3bYBPJe.js +0 -2
  1001. package/dist/session-subagent-reactivation.runtime-aat7tUag.js +0 -2
  1002. package/dist/session-tab-registry-CAJ_oDsb.js +0 -581
  1003. package/dist/session-visibility-Dq88jJYB.js +0 -147
  1004. package/dist/sessions-helpers-C8-IkqhO.js +0 -305
  1005. package/dist/sessions-history-http-4Ftuwnes.js +0 -383
  1006. package/dist/sessions-patch-BsyNHOaz.js +0 -309
  1007. package/dist/sessions-resolve-gKLz2Bup.js +0 -174
  1008. package/dist/sessions.runtime-C1W59rQY.js +0 -2
  1009. package/dist/setup-DhvXyU_5.js +0 -636
  1010. package/dist/setup-api-B9Y4qPgq.js +0 -29
  1011. package/dist/setup-core-CdFQ6ZXC.js +0 -176
  1012. package/dist/setup-core-kXUD3Kat.js +0 -171
  1013. package/dist/setup-surface-BFL9WfBs.js +0 -219
  1014. package/dist/setup-surface-Cxg_nSWc.js +0 -286
  1015. package/dist/setup-surface-DbooMj782.js +0 -403
  1016. package/dist/setup.finalize-CKxukDYi.js +0 -547
  1017. package/dist/setup.gateway-config-BhEtXwaB.js +0 -250
  1018. package/dist/shared-BNVKrp5y.js +0 -76
  1019. package/dist/shared-CM3mnx7z.js +0 -198
  1020. package/dist/shared-CfrsSVhL.js +0 -121
  1021. package/dist/slash-state-2Z-om57Q.js +0 -1911
  1022. package/dist/src-DAoKvK_N.js +0 -3974
  1023. package/dist/startup-context-CtYAdYwd.js +0 -312
  1024. package/dist/status-B2M0Imij.js +0 -3
  1025. package/dist/status-Bd-BNmiE.js +0 -2
  1026. package/dist/status-D6nbpHFi.js +0 -397
  1027. package/dist/status-MByUxUGu.js +0 -209
  1028. package/dist/status-QUjO1tkz.js +0 -2
  1029. package/dist/status-all-DPa-BiHk.js +0 -498
  1030. package/dist/status-erNo8YmW.js +0 -190
  1031. package/dist/status-json-command-C9rbAyj-.js +0 -84
  1032. package/dist/status-json-tO3CQXIQ.js +0 -14
  1033. package/dist/status-runtime-shared-DmBB_gmT.js +0 -257
  1034. package/dist/status-subagents.runtime-BXAZr5y0.js +0 -18
  1035. package/dist/status-text-BCeYk0-q.js +0 -237
  1036. package/dist/status.gateway-connection.runtime-bt35dapy.js +0 -2
  1037. package/dist/status.gather-B9a-CEev.js +0 -292
  1038. package/dist/status.gather-ahBLFzk6.js +0 -2
  1039. package/dist/status.runtime-BrErwtfc.js +0 -2
  1040. package/dist/status.scan-D2mvM4II.js +0 -65
  1041. package/dist/status.scan-overview-uOOaqp1t.js +0 -379
  1042. package/dist/status.scan.fast-json-C9dkN28s.js +0 -2
  1043. package/dist/status.scan.fast-json-DY3Or8S4.js +0 -132
  1044. package/dist/status.summary-Cf4p2BPK.js +0 -2
  1045. package/dist/status.summary-DxfZCcNa.js +0 -214
  1046. package/dist/subagent-announce-CyQZsAIm.js +0 -351
  1047. package/dist/subagent-announce-delivery-CgdPNjMA.js +0 -726
  1048. package/dist/subagent-announce-output-D1xi4Tk1.js +0 -364
  1049. package/dist/subagent-control-D-O6I8Mt.js +0 -506
  1050. package/dist/subagent-followup.runtime-BbA7NPAq.js +0 -68
  1051. package/dist/subagent-orphan-recovery-C6_cmAyE.js +0 -305
  1052. package/dist/subagent-registry-Dn_XpDh0.js +0 -1753
  1053. package/dist/subagent-registry-DodFw3pu.js +0 -3
  1054. package/dist/subagent-spawn-Dw5lttXp.js +0 -1005
  1055. package/dist/system-cli-CSqO2Z4K.js +0 -59
  1056. package/dist/targets-CMdwh9lR.js +0 -67
  1057. package/dist/task-executor-DgZSfcBk.js +0 -360
  1058. package/dist/task-owner-access-9c38idlo.js +0 -74
  1059. package/dist/task-registry-Z-lBPkNj.js +0 -2366
  1060. package/dist/task-registry-delivery-runtime-DOV4qoj4.js +0 -2
  1061. package/dist/task-registry-delivery-runtime-EATr0C3C.js +0 -3
  1062. package/dist/task-registry.maintenance-C1YMEwhk.js +0 -416
  1063. package/dist/task-registry.maintenance-CBfaUWcp.js +0 -2
  1064. package/dist/testing-CFk04o9M.js +0 -575
  1065. package/dist/text-report-QhVG354o.js +0 -587
  1066. package/dist/tool-resolution-D6V4tg-G.js +0 -90
  1067. package/dist/tools-effective-inventory-DFU7yYvD.js +0 -152
  1068. package/dist/tools-invoke-http-y6WIa3Ku.js +0 -206
  1069. package/dist/trash-rhbwNhfQ.js +0 -24
  1070. package/dist/tui-cli-BfxeO4YM.js +0 -4575
  1071. package/dist/update-cli-DaN9bvPV.js +0 -1759
  1072. package/dist/upgrade-f5dlIxir.js +0 -1226
  1073. package/dist/video-generation-task-status-yX54iO8n.js +0 -163
  1074. package/dist/wait-for-idle-before-flush-mZrBNr5z.js +0 -5986
  1075. package/dist/wizard-models-D_avLyHR.js +0 -334
@@ -0,0 +1,4575 @@
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-B1sv_bx7.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-Cj8Hd5K-.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-Duyu_T59.js";
17
+ import "./config-Cuf4dwjh.js";
18
+ import { n as GatewayClientRequestError, t as GatewayClient } from "./client-ClJyHgmq.js";
19
+ import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES, t as GATEWAY_CLIENT_CAPS } from "./client-info-DZtBR4jU.js";
20
+ import { r as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-core-BUIi495-.js";
21
+ import "./message-channel-bhWoqTRw.js";
22
+ import "./protocol-DxLbSF2J.js";
23
+ import { g as resolveResponseUsageMode, m as normalizeUsageDisplay, r as listThinkingLevelLabels, t as formatThinkingLevels } from "./thinking-ItWMrRTh.js";
24
+ import { p as resolveThinkingDefault, t as buildAllowedModelSet } from "./model-selection-Le6XU3cD.js";
25
+ import { t as loadCombinedSessionStoreForGateway } from "./combined-store-gateway-DSi4nAht.js";
26
+ import { o as updateSessionStore } from "./store-4uu5L7Eg.js";
27
+ import "./sessions-qbJQTdke.js";
28
+ import { l as onAgentEvent } from "./agent-events-ZcJylLt0.js";
29
+ import { r as formatTokenCount } from "./usage-format-DFAQjLOq.js";
30
+ import { c as stripEnvelopeFromMessages, i as readSessionMessages, n as capArrayByJsonBytes } from "./session-utils.fs-BWnHyjEg.js";
31
+ import { r as extractAssistantVisibleText } from "./chat-message-content-iIHjZfPu.js";
32
+ import { i as stripInlineDirectiveTagsForDisplay } from "./directive-tags-mCs4tql8.js";
33
+ import { r as stripLeadingInboundMetadata } from "./strip-inbound-meta-CQZop7I_.js";
34
+ import { a as loadSessionEntry, d as resolveGatewaySessionStoreTarget, n as listAgentsForGateway, o as migrateAndPruneGatewaySessionStoreKey, p as resolveSessionModelRef, r as listSessionsFromStore } from "./session-utils-Bd228Qc6.js";
35
+ import { a as isSilentReplyText, n as SILENT_REPLY_TOKEN } from "./tokens-QeRE8ZG7.js";
36
+ import { v as setEmbeddedMode } from "./genesis-tools-Bh6dAUhK.js";
37
+ import "./pi-embedded-helpers-DGOg4B7z.js";
38
+ import { D as formatRawAssistantErrorForUi, m as isAuthErrorMessage } from "./sanitize-user-facing-text-ChBSMati.js";
39
+ import { r as resolveToolDisplay, t as formatToolDetail } from "./tool-display-CHRuFeBq.js";
40
+ import { l as resolveExplicitGatewayAuth, n as buildGatewayConnectionDetails, s as ensureExplicitGatewayAuth } from "./call-wY43fzOF.js";
41
+ import { t as parseTimeoutMs } from "./parse-timeout-DLvea5Xp.js";
42
+ import { r as resolveSessionInfoModelSelection } from "./model-selection-display-FTJqs8uN.js";
43
+ import { n as listChatCommands, r as listChatCommandsForConfig } from "./commands-registry-list-wx0HLiEs.js";
44
+ import "./commands-registry-vIVRcWI1.js";
45
+ import { n as formatTimeAgo, t as formatRelativeTimestamp } from "./format-relative-CkCeIUFz.js";
46
+ import { t as normalizeGroupActivation } from "./group-activation-C-Ka3ubh.js";
47
+ import { r as agentCommandFromIngress } from "./agent-command-C-_EFUUu.js";
48
+ import { t as createDefaultDeps } from "./deps-CMdKE0sw.js";
49
+ import { _ as loadGatewayModelCatalog } from "./http-utils-CjNp35oF.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_i6Wp50.js";
51
+ import { n as timestampOptsFromConfig, t as injectTimestamp } from "./agent-timestamp-Bg8Jh2oV.js";
52
+ import { a as performGatewaySessionReset } from "./session-reset-service-CzDd6PBK.js";
53
+ import { t as applySessionsPatchToStore } from "./sessions-patch-xb4bXPwh.js";
54
+ import { t as resolveGatewayInteractiveSurfaceAuth } from "./auth-surface-resolution-bACJDtmi.js";
55
+ import { n as TUI_SETUP_AUTH_SOURCE_ENV, t as TUI_SETUP_AUTH_SOURCE_CONFIG } from "./setup-launch-env-C7w9B99Q.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],
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 heartbeatAgents = summary.heartbeat?.agents ?? [];
2361
+ if (heartbeatAgents.length > 0) {
2362
+ const heartbeatParts = heartbeatAgents.map((agent) => {
2363
+ const agentId = agent.agentId ?? "unknown";
2364
+ if (!agent.enabled || !agent.everyMs) return `disabled (${agentId})`;
2365
+ return `${agent.every ?? "unknown"} (${agentId})`;
2366
+ });
2367
+ lines.push("");
2368
+ lines.push(`Heartbeat: ${heartbeatParts.join(", ")}`);
2369
+ }
2370
+ const sessionPaths = summary.sessions?.paths ?? [];
2371
+ if (sessionPaths.length === 1) lines.push(`Session store: ${sessionPaths[0]}`);
2372
+ else if (sessionPaths.length > 1) lines.push(`Session stores: ${sessionPaths.length}`);
2373
+ const defaults = summary.sessions?.defaults;
2374
+ const defaultModel = defaults?.model ?? "unknown";
2375
+ const defaultCtx = typeof defaults?.contextTokens === "number" ? ` (${formatTokenCount(defaults.contextTokens)} ctx)` : "";
2376
+ lines.push(`Default model: ${defaultModel}${defaultCtx}`);
2377
+ const sessionCount = summary.sessions?.count ?? 0;
2378
+ lines.push(`Active sessions: ${sessionCount}`);
2379
+ const recent = Array.isArray(summary.sessions?.recent) ? summary.sessions?.recent : [];
2380
+ if (recent.length > 0) {
2381
+ lines.push("Recent sessions:");
2382
+ for (const entry of recent) {
2383
+ const ageLabel = typeof entry.age === "number" ? formatTimeAgo(entry.age) : "no activity";
2384
+ const model = entry.model ?? "unknown";
2385
+ const usage = formatContextUsageLine({
2386
+ total: entry.totalTokens ?? null,
2387
+ context: entry.contextTokens ?? null,
2388
+ remaining: entry.remainingTokens ?? null,
2389
+ percent: entry.percentUsed ?? null
2390
+ });
2391
+ const flags = entry.flags?.length ? ` | flags: ${entry.flags.join(", ")}` : "";
2392
+ lines.push(`- ${entry.key}${entry.kind ? ` [${entry.kind}]` : ""} | ${ageLabel} | model ${model} | ${usage}${flags}`);
2393
+ }
2394
+ }
2395
+ const queued = Array.isArray(summary.queuedSystemEvents) ? summary.queuedSystemEvents : [];
2396
+ if (queued.length > 0) {
2397
+ const preview = queued.slice(0, 3).join(" | ");
2398
+ lines.push(`Queued system events (${queued.length}): ${preview}`);
2399
+ }
2400
+ return lines;
2401
+ }
2402
+ //#endregion
2403
+ //#region src/tui/tui-command-handlers.ts
2404
+ function isBtwCommand(text) {
2405
+ return /^\/btw(?::|\s|$)/i.test(text.trim());
2406
+ }
2407
+ function createCommandHandlers(context) {
2408
+ const { client, chatLog, tui, opts, state, deliverDefault, openOverlay, closeOverlay, refreshSessionInfo, loadHistory, setSession, refreshAgents, abortActive, setActivityStatus, formatSessionKey, applySessionInfoFromPatch, noteLocalBtwRunId, forgetLocalRunId, forgetLocalBtwRunId, runAuthFlow, requestExit } = context;
2409
+ const setAgent = async (id) => {
2410
+ state.currentAgentId = normalizeAgentId(id);
2411
+ await setSession("");
2412
+ };
2413
+ const closeOverlayAndRender = () => {
2414
+ closeOverlay();
2415
+ tui.requestRender();
2416
+ };
2417
+ const openSelector = (selector, onSelect) => {
2418
+ selector.onSelect = (item) => {
2419
+ (async () => {
2420
+ await onSelect(item.value);
2421
+ closeOverlayAndRender();
2422
+ })();
2423
+ };
2424
+ selector.onCancel = closeOverlayAndRender;
2425
+ openOverlay(selector);
2426
+ tui.requestRender();
2427
+ };
2428
+ const openModelSelector = async () => {
2429
+ try {
2430
+ const models = await client.listModels();
2431
+ if (models.length === 0) {
2432
+ chatLog.addSystem("no models available");
2433
+ tui.requestRender();
2434
+ return;
2435
+ }
2436
+ openSelector(createSearchableSelectList(models.map((model) => ({
2437
+ value: `${model.provider}/${model.id}`,
2438
+ label: `${model.provider}/${model.id}`,
2439
+ description: model.name && model.name !== model.id ? model.name : ""
2440
+ })), 9), async (value) => {
2441
+ try {
2442
+ const result = await client.patchSession({
2443
+ key: state.currentSessionKey,
2444
+ model: value
2445
+ });
2446
+ chatLog.addSystem(`model set to ${value}`);
2447
+ applySessionInfoFromPatch(result);
2448
+ await refreshSessionInfo();
2449
+ } catch (err) {
2450
+ chatLog.addSystem(`model set failed: ${String(err)}`);
2451
+ }
2452
+ });
2453
+ } catch (err) {
2454
+ chatLog.addSystem(`model list failed: ${String(err)}`);
2455
+ tui.requestRender();
2456
+ }
2457
+ };
2458
+ const openAgentSelector = async () => {
2459
+ await refreshAgents();
2460
+ if (state.agents.length === 0) {
2461
+ chatLog.addSystem("no agents found");
2462
+ tui.requestRender();
2463
+ return;
2464
+ }
2465
+ openSelector(createSearchableSelectList(state.agents.map((agent) => ({
2466
+ value: agent.id,
2467
+ label: agent.name ? `${agent.id} (${agent.name})` : agent.id,
2468
+ description: agent.id === state.agentDefaultId ? "default" : ""
2469
+ })), 9), async (value) => {
2470
+ await setAgent(value);
2471
+ });
2472
+ };
2473
+ const openSessionSelector = async () => {
2474
+ try {
2475
+ openSelector(createFilterableSelectList((await client.listSessions({
2476
+ includeGlobal: false,
2477
+ includeUnknown: false,
2478
+ includeDerivedTitles: true,
2479
+ includeLastMessage: true,
2480
+ agentId: state.currentAgentId
2481
+ })).sessions.map((session) => {
2482
+ const title = session.derivedTitle ?? session.displayName;
2483
+ const formattedKey = formatSessionKey(session.key);
2484
+ const label = title && title !== formattedKey ? `${title} (${formattedKey})` : formattedKey;
2485
+ const timePart = session.updatedAt ? formatRelativeTimestamp(session.updatedAt, {
2486
+ dateFallback: true,
2487
+ fallback: ""
2488
+ }) : "";
2489
+ const preview = session.lastMessagePreview?.replace(/\s+/g, " ").trim();
2490
+ const description = timePart && preview ? `${timePart} · ${preview}` : preview ?? timePart;
2491
+ return {
2492
+ value: session.key,
2493
+ label,
2494
+ description,
2495
+ searchText: [
2496
+ session.displayName,
2497
+ session.label,
2498
+ session.subject,
2499
+ session.sessionId,
2500
+ session.key,
2501
+ session.lastMessagePreview
2502
+ ].filter(Boolean).join(" ")
2503
+ };
2504
+ }), 9), async (value) => {
2505
+ await setSession(value);
2506
+ });
2507
+ } catch (err) {
2508
+ chatLog.addSystem(`sessions list failed: ${String(err)}`);
2509
+ tui.requestRender();
2510
+ }
2511
+ };
2512
+ const openSettings = () => {
2513
+ openOverlay(createSettingsList([{
2514
+ id: "tools",
2515
+ label: "Tool output",
2516
+ currentValue: state.toolsExpanded ? "expanded" : "collapsed",
2517
+ values: ["collapsed", "expanded"]
2518
+ }, {
2519
+ id: "thinking",
2520
+ label: "Show thinking",
2521
+ currentValue: state.showThinking ? "on" : "off",
2522
+ values: ["off", "on"]
2523
+ }], (id, value) => {
2524
+ if (id === "tools") {
2525
+ state.toolsExpanded = value === "expanded";
2526
+ chatLog.setToolsExpanded(state.toolsExpanded);
2527
+ }
2528
+ if (id === "thinking") {
2529
+ state.showThinking = value === "on";
2530
+ loadHistory();
2531
+ }
2532
+ tui.requestRender();
2533
+ }, () => {
2534
+ closeOverlay();
2535
+ tui.requestRender();
2536
+ }));
2537
+ tui.requestRender();
2538
+ };
2539
+ const handleCommand = async (raw) => {
2540
+ const { name, args } = parseCommand(raw);
2541
+ if (!name) return;
2542
+ switch (name) {
2543
+ case "help":
2544
+ chatLog.addSystem(helpText({
2545
+ local: opts.local,
2546
+ provider: state.sessionInfo.modelProvider,
2547
+ model: state.sessionInfo.model
2548
+ }));
2549
+ break;
2550
+ case "auth": {
2551
+ if (!runAuthFlow) {
2552
+ chatLog.addSystem("auth login is only available in local embedded mode");
2553
+ break;
2554
+ }
2555
+ if (state.activeChatRunId || state.pendingOptimisticUserMessage) {
2556
+ chatLog.addSystem("abort the current run before /auth");
2557
+ break;
2558
+ }
2559
+ const provider = args.trim() || state.sessionInfo.modelProvider || void 0;
2560
+ chatLog.addSystem(provider ? `opening auth flow for ${provider}; TUI will resume when it exits` : "opening auth flow; TUI will resume when it exits");
2561
+ tui.requestRender();
2562
+ setActivityStatus("auth");
2563
+ try {
2564
+ const result = await runAuthFlow({ provider });
2565
+ await refreshSessionInfo();
2566
+ if (result.exitCode === 0 && !result.signal) {
2567
+ chatLog.addSystem(provider ? `auth flow finished for ${provider}` : "auth flow finished");
2568
+ setActivityStatus("idle");
2569
+ } else {
2570
+ const failureSuffix = result.signal ? ` (signal ${result.signal})` : typeof result.exitCode === "number" ? ` (exit ${String(result.exitCode)})` : "";
2571
+ chatLog.addSystem(`auth flow failed${failureSuffix}`);
2572
+ setActivityStatus("error");
2573
+ }
2574
+ } catch (err) {
2575
+ chatLog.addSystem(`auth flow failed: ${sanitizeRenderableText(String(err))}`);
2576
+ setActivityStatus("error");
2577
+ }
2578
+ break;
2579
+ }
2580
+ case "gateway-status":
2581
+ try {
2582
+ const status = await client.getGatewayStatus();
2583
+ if (typeof status === "string") {
2584
+ chatLog.addSystem(status);
2585
+ break;
2586
+ }
2587
+ if (status && typeof status === "object") {
2588
+ const lines = formatStatusSummary(status);
2589
+ for (const line of lines) chatLog.addSystem(line);
2590
+ break;
2591
+ }
2592
+ chatLog.addSystem("status: unknown response");
2593
+ } catch (err) {
2594
+ chatLog.addSystem(`status failed: ${String(err)}`);
2595
+ }
2596
+ break;
2597
+ case "agent":
2598
+ if (!args) await openAgentSelector();
2599
+ else await setAgent(args);
2600
+ break;
2601
+ case "agents":
2602
+ await openAgentSelector();
2603
+ break;
2604
+ case "session":
2605
+ if (!args) await openSessionSelector();
2606
+ else await setSession(args);
2607
+ break;
2608
+ case "sessions":
2609
+ await openSessionSelector();
2610
+ break;
2611
+ case "model":
2612
+ if (!args) await openModelSelector();
2613
+ else try {
2614
+ const result = await client.patchSession({
2615
+ key: state.currentSessionKey,
2616
+ model: args
2617
+ });
2618
+ chatLog.addSystem(`model set to ${args}`);
2619
+ applySessionInfoFromPatch(result);
2620
+ await refreshSessionInfo();
2621
+ } catch (err) {
2622
+ chatLog.addSystem(`model set failed: ${String(err)}`);
2623
+ }
2624
+ break;
2625
+ case "models":
2626
+ await openModelSelector();
2627
+ break;
2628
+ case "think":
2629
+ if (!args) {
2630
+ const levels = formatThinkingLevels(state.sessionInfo.modelProvider, state.sessionInfo.model, "|");
2631
+ chatLog.addSystem(`usage: /think <${levels}>`);
2632
+ break;
2633
+ }
2634
+ try {
2635
+ const result = await client.patchSession({
2636
+ key: state.currentSessionKey,
2637
+ thinkingLevel: args
2638
+ });
2639
+ chatLog.addSystem(`thinking set to ${args}`);
2640
+ applySessionInfoFromPatch(result);
2641
+ await refreshSessionInfo();
2642
+ } catch (err) {
2643
+ chatLog.addSystem(`think failed: ${String(err)}`);
2644
+ }
2645
+ break;
2646
+ case "verbose":
2647
+ if (!args) {
2648
+ chatLog.addSystem("usage: /verbose <on|off>");
2649
+ break;
2650
+ }
2651
+ try {
2652
+ const result = await client.patchSession({
2653
+ key: state.currentSessionKey,
2654
+ verboseLevel: args
2655
+ });
2656
+ chatLog.addSystem(`verbose set to ${args}`);
2657
+ applySessionInfoFromPatch(result);
2658
+ await loadHistory();
2659
+ } catch (err) {
2660
+ chatLog.addSystem(`verbose failed: ${String(err)}`);
2661
+ }
2662
+ break;
2663
+ case "trace":
2664
+ if (!args) {
2665
+ chatLog.addSystem("usage: /trace <on|off>");
2666
+ break;
2667
+ }
2668
+ try {
2669
+ const result = await client.patchSession({
2670
+ key: state.currentSessionKey,
2671
+ traceLevel: args
2672
+ });
2673
+ chatLog.addSystem(`trace set to ${args}`);
2674
+ applySessionInfoFromPatch(result);
2675
+ await loadHistory();
2676
+ } catch (err) {
2677
+ chatLog.addSystem(`trace failed: ${String(err)}`);
2678
+ }
2679
+ break;
2680
+ case "fast":
2681
+ if (!args || args === "status") {
2682
+ chatLog.addSystem(`fast mode: ${state.sessionInfo.fastMode ? "on" : "off"}`);
2683
+ break;
2684
+ }
2685
+ if (args !== "on" && args !== "off") {
2686
+ chatLog.addSystem("usage: /fast <status|on|off>");
2687
+ break;
2688
+ }
2689
+ try {
2690
+ const result = await client.patchSession({
2691
+ key: state.currentSessionKey,
2692
+ fastMode: args === "on"
2693
+ });
2694
+ chatLog.addSystem(`fast mode ${args === "on" ? "enabled" : "disabled"}`);
2695
+ applySessionInfoFromPatch(result);
2696
+ await refreshSessionInfo();
2697
+ } catch (err) {
2698
+ chatLog.addSystem(`fast failed: ${String(err)}`);
2699
+ }
2700
+ break;
2701
+ case "reasoning":
2702
+ if (!args) {
2703
+ chatLog.addSystem("usage: /reasoning <on|off>");
2704
+ break;
2705
+ }
2706
+ try {
2707
+ const result = await client.patchSession({
2708
+ key: state.currentSessionKey,
2709
+ reasoningLevel: args
2710
+ });
2711
+ chatLog.addSystem(`reasoning set to ${args}`);
2712
+ applySessionInfoFromPatch(result);
2713
+ await refreshSessionInfo();
2714
+ } catch (err) {
2715
+ chatLog.addSystem(`reasoning failed: ${String(err)}`);
2716
+ }
2717
+ break;
2718
+ case "usage": {
2719
+ const normalized = args ? normalizeUsageDisplay(args) : void 0;
2720
+ if (args && !normalized) {
2721
+ chatLog.addSystem("usage: /usage <off|tokens|full>");
2722
+ break;
2723
+ }
2724
+ const currentRaw = state.sessionInfo.responseUsage;
2725
+ const current = resolveResponseUsageMode(currentRaw);
2726
+ const next = normalized ?? (current === "off" ? "tokens" : current === "tokens" ? "full" : "off");
2727
+ try {
2728
+ const result = await client.patchSession({
2729
+ key: state.currentSessionKey,
2730
+ responseUsage: next === "off" ? null : next
2731
+ });
2732
+ chatLog.addSystem(`usage footer: ${next}`);
2733
+ applySessionInfoFromPatch(result);
2734
+ await refreshSessionInfo();
2735
+ } catch (err) {
2736
+ chatLog.addSystem(`usage failed: ${String(err)}`);
2737
+ }
2738
+ break;
2739
+ }
2740
+ case "elevated":
2741
+ if (!args) {
2742
+ chatLog.addSystem("usage: /elevated <on|off|ask|full>");
2743
+ break;
2744
+ }
2745
+ if (![
2746
+ "on",
2747
+ "off",
2748
+ "ask",
2749
+ "full"
2750
+ ].includes(args)) {
2751
+ chatLog.addSystem("usage: /elevated <on|off|ask|full>");
2752
+ break;
2753
+ }
2754
+ try {
2755
+ const result = await client.patchSession({
2756
+ key: state.currentSessionKey,
2757
+ elevatedLevel: args
2758
+ });
2759
+ chatLog.addSystem(`elevated set to ${args}`);
2760
+ applySessionInfoFromPatch(result);
2761
+ await refreshSessionInfo();
2762
+ } catch (err) {
2763
+ chatLog.addSystem(`elevated failed: ${String(err)}`);
2764
+ }
2765
+ break;
2766
+ case "activation": {
2767
+ if (!args) {
2768
+ chatLog.addSystem("usage: /activation <mention|always>");
2769
+ break;
2770
+ }
2771
+ const activation = normalizeGroupActivation(args);
2772
+ if (!activation) {
2773
+ chatLog.addSystem("usage: /activation <mention|always>");
2774
+ break;
2775
+ }
2776
+ try {
2777
+ const result = await client.patchSession({
2778
+ key: state.currentSessionKey,
2779
+ groupActivation: activation
2780
+ });
2781
+ chatLog.addSystem(`activation set to ${activation}`);
2782
+ applySessionInfoFromPatch(result);
2783
+ await refreshSessionInfo();
2784
+ } catch (err) {
2785
+ chatLog.addSystem(`activation failed: ${String(err)}`);
2786
+ }
2787
+ break;
2788
+ }
2789
+ case "new":
2790
+ try {
2791
+ state.sessionInfo.inputTokens = null;
2792
+ state.sessionInfo.outputTokens = null;
2793
+ state.sessionInfo.totalTokens = null;
2794
+ tui.requestRender();
2795
+ const uniqueKey = `tui-${randomUUID()}`;
2796
+ await setSession(uniqueKey);
2797
+ chatLog.addSystem(`new session: ${uniqueKey}`);
2798
+ } catch (err) {
2799
+ chatLog.addSystem(`new session failed: ${sanitizeRenderableText(String(err))}`);
2800
+ }
2801
+ break;
2802
+ case "reset":
2803
+ try {
2804
+ state.sessionInfo.inputTokens = null;
2805
+ state.sessionInfo.outputTokens = null;
2806
+ state.sessionInfo.totalTokens = null;
2807
+ tui.requestRender();
2808
+ await client.resetSession(state.currentSessionKey, name);
2809
+ chatLog.addSystem(`session ${state.currentSessionKey} reset`);
2810
+ await loadHistory();
2811
+ } catch (err) {
2812
+ chatLog.addSystem(`reset failed: ${sanitizeRenderableText(String(err))}`);
2813
+ }
2814
+ break;
2815
+ case "abort":
2816
+ await abortActive();
2817
+ break;
2818
+ case "settings":
2819
+ openSettings();
2820
+ break;
2821
+ case "exit":
2822
+ case "quit":
2823
+ requestExit();
2824
+ break;
2825
+ default:
2826
+ await sendMessage(raw);
2827
+ break;
2828
+ }
2829
+ tui.requestRender();
2830
+ };
2831
+ const sendMessage = async (text) => {
2832
+ if (!state.isConnected) {
2833
+ chatLog.addSystem(opts.local ? "local runtime not ready — message not sent" : "not connected to gateway — message not sent");
2834
+ setActivityStatus("disconnected");
2835
+ tui.requestRender();
2836
+ return;
2837
+ }
2838
+ const isBtw = isBtwCommand(text);
2839
+ const runId = randomUUID();
2840
+ try {
2841
+ if (!isBtw) {
2842
+ chatLog.addUser(text);
2843
+ state.pendingOptimisticUserMessage = true;
2844
+ setActivityStatus("sending");
2845
+ } else noteLocalBtwRunId?.(runId);
2846
+ tui.requestRender();
2847
+ await client.sendChat({
2848
+ sessionKey: state.currentSessionKey,
2849
+ message: text,
2850
+ thinking: opts.thinking,
2851
+ deliver: deliverDefault,
2852
+ timeoutMs: opts.timeoutMs,
2853
+ runId
2854
+ });
2855
+ if (!isBtw) {
2856
+ setActivityStatus("waiting");
2857
+ tui.requestRender();
2858
+ }
2859
+ } catch (err) {
2860
+ if (isBtw) forgetLocalBtwRunId?.(runId);
2861
+ if (!isBtw && state.activeChatRunId) forgetLocalRunId?.(state.activeChatRunId);
2862
+ if (!isBtw) {
2863
+ state.pendingOptimisticUserMessage = false;
2864
+ state.activeChatRunId = null;
2865
+ }
2866
+ chatLog.addSystem(`${isBtw ? "btw failed" : "send failed"}: ${String(err)}`);
2867
+ if (!isBtw) setActivityStatus("error");
2868
+ tui.requestRender();
2869
+ }
2870
+ };
2871
+ return {
2872
+ handleCommand,
2873
+ sendMessage,
2874
+ openModelSelector,
2875
+ openAgentSelector,
2876
+ openSessionSelector,
2877
+ openSettings,
2878
+ setAgent
2879
+ };
2880
+ }
2881
+ //#endregion
2882
+ //#region src/tui/tui-stream-assembler.ts
2883
+ function extractTextBlocksAndSignals(message) {
2884
+ if (!message || typeof message !== "object") return {
2885
+ textBlocks: [],
2886
+ sawNonTextContentBlocks: false
2887
+ };
2888
+ const content = message.content;
2889
+ if (typeof content === "string") {
2890
+ const text = content.trim();
2891
+ return {
2892
+ textBlocks: text ? [text] : [],
2893
+ sawNonTextContentBlocks: false
2894
+ };
2895
+ }
2896
+ if (!Array.isArray(content)) return {
2897
+ textBlocks: [],
2898
+ sawNonTextContentBlocks: false
2899
+ };
2900
+ const textBlocks = [];
2901
+ let sawNonTextContentBlocks = false;
2902
+ for (const block of content) {
2903
+ if (!block || typeof block !== "object") continue;
2904
+ const rec = block;
2905
+ if (rec.type === "text" && typeof rec.text === "string") {
2906
+ const text = rec.text.trim();
2907
+ if (text) textBlocks.push(text);
2908
+ continue;
2909
+ }
2910
+ if (typeof rec.type === "string" && rec.type !== "thinking") sawNonTextContentBlocks = true;
2911
+ }
2912
+ return {
2913
+ textBlocks,
2914
+ sawNonTextContentBlocks
2915
+ };
2916
+ }
2917
+ function isDroppedBoundaryTextBlockSubset(params) {
2918
+ const { streamedTextBlocks, finalTextBlocks } = params;
2919
+ if (finalTextBlocks.length === 0 || finalTextBlocks.length >= streamedTextBlocks.length) return false;
2920
+ if (finalTextBlocks.every((block, index) => streamedTextBlocks[index] === block)) return true;
2921
+ const suffixStart = streamedTextBlocks.length - finalTextBlocks.length;
2922
+ return finalTextBlocks.every((block, index) => streamedTextBlocks[suffixStart + index] === block);
2923
+ }
2924
+ function shouldPreserveBoundaryDroppedText(params) {
2925
+ if (params.boundaryDropMode === "off") return false;
2926
+ if (!(params.boundaryDropMode === "streamed-or-incoming" ? params.streamedSawNonTextContentBlocks || params.incomingSawNonTextContentBlocks : params.streamedSawNonTextContentBlocks)) return false;
2927
+ return isDroppedBoundaryTextBlockSubset({
2928
+ streamedTextBlocks: params.streamedTextBlocks,
2929
+ finalTextBlocks: params.nextContentBlocks
2930
+ });
2931
+ }
2932
+ var TuiStreamAssembler = class {
2933
+ constructor() {
2934
+ this.runs = /* @__PURE__ */ new Map();
2935
+ }
2936
+ getOrCreateRun(runId) {
2937
+ let state = this.runs.get(runId);
2938
+ if (!state) {
2939
+ state = {
2940
+ thinkingText: "",
2941
+ contentText: "",
2942
+ contentBlocks: [],
2943
+ sawNonTextContentBlocks: false,
2944
+ displayText: ""
2945
+ };
2946
+ this.runs.set(runId, state);
2947
+ }
2948
+ return state;
2949
+ }
2950
+ updateRunState(state, message, showThinking, opts) {
2951
+ const thinkingText = extractThinkingFromMessage(message);
2952
+ const contentText = extractContentFromMessage(message);
2953
+ const { textBlocks, sawNonTextContentBlocks } = extractTextBlocksAndSignals(message);
2954
+ if (thinkingText) state.thinkingText = thinkingText;
2955
+ if (contentText) {
2956
+ const nextContentBlocks = textBlocks.length > 0 ? textBlocks : [contentText];
2957
+ if (!shouldPreserveBoundaryDroppedText({
2958
+ boundaryDropMode: opts?.boundaryDropMode ?? "off",
2959
+ streamedSawNonTextContentBlocks: state.sawNonTextContentBlocks,
2960
+ incomingSawNonTextContentBlocks: sawNonTextContentBlocks,
2961
+ streamedTextBlocks: state.contentBlocks,
2962
+ nextContentBlocks
2963
+ })) {
2964
+ state.contentText = contentText;
2965
+ state.contentBlocks = nextContentBlocks;
2966
+ }
2967
+ }
2968
+ if (sawNonTextContentBlocks) state.sawNonTextContentBlocks = true;
2969
+ state.displayText = composeThinkingAndContent({
2970
+ thinkingText: state.thinkingText,
2971
+ contentText: state.contentText,
2972
+ showThinking
2973
+ });
2974
+ }
2975
+ ingestDelta(runId, message, showThinking) {
2976
+ const state = this.getOrCreateRun(runId);
2977
+ const previousDisplayText = state.displayText;
2978
+ this.updateRunState(state, message, showThinking, { boundaryDropMode: "streamed-or-incoming" });
2979
+ if (!state.displayText || state.displayText === previousDisplayText) return null;
2980
+ return state.displayText;
2981
+ }
2982
+ finalize(runId, message, showThinking, errorMessage) {
2983
+ const state = this.getOrCreateRun(runId);
2984
+ const streamedDisplayText = state.displayText;
2985
+ const streamedTextBlocks = [...state.contentBlocks];
2986
+ const streamedSawNonTextContentBlocks = state.sawNonTextContentBlocks;
2987
+ this.updateRunState(state, message, showThinking, { boundaryDropMode: "streamed-only" });
2988
+ const finalComposed = state.displayText;
2989
+ const finalText = resolveFinalAssistantText({
2990
+ finalText: streamedSawNonTextContentBlocks && isDroppedBoundaryTextBlockSubset({
2991
+ streamedTextBlocks,
2992
+ finalTextBlocks: state.contentBlocks
2993
+ }) ? streamedDisplayText : finalComposed,
2994
+ streamedText: streamedDisplayText,
2995
+ errorMessage
2996
+ });
2997
+ this.runs.delete(runId);
2998
+ return finalText;
2999
+ }
3000
+ drop(runId) {
3001
+ this.runs.delete(runId);
3002
+ }
3003
+ };
3004
+ //#endregion
3005
+ //#region src/tui/tui-event-handlers.ts
3006
+ const DEFAULT_STREAMING_WATCHDOG_MS = 3e4;
3007
+ function createEventHandlers(context) {
3008
+ const { chatLog, btw, tui, state, setActivityStatus, refreshSessionInfo, loadHistory, noteLocalRunId, isLocalRunId, forgetLocalRunId, clearLocalRunIds, isLocalBtwRunId, forgetLocalBtwRunId, clearLocalBtwRunIds, localMode } = context;
3009
+ const finalizedRuns = /* @__PURE__ */ new Map();
3010
+ const sessionRuns = /* @__PURE__ */ new Map();
3011
+ let streamAssembler = new TuiStreamAssembler();
3012
+ let lastSessionKey = state.currentSessionKey;
3013
+ let pendingHistoryRefresh = false;
3014
+ const streamingWatchdogMs = typeof context.streamingWatchdogMs === "number" && Number.isFinite(context.streamingWatchdogMs) && context.streamingWatchdogMs >= 0 ? Math.floor(context.streamingWatchdogMs) : DEFAULT_STREAMING_WATCHDOG_MS;
3015
+ let streamingWatchdogTimer = null;
3016
+ let streamingWatchdogRunId = null;
3017
+ const clearStreamingWatchdog = () => {
3018
+ if (streamingWatchdogTimer) {
3019
+ clearTimeout(streamingWatchdogTimer);
3020
+ streamingWatchdogTimer = null;
3021
+ }
3022
+ streamingWatchdogRunId = null;
3023
+ };
3024
+ const armStreamingWatchdog = (runId) => {
3025
+ if (streamingWatchdogMs <= 0) return;
3026
+ if (streamingWatchdogTimer) clearTimeout(streamingWatchdogTimer);
3027
+ streamingWatchdogRunId = runId;
3028
+ streamingWatchdogTimer = setTimeout(() => {
3029
+ streamingWatchdogTimer = null;
3030
+ if (streamingWatchdogRunId !== runId || state.activeChatRunId !== runId) return;
3031
+ streamingWatchdogRunId = null;
3032
+ state.activeChatRunId = null;
3033
+ setActivityStatus("idle");
3034
+ 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.`);
3035
+ tui.requestRender();
3036
+ }, streamingWatchdogMs);
3037
+ const maybeUnref = streamingWatchdogTimer.unref;
3038
+ if (typeof maybeUnref === "function") maybeUnref.call(streamingWatchdogTimer);
3039
+ };
3040
+ const pruneRunMap = (runs) => {
3041
+ if (runs.size <= 200) return;
3042
+ const keepUntil = Date.now() - 600 * 1e3;
3043
+ for (const [key, ts] of runs) {
3044
+ if (runs.size <= 150) break;
3045
+ if (ts < keepUntil) runs.delete(key);
3046
+ }
3047
+ if (runs.size > 200) for (const key of runs.keys()) {
3048
+ runs.delete(key);
3049
+ if (runs.size <= 150) break;
3050
+ }
3051
+ };
3052
+ const syncSessionKey = () => {
3053
+ if (state.currentSessionKey === lastSessionKey) return;
3054
+ lastSessionKey = state.currentSessionKey;
3055
+ finalizedRuns.clear();
3056
+ sessionRuns.clear();
3057
+ streamAssembler = new TuiStreamAssembler();
3058
+ pendingHistoryRefresh = false;
3059
+ state.pendingOptimisticUserMessage = false;
3060
+ clearLocalRunIds?.();
3061
+ clearLocalBtwRunIds?.();
3062
+ btw.clear();
3063
+ clearStreamingWatchdog();
3064
+ };
3065
+ const flushPendingHistoryRefreshIfIdle = () => {
3066
+ if (!pendingHistoryRefresh || state.activeChatRunId) return;
3067
+ pendingHistoryRefresh = false;
3068
+ loadHistory?.();
3069
+ };
3070
+ const resolveAuthErrorHint = (errorMessage) => {
3071
+ if (!localMode || !isAuthErrorMessage(errorMessage)) return;
3072
+ const provider = state.sessionInfo.modelProvider?.trim();
3073
+ 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.";
3074
+ };
3075
+ const noteSessionRun = (runId) => {
3076
+ sessionRuns.set(runId, Date.now());
3077
+ pruneRunMap(sessionRuns);
3078
+ };
3079
+ const noteFinalizedRun = (runId) => {
3080
+ finalizedRuns.set(runId, Date.now());
3081
+ sessionRuns.delete(runId);
3082
+ streamAssembler.drop(runId);
3083
+ pruneRunMap(finalizedRuns);
3084
+ };
3085
+ const clearActiveRunIfMatch = (runId) => {
3086
+ if (state.activeChatRunId === runId) state.activeChatRunId = null;
3087
+ };
3088
+ const finalizeRun = (params) => {
3089
+ noteFinalizedRun(params.runId);
3090
+ clearActiveRunIfMatch(params.runId);
3091
+ flushPendingHistoryRefreshIfIdle();
3092
+ if (params.wasActiveRun) {
3093
+ setActivityStatus(params.status);
3094
+ clearStreamingWatchdog();
3095
+ } else if (streamingWatchdogRunId === params.runId) clearStreamingWatchdog();
3096
+ refreshSessionInfo?.();
3097
+ };
3098
+ const terminateRun = (params) => {
3099
+ streamAssembler.drop(params.runId);
3100
+ sessionRuns.delete(params.runId);
3101
+ clearActiveRunIfMatch(params.runId);
3102
+ flushPendingHistoryRefreshIfIdle();
3103
+ if (params.wasActiveRun) {
3104
+ setActivityStatus(params.status);
3105
+ clearStreamingWatchdog();
3106
+ } else if (streamingWatchdogRunId === params.runId) clearStreamingWatchdog();
3107
+ refreshSessionInfo?.();
3108
+ };
3109
+ const hasConcurrentActiveRun = (runId) => {
3110
+ const activeRunId = state.activeChatRunId;
3111
+ if (!activeRunId || activeRunId === runId) return false;
3112
+ return sessionRuns.has(activeRunId);
3113
+ };
3114
+ const maybeRefreshHistoryForRun = (runId, opts) => {
3115
+ if (isLocalRunId?.(runId) ?? false) {
3116
+ forgetLocalRunId?.(runId);
3117
+ if (!opts?.allowLocalWithoutDisplayableFinal) return;
3118
+ if (state.activeChatRunId && state.activeChatRunId !== runId) {
3119
+ pendingHistoryRefresh = true;
3120
+ return;
3121
+ }
3122
+ }
3123
+ if (hasConcurrentActiveRun(runId)) return;
3124
+ pendingHistoryRefresh = false;
3125
+ loadHistory?.();
3126
+ };
3127
+ const isSameSessionKey = (left, right) => {
3128
+ const normalizedLeft = normalizeLowercaseStringOrEmpty(left);
3129
+ const normalizedRight = normalizeLowercaseStringOrEmpty(right);
3130
+ if (!normalizedLeft || !normalizedRight) return false;
3131
+ if (normalizedLeft === normalizedRight) return true;
3132
+ const parsedLeft = parseAgentSessionKey(normalizedLeft);
3133
+ const parsedRight = parseAgentSessionKey(normalizedRight);
3134
+ if (parsedLeft && parsedRight) return parsedLeft.agentId === parsedRight.agentId && parsedLeft.rest === parsedRight.rest;
3135
+ if (parsedLeft) return parsedLeft.rest === normalizedRight;
3136
+ if (parsedRight) return normalizedLeft === parsedRight.rest;
3137
+ return false;
3138
+ };
3139
+ const handleChatEvent = (payload) => {
3140
+ if (!payload || typeof payload !== "object") return;
3141
+ const evt = payload;
3142
+ syncSessionKey();
3143
+ if (!isSameSessionKey(evt.sessionKey, state.currentSessionKey)) return;
3144
+ if (finalizedRuns.has(evt.runId)) {
3145
+ if (evt.state === "delta") return;
3146
+ if (evt.state === "final") return;
3147
+ }
3148
+ noteSessionRun(evt.runId);
3149
+ if (!state.activeChatRunId && !isLocalBtwRunId?.(evt.runId)) {
3150
+ state.activeChatRunId = evt.runId;
3151
+ if (state.pendingOptimisticUserMessage) {
3152
+ noteLocalRunId?.(evt.runId);
3153
+ state.pendingOptimisticUserMessage = false;
3154
+ }
3155
+ }
3156
+ if (evt.state === "delta") {
3157
+ setActivityStatus("streaming");
3158
+ if (state.activeChatRunId === evt.runId) armStreamingWatchdog(evt.runId);
3159
+ const displayText = streamAssembler.ingestDelta(evt.runId, evt.message, state.showThinking);
3160
+ if (!displayText) return;
3161
+ chatLog.updateAssistant(displayText, evt.runId);
3162
+ }
3163
+ if (evt.state === "final") {
3164
+ const isLocalBtwRun = isLocalBtwRunId?.(evt.runId) ?? false;
3165
+ const wasActiveRun = state.activeChatRunId === evt.runId;
3166
+ if (!evt.message && isLocalBtwRun) {
3167
+ forgetLocalBtwRunId?.(evt.runId);
3168
+ noteFinalizedRun(evt.runId);
3169
+ tui.requestRender();
3170
+ return;
3171
+ }
3172
+ if (!evt.message) {
3173
+ maybeRefreshHistoryForRun(evt.runId, { allowLocalWithoutDisplayableFinal: true });
3174
+ chatLog.dropAssistant(evt.runId);
3175
+ finalizeRun({
3176
+ runId: evt.runId,
3177
+ wasActiveRun,
3178
+ status: "idle"
3179
+ });
3180
+ tui.requestRender();
3181
+ return;
3182
+ }
3183
+ if (isCommandMessage(evt.message)) {
3184
+ maybeRefreshHistoryForRun(evt.runId);
3185
+ const text = extractTextFromMessage(evt.message);
3186
+ if (text) chatLog.addSystem(text);
3187
+ finalizeRun({
3188
+ runId: evt.runId,
3189
+ wasActiveRun,
3190
+ status: "idle"
3191
+ });
3192
+ tui.requestRender();
3193
+ return;
3194
+ }
3195
+ maybeRefreshHistoryForRun(evt.runId);
3196
+ const stopReason = evt.message && typeof evt.message === "object" && !Array.isArray(evt.message) ? typeof evt.message.stopReason === "string" ? evt.message.stopReason : "" : "";
3197
+ const finalText = streamAssembler.finalize(evt.runId, evt.message, state.showThinking, evt.errorMessage);
3198
+ if (finalText === "(no output)" && !isLocalRunId?.(evt.runId)) chatLog.dropAssistant(evt.runId);
3199
+ else chatLog.finalizeAssistant(finalText, evt.runId);
3200
+ finalizeRun({
3201
+ runId: evt.runId,
3202
+ wasActiveRun,
3203
+ status: stopReason === "error" ? "error" : "idle"
3204
+ });
3205
+ }
3206
+ if (evt.state === "aborted") {
3207
+ forgetLocalBtwRunId?.(evt.runId);
3208
+ const wasActiveRun = state.activeChatRunId === evt.runId;
3209
+ chatLog.addSystem("run aborted");
3210
+ terminateRun({
3211
+ runId: evt.runId,
3212
+ wasActiveRun,
3213
+ status: "aborted"
3214
+ });
3215
+ maybeRefreshHistoryForRun(evt.runId);
3216
+ }
3217
+ if (evt.state === "error") {
3218
+ forgetLocalBtwRunId?.(evt.runId);
3219
+ const wasActiveRun = state.activeChatRunId === evt.runId;
3220
+ const errorMessage = evt.errorMessage ?? "unknown";
3221
+ chatLog.addSystem(resolveAuthErrorHint(errorMessage) ?? `run error: ${errorMessage}`);
3222
+ terminateRun({
3223
+ runId: evt.runId,
3224
+ wasActiveRun,
3225
+ status: "error"
3226
+ });
3227
+ maybeRefreshHistoryForRun(evt.runId);
3228
+ }
3229
+ tui.requestRender();
3230
+ };
3231
+ const handleAgentEvent = (payload) => {
3232
+ if (!payload || typeof payload !== "object") return;
3233
+ const evt = payload;
3234
+ syncSessionKey();
3235
+ const isActiveRun = evt.runId === state.activeChatRunId;
3236
+ if (!(isActiveRun || sessionRuns.has(evt.runId) || finalizedRuns.has(evt.runId))) return;
3237
+ if (evt.stream === "tool") {
3238
+ const verbose = state.sessionInfo.verboseLevel ?? "off";
3239
+ const allowToolEvents = verbose !== "off";
3240
+ const allowToolOutput = verbose === "full";
3241
+ if (!allowToolEvents) return;
3242
+ const data = evt.data ?? {};
3243
+ const phase = asString(data.phase, "");
3244
+ const toolCallId = asString(data.toolCallId, "");
3245
+ const toolName = asString(data.name, "tool");
3246
+ if (!toolCallId) return;
3247
+ if (phase === "start") chatLog.startTool(toolCallId, toolName, data.args);
3248
+ else if (phase === "update") {
3249
+ if (!allowToolOutput) return;
3250
+ chatLog.updateToolResult(toolCallId, data.partialResult, { partial: true });
3251
+ } else if (phase === "result") if (allowToolOutput) chatLog.updateToolResult(toolCallId, data.result, { isError: Boolean(data.isError) });
3252
+ else chatLog.updateToolResult(toolCallId, { content: [] }, { isError: Boolean(data.isError) });
3253
+ tui.requestRender();
3254
+ return;
3255
+ }
3256
+ if (evt.stream === "lifecycle") {
3257
+ if (!isActiveRun) return;
3258
+ const phase = typeof evt.data?.phase === "string" ? evt.data.phase : "";
3259
+ if (phase === "start") setActivityStatus("running");
3260
+ if (phase === "end") setActivityStatus("idle");
3261
+ if (phase === "error") setActivityStatus("error");
3262
+ tui.requestRender();
3263
+ }
3264
+ };
3265
+ const handleBtwEvent = (payload) => {
3266
+ if (!payload || typeof payload !== "object") return;
3267
+ const evt = payload;
3268
+ syncSessionKey();
3269
+ if (!isSameSessionKey(evt.sessionKey, state.currentSessionKey)) return;
3270
+ if (evt.kind !== "btw") return;
3271
+ const question = evt.question.trim();
3272
+ const text = evt.text.trim();
3273
+ if (!question || !text) return;
3274
+ btw.showResult({
3275
+ question,
3276
+ text,
3277
+ isError: evt.isError
3278
+ });
3279
+ tui.requestRender();
3280
+ };
3281
+ const dispose = () => {
3282
+ clearStreamingWatchdog();
3283
+ };
3284
+ return {
3285
+ handleChatEvent,
3286
+ handleAgentEvent,
3287
+ handleBtwEvent,
3288
+ dispose
3289
+ };
3290
+ }
3291
+ //#endregion
3292
+ //#region src/tui/tui-local-shell.ts
3293
+ function createLocalShellRunner(deps) {
3294
+ let localExecAsked = false;
3295
+ let localExecAllowed = false;
3296
+ const createSelector = deps.createSelector ?? createSearchableSelectList;
3297
+ const spawnCommand = deps.spawnCommand ?? spawn;
3298
+ const getCwd = deps.getCwd ?? (() => process.cwd());
3299
+ const env = deps.env ?? process.env;
3300
+ const maxChars = deps.maxOutputChars ?? 4e4;
3301
+ const ensureLocalExecAllowed = async () => {
3302
+ if (localExecAllowed) return true;
3303
+ if (localExecAsked) return false;
3304
+ localExecAsked = true;
3305
+ return await new Promise((resolve) => {
3306
+ deps.chatLog.addSystem("Allow local shell commands for this session?");
3307
+ deps.chatLog.addSystem("This runs commands on YOUR machine (not the gateway) and may delete files or reveal secrets.");
3308
+ deps.chatLog.addSystem("Select Yes/No (arrows + Enter), Esc to cancel.");
3309
+ const selector = createSelector([{
3310
+ value: "no",
3311
+ label: "No"
3312
+ }, {
3313
+ value: "yes",
3314
+ label: "Yes"
3315
+ }], 2);
3316
+ selector.onSelect = (item) => {
3317
+ deps.closeOverlay();
3318
+ if (item.value === "yes") {
3319
+ localExecAllowed = true;
3320
+ deps.chatLog.addSystem("local shell: enabled for this session");
3321
+ resolve(true);
3322
+ } else {
3323
+ deps.chatLog.addSystem("local shell: not enabled");
3324
+ resolve(false);
3325
+ }
3326
+ deps.tui.requestRender();
3327
+ };
3328
+ selector.onCancel = () => {
3329
+ deps.closeOverlay();
3330
+ deps.chatLog.addSystem("local shell: cancelled");
3331
+ deps.tui.requestRender();
3332
+ resolve(false);
3333
+ };
3334
+ deps.openOverlay(selector);
3335
+ deps.tui.requestRender();
3336
+ });
3337
+ };
3338
+ const runLocalShellLine = async (line) => {
3339
+ const cmd = line.slice(1);
3340
+ if (cmd === "") return;
3341
+ if (localExecAsked && !localExecAllowed) {
3342
+ deps.chatLog.addSystem("local shell: not enabled for this session");
3343
+ deps.tui.requestRender();
3344
+ return;
3345
+ }
3346
+ if (!await ensureLocalExecAllowed()) return;
3347
+ deps.chatLog.addSystem(`[local] $ ${cmd}`);
3348
+ deps.tui.requestRender();
3349
+ const appendWithCap = (text, chunk) => {
3350
+ const combined = text + chunk;
3351
+ return combined.length > maxChars ? combined.slice(-maxChars) : combined;
3352
+ };
3353
+ await new Promise((resolve) => {
3354
+ const child = spawnCommand(cmd, {
3355
+ shell: true,
3356
+ cwd: getCwd(),
3357
+ env: {
3358
+ ...env,
3359
+ GENESIS_SHELL: "tui-local"
3360
+ }
3361
+ });
3362
+ let stdout = "";
3363
+ let stderr = "";
3364
+ child.stdout.on("data", (buf) => {
3365
+ stdout = appendWithCap(stdout, buf.toString("utf8"));
3366
+ });
3367
+ child.stderr.on("data", (buf) => {
3368
+ stderr = appendWithCap(stderr, buf.toString("utf8"));
3369
+ });
3370
+ child.on("close", (code, signal) => {
3371
+ const combined = (stdout + (stderr ? (stdout ? "\n" : "") + stderr : "")).slice(0, maxChars).trimEnd();
3372
+ if (combined) for (const line of combined.split("\n")) deps.chatLog.addSystem(`[local] ${line}`);
3373
+ deps.chatLog.addSystem(`[local] exit ${code ?? "?"}${signal ? ` (signal ${signal})` : ""}`);
3374
+ deps.tui.requestRender();
3375
+ resolve();
3376
+ });
3377
+ child.on("error", (err) => {
3378
+ deps.chatLog.addSystem(`[local] error: ${String(err)}`);
3379
+ deps.tui.requestRender();
3380
+ resolve();
3381
+ });
3382
+ });
3383
+ };
3384
+ return { runLocalShellLine };
3385
+ }
3386
+ //#endregion
3387
+ //#region src/tui/tui-overlays.ts
3388
+ function createOverlayHandlers(host, fallbackFocus) {
3389
+ const openOverlay = (component) => {
3390
+ host.showOverlay(component);
3391
+ };
3392
+ const closeOverlay = () => {
3393
+ if (host.hasOverlay()) {
3394
+ host.hideOverlay();
3395
+ return;
3396
+ }
3397
+ host.setFocus(fallbackFocus);
3398
+ };
3399
+ return {
3400
+ openOverlay,
3401
+ closeOverlay
3402
+ };
3403
+ }
3404
+ //#endregion
3405
+ //#region src/tui/tui-session-actions.ts
3406
+ function createSessionActions(context) {
3407
+ const { client, chatLog, btw, tui, opts, state, agentNames, initialSessionInput, initialSessionAgentId, resolveSessionKey, updateHeader, updateFooter, updateAutocompleteProvider, setActivityStatus, clearLocalRunIds } = context;
3408
+ let refreshSessionInfoPromise = Promise.resolve();
3409
+ let lastSessionDefaults = null;
3410
+ const applyAgentsResult = (result) => {
3411
+ state.agentDefaultId = normalizeAgentId(result.defaultId);
3412
+ state.sessionMainKey = normalizeMainKey(result.mainKey);
3413
+ state.sessionScope = result.scope ?? state.sessionScope;
3414
+ state.agents = result.agents.map((agent) => ({
3415
+ id: normalizeAgentId(agent.id),
3416
+ name: normalizeOptionalString(agent.name)
3417
+ }));
3418
+ agentNames.clear();
3419
+ for (const agent of state.agents) if (agent.name) agentNames.set(agent.id, agent.name);
3420
+ if (!state.initialSessionApplied) {
3421
+ if (initialSessionAgentId) {
3422
+ if (state.agents.some((agent) => agent.id === initialSessionAgentId)) state.currentAgentId = initialSessionAgentId;
3423
+ } else if (!state.agents.some((agent) => agent.id === state.currentAgentId)) state.currentAgentId = state.agents[0]?.id ?? normalizeAgentId(result.defaultId ?? state.currentAgentId);
3424
+ const nextSessionKey = resolveSessionKey(initialSessionInput);
3425
+ if (nextSessionKey !== state.currentSessionKey) state.currentSessionKey = nextSessionKey;
3426
+ state.initialSessionApplied = true;
3427
+ } else if (!state.agents.some((agent) => agent.id === state.currentAgentId)) state.currentAgentId = state.agents[0]?.id ?? normalizeAgentId(result.defaultId ?? state.currentAgentId);
3428
+ updateHeader();
3429
+ updateFooter();
3430
+ };
3431
+ const refreshAgents = async () => {
3432
+ try {
3433
+ applyAgentsResult(await client.listAgents());
3434
+ } catch (err) {
3435
+ chatLog.addSystem(`agents list failed: ${String(err)}`);
3436
+ }
3437
+ };
3438
+ const updateAgentFromSessionKey = (key) => {
3439
+ const parsed = parseAgentSessionKey(key);
3440
+ if (!parsed) return;
3441
+ const next = normalizeAgentId(parsed.agentId);
3442
+ if (next !== state.currentAgentId) state.currentAgentId = next;
3443
+ };
3444
+ const resolveModelSelection = (entry) => {
3445
+ return resolveSessionInfoModelSelection({
3446
+ currentProvider: state.sessionInfo.modelProvider,
3447
+ currentModel: state.sessionInfo.model,
3448
+ defaultProvider: lastSessionDefaults?.modelProvider,
3449
+ defaultModel: lastSessionDefaults?.model,
3450
+ entryProvider: entry?.modelProvider,
3451
+ entryModel: entry?.model,
3452
+ overrideProvider: entry?.providerOverride,
3453
+ overrideModel: entry?.modelOverride
3454
+ });
3455
+ };
3456
+ const applySessionInfo = (params) => {
3457
+ const entry = params.entry ?? void 0;
3458
+ const defaults = params.defaults ?? lastSessionDefaults ?? void 0;
3459
+ const previousDefaults = lastSessionDefaults;
3460
+ const defaultsChanged = params.defaults ? previousDefaults?.model !== params.defaults.model || previousDefaults?.modelProvider !== params.defaults.modelProvider || previousDefaults?.contextTokens !== params.defaults.contextTokens : false;
3461
+ if (params.defaults) lastSessionDefaults = params.defaults;
3462
+ const entryUpdatedAt = entry?.updatedAt ?? null;
3463
+ const currentUpdatedAt = state.sessionInfo.updatedAt ?? null;
3464
+ if (!params.force && entryUpdatedAt !== null && currentUpdatedAt !== null && entryUpdatedAt < currentUpdatedAt && !defaultsChanged) return;
3465
+ const next = { ...state.sessionInfo };
3466
+ if (entry?.thinkingLevel !== void 0) next.thinkingLevel = entry.thinkingLevel;
3467
+ if (entry?.fastMode !== void 0) next.fastMode = entry.fastMode;
3468
+ if (entry?.verboseLevel !== void 0) next.verboseLevel = entry.verboseLevel;
3469
+ if (entry?.traceLevel !== void 0) next.traceLevel = entry.traceLevel;
3470
+ if (entry?.reasoningLevel !== void 0) next.reasoningLevel = entry.reasoningLevel;
3471
+ if (entry?.responseUsage !== void 0) next.responseUsage = entry.responseUsage;
3472
+ if (entry?.inputTokens !== void 0) next.inputTokens = entry.inputTokens;
3473
+ if (entry?.outputTokens !== void 0) next.outputTokens = entry.outputTokens;
3474
+ if (entry?.totalTokens !== void 0) next.totalTokens = entry.totalTokens;
3475
+ if (entry?.contextTokens !== void 0 || defaults?.contextTokens !== void 0) next.contextTokens = entry?.contextTokens ?? defaults?.contextTokens ?? state.sessionInfo.contextTokens;
3476
+ if (entry?.displayName !== void 0) next.displayName = entry.displayName;
3477
+ if (entry?.updatedAt !== void 0) next.updatedAt = entry.updatedAt;
3478
+ const selection = resolveModelSelection(entry);
3479
+ if (selection.modelProvider !== void 0) next.modelProvider = selection.modelProvider;
3480
+ if (selection.model !== void 0) next.model = selection.model;
3481
+ state.sessionInfo = next;
3482
+ updateAutocompleteProvider();
3483
+ updateFooter();
3484
+ tui.requestRender();
3485
+ };
3486
+ const runRefreshSessionInfo = async () => {
3487
+ try {
3488
+ const resolveListAgentId = () => {
3489
+ if (state.currentSessionKey === "global" || state.currentSessionKey === "unknown") return;
3490
+ const parsed = parseAgentSessionKey(state.currentSessionKey);
3491
+ return parsed?.agentId ? normalizeAgentId(parsed.agentId) : state.currentAgentId;
3492
+ };
3493
+ const listAgentId = resolveListAgentId();
3494
+ const result = await client.listSessions({
3495
+ includeGlobal: false,
3496
+ includeUnknown: false,
3497
+ agentId: listAgentId
3498
+ });
3499
+ const normalizeMatchKey = (key) => parseAgentSessionKey(key)?.rest ?? key;
3500
+ const currentMatchKey = normalizeMatchKey(state.currentSessionKey);
3501
+ const entry = result.sessions.find((row) => {
3502
+ if (row.key === state.currentSessionKey) return true;
3503
+ return normalizeMatchKey(row.key) === currentMatchKey;
3504
+ });
3505
+ if (entry?.key && entry.key !== state.currentSessionKey) {
3506
+ updateAgentFromSessionKey(entry.key);
3507
+ state.currentSessionKey = entry.key;
3508
+ updateHeader();
3509
+ }
3510
+ applySessionInfo({
3511
+ entry,
3512
+ defaults: result.defaults
3513
+ });
3514
+ } catch (err) {
3515
+ chatLog.addSystem(`sessions list failed: ${String(err)}`);
3516
+ }
3517
+ };
3518
+ const refreshSessionInfo = async () => {
3519
+ refreshSessionInfoPromise = refreshSessionInfoPromise.then(runRefreshSessionInfo, runRefreshSessionInfo);
3520
+ await refreshSessionInfoPromise;
3521
+ };
3522
+ const applySessionInfoFromPatch = (result) => {
3523
+ if (!result?.entry) return;
3524
+ if (result.key && result.key !== state.currentSessionKey) {
3525
+ updateAgentFromSessionKey(result.key);
3526
+ state.currentSessionKey = result.key;
3527
+ updateHeader();
3528
+ }
3529
+ const resolved = result.resolved;
3530
+ applySessionInfo({
3531
+ entry: resolved && (resolved.modelProvider || resolved.model) ? {
3532
+ ...result.entry,
3533
+ modelProvider: resolved.modelProvider ?? result.entry.modelProvider,
3534
+ model: resolved.model ?? result.entry.model
3535
+ } : result.entry,
3536
+ force: true
3537
+ });
3538
+ };
3539
+ const loadHistory = async () => {
3540
+ try {
3541
+ const record = await client.loadHistory({
3542
+ sessionKey: state.currentSessionKey,
3543
+ limit: opts.historyLimit ?? 200
3544
+ });
3545
+ state.currentSessionId = typeof record.sessionId === "string" ? record.sessionId : null;
3546
+ state.sessionInfo.thinkingLevel = record.thinkingLevel ?? state.sessionInfo.thinkingLevel;
3547
+ state.sessionInfo.fastMode = record.fastMode ?? state.sessionInfo.fastMode;
3548
+ state.sessionInfo.verboseLevel = record.verboseLevel ?? state.sessionInfo.verboseLevel;
3549
+ state.sessionInfo.traceLevel = record.traceLevel ?? state.sessionInfo.traceLevel;
3550
+ const showTools = (state.sessionInfo.verboseLevel ?? "off") !== "off";
3551
+ chatLog.clearAll();
3552
+ btw.clear();
3553
+ chatLog.addSystem(`session ${state.currentSessionKey}`);
3554
+ for (const entry of record.messages ?? []) {
3555
+ if (!entry || typeof entry !== "object") continue;
3556
+ const message = entry;
3557
+ if (isCommandMessage(message)) {
3558
+ const text = extractTextFromMessage(message);
3559
+ if (text) chatLog.addSystem(text);
3560
+ continue;
3561
+ }
3562
+ if (message.role === "user") {
3563
+ const text = extractTextFromMessage(message);
3564
+ if (text) chatLog.addUser(text);
3565
+ continue;
3566
+ }
3567
+ if (message.role === "assistant") {
3568
+ const text = extractTextFromMessage(message, { includeThinking: state.showThinking });
3569
+ if (text) chatLog.finalizeAssistant(text);
3570
+ continue;
3571
+ }
3572
+ if (message.role === "toolResult") {
3573
+ if (!showTools) continue;
3574
+ const toolCallId = asString(message.toolCallId, "");
3575
+ const toolName = asString(message.toolName, "tool");
3576
+ chatLog.startTool(toolCallId, toolName, {}).setResult({
3577
+ content: Array.isArray(message.content) ? message.content : [],
3578
+ details: typeof message.details === "object" && message.details ? message.details : void 0
3579
+ }, { isError: Boolean(message.isError) });
3580
+ }
3581
+ }
3582
+ state.historyLoaded = true;
3583
+ } catch (err) {
3584
+ chatLog.addSystem(`history failed: ${String(err)}`);
3585
+ }
3586
+ await refreshSessionInfo();
3587
+ tui.requestRender();
3588
+ };
3589
+ const setSession = async (rawKey) => {
3590
+ const nextKey = resolveSessionKey(rawKey);
3591
+ updateAgentFromSessionKey(nextKey);
3592
+ state.currentSessionKey = nextKey;
3593
+ state.activeChatRunId = null;
3594
+ setActivityStatus("idle");
3595
+ state.currentSessionId = null;
3596
+ state.sessionInfo.updatedAt = null;
3597
+ state.historyLoaded = false;
3598
+ clearLocalRunIds?.();
3599
+ btw.clear();
3600
+ updateHeader();
3601
+ updateFooter();
3602
+ await loadHistory();
3603
+ };
3604
+ const abortActive = async () => {
3605
+ if (!state.activeChatRunId) {
3606
+ chatLog.addSystem("no active run");
3607
+ tui.requestRender();
3608
+ return;
3609
+ }
3610
+ try {
3611
+ await client.abortChat({
3612
+ sessionKey: state.currentSessionKey,
3613
+ runId: state.activeChatRunId
3614
+ });
3615
+ setActivityStatus("aborted");
3616
+ } catch (err) {
3617
+ chatLog.addSystem(`abort failed: ${String(err)}`);
3618
+ setActivityStatus("abort failed");
3619
+ }
3620
+ tui.requestRender();
3621
+ };
3622
+ return {
3623
+ applyAgentsResult,
3624
+ refreshAgents,
3625
+ refreshSessionInfo,
3626
+ applySessionInfoFromPatch,
3627
+ loadHistory,
3628
+ setSession,
3629
+ abortActive
3630
+ };
3631
+ }
3632
+ //#endregion
3633
+ //#region src/tui/tui-submit.ts
3634
+ function createEditorSubmitHandler(params) {
3635
+ return (text) => {
3636
+ const raw = text;
3637
+ const value = raw.trim();
3638
+ params.editor.setText("");
3639
+ if (!value) return;
3640
+ if (raw.startsWith("!") && raw !== "!") {
3641
+ params.editor.addToHistory(raw);
3642
+ params.handleBangLine(raw);
3643
+ return;
3644
+ }
3645
+ params.editor.addToHistory(value);
3646
+ if (value.startsWith("/")) {
3647
+ params.handleCommand(value);
3648
+ return;
3649
+ }
3650
+ params.sendMessage(value);
3651
+ };
3652
+ }
3653
+ function shouldEnableWindowsGitBashPasteFallback(params) {
3654
+ const platform = params?.platform ?? process.platform;
3655
+ const env = params?.env ?? process.env;
3656
+ const termProgram = normalizeLowercaseStringOrEmpty(env.TERM_PROGRAM);
3657
+ if (platform === "darwin") {
3658
+ if (termProgram.includes("iterm") || termProgram.includes("apple_terminal")) return true;
3659
+ return false;
3660
+ }
3661
+ if (platform !== "win32") return false;
3662
+ const msystem = (env.MSYSTEM ?? "").toUpperCase();
3663
+ const shell = env.SHELL ?? "";
3664
+ if (msystem.startsWith("MINGW") || msystem.startsWith("MSYS")) return true;
3665
+ if (normalizeLowercaseStringOrEmpty(shell).includes("bash")) return true;
3666
+ return termProgram.includes("mintty");
3667
+ }
3668
+ function createSubmitBurstCoalescer(params) {
3669
+ const windowMs = Math.max(1, params.burstWindowMs ?? 50);
3670
+ const now = params.now ?? (() => Date.now());
3671
+ const setTimer = params.setTimer ?? setTimeout;
3672
+ const clearTimer = params.clearTimer ?? clearTimeout;
3673
+ let pending = null;
3674
+ let pendingAt = 0;
3675
+ let flushTimer = null;
3676
+ const clearFlushTimer = () => {
3677
+ if (!flushTimer) return;
3678
+ clearTimer(flushTimer);
3679
+ flushTimer = null;
3680
+ };
3681
+ const flushPending = () => {
3682
+ if (pending === null) return;
3683
+ const value = pending;
3684
+ pending = null;
3685
+ pendingAt = 0;
3686
+ clearFlushTimer();
3687
+ params.submit(value);
3688
+ };
3689
+ const scheduleFlush = () => {
3690
+ clearFlushTimer();
3691
+ flushTimer = setTimer(() => {
3692
+ flushPending();
3693
+ }, windowMs);
3694
+ };
3695
+ return (value) => {
3696
+ if (!params.enabled) {
3697
+ params.submit(value);
3698
+ return;
3699
+ }
3700
+ if (value.includes("\n")) {
3701
+ flushPending();
3702
+ params.submit(value);
3703
+ return;
3704
+ }
3705
+ const ts = now();
3706
+ if (pending === null) {
3707
+ pending = value;
3708
+ pendingAt = ts;
3709
+ scheduleFlush();
3710
+ return;
3711
+ }
3712
+ if (ts - pendingAt <= windowMs) {
3713
+ pending = `${pending}\n${value}`;
3714
+ pendingAt = ts;
3715
+ scheduleFlush();
3716
+ return;
3717
+ }
3718
+ flushPending();
3719
+ pending = value;
3720
+ pendingAt = ts;
3721
+ scheduleFlush();
3722
+ };
3723
+ }
3724
+ //#endregion
3725
+ //#region src/tui/tui-waiting.ts
3726
+ const defaultWaitingPhrases = [
3727
+ "flibbertigibbeting",
3728
+ "kerfuffling",
3729
+ "dillydallying",
3730
+ "twiddling thumbs",
3731
+ "noodling",
3732
+ "bamboozling",
3733
+ "moseying",
3734
+ "hobnobbing",
3735
+ "pondering",
3736
+ "conjuring"
3737
+ ];
3738
+ function pickWaitingPhrase(tick, phrases = defaultWaitingPhrases) {
3739
+ return phrases[Math.floor(tick / 10) % phrases.length] ?? phrases[0] ?? "waiting";
3740
+ }
3741
+ function shimmerText(theme, text, tick) {
3742
+ const width = 6;
3743
+ const hi = (ch) => theme.bold(theme.accentSoft(ch));
3744
+ const pos = tick % (text.length + width);
3745
+ const start = Math.max(0, pos - width);
3746
+ const end = Math.min(text.length - 1, pos);
3747
+ let out = "";
3748
+ for (let i = 0; i < text.length; i++) {
3749
+ const ch = text[i];
3750
+ out += i >= start && i <= end ? hi(ch) : theme.dim(ch);
3751
+ }
3752
+ return out;
3753
+ }
3754
+ function buildWaitingStatusMessage(params) {
3755
+ const phrase = pickWaitingPhrase(params.tick, params.phrases);
3756
+ return `${shimmerText(params.theme, `${phrase}…`, params.tick)} • ${params.elapsed} | ${params.connectionStatus}`;
3757
+ }
3758
+ //#endregion
3759
+ //#region src/tui/tui.ts
3760
+ const GENESIS_CLI_WRAPPER_PATH = fileURLToPath(new URL("../../genesis.mjs", import.meta.url));
3761
+ const GENESIS_RUN_NODE_SCRIPT_PATH = fileURLToPath(new URL("../../scripts/run-node.mjs", import.meta.url));
3762
+ const GENESIS_DIST_ENTRY_JS_PATH = fileURLToPath(new URL("../../dist/entry.js", import.meta.url));
3763
+ const GENESIS_DIST_ENTRY_MJS_PATH = fileURLToPath(new URL("../../dist/entry.mjs", import.meta.url));
3764
+ const OPENAI_CODEX_PROVIDER = "openai-codex";
3765
+ /** Resolve the absolute path to the `codex` CLI binary, or `null` if not installed. */
3766
+ function resolveCodexCliBin() {
3767
+ try {
3768
+ return execFileSync(process.platform === "win32" ? "where" : "which", ["codex"], { encoding: "utf8" }).trim().split(/\r?\n/)[0] || null;
3769
+ } catch {
3770
+ return null;
3771
+ }
3772
+ }
3773
+ function resolveLocalAuthCliInvocation(params) {
3774
+ const hasDistEntry = params?.hasDistEntry ?? (existsSync(GENESIS_DIST_ENTRY_JS_PATH) || existsSync(GENESIS_DIST_ENTRY_MJS_PATH));
3775
+ const hasRunNodeScript = params?.hasRunNodeScript ?? existsSync(GENESIS_RUN_NODE_SCRIPT_PATH);
3776
+ const command = params?.execPath ?? process.execPath;
3777
+ const wrapperPath = params?.wrapperPath ?? GENESIS_CLI_WRAPPER_PATH;
3778
+ const runNodePath = params?.runNodePath ?? GENESIS_RUN_NODE_SCRIPT_PATH;
3779
+ return hasDistEntry || !hasRunNodeScript ? {
3780
+ command,
3781
+ args: [
3782
+ wrapperPath,
3783
+ "models",
3784
+ "auth",
3785
+ "login"
3786
+ ]
3787
+ } : {
3788
+ command,
3789
+ args: [
3790
+ runNodePath,
3791
+ "models",
3792
+ "auth",
3793
+ "login"
3794
+ ]
3795
+ };
3796
+ }
3797
+ function resolveLocalAuthSpawnOptions(params) {
3798
+ return (params.platform ?? process.platform) === "win32" && /\.(cmd|bat)$/iu.test(params.command.trim()) ? { shell: true } : {};
3799
+ }
3800
+ function resolveLocalAuthSpawnCwd(params) {
3801
+ const defaultCwd = params.defaultCwd ?? process.cwd();
3802
+ const entryArg = params.args[0]?.trim();
3803
+ if (!entryArg) return defaultCwd;
3804
+ const entryBase = path.basename(entryArg).toLowerCase();
3805
+ if (entryBase === "genesis.mjs") return path.dirname(entryArg);
3806
+ if (entryBase === "run-node.mjs") return path.dirname(path.dirname(entryArg));
3807
+ return defaultCwd;
3808
+ }
3809
+ function resolveTuiSessionKey(params) {
3810
+ const trimmed = (params.raw ?? "").trim();
3811
+ if (!trimmed) {
3812
+ if (params.sessionScope === "global") return "global";
3813
+ return buildAgentMainSessionKey({
3814
+ agentId: params.currentAgentId,
3815
+ mainKey: params.sessionMainKey
3816
+ });
3817
+ }
3818
+ if (trimmed === "global" || trimmed === "unknown") return trimmed;
3819
+ if (trimmed.startsWith("agent:")) return normalizeLowercaseStringOrEmpty(trimmed);
3820
+ return `agent:${params.currentAgentId}:${normalizeLowercaseStringOrEmpty(trimmed)}`;
3821
+ }
3822
+ function resolveInitialTuiAgentId(params) {
3823
+ const parsed = parseAgentSessionKey((params.initialSessionInput ?? "").trim());
3824
+ if (parsed?.agentId) return normalizeAgentId(parsed.agentId);
3825
+ const inferredFromWorkspace = resolveAgentIdByWorkspacePath(params.cfg, params.cwd ?? process.cwd());
3826
+ if (inferredFromWorkspace) return inferredFromWorkspace;
3827
+ return normalizeAgentId(params.fallbackAgentId);
3828
+ }
3829
+ function resolveGatewayDisconnectState(reason) {
3830
+ const reasonLabel = reason?.trim() ? reason.trim() : "closed";
3831
+ if (/pairing required/i.test(reasonLabel)) return {
3832
+ connectionStatus: `gateway disconnected: ${reasonLabel}`,
3833
+ activityStatus: "pairing required: run genesis devices list",
3834
+ pairingHint: "Pairing required. Run `genesis devices list`, approve your request ID, then reconnect."
3835
+ };
3836
+ return {
3837
+ connectionStatus: `gateway disconnected: ${reasonLabel}`,
3838
+ activityStatus: "idle"
3839
+ };
3840
+ }
3841
+ function createBackspaceDeduper(params) {
3842
+ const dedupeWindowMs = Math.max(0, Math.floor(params?.dedupeWindowMs ?? 8));
3843
+ const now = params?.now ?? (() => Date.now());
3844
+ let lastBackspaceAt = -1;
3845
+ return (data) => {
3846
+ if (!matchesKey(data, Key.backspace)) return data;
3847
+ const ts = now();
3848
+ if (lastBackspaceAt >= 0 && ts - lastBackspaceAt <= dedupeWindowMs) return "";
3849
+ lastBackspaceAt = ts;
3850
+ return data;
3851
+ };
3852
+ }
3853
+ function isIgnorableTuiStopError(error) {
3854
+ if (!error || typeof error !== "object") return false;
3855
+ const err = error;
3856
+ const code = typeof err.code === "string" ? err.code : "";
3857
+ const syscall = typeof err.syscall === "string" ? err.syscall : "";
3858
+ const message = typeof err.message === "string" ? err.message : "";
3859
+ if (code === "EBADF" && syscall === "setRawMode") return true;
3860
+ return /setRawMode/i.test(message) && /EBADF/i.test(message);
3861
+ }
3862
+ function stopTuiSafely(stop) {
3863
+ try {
3864
+ stop();
3865
+ } catch (error) {
3866
+ if (!isIgnorableTuiStopError(error)) throw error;
3867
+ }
3868
+ }
3869
+ async function drainAndStopTuiSafely(tui) {
3870
+ if (typeof tui.terminal?.drainInput === "function") try {
3871
+ await tui.terminal.drainInput();
3872
+ } catch {}
3873
+ stopTuiSafely(() => tui.stop());
3874
+ }
3875
+ function resolveCtrlCAction(params) {
3876
+ const exitWindowMs = Math.max(1, Math.floor(params.exitWindowMs ?? 1e3));
3877
+ if (params.hasInput) return {
3878
+ action: "clear",
3879
+ nextLastCtrlCAt: params.now
3880
+ };
3881
+ if (params.now - params.lastCtrlCAt <= exitWindowMs) return {
3882
+ action: "exit",
3883
+ nextLastCtrlCAt: params.lastCtrlCAt
3884
+ };
3885
+ return {
3886
+ action: "warn",
3887
+ nextLastCtrlCAt: params.now
3888
+ };
3889
+ }
3890
+ async function runTui(opts) {
3891
+ const isLocalMode = opts.local === true;
3892
+ const config = loadConfig();
3893
+ const initialSessionInput = (opts.session ?? "").trim();
3894
+ let sessionScope = config.session?.scope ?? "per-sender";
3895
+ let sessionMainKey = normalizeMainKey(config.session?.mainKey);
3896
+ let agentDefaultId = resolveDefaultAgentId(config);
3897
+ let currentAgentId = resolveInitialTuiAgentId({
3898
+ cfg: config,
3899
+ fallbackAgentId: agentDefaultId,
3900
+ initialSessionInput,
3901
+ cwd: process.cwd()
3902
+ });
3903
+ let agents = [];
3904
+ const agentNames = /* @__PURE__ */ new Map();
3905
+ let currentSessionKey = "";
3906
+ let initialSessionApplied = false;
3907
+ let currentSessionId = null;
3908
+ let activeChatRunId = null;
3909
+ let pendingOptimisticUserMessage = false;
3910
+ let historyLoaded = false;
3911
+ let isConnected = false;
3912
+ let wasDisconnected = false;
3913
+ let toolsExpanded = false;
3914
+ let showThinking = false;
3915
+ let pairingHintShown = false;
3916
+ const localRunIds = /* @__PURE__ */ new Set();
3917
+ const localBtwRunIds = /* @__PURE__ */ new Set();
3918
+ const deliverDefault = opts.deliver ?? false;
3919
+ const autoMessage = opts.message?.trim();
3920
+ let autoMessageSent = false;
3921
+ let sessionInfo = {};
3922
+ let lastCtrlCAt = 0;
3923
+ let exitRequested = false;
3924
+ let activityStatus = "idle";
3925
+ let connectionStatus = isLocalMode ? "starting local runtime" : "connecting";
3926
+ let statusTimeout = null;
3927
+ let statusTimer = null;
3928
+ let statusStartedAt = null;
3929
+ let lastActivityStatus = activityStatus;
3930
+ const state = {
3931
+ get agentDefaultId() {
3932
+ return agentDefaultId;
3933
+ },
3934
+ set agentDefaultId(value) {
3935
+ agentDefaultId = value;
3936
+ },
3937
+ get sessionMainKey() {
3938
+ return sessionMainKey;
3939
+ },
3940
+ set sessionMainKey(value) {
3941
+ sessionMainKey = value;
3942
+ },
3943
+ get sessionScope() {
3944
+ return sessionScope;
3945
+ },
3946
+ set sessionScope(value) {
3947
+ sessionScope = value;
3948
+ },
3949
+ get agents() {
3950
+ return agents;
3951
+ },
3952
+ set agents(value) {
3953
+ agents = value;
3954
+ },
3955
+ get currentAgentId() {
3956
+ return currentAgentId;
3957
+ },
3958
+ set currentAgentId(value) {
3959
+ currentAgentId = value;
3960
+ },
3961
+ get currentSessionKey() {
3962
+ return currentSessionKey;
3963
+ },
3964
+ set currentSessionKey(value) {
3965
+ currentSessionKey = value;
3966
+ },
3967
+ get currentSessionId() {
3968
+ return currentSessionId;
3969
+ },
3970
+ set currentSessionId(value) {
3971
+ currentSessionId = value;
3972
+ },
3973
+ get activeChatRunId() {
3974
+ return activeChatRunId;
3975
+ },
3976
+ set activeChatRunId(value) {
3977
+ activeChatRunId = value;
3978
+ },
3979
+ get pendingOptimisticUserMessage() {
3980
+ return pendingOptimisticUserMessage;
3981
+ },
3982
+ set pendingOptimisticUserMessage(value) {
3983
+ pendingOptimisticUserMessage = value;
3984
+ },
3985
+ get historyLoaded() {
3986
+ return historyLoaded;
3987
+ },
3988
+ set historyLoaded(value) {
3989
+ historyLoaded = value;
3990
+ },
3991
+ get sessionInfo() {
3992
+ return sessionInfo;
3993
+ },
3994
+ set sessionInfo(value) {
3995
+ sessionInfo = value;
3996
+ },
3997
+ get initialSessionApplied() {
3998
+ return initialSessionApplied;
3999
+ },
4000
+ set initialSessionApplied(value) {
4001
+ initialSessionApplied = value;
4002
+ },
4003
+ get isConnected() {
4004
+ return isConnected;
4005
+ },
4006
+ set isConnected(value) {
4007
+ isConnected = value;
4008
+ },
4009
+ get autoMessageSent() {
4010
+ return autoMessageSent;
4011
+ },
4012
+ set autoMessageSent(value) {
4013
+ autoMessageSent = value;
4014
+ },
4015
+ get toolsExpanded() {
4016
+ return toolsExpanded;
4017
+ },
4018
+ set toolsExpanded(value) {
4019
+ toolsExpanded = value;
4020
+ },
4021
+ get showThinking() {
4022
+ return showThinking;
4023
+ },
4024
+ set showThinking(value) {
4025
+ showThinking = value;
4026
+ },
4027
+ get connectionStatus() {
4028
+ return connectionStatus;
4029
+ },
4030
+ set connectionStatus(value) {
4031
+ connectionStatus = value;
4032
+ },
4033
+ get activityStatus() {
4034
+ return activityStatus;
4035
+ },
4036
+ set activityStatus(value) {
4037
+ activityStatus = value;
4038
+ },
4039
+ get statusTimeout() {
4040
+ return statusTimeout;
4041
+ },
4042
+ set statusTimeout(value) {
4043
+ statusTimeout = value;
4044
+ },
4045
+ get lastCtrlCAt() {
4046
+ return lastCtrlCAt;
4047
+ },
4048
+ set lastCtrlCAt(value) {
4049
+ lastCtrlCAt = value;
4050
+ }
4051
+ };
4052
+ const noteLocalRunId = (runId) => {
4053
+ if (!runId) return;
4054
+ localRunIds.add(runId);
4055
+ if (localRunIds.size > 200) {
4056
+ const [first] = localRunIds;
4057
+ if (first) localRunIds.delete(first);
4058
+ }
4059
+ };
4060
+ const forgetLocalRunId = (runId) => {
4061
+ localRunIds.delete(runId);
4062
+ };
4063
+ const isLocalRunId = (runId) => localRunIds.has(runId);
4064
+ const clearLocalRunIds = () => {
4065
+ localRunIds.clear();
4066
+ };
4067
+ const noteLocalBtwRunId = (runId) => {
4068
+ if (!runId) return;
4069
+ localBtwRunIds.add(runId);
4070
+ if (localBtwRunIds.size > 200) {
4071
+ const [first] = localBtwRunIds;
4072
+ if (first) localBtwRunIds.delete(first);
4073
+ }
4074
+ };
4075
+ const forgetLocalBtwRunId = (runId) => {
4076
+ localBtwRunIds.delete(runId);
4077
+ };
4078
+ const isLocalBtwRunId = (runId) => localBtwRunIds.has(runId);
4079
+ const clearLocalBtwRunIds = () => {
4080
+ localBtwRunIds.clear();
4081
+ };
4082
+ const client = opts.local ? new EmbeddedTuiBackend() : await GatewayChatClient.connect({
4083
+ url: opts.url,
4084
+ token: opts.token,
4085
+ password: opts.password
4086
+ });
4087
+ const previousConsoleSubsystemFilter = isLocalMode ? loggingState.consoleSubsystemFilter ? [...loggingState.consoleSubsystemFilter] : null : null;
4088
+ if (isLocalMode) setConsoleSubsystemFilter(["__genesis_tui_quiet__"]);
4089
+ const tui = new TUI(new ProcessTerminal());
4090
+ const dedupeBackspace = createBackspaceDeduper();
4091
+ tui.addInputListener((data) => {
4092
+ const next = dedupeBackspace(data);
4093
+ if (next.length === 0) return { consume: true };
4094
+ return { data: next };
4095
+ });
4096
+ const header = new Text("", 1, 0);
4097
+ const statusContainer = new Container();
4098
+ const footer = new Text("", 1, 0);
4099
+ const chatLog = new ChatLog();
4100
+ const editor = new CustomEditor(tui, editorTheme);
4101
+ const root = new Container();
4102
+ root.addChild(header);
4103
+ root.addChild(chatLog);
4104
+ root.addChild(statusContainer);
4105
+ root.addChild(footer);
4106
+ root.addChild(editor);
4107
+ const updateAutocompleteProvider = () => {
4108
+ editor.setAutocompleteProvider(new CombinedAutocompleteProvider(getSlashCommands({
4109
+ cfg: config,
4110
+ local: isLocalMode,
4111
+ provider: sessionInfo.modelProvider,
4112
+ model: sessionInfo.model
4113
+ }), process.cwd()));
4114
+ };
4115
+ tui.addChild(root);
4116
+ tui.setFocus(editor);
4117
+ const formatSessionKey = (key) => {
4118
+ if (key === "global" || key === "unknown") return key;
4119
+ return parseAgentSessionKey(key)?.rest ?? key;
4120
+ };
4121
+ const formatAgentLabel = (id) => {
4122
+ const name = agentNames.get(id);
4123
+ return name ? `${id} (${name})` : id;
4124
+ };
4125
+ const resolveSessionKey = (raw) => {
4126
+ return resolveTuiSessionKey({
4127
+ raw,
4128
+ sessionScope,
4129
+ currentAgentId,
4130
+ sessionMainKey
4131
+ });
4132
+ };
4133
+ currentSessionKey = resolveSessionKey(initialSessionInput);
4134
+ const updateHeader = () => {
4135
+ const sessionLabel = formatSessionKey(currentSessionKey);
4136
+ const agentLabel = formatAgentLabel(currentAgentId);
4137
+ header.setText(theme.header(`genesis tui - ${client.connection.url} - agent ${agentLabel} - session ${sessionLabel}`));
4138
+ };
4139
+ const busyStates = new Set([
4140
+ "sending",
4141
+ "waiting",
4142
+ "streaming",
4143
+ "running"
4144
+ ]);
4145
+ let statusText = null;
4146
+ let statusLoader = null;
4147
+ const formatElapsed = (startMs) => {
4148
+ const totalSeconds = Math.max(0, Math.floor((Date.now() - startMs) / 1e3));
4149
+ if (totalSeconds < 60) return `${totalSeconds}s`;
4150
+ return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`;
4151
+ };
4152
+ const ensureStatusText = () => {
4153
+ if (statusText) return;
4154
+ statusContainer.clear();
4155
+ statusLoader?.stop();
4156
+ statusLoader = null;
4157
+ statusText = new Text("", 1, 0);
4158
+ statusContainer.addChild(statusText);
4159
+ };
4160
+ const ensureStatusLoader = () => {
4161
+ if (statusLoader) return;
4162
+ statusContainer.clear();
4163
+ statusText = null;
4164
+ statusLoader = new Loader(tui, (spinner) => theme.accent(spinner), (text) => theme.bold(theme.accentSoft(text)), "");
4165
+ statusContainer.addChild(statusLoader);
4166
+ };
4167
+ let waitingTick = 0;
4168
+ let waitingTimer = null;
4169
+ let waitingPhrase = null;
4170
+ const updateBusyStatusMessage = () => {
4171
+ if (!statusLoader || !statusStartedAt) return;
4172
+ const elapsed = formatElapsed(statusStartedAt);
4173
+ if (activityStatus === "waiting") {
4174
+ waitingTick++;
4175
+ statusLoader.setMessage(buildWaitingStatusMessage({
4176
+ theme,
4177
+ tick: waitingTick,
4178
+ elapsed,
4179
+ connectionStatus,
4180
+ phrases: waitingPhrase ? [waitingPhrase] : void 0
4181
+ }));
4182
+ return;
4183
+ }
4184
+ statusLoader.setMessage(`${activityStatus} • ${elapsed} | ${connectionStatus}`);
4185
+ };
4186
+ const startStatusTimer = () => {
4187
+ if (statusTimer) return;
4188
+ statusTimer = setInterval(() => {
4189
+ if (!busyStates.has(activityStatus)) return;
4190
+ updateBusyStatusMessage();
4191
+ }, 1e3);
4192
+ };
4193
+ const stopStatusTimer = () => {
4194
+ if (!statusTimer) return;
4195
+ clearInterval(statusTimer);
4196
+ statusTimer = null;
4197
+ };
4198
+ const startWaitingTimer = () => {
4199
+ if (waitingTimer) return;
4200
+ if (!waitingPhrase) waitingPhrase = defaultWaitingPhrases[Math.floor(Math.random() * defaultWaitingPhrases.length)] ?? defaultWaitingPhrases[0] ?? "waiting";
4201
+ waitingTick = 0;
4202
+ waitingTimer = setInterval(() => {
4203
+ if (activityStatus !== "waiting") return;
4204
+ updateBusyStatusMessage();
4205
+ }, 120);
4206
+ };
4207
+ const stopWaitingTimer = () => {
4208
+ if (!waitingTimer) return;
4209
+ clearInterval(waitingTimer);
4210
+ waitingTimer = null;
4211
+ waitingPhrase = null;
4212
+ };
4213
+ const renderStatus = () => {
4214
+ if (busyStates.has(activityStatus)) {
4215
+ if (!statusStartedAt || lastActivityStatus !== activityStatus) statusStartedAt = Date.now();
4216
+ ensureStatusLoader();
4217
+ if (activityStatus === "waiting") {
4218
+ stopStatusTimer();
4219
+ startWaitingTimer();
4220
+ } else {
4221
+ stopWaitingTimer();
4222
+ startStatusTimer();
4223
+ }
4224
+ updateBusyStatusMessage();
4225
+ } else {
4226
+ statusStartedAt = null;
4227
+ stopStatusTimer();
4228
+ stopWaitingTimer();
4229
+ statusLoader?.stop();
4230
+ statusLoader = null;
4231
+ ensureStatusText();
4232
+ const text = activityStatus ? `${connectionStatus} | ${activityStatus}` : connectionStatus;
4233
+ statusText?.setText(theme.dim(text));
4234
+ }
4235
+ lastActivityStatus = activityStatus;
4236
+ };
4237
+ const setConnectionStatus = (text, ttlMs) => {
4238
+ connectionStatus = text;
4239
+ renderStatus();
4240
+ if (statusTimeout) clearTimeout(statusTimeout);
4241
+ if (ttlMs && ttlMs > 0) statusTimeout = setTimeout(() => {
4242
+ connectionStatus = isConnected ? isLocalMode ? "local ready" : "connected" : isLocalMode ? "local stopped" : "disconnected";
4243
+ renderStatus();
4244
+ }, ttlMs);
4245
+ };
4246
+ const setActivityStatus = (text) => {
4247
+ activityStatus = text;
4248
+ renderStatus();
4249
+ };
4250
+ const withTuiSuspended = async (work) => {
4251
+ await drainAndStopTuiSafely(tui);
4252
+ if (isLocalMode) setConsoleSubsystemFilter(previousConsoleSubsystemFilter);
4253
+ try {
4254
+ return await work();
4255
+ } finally {
4256
+ if (isLocalMode) setConsoleSubsystemFilter(["__genesis_tui_quiet__"]);
4257
+ tui.start();
4258
+ tui.setFocus(editor);
4259
+ updateHeader();
4260
+ updateFooter();
4261
+ tui.requestRender(true);
4262
+ }
4263
+ };
4264
+ const runAuthFlow = isLocalMode ? async (params) => await withTuiSuspended(async () => await new Promise((resolve, reject) => {
4265
+ const provider = params.provider?.trim() || void 0;
4266
+ const codexBin = provider === OPENAI_CODEX_PROVIDER || !provider && sessionInfo.modelProvider === OPENAI_CODEX_PROVIDER ? resolveCodexCliBin() : null;
4267
+ let command;
4268
+ let args;
4269
+ if (codexBin) {
4270
+ command = codexBin;
4271
+ args = ["login"];
4272
+ } else {
4273
+ ({command, args} = resolveLocalAuthCliInvocation());
4274
+ if (provider) args.push("--provider", provider);
4275
+ }
4276
+ const child = spawn(command, args, {
4277
+ cwd: resolveLocalAuthSpawnCwd({
4278
+ args,
4279
+ defaultCwd: process.cwd()
4280
+ }),
4281
+ env: process.env,
4282
+ stdio: "inherit",
4283
+ ...resolveLocalAuthSpawnOptions({ command })
4284
+ });
4285
+ child.once("error", reject);
4286
+ child.once("exit", (exitCode, signal) => {
4287
+ resolve({
4288
+ exitCode,
4289
+ signal
4290
+ });
4291
+ });
4292
+ })) : void 0;
4293
+ const updateFooter = () => {
4294
+ const sessionKeyLabel = formatSessionKey(currentSessionKey);
4295
+ const sessionLabel = sessionInfo.displayName ? `${sessionKeyLabel} (${sessionInfo.displayName})` : sessionKeyLabel;
4296
+ const agentLabel = formatAgentLabel(currentAgentId);
4297
+ const modelLabel = sessionInfo.model ? sessionInfo.modelProvider ? `${sessionInfo.modelProvider}/${sessionInfo.model}` : sessionInfo.model : "unknown";
4298
+ const tokens = formatTokens(sessionInfo.totalTokens ?? null, sessionInfo.contextTokens ?? null);
4299
+ const think = sessionInfo.thinkingLevel ?? "off";
4300
+ const fast = sessionInfo.fastMode === true;
4301
+ const verbose = sessionInfo.verboseLevel ?? "off";
4302
+ const reasoning = sessionInfo.reasoningLevel ?? "off";
4303
+ const reasoningLabel = reasoning === "on" ? "reasoning" : reasoning === "stream" ? "reasoning:stream" : null;
4304
+ const footerParts = [
4305
+ `agent ${agentLabel}`,
4306
+ `session ${sessionLabel}`,
4307
+ modelLabel,
4308
+ think !== "off" ? `think ${think}` : null,
4309
+ fast ? "fast" : null,
4310
+ verbose !== "off" ? `verbose ${verbose}` : null,
4311
+ reasoningLabel,
4312
+ tokens
4313
+ ].filter(Boolean);
4314
+ footer.setText(theme.dim(footerParts.join(" | ")));
4315
+ };
4316
+ const { openOverlay, closeOverlay } = createOverlayHandlers(tui, editor);
4317
+ const btw = {
4318
+ showResult: (params) => {
4319
+ chatLog.showBtw(params);
4320
+ },
4321
+ clear: () => {
4322
+ chatLog.dismissBtw();
4323
+ }
4324
+ };
4325
+ const { refreshAgents, refreshSessionInfo, applySessionInfoFromPatch, loadHistory, setSession, abortActive } = createSessionActions({
4326
+ client,
4327
+ chatLog,
4328
+ btw,
4329
+ tui,
4330
+ opts,
4331
+ state,
4332
+ agentNames,
4333
+ initialSessionInput,
4334
+ initialSessionAgentId: (() => {
4335
+ if (!initialSessionInput) return null;
4336
+ const parsed = parseAgentSessionKey(initialSessionInput);
4337
+ return parsed ? normalizeAgentId(parsed.agentId) : null;
4338
+ })(),
4339
+ resolveSessionKey,
4340
+ updateHeader,
4341
+ updateFooter,
4342
+ updateAutocompleteProvider,
4343
+ setActivityStatus,
4344
+ clearLocalRunIds
4345
+ });
4346
+ const { handleChatEvent, handleAgentEvent, handleBtwEvent } = createEventHandlers({
4347
+ chatLog,
4348
+ btw,
4349
+ tui,
4350
+ state,
4351
+ localMode: isLocalMode,
4352
+ setActivityStatus,
4353
+ refreshSessionInfo,
4354
+ loadHistory,
4355
+ noteLocalRunId,
4356
+ isLocalRunId,
4357
+ forgetLocalRunId,
4358
+ clearLocalRunIds,
4359
+ isLocalBtwRunId,
4360
+ forgetLocalBtwRunId,
4361
+ clearLocalBtwRunIds
4362
+ });
4363
+ const requestExit = () => {
4364
+ if (exitRequested) return;
4365
+ exitRequested = true;
4366
+ client.stop();
4367
+ drainAndStopTuiSafely(tui).then(() => {
4368
+ process.exit(0);
4369
+ });
4370
+ };
4371
+ const { handleCommand, sendMessage, openModelSelector, openAgentSelector, openSessionSelector } = createCommandHandlers({
4372
+ client,
4373
+ chatLog,
4374
+ tui,
4375
+ opts,
4376
+ state,
4377
+ deliverDefault,
4378
+ openOverlay,
4379
+ closeOverlay,
4380
+ refreshSessionInfo,
4381
+ applySessionInfoFromPatch,
4382
+ loadHistory,
4383
+ setSession,
4384
+ refreshAgents,
4385
+ abortActive,
4386
+ setActivityStatus,
4387
+ formatSessionKey,
4388
+ noteLocalRunId,
4389
+ noteLocalBtwRunId,
4390
+ forgetLocalRunId,
4391
+ forgetLocalBtwRunId,
4392
+ runAuthFlow,
4393
+ requestExit
4394
+ });
4395
+ const { runLocalShellLine } = createLocalShellRunner({
4396
+ chatLog,
4397
+ tui,
4398
+ openOverlay,
4399
+ closeOverlay
4400
+ });
4401
+ updateAutocompleteProvider();
4402
+ editor.onSubmit = createSubmitBurstCoalescer({
4403
+ submit: createEditorSubmitHandler({
4404
+ editor,
4405
+ handleCommand,
4406
+ sendMessage,
4407
+ handleBangLine: runLocalShellLine
4408
+ }),
4409
+ enabled: shouldEnableWindowsGitBashPasteFallback()
4410
+ });
4411
+ editor.onEscape = () => {
4412
+ if (chatLog.hasVisibleBtw()) {
4413
+ chatLog.dismissBtw();
4414
+ tui.requestRender();
4415
+ return;
4416
+ }
4417
+ abortActive();
4418
+ };
4419
+ const handleCtrlC = () => {
4420
+ const now = Date.now();
4421
+ const decision = resolveCtrlCAction({
4422
+ hasInput: editor.getText().trim().length > 0,
4423
+ now,
4424
+ lastCtrlCAt
4425
+ });
4426
+ lastCtrlCAt = decision.nextLastCtrlCAt;
4427
+ if (decision.action === "clear") {
4428
+ editor.setText("");
4429
+ setActivityStatus("cleared input; press ctrl+c again to exit");
4430
+ tui.requestRender();
4431
+ return;
4432
+ }
4433
+ if (decision.action === "exit") {
4434
+ requestExit();
4435
+ return;
4436
+ }
4437
+ setActivityStatus("press ctrl+c again to exit");
4438
+ tui.requestRender();
4439
+ };
4440
+ editor.onCtrlC = () => {
4441
+ handleCtrlC();
4442
+ };
4443
+ editor.onCtrlD = () => {
4444
+ requestExit();
4445
+ };
4446
+ editor.onCtrlO = () => {
4447
+ toolsExpanded = !toolsExpanded;
4448
+ chatLog.setToolsExpanded(toolsExpanded);
4449
+ setActivityStatus(toolsExpanded ? "tools expanded" : "tools collapsed");
4450
+ tui.requestRender();
4451
+ };
4452
+ editor.onCtrlL = () => {
4453
+ openModelSelector();
4454
+ };
4455
+ editor.onCtrlG = () => {
4456
+ openAgentSelector();
4457
+ };
4458
+ editor.onCtrlP = () => {
4459
+ openSessionSelector();
4460
+ };
4461
+ editor.onCtrlT = () => {
4462
+ showThinking = !showThinking;
4463
+ loadHistory();
4464
+ };
4465
+ tui.addInputListener((data) => {
4466
+ if (!chatLog.hasVisibleBtw()) return;
4467
+ if (editor.getText().length > 0) return;
4468
+ if (matchesKey(data, "enter")) {
4469
+ chatLog.dismissBtw();
4470
+ tui.requestRender();
4471
+ return { consume: true };
4472
+ }
4473
+ });
4474
+ client.onEvent = (evt) => {
4475
+ if (evt.event === "chat") handleChatEvent(evt.payload);
4476
+ if (evt.event === "chat.side_result") handleBtwEvent(evt.payload);
4477
+ if (evt.event === "agent") handleAgentEvent(evt.payload);
4478
+ };
4479
+ client.onConnected = () => {
4480
+ isConnected = true;
4481
+ pairingHintShown = false;
4482
+ const reconnected = wasDisconnected;
4483
+ wasDisconnected = false;
4484
+ setConnectionStatus(isLocalMode ? "local ready" : "connected");
4485
+ (async () => {
4486
+ await refreshAgents();
4487
+ updateHeader();
4488
+ await loadHistory();
4489
+ setConnectionStatus(isLocalMode ? "local ready" : reconnected ? "gateway reconnected" : "gateway connected", 4e3);
4490
+ tui.requestRender();
4491
+ if (!autoMessageSent && autoMessage) {
4492
+ autoMessageSent = true;
4493
+ await sendMessage(autoMessage);
4494
+ }
4495
+ updateFooter();
4496
+ tui.requestRender();
4497
+ })();
4498
+ };
4499
+ client.onDisconnected = (reason) => {
4500
+ isConnected = false;
4501
+ wasDisconnected = true;
4502
+ historyLoaded = false;
4503
+ const disconnectState = isLocalMode ? {
4504
+ connectionStatus: `local runtime stopped${reason ? `: ${reason}` : ""}`,
4505
+ activityStatus: "idle",
4506
+ pairingHint: void 0
4507
+ } : resolveGatewayDisconnectState(reason);
4508
+ setConnectionStatus(disconnectState.connectionStatus, 5e3);
4509
+ setActivityStatus(disconnectState.activityStatus);
4510
+ if (disconnectState.pairingHint && !pairingHintShown) {
4511
+ pairingHintShown = true;
4512
+ chatLog.addSystem(disconnectState.pairingHint);
4513
+ }
4514
+ updateFooter();
4515
+ tui.requestRender();
4516
+ };
4517
+ client.onGap = (info) => {
4518
+ setConnectionStatus(`event gap: expected ${info.expected}, got ${info.received}`, 5e3);
4519
+ tui.requestRender();
4520
+ };
4521
+ updateHeader();
4522
+ setConnectionStatus(isLocalMode ? "starting local runtime" : "connecting");
4523
+ updateFooter();
4524
+ const sigintHandler = () => {
4525
+ handleCtrlC();
4526
+ };
4527
+ const sigtermHandler = () => {
4528
+ requestExit();
4529
+ };
4530
+ process.on("SIGINT", sigintHandler);
4531
+ process.on("SIGTERM", sigtermHandler);
4532
+ tui.start();
4533
+ client.start();
4534
+ await new Promise((resolve) => {
4535
+ const finish = () => {
4536
+ if (isLocalMode) setConsoleSubsystemFilter(previousConsoleSubsystemFilter);
4537
+ process.removeListener("SIGINT", sigintHandler);
4538
+ process.removeListener("SIGTERM", sigtermHandler);
4539
+ resolve();
4540
+ };
4541
+ process.once("exit", finish);
4542
+ });
4543
+ }
4544
+ //#endregion
4545
+ //#region src/cli/tui-cli.ts
4546
+ function registerTuiCli(program) {
4547
+ 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) => {
4548
+ try {
4549
+ const invokedSubcommand = cmd.parent?.args[0];
4550
+ const invokedAsLocalAlias = invokedSubcommand === "terminal" || invokedSubcommand === "chat";
4551
+ const isLocal = Boolean(opts.local) || invokedAsLocalAlias;
4552
+ if (isLocal && (opts.url || opts.token || opts.password)) throw new Error("--local cannot be combined with --url, --token, or --password");
4553
+ const timeoutMs = parseTimeoutMs(opts.timeoutMs);
4554
+ if (opts.timeoutMs !== void 0 && timeoutMs === void 0) defaultRuntime.error(`warning: invalid --timeout-ms "${String(opts.timeoutMs)}"; ignoring`);
4555
+ const historyLimit = Number.parseInt(String(opts.historyLimit ?? "200"), 10);
4556
+ await runTui({
4557
+ local: isLocal,
4558
+ url: opts.url,
4559
+ token: opts.token,
4560
+ password: opts.password,
4561
+ session: opts.session,
4562
+ deliver: Boolean(opts.deliver),
4563
+ thinking: opts.thinking,
4564
+ message: opts.message,
4565
+ timeoutMs,
4566
+ historyLimit: Number.isNaN(historyLimit) ? void 0 : historyLimit
4567
+ });
4568
+ } catch (err) {
4569
+ defaultRuntime.error(String(err));
4570
+ defaultRuntime.exit(1);
4571
+ }
4572
+ });
4573
+ }
4574
+ //#endregion
4575
+ export { registerTuiCli };