@pixelzx/genesis 2026.5.3-5 → 2026.5.5

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 (996) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/.buildstamp +1 -1
  3. package/dist/abort-t5XiT6Yl.js +201 -0
  4. package/dist/abort.runtime-C_xk0DkL.js +2 -0
  5. package/dist/abort.runtime.js +1 -1
  6. package/dist/accounts-B7yDKwxi.js +104 -0
  7. package/dist/accounts-CS7VL356.js +107 -0
  8. package/dist/accounts-XvHcAtMf.js +2 -0
  9. package/dist/acp-cli-B5H0nvID.js +2193 -0
  10. package/dist/acp-spawn-BRTMqPlq.js +2 -0
  11. package/dist/acp-spawn-Dsw3dzWY.js +1093 -0
  12. package/dist/acp-stateful-target-driver-BYhkJnyh.js +89 -0
  13. package/dist/action-agents-Ca9kTFvv.js +67 -0
  14. package/dist/action-focus-D4pT0hra.js +132 -0
  15. package/dist/action-help-DMzMxFEQ.js +7 -0
  16. package/dist/action-info-Dzn_fn6G.js +101 -0
  17. package/dist/action-kill-2AQuhnLy.js +33 -0
  18. package/dist/action-list-DI1M2pKU.js +21 -0
  19. package/dist/action-log-BVKGgOki.js +30 -0
  20. package/dist/action-send-CZ2wciMW.js +39 -0
  21. package/dist/action-spawn-BdclQLrK.js +47 -0
  22. package/dist/action-unfocus-DfQuRf8d.js +29 -0
  23. package/dist/actions.runtime-B2-oz_B6.js +5 -0
  24. package/dist/actions.runtime-BoUxrcw3.js +18 -0
  25. package/dist/actions.runtime.js +1 -1
  26. package/dist/agent-CnQ3yCIw.js +2 -0
  27. package/dist/agent-command-C4H_9c2N.js +874 -0
  28. package/dist/agent-harness-runtime-D2oXzgyL.js +144 -0
  29. package/dist/agent-runner-utils-CWgPcOYn.js +239 -0
  30. package/dist/agent-runner.runtime-DvK-HQhq.js +3455 -0
  31. package/dist/agent-runner.runtime.js +1 -1
  32. package/dist/agent-runtime-BDslXtCf.js +18 -0
  33. package/dist/agents-4T7YaeKy.js +953 -0
  34. package/dist/agents-C_Gty_RK.js +5 -0
  35. package/dist/aliases-BkVpehd-.js +96 -0
  36. package/dist/aliases-DWkJWJ5A.js +2 -0
  37. package/dist/api-CgW6fcU2.js +3 -0
  38. package/dist/api-DYPaGKUj.js +5 -0
  39. package/dist/api-DdoV90Cn.js +139 -0
  40. package/dist/approval-gateway-resolver-Ba_2kb3B.js +29 -0
  41. package/dist/approval-gateway-runtime-7VMivk0A.js +2 -0
  42. package/dist/approval-handler-runtime-DUDpOwG7.js +439 -0
  43. package/dist/approval-native-runtime-KkmX9gwQ.js +729 -0
  44. package/dist/attempt-execution.runtime-CQkeVpDx.js +509 -0
  45. package/dist/attempt-execution.runtime.js +1 -1
  46. package/dist/attempt.prompt-helpers-MoT6VaD0.js +221 -0
  47. package/dist/attempt.tool-run-context-B53GhX-d.js +933 -0
  48. package/dist/audit-CvHcVVb-.js +939 -0
  49. package/dist/audit.runtime-C7n442Rc.js +7 -0
  50. package/dist/audit.runtime.js +1 -1
  51. package/dist/auth-CAnSldtM.js +2 -0
  52. package/dist/auth-Czf_o5iE.js +383 -0
  53. package/dist/auth-order-Cu9Vj7lA.js +96 -0
  54. package/dist/auth-order-q1IFw7L3.js +2 -0
  55. package/dist/bash-tools-BS4TrA4X.js +2824 -0
  56. package/dist/bash-tools-DbHYuk8O.js +3 -0
  57. package/dist/binding-routing-CnNQE65Q.js +85 -0
  58. package/dist/binding-targets-DW0ScIRI.js +121 -0
  59. package/dist/bridge-server-BGS08n2f.js +113 -0
  60. package/dist/browser-control-auth-DMlQOsyN.js +2 -0
  61. package/dist/browser-node-runtime-CF32scUO.js +12 -0
  62. package/dist/browser-profiles-CmER65eh.js +2 -0
  63. package/dist/browser-runtime-D73M9fg3.js +387 -0
  64. package/dist/browser-setup-tools-Cr0UI1rf.js +13 -0
  65. package/dist/build-BL7WirDF.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-Ckws4Nlw.js +3 -0
  70. package/dist/call-DkGNVvLy.js +331 -0
  71. package/dist/call.runtime-DfLBtAIr.js +2 -0
  72. package/dist/call.runtime.js +1 -1
  73. package/dist/capability-cli-tSqSJf2o.js +1401 -0
  74. package/dist/catchup-Dp2L1RcY.js +300 -0
  75. package/dist/channel-BIFp1GJd.js +1320 -0
  76. package/dist/channel-BZMzoXhw.js +840 -0
  77. package/dist/channel-BtPZ0i4g.js +297 -0
  78. package/dist/channel-DDd7xwLG.js +226 -0
  79. package/dist/channel-DLezQPqR.js +350 -0
  80. package/dist/channel-DcYHXn_7.js +1100 -0
  81. package/dist/channel-DzKtLfJj.js +1802 -0
  82. package/dist/channel-LlY18tI5.js +595 -0
  83. package/dist/channel-NjZviHcJ.js +1174 -0
  84. package/dist/channel-core-Cg1mFpva.js +5 -0
  85. package/dist/channel-inbound-CZpi-vp5.js +31 -0
  86. package/dist/channel-pDXIWFS4.js +453 -0
  87. package/dist/channel-plugin-runtime-DHl81Ror.js +771 -0
  88. package/dist/channel-runtime-CtYrrwow.js +425 -0
  89. package/dist/channel-wMkGGyIY.js +491 -0
  90. package/dist/channel.runtime-B1n0hvUI.js +430 -0
  91. package/dist/channel.runtime-B9iR26l_.js +576 -0
  92. package/dist/channel.runtime-C8eBQk67.js +4 -0
  93. package/dist/channel.runtime-Db8g8JCg.js +89 -0
  94. package/dist/channel.runtime-DfRfisV2.js +34702 -0
  95. package/dist/channel.runtime-gPdBMu3V.js +109 -0
  96. package/dist/channel.runtime-rG9pJ5NO.js +2364 -0
  97. package/dist/channel.runtime.js +1 -1
  98. package/dist/channel.setup-CWblUOhD.js +10 -0
  99. package/dist/channels-B4dYRKsI.js +733 -0
  100. package/dist/channels-cli-GMAOUYU3.js +268 -0
  101. package/dist/chat-D2XaZNiP.js +2758 -0
  102. package/dist/clawbot-cli-CSmdcIMT.js +9 -0
  103. package/dist/cli/daemon-cli.js +3 -3
  104. package/dist/cli-2u5IZTMS.js +219 -0
  105. package/dist/cli-Bk8uXnyc.js +72 -0
  106. package/dist/cli-DBfw9jCz.js +2 -0
  107. package/dist/cli-runner-BEqvX1ky.js +286 -0
  108. package/dist/cli-runner.runtime-BIUcUGDa.js +4 -0
  109. package/dist/cli-runner.runtime-D2u3Yw0W.js +3 -0
  110. package/dist/cli-runner.runtime.js +1 -1
  111. package/dist/cli-startup-metadata.json +2 -2
  112. package/dist/cli-waH8839u.js +2 -0
  113. package/dist/cli.runtime-mKvJpLwI.js +1261 -0
  114. package/dist/cli.runtime.js +1 -1
  115. package/dist/client-CKizOsGp.js +138 -0
  116. package/dist/client-CrPccv7a.js +713 -0
  117. package/dist/command-auth-DPkjKHdv.js +76 -0
  118. package/dist/command-config-resolution-BTjtnAp2.js +2 -0
  119. package/dist/command-config-resolution-Be3KZA_l.js +23 -0
  120. package/dist/command-config-resolution.runtime-DXgL8cm7.js +2 -0
  121. package/dist/command-config-resolution.runtime.js +1 -1
  122. package/dist/command-registry-BL1Z4Cen.js +4 -0
  123. package/dist/command-registry-BMePAw9w.js +9 -0
  124. package/dist/command-registry-core-CAay55-n.js +104 -0
  125. package/dist/command-secret-gateway-jj1Qmk9L.js +528 -0
  126. package/dist/command-status.runtime-BVcCm9_0.js +87 -0
  127. package/dist/command-status.runtime.js +1 -1
  128. package/dist/commands-acp-COdUW69f.js +77 -0
  129. package/dist/commands-compact.runtime-C0Fedews.js +10 -0
  130. package/dist/commands-compact.runtime.js +1 -1
  131. package/dist/commands-handlers.runtime-BXVM3PWG.js +4597 -0
  132. package/dist/commands-handlers.runtime.js +1 -1
  133. package/dist/commands-status-DaApOLoQ.js +16 -0
  134. package/dist/commands-status.runtime-CxSjrKne.js +3 -0
  135. package/dist/commands-status.runtime.js +1 -1
  136. package/dist/commands-subagents-control.runtime-BEfW44br.js +2 -0
  137. package/dist/commands-subagents-control.runtime-DB3AROHI.js +3 -0
  138. package/dist/commands-subagents-control.runtime.js +1 -1
  139. package/dist/commands-system-prompt-CCrUy7xq.js +158 -0
  140. package/dist/commands-system-prompt-CN56TtaC.js +2 -0
  141. package/dist/commands.runtime-Bee6dM3V.js +166 -0
  142. package/dist/commands.runtime.js +1 -1
  143. package/dist/compact-7YtEe1kG.js +1118 -0
  144. package/dist/compact.runtime-4gW_cs7D.js +12 -0
  145. package/dist/compact.runtime.js +1 -1
  146. package/dist/completion-cli-COv-r8_h.js +313 -0
  147. package/dist/config-DSsLlg8J.js +251 -0
  148. package/dist/config-cli-C9oGe9gl.js +1078 -0
  149. package/dist/configure-Bfy9tVmS.js +2 -0
  150. package/dist/configure-DpIFRaAD.js +1245 -0
  151. package/dist/connect-options-CPixzqP_.js +699 -0
  152. package/dist/control-auth-L7U2ivRJ.js +125 -0
  153. package/dist/control-service-CbUz8qU5.js +156 -0
  154. package/dist/conversation-id-BroDIGeT.js +38 -0
  155. package/dist/conversation-id-CuVi0tWe.js +235 -0
  156. package/dist/conversation-runtime-weaahZQN.js +31 -0
  157. package/dist/core-PXv1nsc-.js +275 -0
  158. package/dist/cron-cli-DZNSQBuA.js +713 -0
  159. package/dist/daemon-cli-C_9CNoZA.js +12 -0
  160. package/dist/delegate-B8wh-jjf.js +64 -0
  161. package/dist/detached-task-runtime-BTq-jIGw.js +73 -0
  162. package/dist/devices-cli-C_amY-AS.js +496 -0
  163. package/dist/diagnostics-Bw-fd0ug.js +154 -0
  164. package/dist/direct-dm-Dvqjch3O.js +64 -0
  165. package/dist/dispatch-DHPQS49Q.js +1131 -0
  166. package/dist/dispatch-acp-manager.runtime-y-oykPUz.js +3 -0
  167. package/dist/dispatch-acp-manager.runtime.js +1 -1
  168. package/dist/dispatch-acp-taSuJD5W.js +981 -0
  169. package/dist/dispatch-acp.runtime-DgyaFFNX.js +19 -0
  170. package/dist/dispatch-acp.runtime.js +1 -1
  171. package/dist/doctor-device-pairing-rxwogzYF.js +307 -0
  172. package/dist/doctor-gateway-daemon-flow-Dm4wxnTt.js +250 -0
  173. package/dist/doctor-gateway-health-wJVW5xUW.js +60 -0
  174. package/dist/doctor-health-DaodspKU.js +59 -0
  175. package/dist/doctor-health-contributions-CBVyN6ju.js +486 -0
  176. package/dist/doctor-prompter-vO6LPeXZ.js +56 -0
  177. package/dist/doctor-workspace-status-BnXA04-6.js +75 -0
  178. package/dist/dreaming-1RLie1iF.js +1574 -0
  179. package/dist/dreaming-narrative-BRtTdpbt.js +595 -0
  180. package/dist/embedded-gateway-stub.runtime-GMix51Tf.js +9 -0
  181. package/dist/embedded-gateway-stub.runtime.js +1 -1
  182. package/dist/entry.js +2 -2
  183. package/dist/exec-approvals-cli-R6jgupQH.js +498 -0
  184. package/dist/extensionAPI.js +1 -1
  185. package/dist/extensions/active-memory/index.js +1 -1
  186. package/dist/extensions/bluebubbles/api.js +3 -3
  187. package/dist/extensions/bluebubbles/channel-plugin-api.js +1 -1
  188. package/dist/extensions/browser/browser-bridge.js +1 -1
  189. package/dist/extensions/browser/browser-config.js +4 -4
  190. package/dist/extensions/browser/browser-control-auth.js +2 -2
  191. package/dist/extensions/browser/browser-doctor.js +2 -2
  192. package/dist/extensions/browser/browser-maintenance.js +2 -2
  193. package/dist/extensions/browser/browser-profiles.js +2 -2
  194. package/dist/extensions/browser/browser-runtime-api.js +10 -10
  195. package/dist/extensions/browser/index.js +1 -1
  196. package/dist/extensions/browser/plugin-registration.js +1 -1
  197. package/dist/extensions/browser/register.runtime.js +3 -3
  198. package/dist/extensions/browser/runtime-api.js +11 -11
  199. package/dist/extensions/browser/test-support.js +1 -1
  200. package/dist/extensions/device-pair/api.js +1 -1
  201. package/dist/extensions/device-pair/index.js +3 -3
  202. package/dist/extensions/device-pair/notify.js +1 -1
  203. package/dist/extensions/device-pair/pair-command-approve.js +1 -1
  204. package/dist/extensions/google-meet/index.js +2 -2
  205. package/dist/extensions/imessage/api.js +3 -3
  206. package/dist/extensions/imessage/channel-plugin-api.js +1 -1
  207. package/dist/extensions/imessage/runtime-api.js +3 -3
  208. package/dist/extensions/irc/api.js +2 -2
  209. package/dist/extensions/irc/channel-plugin-api.js +1 -1
  210. package/dist/extensions/line/api.js +2 -2
  211. package/dist/extensions/line/channel-plugin-api.js +1 -1
  212. package/dist/extensions/line/contract-api.js +1 -1
  213. package/dist/extensions/line/runtime-api.js +4 -4
  214. package/dist/extensions/line/setup-api.js +1 -1
  215. package/dist/extensions/llm-task/index.js +2 -2
  216. package/dist/extensions/lobster/index.js +3 -3
  217. package/dist/extensions/lobster/runtime-api.js +1 -1
  218. package/dist/extensions/mattermost/api.js +1 -1
  219. package/dist/extensions/mattermost/channel-plugin-api.js +1 -1
  220. package/dist/extensions/mattermost/channel-plugin-runtime.js +1 -1
  221. package/dist/extensions/mattermost/policy-api.js +1 -1
  222. package/dist/extensions/mattermost/runtime-api.js +4 -4
  223. package/dist/extensions/mattermost/slash-route-api.js +1 -1
  224. package/dist/extensions/memory-core/api.js +1 -1
  225. package/dist/extensions/memory-core/cli-metadata.js +2 -2
  226. package/dist/extensions/memory-core/index.js +3 -3
  227. package/dist/extensions/memory-lancedb/cli-metadata.js +1 -1
  228. package/dist/extensions/msteams/api.js +1 -1
  229. package/dist/extensions/msteams/channel-plugin-api.js +1 -1
  230. package/dist/extensions/msteams/runtime-api.js +3 -3
  231. package/dist/extensions/msteams/test-api.js +1 -1
  232. package/dist/extensions/nextcloud-talk/api.js +1 -1
  233. package/dist/extensions/nextcloud-talk/channel-plugin-api.js +1 -1
  234. package/dist/extensions/nextcloud-talk/runtime-api.js +2 -2
  235. package/dist/extensions/openshell/index.js +2 -2
  236. package/dist/extensions/signal/api.js +6 -6
  237. package/dist/extensions/signal/channel-plugin-api.js +1 -1
  238. package/dist/extensions/signal/reaction-runtime-api.js +1 -1
  239. package/dist/extensions/signal/runtime-api.js +7 -7
  240. package/dist/extensions/skill-workshop/api.js +1 -1
  241. package/dist/extensions/skill-workshop/index.js +1 -1
  242. package/dist/extensions/synology-chat/api.js +1 -1
  243. package/dist/extensions/synology-chat/channel-plugin-api.js +1 -1
  244. package/dist/extensions/tlon/api.js +2 -2
  245. package/dist/extensions/tlon/channel-plugin-api.js +1 -1
  246. package/dist/extensions/tlon/runtime-api.js +1 -1
  247. package/dist/extensions/tlon/test-api.js +1 -1
  248. package/dist/extensions/twitch/api.js +1 -1
  249. package/dist/extensions/twitch/channel-plugin-api.js +1 -1
  250. package/dist/extensions/twitch/setup-plugin-api.js +1 -1
  251. package/dist/extensions/zalo/api.js +3 -3
  252. package/dist/extensions/zalo/channel-plugin-api.js +1 -1
  253. package/dist/extensions/zalo/runtime-api.js +2 -2
  254. package/dist/extensions/zalo/setup-api.js +2 -2
  255. package/dist/extensions/zalouser/api.js +3 -3
  256. package/dist/extensions/zalouser/channel-plugin-api.js +1 -1
  257. package/dist/extensions/zalouser/runtime-api.js +6 -6
  258. package/dist/extensions/zalouser/setup-plugin-api.js +1 -1
  259. package/dist/extensions/zalouser/test-api.js +1 -1
  260. package/dist/fallbacks-Cckv3nng.js +2 -0
  261. package/dist/fallbacks-Y_nNY8_a.js +31 -0
  262. package/dist/fallbacks-shared-DZiG1Gr_.js +111 -0
  263. package/dist/gateway-CDfn0J87.js +115 -0
  264. package/dist/gateway-cli-D197U6l0.js +1325 -0
  265. package/dist/gateway-rpc-Bomz8HKq.js +14 -0
  266. package/dist/gateway-rpc.runtime-597tksmo.js +23 -0
  267. package/dist/gateway-rpc.runtime.js +1 -1
  268. package/dist/gateway-runtime-Bm2_MhFn.js +15 -0
  269. package/dist/gateway-status-Cr4UJKUx.js +584 -0
  270. package/dist/genesis-tools-DCRaVVjY.js +8999 -0
  271. package/dist/genesis-tools.runtime-idgd5fjy.js +2 -0
  272. package/dist/genesis-tools.runtime.js +1 -1
  273. package/dist/get-reply-BF_7bR5f.js +3879 -0
  274. package/dist/get-reply-from-config.runtime-DEq5XM_s.js +2 -0
  275. package/dist/get-reply-from-config.runtime.js +1 -1
  276. package/dist/graph-users-Bhlw-_4i.js +1337 -0
  277. package/dist/health-9ifMvGZN.js +3 -0
  278. package/dist/health-CzOJa6SX.js +469 -0
  279. package/dist/heartbeat-runner-B2Tkbj5e.js +5 -0
  280. package/dist/heartbeat-runner-B63G8dbO.js +1292 -0
  281. package/dist/heartbeat-runner.runtime-QJ_2AMjN.js +4 -0
  282. package/dist/heartbeat-runner.runtime.js +1 -1
  283. package/dist/hooks-cli-ZWI1iJnh.js +433 -0
  284. package/dist/image-fallbacks-BpTfBvbi.js +2 -0
  285. package/dist/image-fallbacks-DpVwnB41.js +31 -0
  286. package/dist/inbound-reply-dispatch-mKybIcNA.js +73 -0
  287. package/dist/index.js +2 -2
  288. package/dist/infra-runtime-CvwvzUfM.js +39 -0
  289. package/dist/init-CWeM0DfJ.js +59 -0
  290. package/dist/library-ClQalZ3x.js +45 -0
  291. package/dist/lifecycle-CgV7Cgt-.js +571 -0
  292. package/dist/lifecycle-DVWaxj-A.js +229 -0
  293. package/dist/lifecycle.runtime-DErLwVJ_.js +2 -0
  294. package/dist/lifecycle.runtime.js +1 -1
  295. package/dist/list-5RIS3LMG.js +2 -0
  296. package/dist/list-BNesYDN2.js +2 -0
  297. package/dist/list-Dk1hCKis.js +1201 -0
  298. package/dist/list-eUjt_6__.js +131 -0
  299. package/dist/list.probe-C51ceJSY.js +419 -0
  300. package/dist/llm-slug-generator-D64IMUoy.js +79 -0
  301. package/dist/llm-slug-generator.js +1 -1
  302. package/dist/load-config-Ccss2uTi.js +35 -0
  303. package/dist/local-dispatch.runtime-u7Ir1N07.js +8 -0
  304. package/dist/local-dispatch.runtime.js +1 -1
  305. package/dist/logs-cli-BYHTboPa.js +265 -0
  306. package/dist/logs-cli.runtime-CQwNptr-.js +2 -0
  307. package/dist/logs-cli.runtime.js +1 -1
  308. package/dist/main-session-restart-recovery-CA9bvC1W.js +206 -0
  309. package/dist/managed-image-attachments-B_gpkI1u.js +635 -0
  310. package/dist/managed-image-attachments-C0Y6nAP2.js +2 -0
  311. package/dist/manager-DZGFArgz.js +2 -0
  312. package/dist/manager-Df8TC4rX.js +2057 -0
  313. package/dist/markdown-to-line-xXLdnzcE.js +790 -0
  314. package/dist/mcp/plugin-tools-serve.js +1 -1
  315. package/dist/mcp-cli-B50W9Pkc.js +725 -0
  316. package/dist/mcp-http-BiUGVpJ4.js +529 -0
  317. package/dist/memory-core-host-runtime-cli-UgLo6ezC.js +9 -0
  318. package/dist/message-C95gttLd.js +232 -0
  319. package/dist/message-action-runner-0KAp6ccG.js +1407 -0
  320. package/dist/message-action-runner-BSUDvECO.js +2 -0
  321. package/dist/message-actions-Be4Ob151.js +143 -0
  322. package/dist/message.gateway.runtime-DMMRMIln.js +2 -0
  323. package/dist/message.gateway.runtime.js +1 -1
  324. package/dist/models-auth-status-DhYxBz7G.js +201 -0
  325. package/dist/models-cli-C2prinXb.js +219 -0
  326. package/dist/monitor-BEI21vNQ.js +1661 -0
  327. package/dist/monitor-BUgTAJvZ.js +1237 -0
  328. package/dist/monitor-BdJRIhi1.js +2 -0
  329. package/dist/monitor-C7wuttQJ.js +1459 -0
  330. package/dist/monitor-DMumiWnt.js +788 -0
  331. package/dist/monitor-IQo2ExmV.js +671 -0
  332. package/dist/monitor-auth-DW0lvfm3.js +207 -0
  333. package/dist/monitor-processing-DTrsRdyz.js +1974 -0
  334. package/dist/monitor.runtime-DwqyCQcb.js +2 -0
  335. package/dist/monitor.runtime.js +1 -1
  336. package/dist/monitor.webhook-D11nrUh9.js +180 -0
  337. package/dist/msteams-DO-PW98M.js +35 -0
  338. package/dist/native-hook-relay-CNZrcPIw.js +519 -0
  339. package/dist/nextcloud-talk-BeYFnATY.js +17 -0
  340. package/dist/node-cli-BFrdTPdH.js +2506 -0
  341. package/dist/nodes-cli-B3Wj_MvP.js +1046 -0
  342. package/dist/nodes-utils-AsgrCa7K.js +84 -0
  343. package/dist/nodes.helpers-CMXxavTs.js +34 -0
  344. package/dist/notify-CNS0kRWM.js +315 -0
  345. package/dist/onboard-D4ehf66t.js +632 -0
  346. package/dist/onboard-helpers-DWxdMyCs.js +6 -0
  347. package/dist/onboard-helpers-o78s0lR1.js +204 -0
  348. package/dist/onboard-remote-Cc1XlRzr.js +193 -0
  349. package/dist/onboard-remote-D8THwo3P.js +2 -0
  350. package/dist/onboard-skills-B2VoCq7v.js +134 -0
  351. package/dist/onboard-skills-DtOgSJZo.js +2 -0
  352. package/dist/openai-http-DKQZWsqY.js +500 -0
  353. package/dist/openresponses-http-C4kol41X.js +1128 -0
  354. package/dist/operator-approvals-client-BoN_VmkB.js +68 -0
  355. package/dist/outbound.runtime-D-L8FN8E.js +2 -0
  356. package/dist/outbound.runtime.js +1 -1
  357. package/dist/pair-command-approve-DMeQ6uD4.js +44 -0
  358. package/dist/persistent-bindings.lifecycle-O-RnoTW4.js +2 -0
  359. package/dist/persistent-bindings.lifecycle-bptWQEFT.js +85 -0
  360. package/dist/pi-embedded-BM79sXqb.js +2905 -0
  361. package/dist/pi-embedded-BUDWcDt8.js +4 -0
  362. package/dist/pi-embedded.runtime-D53bCPOr.js +4 -0
  363. package/dist/pi-embedded.runtime.js +1 -1
  364. package/dist/pi-tool-definition-adapter-DdYQtumi.js +217 -0
  365. package/dist/pi-tools-ihbjTP0K.js +1057 -0
  366. package/dist/pi-tools.before-tool-call-DrEqr96j.js +433 -0
  367. package/dist/pi-tools.before-tool-call-VB9YEPOv.js +2 -0
  368. package/dist/plugin-DwNULpmw.js +12195 -0
  369. package/dist/plugin-enabled-DbO9GyRJ.js +140 -0
  370. package/dist/plugin-registration-Du6hgUkp.js +23 -0
  371. package/dist/plugin-sdk/.boundary-entry-shims.stamp +1 -1
  372. package/dist/plugin-sdk/acp-binding-runtime.js +1 -1
  373. package/dist/plugin-sdk/acp-runtime.js +2 -2
  374. package/dist/plugin-sdk/agent-harness-runtime.js +5 -5
  375. package/dist/plugin-sdk/agent-harness.js +6 -6
  376. package/dist/plugin-sdk/agent-runtime.js +2 -2
  377. package/dist/plugin-sdk/approval-gateway-runtime.js +2 -2
  378. package/dist/plugin-sdk/approval-handler-runtime.js +3 -3
  379. package/dist/plugin-sdk/approval-runtime.js +1 -1
  380. package/dist/plugin-sdk/browser-node-runtime.js +4 -4
  381. package/dist/plugin-sdk/browser-setup-tools.js +3 -3
  382. package/dist/plugin-sdk/browser-support.js +7 -7
  383. package/dist/plugin-sdk/channel-core.js +2 -2
  384. package/dist/plugin-sdk/channel-inbound.js +2 -2
  385. package/dist/plugin-sdk/command-auth.js +1 -1
  386. package/dist/plugin-sdk/command-status-runtime.js +1 -1
  387. package/dist/plugin-sdk/compat.js +1 -1
  388. package/dist/plugin-sdk/conversation-binding-runtime.js +1 -1
  389. package/dist/plugin-sdk/conversation-runtime.js +3 -3
  390. package/dist/plugin-sdk/core.js +2 -2
  391. package/dist/plugin-sdk/direct-dm.js +1 -1
  392. package/dist/plugin-sdk/gateway-runtime.js +3 -3
  393. package/dist/plugin-sdk/inbound-reply-dispatch.js +1 -1
  394. package/dist/plugin-sdk/index.js +1 -1
  395. package/dist/plugin-sdk/infra-runtime.js +2 -2
  396. package/dist/plugin-sdk/irc.js +2 -2
  397. package/dist/plugin-sdk/matrix.js +1 -1
  398. package/dist/plugin-sdk/memory-core-host-runtime-cli.js +2 -2
  399. package/dist/plugin-sdk/memory-core.js +2 -2
  400. package/dist/plugin-sdk/msteams.js +2 -2
  401. package/dist/plugin-sdk/nextcloud-talk.js +2 -2
  402. package/dist/plugin-sdk/nostr.js +1 -1
  403. package/dist/plugin-sdk/reply-dispatch-runtime.js +1 -1
  404. package/dist/plugin-sdk/reply-runtime.js +4 -4
  405. package/dist/plugin-sdk/runtime-secret-resolution.js +1 -1
  406. package/dist/plugin-sdk/runtime.js +2 -2
  407. package/dist/plugin-sdk/session-visibility.js +1 -1
  408. package/dist/plugin-sdk/testing.js +4 -4
  409. package/dist/plugin-sdk/tlon.js +1 -1
  410. package/dist/plugin-sdk/zalo.js +1 -1
  411. package/dist/plugin-sdk/zalouser.js +1 -1
  412. package/dist/plugin-service-DcSnRF5x.js +2890 -0
  413. package/dist/plugins/runtime/index.js +1 -1
  414. package/dist/policy-uc224usV.js +328 -0
  415. package/dist/postinstall-inventory.json +407 -407
  416. package/dist/prepare.runtime-BPA6jMiM.js +815 -0
  417. package/dist/prepare.runtime.js +1 -1
  418. package/dist/probe-5ToseFjd.js +1443 -0
  419. package/dist/probe-BdCXAH_u.js +2 -0
  420. package/dist/probe-ByVoZEdq.js +45 -0
  421. package/dist/probe-D-D_1oc4.js +241 -0
  422. package/dist/probe-D6s_1Z5k.js +2 -0
  423. package/dist/probe-DIMAmSsO.js +74 -0
  424. package/dist/probe-DYuL-s4A.js +2205 -0
  425. package/dist/program-DDTWTh6g.js +111 -0
  426. package/dist/prompt-select-styled-kf1dPqNa.js +20 -0
  427. package/dist/protocol-Batc2DmY.js +2234 -0
  428. package/dist/provider-dispatcher-DdUqCa6H.js +2 -0
  429. package/dist/provider-dispatcher-uioW38XW.js +22 -0
  430. package/dist/qr-cli-B1WUe8Eb.js +2 -0
  431. package/dist/qr-cli-DmPti3xe.js +349 -0
  432. package/dist/reaction-runtime-api-5G3e9J0C.js +116 -0
  433. package/dist/reactions-x7VH-B95.js +998 -0
  434. package/dist/register-service-commands-DcW5qPTu.js +71 -0
  435. package/dist/register.agent-Dtj4HC7R.js +248 -0
  436. package/dist/register.configure-CJHb84Ce.js +15 -0
  437. package/dist/register.maintenance-BUkPfMcX.js +438 -0
  438. package/dist/register.message-DGFpyYBl.js +329 -0
  439. package/dist/register.onboard-D3v3xIfF.js +81 -0
  440. package/dist/register.runtime-DI4QxYdj.js +81 -0
  441. package/dist/register.runtime.js +1 -1
  442. package/dist/register.setup-CXTyuIFM.js +150 -0
  443. package/dist/register.status-health-sessions-CYUnRi97.js +1215 -0
  444. package/dist/register.subclis-DKMVrwRc.js +3 -0
  445. package/dist/register.subclis-NWRi2XKp.js +29 -0
  446. package/dist/register.subclis-core-De6qmQkr.js +243 -0
  447. package/dist/reply-dispatch-runtime-B8_j6pJi.js +13 -0
  448. package/dist/reply-runtime-DGHQDC9d.js +11 -0
  449. package/dist/reply.runtime-BCfqw2Co.js +2 -0
  450. package/dist/reply.runtime.js +1 -1
  451. package/dist/restart-health-6cjrRBpF.js +202 -0
  452. package/dist/restart-health-b6Qw43Tj.js +2 -0
  453. package/dist/root-help-BTIH_eUe.js +44 -0
  454. package/dist/routes-C3J2GfHR.js +3341 -0
  455. package/dist/routes-SMmfW6k8.js +2 -0
  456. package/dist/rpc-DQbAcIKu.js +61 -0
  457. package/dist/rpc.runtime-Q3qyofLf.js +21 -0
  458. package/dist/rpc.runtime.js +1 -1
  459. package/dist/run-delivery.runtime-BsLouK3f.js +530 -0
  460. package/dist/run-delivery.runtime.js +1 -1
  461. package/dist/run-embedded.runtime-CXd0oZQP.js +4 -0
  462. package/dist/run-embedded.runtime.js +1 -1
  463. package/dist/run-execution-cli.runtime-D-MKbq8r.js +4 -0
  464. package/dist/run-execution-cli.runtime.js +1 -1
  465. package/dist/run-executor.runtime-Cz0I8mDt.js +277 -0
  466. package/dist/run-executor.runtime.js +1 -1
  467. package/dist/run-main-CkXBTQut.js +516 -0
  468. package/dist/run-subagent-registry.runtime-Cyb8amrH.js +2 -0
  469. package/dist/run-subagent-registry.runtime.js +1 -1
  470. package/dist/run-wait-KlS0pdIK.js +135 -0
  471. package/dist/runtime-3niXLiFY.js +9 -0
  472. package/dist/runtime-api-B79e2jL2.js +4 -0
  473. package/dist/runtime-api-CM2c2bSC.js +9 -0
  474. package/dist/runtime-api-CnOFFN5q.js +14 -0
  475. package/dist/runtime-api-TnwM-EZH.js +9 -0
  476. package/dist/runtime-embedded-pi.runtime-9csGjukF.js +2 -0
  477. package/dist/runtime-embedded-pi.runtime.js +1 -1
  478. package/dist/runtime-internal-CQX4Zehn.js +2 -0
  479. package/dist/runtime-options-C0qP2VlT.js +275 -0
  480. package/dist/runtime-schema-DanWbDoL.js +27780 -0
  481. package/dist/runtime-vycfMfew.js +973 -0
  482. package/dist/scan-Bs5zROOQ.js +2 -0
  483. package/dist/scan-CP2zJb_w.js +523 -0
  484. package/dist/secrets-cli-YFTlIMmq.js +2101 -0
  485. package/dist/security-cli-B2WBRU9C.js +486 -0
  486. package/dist/selection-DSZGsU6m.js +2 -0
  487. package/dist/selection-hUGDnCgX.js +7736 -0
  488. package/dist/send-B3Ygb3r3.js +156 -0
  489. package/dist/send-DMwqnu6K.js +102 -0
  490. package/dist/send.runtime-D86atcfW.js +2 -0
  491. package/dist/send.runtime.js +1 -1
  492. package/dist/server-4gQCBM3M.js +77 -0
  493. package/dist/server-CK9eCPCG.js +13 -0
  494. package/dist/server-context-ih3GaGaI.js +847 -0
  495. package/dist/server-context-kZ_QADic.js +2 -0
  496. package/dist/server-node-events-CMlHOIKa.js +481 -0
  497. package/dist/server-plugin-bootstrap-B0XitldT.js +11333 -0
  498. package/dist/server-plugin-bootstrap-CHlVF8XB.js +2 -0
  499. package/dist/server-restart-sentinel-TpXCoiYX.js +697 -0
  500. package/dist/server.impl-B6at3Orl.js +12734 -0
  501. package/dist/session-kill-http-DvYp5h-j.js +110 -0
  502. package/dist/session-reset-service-C9rIVqF7.js +471 -0
  503. package/dist/session-route-FaMcEc7I.js +93 -0
  504. package/dist/session-status.runtime-BfPn8qA8.js +2 -0
  505. package/dist/session-status.runtime.js +1 -1
  506. package/dist/session-subagent-reactivation.runtime-C1fGNaiM.js +2 -0
  507. package/dist/session-subagent-reactivation.runtime.js +1 -1
  508. package/dist/session-tab-registry-BDK2AlxL.js +491 -0
  509. package/dist/session-visibility-BkrL2kFF.js +147 -0
  510. package/dist/sessions-helpers-YOu_5tl0.js +304 -0
  511. package/dist/sessions-history-http-DxNaoDfb.js +383 -0
  512. package/dist/sessions-patch-BPtlF0Lu.js +309 -0
  513. package/dist/sessions-resolve-B2rpvSka.js +174 -0
  514. package/dist/sessions.runtime-DEk_x65_.js +2 -0
  515. package/dist/sessions.runtime.js +1 -1
  516. package/dist/setup-DZJZF2R6.js +495 -0
  517. package/dist/setup-api-BkYWhB-B.js +29 -0
  518. package/dist/setup-core-BXBabSEx.js +171 -0
  519. package/dist/setup-core-eahC1DXh.js +176 -0
  520. package/dist/setup-surface-BEf8reey.js +286 -0
  521. package/dist/setup-surface-DAOKJ-ai.js +219 -0
  522. package/dist/setup-surface-b6gu0S8l.js +403 -0
  523. package/dist/setup.finalize-DXUCLT5O.js +539 -0
  524. package/dist/setup.gateway-config-BH4xbjcX.js +250 -0
  525. package/dist/shared-BhHdyXun.js +198 -0
  526. package/dist/shared-CKv38qsN.js +121 -0
  527. package/dist/shared-DUw9Q4Lf.js +76 -0
  528. package/dist/slash-state-BQgmhum1.js +1911 -0
  529. package/dist/src-C1B3uJMu.js +3974 -0
  530. package/dist/startup-context-DTpThe3H.js +312 -0
  531. package/dist/status-63GZxfe4.js +2 -0
  532. package/dist/status-C6qTe-QQ.js +397 -0
  533. package/dist/status-CSIGAUly.js +190 -0
  534. package/dist/status-DOW91Kcx.js +2 -0
  535. package/dist/status-all-7hqTcvxr.js +498 -0
  536. package/dist/status-json-CUzzv8An.js +14 -0
  537. package/dist/status-json-command-DwWlqvoV.js +84 -0
  538. package/dist/status-p4yx6E3C.js +209 -0
  539. package/dist/status-runtime-shared-yrzbsOR8.js +257 -0
  540. package/dist/status-subagents.runtime-CuRGoNNn.js +18 -0
  541. package/dist/status-subagents.runtime.js +1 -1
  542. package/dist/status-text-BrcRsCFE.js +237 -0
  543. package/dist/status-zV1BflCE.js +3 -0
  544. package/dist/status.gateway-connection.runtime-BKd4Zivg.js +2 -0
  545. package/dist/status.gateway-connection.runtime.js +1 -1
  546. package/dist/status.gather-B7WlHpIR.js +292 -0
  547. package/dist/status.gather-Ccewg4ce.js +2 -0
  548. package/dist/status.runtime-BFru2C4v.js +2 -0
  549. package/dist/status.runtime.js +1 -1
  550. package/dist/status.scan-mEKnAmP3.js +65 -0
  551. package/dist/status.scan-overview-B0qQVJd0.js +379 -0
  552. package/dist/status.scan.fast-json-CsU-fWhj.js +132 -0
  553. package/dist/status.scan.fast-json-tEc36TAC.js +2 -0
  554. package/dist/status.summary-Bvgry977.js +214 -0
  555. package/dist/status.summary-DRolowE_.js +2 -0
  556. package/dist/subagent-announce-Bhe55Ktf.js +351 -0
  557. package/dist/subagent-announce-delivery-NDBIRwuZ.js +726 -0
  558. package/dist/subagent-announce-output-DsmGO7Oi.js +364 -0
  559. package/dist/subagent-control-Bn8n-535.js +506 -0
  560. package/dist/subagent-followup.runtime-C7s-lOGN.js +68 -0
  561. package/dist/subagent-followup.runtime.js +1 -1
  562. package/dist/subagent-orphan-recovery-CJEhSvFZ.js +305 -0
  563. package/dist/subagent-registry-BgQA8eP1.js +1753 -0
  564. package/dist/subagent-registry-DAm-N9-O.js +3 -0
  565. package/dist/subagent-registry.runtime.js +1 -1
  566. package/dist/subagent-spawn-EXtecXVT.js +1005 -0
  567. package/dist/system-cli-CFS_PN8R.js +59 -0
  568. package/dist/targets-BXWH2MfM.js +67 -0
  569. package/dist/task-executor-DfugjJEq.js +360 -0
  570. package/dist/task-owner-access-CSwIy-v-.js +74 -0
  571. package/dist/task-registry-B-kQGKt_.js +2366 -0
  572. package/dist/task-registry-delivery-runtime-DD1_7xUF.js +3 -0
  573. package/dist/task-registry-delivery-runtime-DIsasFa1.js +2 -0
  574. package/dist/task-registry.maintenance-CxAx195T.js +2 -0
  575. package/dist/task-registry.maintenance-DIFuNnzy.js +416 -0
  576. package/dist/telegram/token.js +1 -1
  577. package/dist/testing-C7oUBiZL.js +575 -0
  578. package/dist/text-report-hYiQ_Kcv.js +587 -0
  579. package/dist/tool-resolution-CnnOHyxg.js +90 -0
  580. package/dist/tools-effective-inventory-DqYXIS6R.js +152 -0
  581. package/dist/tools-invoke-http-zop5qWa_.js +206 -0
  582. package/dist/trash-DZRlsk_R.js +24 -0
  583. package/dist/tui-cli-2cKXF0J8.js +4575 -0
  584. package/dist/update-cli-DP1KXasM.js +1759 -0
  585. package/dist/upgrade-DPFxH2YB.js +1226 -0
  586. package/dist/video-generation-task-status-BEgeadFu.js +163 -0
  587. package/dist/wait-for-idle-before-flush-CmSNfAco.js +5986 -0
  588. package/dist/wizard-models-BJGn0RnU.js +161 -0
  589. package/package.json +1 -1
  590. package/dist/abort-ca8hDmJr.js +0 -201
  591. package/dist/abort.runtime-BrChEuUS.js +0 -2
  592. package/dist/accounts-C1ECKXaw.js +0 -107
  593. package/dist/accounts-DH8HU_Fu.js +0 -104
  594. package/dist/accounts-DWQpG06j.js +0 -2
  595. package/dist/acp-cli-BLpWVnc7.js +0 -2193
  596. package/dist/acp-spawn-D1p6b1gk.js +0 -2
  597. package/dist/acp-spawn-qoyl9NiU.js +0 -1093
  598. package/dist/acp-stateful-target-driver-NL9txhIM.js +0 -89
  599. package/dist/action-agents-C729fJ_P.js +0 -67
  600. package/dist/action-focus-53k9XP4K.js +0 -132
  601. package/dist/action-help-bIJZBYLz.js +0 -7
  602. package/dist/action-info-BBzvYFX_.js +0 -101
  603. package/dist/action-kill-C4fa3E9I.js +0 -33
  604. package/dist/action-list-BEiIbwP1.js +0 -21
  605. package/dist/action-log-Cq7RLW2T.js +0 -30
  606. package/dist/action-send-DyiHgRwh.js +0 -39
  607. package/dist/action-spawn-CEZfDvXU.js +0 -47
  608. package/dist/action-unfocus-CpAw3JOi.js +0 -29
  609. package/dist/actions.runtime-BKEwPyo7.js +0 -18
  610. package/dist/actions.runtime-Bp0UusIf.js +0 -5
  611. package/dist/agent-C2hwJefQ.js +0 -2
  612. package/dist/agent-command-BAAeGRql.js +0 -874
  613. package/dist/agent-harness-runtime-Czrx53YL.js +0 -144
  614. package/dist/agent-runner-utils-DzShckNa.js +0 -239
  615. package/dist/agent-runner.runtime-d_EtNxBK.js +0 -3455
  616. package/dist/agent-runtime-DNgz7AOP.js +0 -18
  617. package/dist/agents-CZmpon7q.js +0 -5
  618. package/dist/agents-Cs9je_gQ.js +0 -953
  619. package/dist/aliases-CZemdpTj.js +0 -2
  620. package/dist/aliases-KefnmoaT.js +0 -96
  621. package/dist/api-CO05iXNH.js +0 -139
  622. package/dist/api-CyjlApHT.js +0 -3
  623. package/dist/api-DArm1ECd.js +0 -5
  624. package/dist/approval-gateway-resolver-URpDQMld.js +0 -29
  625. package/dist/approval-gateway-runtime-B087BMms.js +0 -2
  626. package/dist/approval-handler-runtime-BgRQnG4g.js +0 -439
  627. package/dist/approval-native-runtime-DAsraihr.js +0 -729
  628. package/dist/attempt-execution.runtime-D_FGkDQz.js +0 -509
  629. package/dist/attempt.prompt-helpers-CDzDUi1C.js +0 -221
  630. package/dist/attempt.tool-run-context-DitxaTPJ.js +0 -933
  631. package/dist/audit-Bq8vlxok.js +0 -939
  632. package/dist/audit.runtime-CU42yh1v.js +0 -7
  633. package/dist/auth-CQfwC-AH.js +0 -383
  634. package/dist/auth-DyWcaG4X.js +0 -2
  635. package/dist/auth-order-C3zGI0s9.js +0 -96
  636. package/dist/auth-order-XQ9ZGPd9.js +0 -2
  637. package/dist/bash-tools-BBRtIa6j.js +0 -2824
  638. package/dist/bash-tools-BI0d1TdC.js +0 -3
  639. package/dist/binding-routing-Cvm5c1IV.js +0 -85
  640. package/dist/binding-targets-DSs4NXbd.js +0 -121
  641. package/dist/bridge-server-CwWzSgv8.js +0 -113
  642. package/dist/browser-control-auth-y1f-9HRI.js +0 -2
  643. package/dist/browser-node-runtime-3UAeP8a6.js +0 -12
  644. package/dist/browser-profiles-BzzxphNW.js +0 -2
  645. package/dist/browser-runtime-jj11LR-E.js +0 -387
  646. package/dist/browser-setup-tools-CFB52yQc.js +0 -13
  647. package/dist/build-TlobwpQW.js +0 -550
  648. package/dist/call-Bx8lENb2.js +0 -3
  649. package/dist/call-jYRpeAWm.js +0 -331
  650. package/dist/call.runtime-BRluUZbD.js +0 -2
  651. package/dist/capability-cli-Iyj9Zi3g.js +0 -1401
  652. package/dist/catchup-CtxTwzY8.js +0 -300
  653. package/dist/channel-BJKHBfnq.js +0 -491
  654. package/dist/channel-BNNnYzwK.js +0 -1100
  655. package/dist/channel-BXS-Hd8p.js +0 -226
  656. package/dist/channel-C4XWpowe.js +0 -1174
  657. package/dist/channel-CJQdQgPr.js +0 -840
  658. package/dist/channel-C_zWAu4D.js +0 -595
  659. package/dist/channel-CtGzrF-K.js +0 -1802
  660. package/dist/channel-O9DE4IIq.js +0 -350
  661. package/dist/channel-WHUOtJme.js +0 -297
  662. package/dist/channel-WoDWDxqx.js +0 -1320
  663. package/dist/channel-core-BJjq9SOq.js +0 -5
  664. package/dist/channel-inbound-DLs-YfUs.js +0 -31
  665. package/dist/channel-plugin-runtime-CMG8ac2K.js +0 -771
  666. package/dist/channel-runtime-4UjeDmDI.js +0 -425
  667. package/dist/channel-ys2FFqi1.js +0 -453
  668. package/dist/channel.runtime-B38Ky3R9.js +0 -109
  669. package/dist/channel.runtime-Bl8WYZvF.js +0 -576
  670. package/dist/channel.runtime-D3kAsCsR.js +0 -89
  671. package/dist/channel.runtime-DEQ-anMf.js +0 -2364
  672. package/dist/channel.runtime-DG-EUnSC.js +0 -4
  673. package/dist/channel.runtime-IfV1Md6p.js +0 -430
  674. package/dist/channel.runtime-w1tHjTOa.js +0 -34702
  675. package/dist/channel.setup-dXwiMlyi.js +0 -10
  676. package/dist/channels-B2G1Y-iD.js +0 -733
  677. package/dist/channels-cli-YintLKAt.js +0 -268
  678. package/dist/chat-DdKbu8CA.js +0 -2758
  679. package/dist/clawbot-cli-CnHERFYk.js +0 -9
  680. package/dist/cli-CSNAd6Sz.js +0 -72
  681. package/dist/cli-CdRioBfN.js +0 -2
  682. package/dist/cli-DMPwqYqc.js +0 -219
  683. package/dist/cli-ctyAqh0j.js +0 -2
  684. package/dist/cli-runner-CNlk7xmx.js +0 -286
  685. package/dist/cli-runner.runtime-BK4sQk1m.js +0 -3
  686. package/dist/cli-runner.runtime-BT8ZZn-R.js +0 -4
  687. package/dist/cli.runtime-DU7swpBI.js +0 -1261
  688. package/dist/client-CQdcTPUf.js +0 -138
  689. package/dist/client-Vx7pseEY.js +0 -713
  690. package/dist/command-auth-DkJWb2HE.js +0 -76
  691. package/dist/command-config-resolution-CIRWRfR8.js +0 -23
  692. package/dist/command-config-resolution-DYZWj6Zm.js +0 -2
  693. package/dist/command-config-resolution.runtime-CUtVJOf0.js +0 -2
  694. package/dist/command-registry-CHy5EH0v.js +0 -4
  695. package/dist/command-registry-CyKgELQP.js +0 -9
  696. package/dist/command-registry-core-DQeRIuot.js +0 -104
  697. package/dist/command-secret-gateway-BNnWdAlq.js +0 -528
  698. package/dist/command-status.runtime-CKgimR6Y.js +0 -87
  699. package/dist/commands-acp-DSm97O5v.js +0 -77
  700. package/dist/commands-compact.runtime-BXhP6WJ6.js +0 -10
  701. package/dist/commands-handlers.runtime-FzK-n0L8.js +0 -4597
  702. package/dist/commands-status-BQnB5OSX.js +0 -16
  703. package/dist/commands-status.runtime-B6GcfEDm.js +0 -3
  704. package/dist/commands-subagents-control.runtime-CByd528A.js +0 -2
  705. package/dist/commands-subagents-control.runtime-CqI4LMYa.js +0 -3
  706. package/dist/commands-system-prompt-BD_LeeZk.js +0 -2
  707. package/dist/commands-system-prompt-C2Md_Ia1.js +0 -158
  708. package/dist/commands.runtime-CwiPf7Cc.js +0 -166
  709. package/dist/compact-B_4bMVpw.js +0 -1118
  710. package/dist/compact.runtime-BhRqiBXG.js +0 -12
  711. package/dist/completion-cli-D07hGGMI.js +0 -313
  712. package/dist/config-B1lvYOd7.js +0 -251
  713. package/dist/config-cli-BgepNwob.js +0 -1078
  714. package/dist/configure-CEfl0ORM.js +0 -2
  715. package/dist/configure-TsykzQqM.js +0 -1245
  716. package/dist/connect-options-zqTIEl6K.js +0 -699
  717. package/dist/control-auth-CNa_KHpo.js +0 -125
  718. package/dist/control-service-CZl5wFdZ.js +0 -156
  719. package/dist/conversation-id-BLY9ffjm.js +0 -38
  720. package/dist/conversation-id-DVeOM5Jh.js +0 -235
  721. package/dist/conversation-runtime-gJt7AAg2.js +0 -31
  722. package/dist/core-BtmNtOpS.js +0 -275
  723. package/dist/cron-cli-s9SF4__G.js +0 -713
  724. package/dist/daemon-cli-TCubZfI_.js +0 -12
  725. package/dist/delegate-DyITI93V.js +0 -64
  726. package/dist/detached-task-runtime-CTUQj84i.js +0 -73
  727. package/dist/devices-cli-SXcLjGmh.js +0 -496
  728. package/dist/diagnostics-waSemGnZ.js +0 -154
  729. package/dist/direct-dm-CiSjkmkL.js +0 -64
  730. package/dist/dispatch-BnQSIx2G.js +0 -1131
  731. package/dist/dispatch-acp-CaNQyl2L.js +0 -981
  732. package/dist/dispatch-acp-manager.runtime-DJK1eHYX.js +0 -3
  733. package/dist/dispatch-acp.runtime-Bl5cvtX4.js +0 -19
  734. package/dist/doctor-device-pairing-DBhEA-8G.js +0 -307
  735. package/dist/doctor-gateway-daemon-flow-Ds47Er3Y.js +0 -250
  736. package/dist/doctor-gateway-health-EWwTw5JR.js +0 -60
  737. package/dist/doctor-health-C6muRn7t.js +0 -59
  738. package/dist/doctor-health-contributions-B984415a.js +0 -486
  739. package/dist/doctor-prompter-BpOi4ndi.js +0 -56
  740. package/dist/doctor-workspace-status-CiEWZXrx.js +0 -75
  741. package/dist/dreaming-DFPenC85.js +0 -1574
  742. package/dist/dreaming-narrative-6A27_Gft.js +0 -595
  743. package/dist/embedded-gateway-stub.runtime-UVgfXZzk.js +0 -9
  744. package/dist/exec-approvals-cli-Cc_GG9ZT.js +0 -498
  745. package/dist/fallbacks-DX4YcmAx.js +0 -2
  746. package/dist/fallbacks-inTaaG-m.js +0 -31
  747. package/dist/fallbacks-shared-ow1la-U2.js +0 -111
  748. package/dist/gateway-D4iWwu3_.js +0 -115
  749. package/dist/gateway-cli-D6j0Aj3R.js +0 -1325
  750. package/dist/gateway-rpc-Dd_x2GX5.js +0 -14
  751. package/dist/gateway-rpc.runtime-Btnvsv-7.js +0 -23
  752. package/dist/gateway-runtime-DctMRv_p.js +0 -15
  753. package/dist/gateway-status-DJCtvUVn.js +0 -584
  754. package/dist/genesis-tools-CvMcpUvH.js +0 -8999
  755. package/dist/genesis-tools.runtime-Ch3NDEDq.js +0 -2
  756. package/dist/get-reply-Cm39MCyU.js +0 -3879
  757. package/dist/get-reply-from-config.runtime-CSqCYatb.js +0 -2
  758. package/dist/graph-users-BJxYqA3A.js +0 -1337
  759. package/dist/health-C14jIilQ.js +0 -469
  760. package/dist/health-C6yJSCMc.js +0 -3
  761. package/dist/heartbeat-runner-C6-gFnyC.js +0 -5
  762. package/dist/heartbeat-runner-yUYjgzIM.js +0 -1292
  763. package/dist/heartbeat-runner.runtime-DZzyrUNB.js +0 -4
  764. package/dist/hooks-cli-CCRaHheu.js +0 -433
  765. package/dist/image-fallbacks-BH9qLbBG.js +0 -31
  766. package/dist/image-fallbacks-DUOPO1ic.js +0 -2
  767. package/dist/inbound-reply-dispatch-DPf_IrbV.js +0 -73
  768. package/dist/infra-runtime-CLND6LJ0.js +0 -39
  769. package/dist/init-CzWob-9v.js +0 -59
  770. package/dist/library-C0a9Bz2M.js +0 -45
  771. package/dist/lifecycle-B_B_jt3r.js +0 -571
  772. package/dist/lifecycle-DuqKKZop.js +0 -229
  773. package/dist/lifecycle.runtime-DoosWTnK.js +0 -2
  774. package/dist/list-Bly8XeOF.js +0 -2
  775. package/dist/list-C5HvtbwZ.js +0 -2
  776. package/dist/list-CHIiamt1.js +0 -131
  777. package/dist/list-CMmJiacX.js +0 -1201
  778. package/dist/list.probe-kmHRFlrP.js +0 -419
  779. package/dist/llm-slug-generator-C3u6Ptgq.js +0 -79
  780. package/dist/load-config-CXvIGI7N.js +0 -35
  781. package/dist/local-dispatch.runtime-BNQF4rqW.js +0 -8
  782. package/dist/logs-cli-DEy1GPk2.js +0 -265
  783. package/dist/logs-cli.runtime-jWShKzQC.js +0 -2
  784. package/dist/main-session-restart-recovery-CzfY6Cd8.js +0 -206
  785. package/dist/managed-image-attachments-BGPKA7Mn.js +0 -2
  786. package/dist/managed-image-attachments-CTrq9ym-.js +0 -635
  787. package/dist/manager-C_ZGa9x8.js +0 -2057
  788. package/dist/manager-DIHLRzYF.js +0 -2
  789. package/dist/markdown-to-line-CRbbXtJK.js +0 -790
  790. package/dist/mcp-cli-FMJb3T4k.js +0 -725
  791. package/dist/mcp-http-b6UMoE_J.js +0 -529
  792. package/dist/memory-core-host-runtime-cli-CquxELNj.js +0 -9
  793. package/dist/message-CmjuvIFf.js +0 -232
  794. package/dist/message-action-runner-CiY3rhqt.js +0 -1407
  795. package/dist/message-action-runner-Do4P0h5i.js +0 -2
  796. package/dist/message-actions-BYREqFJA.js +0 -143
  797. package/dist/message.gateway.runtime-gkoWzaYV.js +0 -2
  798. package/dist/models-auth-status-B_Pcr0tl.js +0 -201
  799. package/dist/models-cli-BZSuW2gw.js +0 -219
  800. package/dist/monitor-22LY8y6z.js +0 -788
  801. package/dist/monitor-BZdf_CEm.js +0 -1237
  802. package/dist/monitor-CTVDlTs2.js +0 -671
  803. package/dist/monitor-Cfv-KGAl.js +0 -1661
  804. package/dist/monitor-DuA69-8E.js +0 -2
  805. package/dist/monitor-auth-BNDlfcw7.js +0 -207
  806. package/dist/monitor-cmWeDVxf.js +0 -1459
  807. package/dist/monitor-processing-D9Xcsagt.js +0 -1974
  808. package/dist/monitor.runtime-zWvcbNim.js +0 -2
  809. package/dist/monitor.webhook-BYWQa5lY.js +0 -180
  810. package/dist/msteams-n9HDT4O-.js +0 -35
  811. package/dist/native-hook-relay-CKyIfLOm.js +0 -519
  812. package/dist/nextcloud-talk-BuJVVP0J.js +0 -17
  813. package/dist/node-cli-DBK2TIEH.js +0 -2506
  814. package/dist/nodes-cli-D5Y1_ZVD.js +0 -1046
  815. package/dist/nodes-utils-C6IKaTjm.js +0 -84
  816. package/dist/nodes.helpers-CkJO5i0d.js +0 -34
  817. package/dist/notify-v0zoiI-O.js +0 -315
  818. package/dist/onboard-BCaLBJor.js +0 -632
  819. package/dist/onboard-helpers-Ba7ES7kB.js +0 -204
  820. package/dist/onboard-helpers-D5qdyBIj.js +0 -6
  821. package/dist/onboard-remote-BaHm_VrY.js +0 -2
  822. package/dist/onboard-remote-DbGAo_Ad.js +0 -193
  823. package/dist/onboard-skills-BA7c4li1.js +0 -2
  824. package/dist/onboard-skills-upyHp6T9.js +0 -134
  825. package/dist/openai-http-DwCqhEcX.js +0 -500
  826. package/dist/openresponses-http-tJr67vC1.js +0 -1128
  827. package/dist/operator-approvals-client-C0t_-2xC.js +0 -68
  828. package/dist/outbound.runtime-nXA4k1xA.js +0 -2
  829. package/dist/pair-command-approve-G5y-rKn9.js +0 -44
  830. package/dist/persistent-bindings.lifecycle-C56aKBVc.js +0 -2
  831. package/dist/persistent-bindings.lifecycle-CfBqvz9L.js +0 -85
  832. package/dist/pi-embedded-B1wvxHXL.js +0 -2905
  833. package/dist/pi-embedded-DmDb-oUB.js +0 -4
  834. package/dist/pi-embedded.runtime-D5xqw9Ko.js +0 -4
  835. package/dist/pi-tool-definition-adapter-CAxlo-Va.js +0 -217
  836. package/dist/pi-tools-C69yvznf.js +0 -1057
  837. package/dist/pi-tools.before-tool-call-BDeCmoAy.js +0 -2
  838. package/dist/pi-tools.before-tool-call-DG7VVNBn.js +0 -433
  839. package/dist/plugin-B9Ld0CUs.js +0 -12195
  840. package/dist/plugin-enabled-BguUplCN.js +0 -140
  841. package/dist/plugin-registration-DPBnSoak.js +0 -23
  842. package/dist/plugin-service-CdNFnRyN.js +0 -2890
  843. package/dist/policy-DgfegT_Y.js +0 -328
  844. package/dist/prepare.runtime-C_sRmuFC.js +0 -815
  845. package/dist/probe-8vb_Ssot.js +0 -45
  846. package/dist/probe-BjmKFiz1.js +0 -2205
  847. package/dist/probe-CVlOo8Hr.js +0 -74
  848. package/dist/probe-CakOsrSu.js +0 -241
  849. package/dist/probe-CbOoVumf.js +0 -2
  850. package/dist/probe-D6yFcZpK.js +0 -1443
  851. package/dist/probe-OcOYm1bj.js +0 -2
  852. package/dist/program-BJnTb7UE.js +0 -111
  853. package/dist/prompt-select-styled-C8kGHNpY.js +0 -20
  854. package/dist/protocol-C40iRm9c.js +0 -2234
  855. package/dist/provider-dispatcher-BIOPYzb9.js +0 -2
  856. package/dist/provider-dispatcher-CpwviX0O.js +0 -22
  857. package/dist/qr-cli-CJXKCj0L.js +0 -2
  858. package/dist/qr-cli-kSU9X-N0.js +0 -349
  859. package/dist/reaction-runtime-api-3XFmruJA.js +0 -116
  860. package/dist/reactions-By-nqZC6.js +0 -998
  861. package/dist/register-service-commands-fwB-T6mW.js +0 -71
  862. package/dist/register.agent-CpScU3CV.js +0 -248
  863. package/dist/register.configure-DpD3_BCK.js +0 -15
  864. package/dist/register.maintenance-ByoQXpk9.js +0 -438
  865. package/dist/register.message-BTXNOZMD.js +0 -329
  866. package/dist/register.onboard-B83CAOYy.js +0 -81
  867. package/dist/register.runtime-Doz01zcH.js +0 -81
  868. package/dist/register.setup-BKI5rwWy.js +0 -150
  869. package/dist/register.status-health-sessions-DRPszDQ-.js +0 -1215
  870. package/dist/register.subclis-DeXklyQL.js +0 -3
  871. package/dist/register.subclis-YkmoZoxl.js +0 -29
  872. package/dist/register.subclis-core-BPo4hV1Q.js +0 -243
  873. package/dist/reply-dispatch-runtime-DjIuN_dr.js +0 -13
  874. package/dist/reply-runtime-5TFidLR3.js +0 -11
  875. package/dist/reply.runtime-6d1e0INl.js +0 -2
  876. package/dist/restart-health-BWUPc4R-.js +0 -202
  877. package/dist/restart-health-CWvsjHVN.js +0 -2
  878. package/dist/root-help-D2YiFpS6.js +0 -44
  879. package/dist/routes-BdYdVpe7.js +0 -3341
  880. package/dist/routes-jYoN_qOU.js +0 -2
  881. package/dist/rpc-5tMjebZH.js +0 -61
  882. package/dist/rpc.runtime-BzAHjcm4.js +0 -21
  883. package/dist/run-delivery.runtime-qZIB76oE.js +0 -530
  884. package/dist/run-embedded.runtime-nHunVmCv.js +0 -4
  885. package/dist/run-execution-cli.runtime-CMT7La6D.js +0 -4
  886. package/dist/run-executor.runtime-BG6SDi3f.js +0 -277
  887. package/dist/run-main-CNf_LLX7.js +0 -516
  888. package/dist/run-subagent-registry.runtime-D0RcqcJr.js +0 -2
  889. package/dist/run-wait--kou3jZ7.js +0 -135
  890. package/dist/runtime-BvxkGJm2.js +0 -9
  891. package/dist/runtime-DgQ5oUKq.js +0 -973
  892. package/dist/runtime-api-6SzMK-FZ.js +0 -4
  893. package/dist/runtime-api-BAMrcB-5.js +0 -9
  894. package/dist/runtime-api-DLSrxS5O.js +0 -9
  895. package/dist/runtime-api-DsPleWQg.js +0 -14
  896. package/dist/runtime-embedded-pi.runtime-eyjaJfAz.js +0 -2
  897. package/dist/runtime-internal-BTfGDlHi.js +0 -2
  898. package/dist/runtime-options-B5_eZxMV.js +0 -275
  899. package/dist/runtime-schema-BB3QzGXJ.js +0 -27780
  900. package/dist/scan-D0fsxqed.js +0 -2
  901. package/dist/scan-DrjjN66Z.js +0 -523
  902. package/dist/secrets-cli-B7-qbfn-.js +0 -2101
  903. package/dist/security-cli-CYTPgL67.js +0 -486
  904. package/dist/selection-DEAdLh1Q.js +0 -2
  905. package/dist/selection-zPPyzfBX.js +0 -7736
  906. package/dist/send-CYKfZTCJ.js +0 -156
  907. package/dist/send-Di1tRwJD.js +0 -102
  908. package/dist/send.runtime-Bw22DBkL.js +0 -2
  909. package/dist/server-BIF5dPI_.js +0 -13
  910. package/dist/server-BJK0Q4xw.js +0 -77
  911. package/dist/server-context-CiVVCQNp.js +0 -847
  912. package/dist/server-context-DXvk5Tdy.js +0 -2
  913. package/dist/server-node-events-CdZP3Kok.js +0 -481
  914. package/dist/server-plugin-bootstrap-Di15EOt4.js +0 -11333
  915. package/dist/server-plugin-bootstrap-dboO44LL.js +0 -2
  916. package/dist/server-restart-sentinel-BWiOzljY.js +0 -697
  917. package/dist/server.impl-Ph8YCQpT.js +0 -12734
  918. package/dist/session-kill-http-B_J1fJ4-.js +0 -110
  919. package/dist/session-reset-service-DPgw70iw.js +0 -471
  920. package/dist/session-route-B0h6MEyB.js +0 -93
  921. package/dist/session-status.runtime-DCvgI1pG.js +0 -2
  922. package/dist/session-subagent-reactivation.runtime-BgsCnI-h.js +0 -2
  923. package/dist/session-tab-registry-FyN6CWh5.js +0 -491
  924. package/dist/session-visibility-CZjMA1SL.js +0 -147
  925. package/dist/sessions-helpers-B3W7MdIb.js +0 -304
  926. package/dist/sessions-history-http-Bw5J6HQ-.js +0 -383
  927. package/dist/sessions-patch-2sBcHc9a.js +0 -309
  928. package/dist/sessions-resolve-C-VZh_56.js +0 -174
  929. package/dist/sessions.runtime-cLuc67tJ.js +0 -2
  930. package/dist/setup-FW8xH-S-.js +0 -495
  931. package/dist/setup-api-Culp0Usf.js +0 -29
  932. package/dist/setup-core-CaTBS6Tz.js +0 -171
  933. package/dist/setup-core-youmXvW_.js +0 -176
  934. package/dist/setup-surface-BeMn-9hU.js +0 -403
  935. package/dist/setup-surface-CUd-s0wh.js +0 -286
  936. package/dist/setup-surface-DtscjAY3.js +0 -219
  937. package/dist/setup.finalize-BWyA4f4q.js +0 -539
  938. package/dist/setup.gateway-config-CvzMdftA.js +0 -250
  939. package/dist/shared-B3Pz1Xcr.js +0 -121
  940. package/dist/shared-Bc3x3THS.js +0 -76
  941. package/dist/shared-CxbLx0Ww.js +0 -198
  942. package/dist/slash-state-XfeMEeuI.js +0 -1911
  943. package/dist/src-BiDxQvtV.js +0 -3974
  944. package/dist/startup-context-CXQi-7YB.js +0 -312
  945. package/dist/status-Ch3bm70K.js +0 -2
  946. package/dist/status-CiQSxvY-.js +0 -3
  947. package/dist/status-DY0DlWlw.js +0 -190
  948. package/dist/status-DjdByQv-.js +0 -209
  949. package/dist/status-MT62_Jgw.js +0 -2
  950. package/dist/status-all-BD2viQD9.js +0 -498
  951. package/dist/status-json-CWS2oYON.js +0 -14
  952. package/dist/status-json-command-B6lZefoe.js +0 -84
  953. package/dist/status-pujDHwRb.js +0 -397
  954. package/dist/status-runtime-shared-Bu9Zhd7x.js +0 -257
  955. package/dist/status-subagents.runtime-B4UXD0lL.js +0 -18
  956. package/dist/status-text-myqmk4OL.js +0 -237
  957. package/dist/status.gateway-connection.runtime-B0Iwl2iZ.js +0 -2
  958. package/dist/status.gather-C51Ja0wP.js +0 -292
  959. package/dist/status.gather-DQ7WZp3H.js +0 -2
  960. package/dist/status.runtime-Cxyb3wHZ.js +0 -2
  961. package/dist/status.scan-C1aqDsy2.js +0 -65
  962. package/dist/status.scan-overview-BerlJz2l.js +0 -379
  963. package/dist/status.scan.fast-json-BXY82vu2.js +0 -2
  964. package/dist/status.scan.fast-json-DJqgEbzZ.js +0 -132
  965. package/dist/status.summary-CCdLUph8.js +0 -214
  966. package/dist/status.summary-CHAn0_FS.js +0 -2
  967. package/dist/subagent-announce-D4jG75Ub.js +0 -351
  968. package/dist/subagent-announce-delivery-BkQYzDcy.js +0 -726
  969. package/dist/subagent-announce-output-C3pkuu-t.js +0 -364
  970. package/dist/subagent-control-DVVK8du2.js +0 -506
  971. package/dist/subagent-followup.runtime-CdeweG-S.js +0 -68
  972. package/dist/subagent-orphan-recovery-ZQanOHb4.js +0 -305
  973. package/dist/subagent-registry-BcPa3ho0.js +0 -3
  974. package/dist/subagent-registry-hJUso5eL.js +0 -1753
  975. package/dist/subagent-spawn-DTaeQc9q.js +0 -1005
  976. package/dist/system-cli-CT8VaSDY.js +0 -59
  977. package/dist/targets-BPdSjnQH.js +0 -67
  978. package/dist/task-executor-B62Qzfi-.js +0 -360
  979. package/dist/task-owner-access-BBMrMOlN.js +0 -74
  980. package/dist/task-registry-BD-ew2bT.js +0 -2366
  981. package/dist/task-registry-delivery-runtime-B2WyGY0d.js +0 -3
  982. package/dist/task-registry-delivery-runtime-MFJszOHI.js +0 -2
  983. package/dist/task-registry.maintenance-0D2Yxl49.js +0 -416
  984. package/dist/task-registry.maintenance-OPlfB5W9.js +0 -2
  985. package/dist/testing-DmxZ16UC.js +0 -575
  986. package/dist/text-report-BwIpU54R.js +0 -587
  987. package/dist/tool-resolution-vn72hwMo.js +0 -90
  988. package/dist/tools-effective-inventory-DII_pOSr.js +0 -152
  989. package/dist/tools-invoke-http-DdthGR52.js +0 -206
  990. package/dist/trash-BVZu6rU7.js +0 -24
  991. package/dist/tui-cli-Bz51WCAi.js +0 -4575
  992. package/dist/update-cli-DkH8vHQP.js +0 -1759
  993. package/dist/upgrade-Dvj8K4WB.js +0 -1226
  994. package/dist/video-generation-task-status-CHYB_IeZ.js +0 -163
  995. package/dist/wait-for-idle-before-flush-DJMxeE2X.js +0 -5986
  996. package/dist/wizard-models-BNQQ7fvr.js +0 -161
@@ -0,0 +1,4575 @@
1
+ import { i as formatErrorMessage } from "./errors-Jbvi20TW.js";
2
+ import { a as normalizeLowercaseStringOrEmpty, c as normalizeOptionalString, s as normalizeOptionalLowercaseString } from "./string-coerce-C1IzJjqi.js";
3
+ import { h as loggingState } from "./logger-QwLssHIf.js";
4
+ import { n as defaultRuntime } from "./runtime-CQ7eH0le.js";
5
+ import { i as visibleWidth, r as stripAnsi$1 } from "./ansi-BZHMLcUk.js";
6
+ import { u as setConsoleSubsystemFilter } from "./subsystem-DTMy5YmO.js";
7
+ import { t as formatDocsLink } from "./links-DmsJCU7L.js";
8
+ import { r as theme$1 } from "./theme-BrRleVfL.js";
9
+ import { n as VERSION } from "./version-BoqlEm3e.js";
10
+ import { n as assertExplicitGatewayAuthModeWhenBothConfigured } from "./auth-mode-policy-BM9E_-zc.js";
11
+ import { a as isLoopbackHost } from "./net-AycWGi8-.js";
12
+ import { a as loadConfig } from "./io-h8M_Z0Lj.js";
13
+ import { o as parseAgentSessionKey } from "./session-key-utils-BT0y7mVK.js";
14
+ import { c as normalizeAgentId, l as normalizeMainKey, r as buildAgentMainSessionKey } from "./session-key-EpIbK3Oz.js";
15
+ import { r as DEFAULT_PROVIDER } from "./defaults-DM8yIn8C.js";
16
+ import { a as resolveAgentIdByWorkspacePath, p as resolveSessionAgentId, x as resolveDefaultAgentId } from "./agent-scope-CDjZLqNk.js";
17
+ import "./config-B3ZoZd5V.js";
18
+ import { n as GatewayClientRequestError, t as GatewayClient } from "./client-CrPccv7a.js";
19
+ import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES, t as GATEWAY_CLIENT_CAPS } from "./client-info-CfESmEX1.js";
20
+ import { r as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-core-CtbksRwN.js";
21
+ import "./message-channel-BbI8d0sw.js";
22
+ import "./protocol-Batc2DmY.js";
23
+ import { g as resolveResponseUsageMode, m as normalizeUsageDisplay, r as listThinkingLevelLabels, t as formatThinkingLevels } from "./thinking-CM0wvLlr.js";
24
+ import { p as resolveThinkingDefault, t as buildAllowedModelSet } from "./model-selection-BRmopwFB.js";
25
+ import { t as loadCombinedSessionStoreForGateway } from "./combined-store-gateway-Cp7gSMlV.js";
26
+ import { o as updateSessionStore } from "./store-DsNJP7a2.js";
27
+ import "./sessions-BsnttWP_.js";
28
+ import { l as onAgentEvent } from "./agent-events-CrZzR8Z1.js";
29
+ import { r as formatTokenCount } from "./usage-format-Hc-FyvzW.js";
30
+ import { c as stripEnvelopeFromMessages, i as readSessionMessages, n as capArrayByJsonBytes } from "./session-utils.fs-sxwRHULR.js";
31
+ import { r as extractAssistantVisibleText } from "./chat-message-content-f1D-O-pU.js";
32
+ import { i as stripInlineDirectiveTagsForDisplay } from "./directive-tags-Db1TRP8U.js";
33
+ import { r as stripLeadingInboundMetadata } from "./strip-inbound-meta-BpubGgAq.js";
34
+ import { a as loadSessionEntry, d as resolveGatewaySessionStoreTarget, n as listAgentsForGateway, o as migrateAndPruneGatewaySessionStoreKey, p as resolveSessionModelRef, r as listSessionsFromStore } from "./session-utils-BrGPE9ed.js";
35
+ import { a as isSilentReplyText, n as SILENT_REPLY_TOKEN } from "./tokens-Bq9TB3gs.js";
36
+ import { v as setEmbeddedMode } from "./genesis-tools-DCRaVVjY.js";
37
+ import "./pi-embedded-helpers-BhsTiD6Y.js";
38
+ import { D as formatRawAssistantErrorForUi, m as isAuthErrorMessage } from "./sanitize-user-facing-text-CL1kXS2D.js";
39
+ import { r as resolveToolDisplay, t as formatToolDetail } from "./tool-display-BWPMZ4Xm.js";
40
+ import { l as resolveExplicitGatewayAuth, n as buildGatewayConnectionDetails, s as ensureExplicitGatewayAuth } from "./call-DkGNVvLy.js";
41
+ import { t as parseTimeoutMs } from "./parse-timeout-DF24GSy6.js";
42
+ import { r as resolveSessionInfoModelSelection } from "./model-selection-display-BiU1dZp5.js";
43
+ import { n as listChatCommands, r as listChatCommandsForConfig } from "./commands-registry-list-eSZzx2TM.js";
44
+ import "./commands-registry-BUxuRHG0.js";
45
+ import { n as formatTimeAgo, t as formatRelativeTimestamp } from "./format-relative-uQtNNoGl.js";
46
+ import { t as normalizeGroupActivation } from "./group-activation-C_gTAl_1.js";
47
+ import { r as agentCommandFromIngress } from "./agent-command-C4H_9c2N.js";
48
+ import { t as createDefaultDeps } from "./deps-BMuC_6j0.js";
49
+ import { _ as loadGatewayModelCatalog } from "./http-utils-C2hu7rtC.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-D2XaZNiP.js";
51
+ import { n as timestampOptsFromConfig, t as injectTimestamp } from "./agent-timestamp-X705errr.js";
52
+ import { a as performGatewaySessionReset } from "./session-reset-service-C9rIVqF7.js";
53
+ import { t as applySessionsPatchToStore } from "./sessions-patch-BPtlF0Lu.js";
54
+ import { t as resolveGatewayInteractiveSurfaceAuth } from "./auth-surface-resolution-ur3TwQ2p.js";
55
+ import { n as TUI_SETUP_AUTH_SOURCE_ENV, t as TUI_SETUP_AUTH_SOURCE_CONFIG } from "./setup-launch-env-DcRVq6al.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 "@mariozechner/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", "docs.genesis.ai/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 };