@spacebar_ai/moldclaw-core 2026.3.14 → 2026.3.16

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 (1074) hide show
  1. package/README.md +108 -3
  2. package/dist/account-id-plS5L20e.d.ts +1 -0
  3. package/dist/accounts-BAYVGC2k.js +109 -0
  4. package/dist/accounts-DrjRgReV.d.ts +103 -0
  5. package/dist/acp-cli-at_UYEOS.js +2088 -0
  6. package/dist/acpx-Chy1GQ_k.d.ts +5 -0
  7. package/dist/actions.runtime-C0F7dMfO.js +114 -0
  8. package/dist/actions.runtime-caI2LG9o.js +128 -0
  9. package/dist/agent-media-payload-CkpAqaOh.d.ts +16 -0
  10. package/dist/agents-B98yPGc5.js +853 -0
  11. package/dist/agents-BrLr08L3.js +217 -0
  12. package/dist/allow-from-BIwT4dl7.d.ts +42 -0
  13. package/dist/allow-list-CHt7yvAf.js +81 -0
  14. package/dist/allowlist-CxQo2wQc.js +142 -0
  15. package/dist/allowlist-resolution-B7ib7gye.d.ts +17 -0
  16. package/dist/api-Co7TNHbL.js +6953 -0
  17. package/dist/api-cEQ_ql_8.js +112 -0
  18. package/dist/audit-AnKnnlaZ.js +787 -0
  19. package/dist/audit-channel.collect.runtime-CAk1DFQ3.js +600 -0
  20. package/dist/audit-channel.runtime-5phdZp_m.js +116 -0
  21. package/dist/audit-extra.async-B8ZXFxic.js +813 -0
  22. package/dist/audit-hdKa3D-u.js +54 -0
  23. package/dist/audit-membership-runtime-CJV5XvGU.js +157 -0
  24. package/dist/audit.deep.runtime-DNMcRQrp.js +24 -0
  25. package/dist/audit.nondeep.runtime-DhNDL6yM.js +831 -0
  26. package/dist/audit.runtime-Bx7uWEh8.js +113 -0
  27. package/dist/auth-choice-C37W9MA7.js +268 -0
  28. package/dist/auth-choice-CNppOY_V.js +117 -0
  29. package/dist/auth-choice-XYFnp6fI.js +502 -0
  30. package/dist/auth-choice-options-D6oZY4Xo.js +123 -0
  31. package/dist/auth-choice-prompt-BhRqchJx.js +110 -0
  32. package/dist/auth-choice-prompt-C1xv0N08.js +36 -0
  33. package/dist/auth-choice.plugin-providers.runtime-DhLEtbmR.js +114 -0
  34. package/dist/auth-profiles-9zZdaXJK.js +127756 -0
  35. package/dist/auth-profiles.runtime-HONFDgiu.js +111 -0
  36. package/dist/bluebubbles-BY8JhO4y.js +64 -0
  37. package/dist/bluebubbles-CQjEnzK_.d.ts +6 -0
  38. package/dist/bluebubbles-RmcKgkBa.d.ts +45 -0
  39. package/dist/boolean-param-F1sMwnPu.d.ts +5 -0
  40. package/dist/bot-BGh-ATV7.d.ts +478 -0
  41. package/dist/brave-CljenznH.js +24 -0
  42. package/dist/browser-cli-CX8i0wf0.js +1492 -0
  43. package/dist/build-info.json +3 -3
  44. package/dist/bundled/boot-md/handler.d.ts +6 -0
  45. package/dist/bundled/boot-md/handler.js +26 -26
  46. package/dist/bundled/bootstrap-extra-files/handler.d.ts +6 -0
  47. package/dist/bundled/command-logger/handler.d.ts +9 -0
  48. package/dist/bundled/session-memory/handler.d.ts +9 -0
  49. package/dist/bundled/session-memory/handler.js +27 -27
  50. package/dist/call-Bc257L16.js +37 -0
  51. package/dist/call-DYFR7oGy.js +639 -0
  52. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  53. package/dist/channel-Bd-igGEW.js +803 -0
  54. package/dist/channel-BgRMb6bZ.js +575 -0
  55. package/dist/channel-BtcLrU6J.js +1598 -0
  56. package/dist/channel-Bwf6m_hD.js +538 -0
  57. package/dist/channel-C7-kgDBd.js +562 -0
  58. package/dist/channel-CEXOAxIc.js +949 -0
  59. package/dist/channel-CpZ3p9MJ.js +226 -0
  60. package/dist/channel-CqBlN6A2.js +619 -0
  61. package/dist/channel-DKhfHW4U.js +352 -0
  62. package/dist/channel-DS3t_KdJ2.js +316 -0
  63. package/dist/channel-DY24FA1v.js +4681 -0
  64. package/dist/channel-DYFGmImJ.js +542 -0
  65. package/dist/channel-DcyIqX5p.js +207 -0
  66. package/dist/channel-J-2XcAli.js +214 -0
  67. package/dist/channel-N616f4gZ.js +306 -0
  68. package/dist/channel-NY7aU2Gj.js +397 -0
  69. package/dist/channel-PNI8BOmm.js +1321 -0
  70. package/dist/channel-UcXepDJs.js +943 -0
  71. package/dist/channel-account-context-CL3hEq1j.js +103 -0
  72. package/dist/channel-config-schema-Q2nzcCCR.d.ts +1 -0
  73. package/dist/channel-jA_jodJo.js +920 -0
  74. package/dist/channel-options-CtgU5qkG.js +50 -0
  75. package/dist/channel-policy-7wXDp6d3.d.ts +1 -0
  76. package/dist/channel-rGI8uig4.js +497 -0
  77. package/dist/channel-summary-DGJZXo0r.js +106 -0
  78. package/dist/channel.runtime--WZvlNJM.js +413 -0
  79. package/dist/channel.runtime-B0ct42DL.js +122 -0
  80. package/dist/channel.runtime-BEZUZrYB.js +177 -0
  81. package/dist/channel.runtime-BMuWmsIC.js +166 -0
  82. package/dist/channel.runtime-BtvHP0po.js +4006 -0
  83. package/dist/channel.runtime-Cwf993pX.js +194 -0
  84. package/dist/channel.runtime-Cy4lEpTX.js +174 -0
  85. package/dist/channel.runtime-DAz6axda.js +865 -0
  86. package/dist/channel.runtime-DdQ2mOVh.js +236 -0
  87. package/dist/channel.runtime-Dy3HPgOU.js +399 -0
  88. package/dist/channel.runtime-iqfC25k7.js +213 -0
  89. package/dist/channel.setup-B4VYMZlQ.js +9 -0
  90. package/dist/channel.setup-BohGbCbI.js +57 -0
  91. package/dist/channel.setup-Bq2AQqqc.js +6 -0
  92. package/dist/channel.setup-BxiSfLp1.js +8 -0
  93. package/dist/channel.setup-DOUS6fjO.js +8 -0
  94. package/dist/channel.setup-DXhdYU3g.js +9 -0
  95. package/dist/channel.setup-N51CgfNy.js +11 -0
  96. package/dist/channels/plugins/actions/discord.d.ts +3 -0
  97. package/dist/channels/plugins/actions/discord.js +26 -26
  98. package/dist/channels/plugins/actions/signal.d.ts +2 -0
  99. package/dist/channels/plugins/actions/signal.js +26 -26
  100. package/dist/channels/plugins/actions/telegram.d.ts +3 -0
  101. package/dist/channels/plugins/actions/telegram.js +26 -26
  102. package/dist/channels/plugins/agent-tools/whatsapp-login.d.ts +4 -0
  103. package/dist/channels/plugins/agent-tools/whatsapp-login.js +26 -26
  104. package/dist/channels-CueeFf0q.js +404 -0
  105. package/dist/channels-PheAd73E.js +1113 -0
  106. package/dist/channels-cli-CXzVF84v.js +286 -0
  107. package/dist/channels-status-issues-BjWBQHhU.js +16 -0
  108. package/dist/chat-type-BlSN0vo4.d.ts +5 -0
  109. package/dist/clawbot-cli-BBehDXW1.js +113 -0
  110. package/dist/cli/daemon-cli.d.ts +58 -0
  111. package/dist/cli/daemon-cli.js +1 -1
  112. package/dist/cli-CIm7d5Id.js +149 -0
  113. package/dist/command-format-pq3tS8t2.d.ts +4 -0
  114. package/dist/command-registry-CDkp__KH.js +13 -0
  115. package/dist/command-registry-DSEkUBW1.js +212 -0
  116. package/dist/command-secret-gateway-CqP_o0n8.js +106 -0
  117. package/dist/compact.runtime-Qm_csEtG.js +111 -0
  118. package/dist/completion-cli-Ch1sgSLQ.js +445 -0
  119. package/dist/completion-cli-vF067Tso.js +16 -0
  120. package/dist/config-B2W1zTP1.js +44 -0
  121. package/dist/config-CMhKplgO.js +938 -0
  122. package/dist/config-DchtRsvs.js +30 -0
  123. package/dist/config-cli-C41d88_c.js +428 -0
  124. package/dist/config-guard-B_vjkXCQ.js +117 -0
  125. package/dist/config-schema-pPBCF4hz.js +31 -0
  126. package/dist/config-validation-6om9cBUx.js +262 -0
  127. package/dist/config-value-Dl3XEpA6.js +132 -0
  128. package/dist/configure-BxzvDSzu.js +1100 -0
  129. package/dist/configure-CLMLoWAn.js +238 -0
  130. package/dist/control-ui-shared-E8Nz6uKZ.js +29 -0
  131. package/dist/core-Cd3fMFKq.d.ts +87 -0
  132. package/dist/credentials-yYt6VWCq.js +268 -0
  133. package/dist/cron-cli-CA3lV3kh.js +634 -0
  134. package/dist/daemon-cli-BtQuIXEk.js +339 -0
  135. package/dist/daemon-install-BWKGzgMm.js +175 -0
  136. package/dist/deliver-CgMNmfTy.js +106 -0
  137. package/dist/deliver-runtime-Bn1KWoiQ.js +106 -0
  138. package/dist/devices-cli-D601npiL.js +340 -0
  139. package/dist/diagnostic-CkiYEGqt.js +310 -0
  140. package/dist/diffs-B5tZ8Coj.d.ts +1 -0
  141. package/dist/directory-cli-skEV8MT7.js +306 -0
  142. package/dist/directory-config-helpers-B-tiBKIv.d.ts +38 -0
  143. package/dist/directory-runtime-BEJ2fCIR.d.ts +1 -0
  144. package/dist/directory.static-CnyzoWbV.js +44 -0
  145. package/dist/discord-B_gbzPti.js +109 -0
  146. package/dist/discovery-CqI-e_Mv.js +48 -0
  147. package/dist/dm-policy-shared-nybkS1uP.d.ts +95 -0
  148. package/dist/dns-cli-Cjes3Ruw.js +216 -0
  149. package/dist/docs-cli-C3g3Gi_d.js +173 -0
  150. package/dist/doctor-completion-TvgV4SZH.js +90 -0
  151. package/dist/doctor-config-flow-0w9Ux7V8.js +107 -0
  152. package/dist/doctor-config-flow-DLzr8W7Y.js +2437 -0
  153. package/dist/enable-VYzv8b2z.js +24 -0
  154. package/dist/entry.d.ts +7 -0
  155. package/dist/entry.js +1 -1
  156. package/dist/env-overrides-DYVIkuvN.js +434 -0
  157. package/dist/env-overrides.runtime-6kijpIuu.js +17 -0
  158. package/dist/exec-approvals-cli-D_lkTG-l.js +419 -0
  159. package/dist/exec-sVmouhA9.d.ts +39 -0
  160. package/dist/extensions/acpx/index.d.ts +11 -0
  161. package/dist/extensions/acpx/index.js +1 -1
  162. package/dist/extensions/amazon-bedrock/index.d.ts +11 -0
  163. package/dist/extensions/anthropic/index.d.ts +11 -0
  164. package/dist/extensions/anthropic/index.js +26 -26
  165. package/dist/extensions/bluebubbles/index.d.ts +11 -0
  166. package/dist/extensions/bluebubbles/index.js +30 -30
  167. package/dist/extensions/bluebubbles/setup-entry.d.ts +59 -0
  168. package/dist/extensions/bluebubbles/setup-entry.js +30 -30
  169. package/dist/extensions/brave/index.d.ts +11 -0
  170. package/dist/extensions/brave/index.js +2 -2
  171. package/dist/extensions/byteplus/index.d.ts +11 -0
  172. package/dist/extensions/byteplus/index.js +26 -26
  173. package/dist/extensions/cloudflare-ai-gateway/index.d.ts +11 -0
  174. package/dist/extensions/cloudflare-ai-gateway/index.js +27 -27
  175. package/dist/extensions/copilot-proxy/index.d.ts +11 -0
  176. package/dist/extensions/device-pair/index.d.ts +12 -0
  177. package/dist/extensions/diagnostics-otel/index.d.ts +11 -0
  178. package/dist/extensions/diffs/index.d.ts +11 -0
  179. package/dist/extensions/discord/index.d.ts +11 -0
  180. package/dist/extensions/discord/index.js +31 -31
  181. package/dist/extensions/discord/setup-entry.d.ts +7 -0
  182. package/dist/extensions/discord/setup-entry.js +29 -29
  183. package/dist/extensions/elevenlabs/index.d.ts +11 -0
  184. package/dist/extensions/elevenlabs/index.js +26 -26
  185. package/dist/extensions/feishu/index.d.ts +229 -0
  186. package/dist/extensions/feishu/index.js +31 -31
  187. package/dist/extensions/feishu/setup-entry.d.ts +9 -0
  188. package/dist/extensions/feishu/setup-entry.js +28 -28
  189. package/dist/extensions/firecrawl/index.d.ts +11 -0
  190. package/dist/extensions/firecrawl/index.js +26 -26
  191. package/dist/extensions/github-copilot/index.d.ts +11 -0
  192. package/dist/extensions/github-copilot/index.js +27 -27
  193. package/dist/extensions/google/index.d.ts +11 -0
  194. package/dist/extensions/google/index.js +26 -26
  195. package/dist/extensions/googlechat/index.d.ts +11 -0
  196. package/dist/extensions/googlechat/index.js +30 -30
  197. package/dist/extensions/googlechat/setup-entry.d.ts +19 -0
  198. package/dist/extensions/googlechat/setup-entry.js +30 -30
  199. package/dist/extensions/huggingface/index.d.ts +11 -0
  200. package/dist/extensions/huggingface/index.js +26 -26
  201. package/dist/extensions/imessage/index.d.ts +11 -0
  202. package/dist/extensions/imessage/index.js +30 -30
  203. package/dist/extensions/imessage/setup-entry.d.ts +7 -0
  204. package/dist/extensions/imessage/setup-entry.js +30 -30
  205. package/dist/extensions/irc/index.d.ts +11 -0
  206. package/dist/extensions/irc/index.js +29 -29
  207. package/dist/extensions/irc/setup-entry.d.ts +8 -0
  208. package/dist/extensions/irc/setup-entry.js +29 -29
  209. package/dist/extensions/kakao-talkchannel/index.d.ts +19 -0
  210. package/dist/extensions/kakao-talkchannel/index.js +1762 -0
  211. package/dist/extensions/kakao-talkchannel/moldclaw.plugin.json +111 -0
  212. package/dist/extensions/kakao-talkchannel/package.json +12 -0
  213. package/dist/extensions/kilocode/index.d.ts +11 -0
  214. package/dist/extensions/kilocode/index.js +26 -26
  215. package/dist/extensions/kimi-coding/index.d.ts +11 -0
  216. package/dist/extensions/kimi-coding/index.js +26 -26
  217. package/dist/extensions/line/index.d.ts +11 -0
  218. package/dist/extensions/line/index.js +28 -28
  219. package/dist/extensions/line/setup-entry.d.ts +7 -0
  220. package/dist/extensions/line/setup-entry.js +28 -28
  221. package/dist/extensions/llm-task/index.d.ts +11 -0
  222. package/dist/extensions/llm-task/index.js +28 -28
  223. package/dist/extensions/lobster/index.d.ts +11 -0
  224. package/dist/extensions/matrix/index.d.ts +11 -0
  225. package/dist/extensions/matrix/index.js +31 -31
  226. package/dist/extensions/matrix/setup-entry.d.ts +20 -0
  227. package/dist/extensions/matrix/setup-entry.js +31 -31
  228. package/dist/extensions/mattermost/index.d.ts +11 -0
  229. package/dist/extensions/mattermost/index.js +28 -28
  230. package/dist/extensions/mattermost/setup-entry.d.ts +88 -0
  231. package/dist/extensions/mattermost/setup-entry.js +28 -28
  232. package/dist/extensions/memory-core/index.d.ts +11 -0
  233. package/dist/extensions/memory-lancedb/index.d.ts +25 -0
  234. package/dist/extensions/microsoft/index.d.ts +11 -0
  235. package/dist/extensions/microsoft/index.js +26 -26
  236. package/dist/extensions/minimax/index.d.ts +11 -0
  237. package/dist/extensions/minimax/index.js +26 -26
  238. package/dist/extensions/mistral/index.d.ts +11 -0
  239. package/dist/extensions/mistral/index.js +26 -26
  240. package/dist/extensions/modelstudio/index.d.ts +11 -0
  241. package/dist/extensions/modelstudio/index.js +26 -26
  242. package/dist/extensions/moonshot/index.d.ts +11 -0
  243. package/dist/extensions/moonshot/index.js +26 -26
  244. package/dist/extensions/msteams/index.d.ts +11 -0
  245. package/dist/extensions/msteams/index.js +31 -31
  246. package/dist/extensions/msteams/setup-entry.d.ts +11 -0
  247. package/dist/extensions/msteams/setup-entry.js +31 -31
  248. package/dist/extensions/nextcloud-talk/index.d.ts +11 -0
  249. package/dist/extensions/nextcloud-talk/index.js +28 -28
  250. package/dist/extensions/nextcloud-talk/setup-entry.d.ts +60 -0
  251. package/dist/extensions/nextcloud-talk/setup-entry.js +28 -28
  252. package/dist/extensions/nostr/index.d.ts +11 -0
  253. package/dist/extensions/nostr/index.js +28 -28
  254. package/dist/extensions/nostr/setup-entry.d.ts +49 -0
  255. package/dist/extensions/nostr/setup-entry.js +28 -28
  256. package/dist/extensions/nvidia/index.d.ts +11 -0
  257. package/dist/extensions/ollama/index.d.ts +11 -0
  258. package/dist/extensions/open-prose/index.d.ts +11 -0
  259. package/dist/extensions/openai/index.d.ts +11 -0
  260. package/dist/extensions/openai/index.js +26 -26
  261. package/dist/extensions/opencode/index.d.ts +11 -0
  262. package/dist/extensions/opencode/index.js +26 -26
  263. package/dist/extensions/opencode-go/index.d.ts +11 -0
  264. package/dist/extensions/opencode-go/index.js +26 -26
  265. package/dist/extensions/openrouter/index.d.ts +11 -0
  266. package/dist/extensions/openrouter/index.js +26 -26
  267. package/dist/extensions/openshell/index.d.ts +11 -0
  268. package/dist/extensions/openshell/index.js +26 -26
  269. package/dist/extensions/perplexity/index.d.ts +11 -0
  270. package/dist/extensions/perplexity/index.js +2 -2
  271. package/dist/extensions/phone-control/index.d.ts +12 -0
  272. package/dist/extensions/qianfan/index.d.ts +11 -0
  273. package/dist/extensions/qianfan/index.js +26 -26
  274. package/dist/extensions/qwen-portal-auth/index.d.ts +12 -0
  275. package/dist/extensions/qwen-portal-auth/index.js +26 -26
  276. package/dist/extensions/sglang/index.d.ts +11 -0
  277. package/dist/extensions/sglang/index.js +26 -26
  278. package/dist/extensions/signal/index.d.ts +11 -0
  279. package/dist/extensions/signal/index.js +29 -29
  280. package/dist/extensions/signal/setup-entry.d.ts +7 -0
  281. package/dist/extensions/signal/setup-entry.js +29 -29
  282. package/dist/extensions/slack/index.d.ts +11 -0
  283. package/dist/extensions/slack/index.js +30 -30
  284. package/dist/extensions/slack/setup-entry.d.ts +7 -0
  285. package/dist/extensions/slack/setup-entry.js +29 -29
  286. package/dist/extensions/synology-chat/index.d.ts +11 -0
  287. package/dist/extensions/synology-chat/index.js +28 -28
  288. package/dist/extensions/synology-chat/setup-entry.d.ts +138 -0
  289. package/dist/extensions/synology-chat/setup-entry.js +28 -28
  290. package/dist/extensions/synthetic/index.d.ts +11 -0
  291. package/dist/extensions/synthetic/index.js +26 -26
  292. package/dist/extensions/talk-voice/index.d.ts +12 -0
  293. package/dist/extensions/talk-voice/index.js +26 -26
  294. package/dist/extensions/telegram/index.d.ts +11 -0
  295. package/dist/extensions/telegram/index.js +29 -29
  296. package/dist/extensions/telegram/setup-entry.d.ts +7 -0
  297. package/dist/extensions/telegram/setup-entry.js +28 -28
  298. package/dist/extensions/thread-ownership/index.d.ts +12 -0
  299. package/dist/extensions/tlon/index.d.ts +11 -0
  300. package/dist/extensions/tlon/index.js +28 -28
  301. package/dist/extensions/tlon/setup-entry.d.ts +7 -0
  302. package/dist/extensions/tlon/setup-entry.js +28 -28
  303. package/dist/extensions/together/index.d.ts +11 -0
  304. package/dist/extensions/together/index.js +26 -26
  305. package/dist/extensions/twitch/index.d.ts +39 -0
  306. package/dist/extensions/twitch/index.js +28 -28
  307. package/dist/extensions/venice/index.d.ts +11 -0
  308. package/dist/extensions/venice/index.js +26 -26
  309. package/dist/extensions/vercel-ai-gateway/index.d.ts +11 -0
  310. package/dist/extensions/vercel-ai-gateway/index.js +26 -26
  311. package/dist/extensions/vllm/index.d.ts +11 -0
  312. package/dist/extensions/vllm/index.js +26 -26
  313. package/dist/extensions/voice-call/index.d.ts +11 -0
  314. package/dist/extensions/voice-call/index.js +26 -26
  315. package/dist/extensions/volcengine/index.d.ts +11 -0
  316. package/dist/extensions/volcengine/index.js +26 -26
  317. package/dist/extensions/whatsapp/index.d.ts +11 -0
  318. package/dist/extensions/whatsapp/index.js +29 -29
  319. package/dist/extensions/whatsapp/setup-entry.d.ts +7 -0
  320. package/dist/extensions/whatsapp/setup-entry.js +29 -29
  321. package/dist/extensions/xai/index.d.ts +11 -0
  322. package/dist/extensions/xai/index.js +26 -26
  323. package/dist/extensions/xiaomi/index.d.ts +11 -0
  324. package/dist/extensions/xiaomi/index.js +26 -26
  325. package/dist/extensions/zai/index.d.ts +11 -0
  326. package/dist/extensions/zai/index.js +26 -26
  327. package/dist/extensions/zalo/index.d.ts +11 -0
  328. package/dist/extensions/zalo/index.js +30 -30
  329. package/dist/extensions/zalo/setup-entry.d.ts +34 -0
  330. package/dist/extensions/zalo/setup-entry.js +30 -30
  331. package/dist/extensions/zalouser/index.d.ts +11 -0
  332. package/dist/extensions/zalouser/index.js +31 -31
  333. package/dist/extensions/zalouser/setup-entry.d.ts +42 -0
  334. package/dist/extensions/zalouser/setup-entry.js +31 -31
  335. package/dist/feishu-DCKEC3ao.d.ts +36 -0
  336. package/dist/gateway-cli-DN1Ii6J-.js +26432 -0
  337. package/dist/gateway-install-token-CJYFJBaC.js +163 -0
  338. package/dist/gateway-rpc-CroQg9MB.js +26 -0
  339. package/dist/gateway-runtime-D9FRZqKP.js +69 -0
  340. package/dist/googlechat-CBCkerAy.js +307 -0
  341. package/dist/googlechat-CSUNieHX.d.ts +12 -0
  342. package/dist/group-access-rSvkIglb.d.ts +61 -0
  343. package/dist/health-B6WwLJp4.js +570 -0
  344. package/dist/health-CAlJydXv.js +108 -0
  345. package/dist/history-BwNxb0sJ.d.ts +75 -0
  346. package/dist/hooks-BYlfU3Nf.d.ts +6 -0
  347. package/dist/hooks-cli-DuKmdo_H.js +995 -0
  348. package/dist/http-registry-DX_LVtuK.d.ts +20 -0
  349. package/dist/image-generation-DKkdRpve.d.ts +9 -0
  350. package/dist/imessage-7abjbe2Q.js +31 -0
  351. package/dist/imessage-DOH1yaDE.js +110 -0
  352. package/dist/inbound-envelope-CmvweL6U.d.ts +78 -0
  353. package/dist/inbound-reply-dispatch-BvnKTOec.js +71 -0
  354. package/dist/inbound-reply-dispatch-C7LjHRZN.d.ts +72 -0
  355. package/dist/index-DTQqfqj9.d.ts +1 -0
  356. package/dist/index.d.ts +27 -0
  357. package/dist/index.js +2 -2
  358. package/dist/infra/warning-filter.d.ts +10 -0
  359. package/dist/install-target-tXRD7VkM.js +574 -0
  360. package/dist/installs-C8fz8sm3.js +532 -0
  361. package/dist/io-C6XifaT4.js +9737 -0
  362. package/dist/io-C8awRnSW.js +28 -0
  363. package/dist/ipv4-d88_Jn2p.js +82 -0
  364. package/dist/irc-DpR6FXjN.js +672 -0
  365. package/dist/json-store-Sr_kk-II.d.ts +14 -0
  366. package/dist/keyed-async-queue-BA3BKukE.d.ts +19 -0
  367. package/dist/library-DOwowAGN.js +107 -0
  368. package/dist/lifecycle-core-BHHBoRTY.js +382 -0
  369. package/dist/line/accounts.d.ts +3 -0
  370. package/dist/line/send.d.ts +2 -0
  371. package/dist/line/send.js +4 -4
  372. package/dist/line/template-messages.d.ts +2 -0
  373. package/dist/line-8rsNbJCP.js +530 -0
  374. package/dist/line-D_cvIf6B.d.ts +75 -0
  375. package/dist/links-BOnvOj1z.d.ts +7 -0
  376. package/dist/llm-slug-generator-D9HjWtJT.js +67 -0
  377. package/dist/llm-slug-generator.d.ts +12 -0
  378. package/dist/llm-slug-generator.js +27 -27
  379. package/dist/logging-BhqLWxTD.js +13 -0
  380. package/dist/logging-DfaiL4OX.js +29 -0
  381. package/dist/login-qr-COBYR52w.js +233 -0
  382. package/dist/login-qr-xK4QIpPc.js +107 -0
  383. package/dist/logs-cli-RSSTw8L_.js +254 -0
  384. package/dist/manager-runtime-DL6JoSj9.js +106 -0
  385. package/dist/manager.runtime-Cbyhg1vB.js +710 -0
  386. package/dist/markdown-to-line-BTlEkOls.d.ts +91 -0
  387. package/dist/matrix-DX-jaB88.js +1490 -0
  388. package/dist/matrix-H6Yyj1QZ.d.ts +68 -0
  389. package/dist/matrix-J8s45tRw.js +1269 -0
  390. package/dist/mattermost-D75n6bRI.d.ts +6 -0
  391. package/dist/mcp-cli-CLc3_yCO.js +86 -0
  392. package/dist/media-understanding.runtime-BI0Lljbl.js +111 -0
  393. package/dist/memory-cli-CTp2cYrf.js +106 -0
  394. package/dist/method-scopes-Du8ODGFW.js +2586 -0
  395. package/dist/model-auth-markers-DEDakSUW.d.ts +20 -0
  396. package/dist/model-picker-CDBs7LJF.js +390 -0
  397. package/dist/model-picker-CRix4Wwv.js +107 -0
  398. package/dist/model-picker.runtime-CITyy3Rn.js +120 -0
  399. package/dist/model-suppression.runtime-Ce7D6QUT.js +111 -0
  400. package/dist/models-BK1eanuP.js +113 -0
  401. package/dist/models-X4Czy3uE.js +2514 -0
  402. package/dist/models-cli-C79Ulviy.js +304 -0
  403. package/dist/models-config-DALlu3S9.js +106 -0
  404. package/dist/models-config.providers.discovery-CSJ1STM1.d.ts +18 -0
  405. package/dist/monitor-B45a_RpX.js +3468 -0
  406. package/dist/monitor-C8KbJ-i0.js +767 -0
  407. package/dist/monitor-CIhrvegZ.js +3076 -0
  408. package/dist/monitor-CQut7klP.js +6823 -0
  409. package/dist/monitor-DZb5IJle.js +777 -0
  410. package/dist/monitor-DaFkdD27.js +108 -0
  411. package/dist/monitor-Do9Tp2Ii.js +110 -0
  412. package/dist/monitor-shared-CMK9cDOb.js +444 -0
  413. package/dist/msteams-A6H_wv5F.js +852 -0
  414. package/dist/net-DpMJgN-o.d.ts +19 -0
  415. package/dist/nextcloud-talk-f1pZ5Bge.d.ts +1 -0
  416. package/dist/node-cli-BXnmsjzL.js +2498 -0
  417. package/dist/node-resolve-CupmrA0Y.js +835 -0
  418. package/dist/nodes-cli-DZVrah_8.js +1375 -0
  419. package/dist/nostr-DMV534Ks.d.ts +7 -0
  420. package/dist/nostr-SAk3tjtR.js +8744 -0
  421. package/dist/npm-resolution-Dr9wssCY.js +60 -0
  422. package/dist/oauth-utils-DnyXdWU9.d.ts +10 -0
  423. package/dist/onboard-BE5pmb1g.js +589 -0
  424. package/dist/onboard-channels-3hNVY0E7.js +1241 -0
  425. package/dist/onboard-channels-vaO3nWLL.js +200 -0
  426. package/dist/onboard-custom-CI5uFyWH.js +571 -0
  427. package/dist/onboard-custom-eIvRswgv.js +109 -0
  428. package/dist/onboard-helpers-ChMWfUnl.js +335 -0
  429. package/dist/onboard-helpers-DRFi9oaD.js +108 -0
  430. package/dist/onboard-remote-BTspTgA4.js +112 -0
  431. package/dist/onboard-remote-so38yXlX.js +181 -0
  432. package/dist/onboard-search-DS0tZS24.js +297 -0
  433. package/dist/onboard-skills-B9DxCCiU.js +133 -0
  434. package/dist/onboard-skills-so0a_BJV.js +112 -0
  435. package/dist/outbound-media-BiJscGlR.js +11 -0
  436. package/dist/outbound-media-DJF-TuJu.d.ts +11 -0
  437. package/dist/pairing-access-CuiJP9xN.d.ts +21 -0
  438. package/dist/pairing-cli-DN0u1Cez.js +212 -0
  439. package/dist/parse-finite-number-B3FJTjyQ.d.ts +5 -0
  440. package/dist/perplexity-Bw1u3CAF.js +24 -0
  441. package/dist/persistent-dedupe-DR5Ka6BX.d.ts +26 -0
  442. package/dist/pi-model-discovery-runtime-iwKNCaYu.js +106 -0
  443. package/dist/pi-tools.before-tool-call.runtime-BM_N-JZe.js +380 -0
  444. package/dist/plugin-install--KVul05Z.js +184 -0
  445. package/dist/plugin-install-DVpPsLkS.js +112 -0
  446. package/dist/plugin-install-plan-Dwc6-coz.js +49 -0
  447. package/dist/plugin-registry-XRswugE9.js +108 -0
  448. package/dist/plugin-registry-jozQafRo.js +49 -0
  449. package/dist/plugin-sdk/account-resolution.js +26 -26
  450. package/dist/plugin-sdk/acp-runtime.js +26 -26
  451. package/dist/plugin-sdk/acpx.js +1 -1
  452. package/dist/plugin-sdk/agent-runtime.js +26 -26
  453. package/dist/plugin-sdk/bluebubbles.js +29 -29
  454. package/dist/plugin-sdk/channel-config-helpers.js +26 -26
  455. package/dist/plugin-sdk/channel-config-schema.js +2 -2
  456. package/dist/plugin-sdk/channel-policy.js +26 -26
  457. package/dist/plugin-sdk/channel-runtime.js +26 -26
  458. package/dist/plugin-sdk/compat.js +27 -27
  459. package/dist/plugin-sdk/config-runtime.js +28 -28
  460. package/dist/plugin-sdk/conversation-runtime.js +26 -26
  461. package/dist/plugin-sdk/discord.js +26 -26
  462. package/dist/plugin-sdk/feishu.js +27 -27
  463. package/dist/plugin-sdk/gateway-runtime.js +8 -8
  464. package/dist/plugin-sdk/googlechat.js +29 -29
  465. package/dist/plugin-sdk/image-generation-runtime.js +26 -26
  466. package/dist/plugin-sdk/image-generation.js +26 -26
  467. package/dist/plugin-sdk/imessage.js +27 -27
  468. package/dist/plugin-sdk/index.js +26 -26
  469. package/dist/plugin-sdk/infra-runtime.js +26 -26
  470. package/dist/plugin-sdk/irc.js +29 -29
  471. package/dist/plugin-sdk/line.js +27 -27
  472. package/dist/plugin-sdk/llm-task.js +26 -26
  473. package/dist/plugin-sdk/matrix.js +29 -29
  474. package/dist/plugin-sdk/mattermost.js +28 -28
  475. package/dist/plugin-sdk/media-runtime.js +26 -26
  476. package/dist/plugin-sdk/media-understanding-runtime.js +26 -26
  477. package/dist/plugin-sdk/media-understanding.js +26 -26
  478. package/dist/plugin-sdk/msteams.js +30 -30
  479. package/dist/plugin-sdk/nextcloud-talk.js +28 -28
  480. package/dist/plugin-sdk/nostr.js +27 -27
  481. package/dist/plugin-sdk/plugin-runtime.js +26 -26
  482. package/dist/plugin-sdk/provider-auth.js +28 -28
  483. package/dist/plugin-sdk/provider-setup.js +27 -27
  484. package/dist/plugin-sdk/provider-web-search.js +1 -1
  485. package/dist/plugin-sdk/qwen-portal-auth.js +26 -26
  486. package/dist/plugin-sdk/reply-history.js +26 -26
  487. package/dist/plugin-sdk/reply-runtime.js +26 -26
  488. package/dist/plugin-sdk/sandbox.js +26 -26
  489. package/dist/plugin-sdk/security-runtime.js +26 -26
  490. package/dist/plugin-sdk/self-hosted-provider-setup.js +27 -27
  491. package/dist/plugin-sdk/setup.js +27 -27
  492. package/dist/plugin-sdk/signal.js +26 -26
  493. package/dist/plugin-sdk/slack.js +26 -26
  494. package/dist/plugin-sdk/speech-runtime.js +26 -26
  495. package/dist/plugin-sdk/speech.js +26 -26
  496. package/dist/plugin-sdk/src/channels/plugins/setup-wizard-helpers.d.ts +3 -0
  497. package/dist/plugin-sdk/src/config/config-lock.d.ts +38 -0
  498. package/dist/plugin-sdk/src/config/config.d.ts +1 -1
  499. package/dist/plugin-sdk/src/config/io.d.ts +39 -0
  500. package/dist/plugin-sdk/src/config/types.gateway.d.ts +12 -0
  501. package/dist/plugin-sdk/src/config/types.secrets.d.ts +10 -0
  502. package/dist/plugin-sdk/src/config/zod-schema.d.ts +2 -0
  503. package/dist/plugin-sdk/src/gateway/credential-planner.d.ts +3 -1
  504. package/dist/plugin-sdk/src/secrets/provider-env-vars.d.ts +61 -0
  505. package/dist/plugin-sdk/src/secrets/sec1-placeholder.d.ts +181 -0
  506. package/dist/plugin-sdk/src/secrets/sec1-utils.d.ts +57 -0
  507. package/dist/plugin-sdk/synology-chat.js +27 -27
  508. package/dist/plugin-sdk/telegram.js +26 -26
  509. package/dist/plugin-sdk/text-runtime.js +4 -4
  510. package/dist/plugin-sdk/tlon.js +27 -27
  511. package/dist/plugin-sdk/twitch.js +26 -26
  512. package/dist/plugin-sdk/voice-call.js +26 -26
  513. package/dist/plugin-sdk/whatsapp.js +26 -26
  514. package/dist/plugin-sdk/zalo.js +30 -30
  515. package/dist/plugin-sdk/zalouser.js +29 -29
  516. package/dist/plugins/runtime/index.d.ts +22 -0
  517. package/dist/plugins/runtime/index.js +26 -26
  518. package/dist/plugins-C4PiDdjc.js +106 -0
  519. package/dist/plugins-cli-zhmliYNU.js +912 -0
  520. package/dist/policy-CcSolumc.js +143 -0
  521. package/dist/preflight-audio.runtime-BAbfqqzW.js +111 -0
  522. package/dist/probe-Bgt5c-cr.js +129 -0
  523. package/dist/probe-CPk5iGcg.js +47 -0
  524. package/dist/probe-DR4KRKXz.js +19 -0
  525. package/dist/probe-DnoCyJ_m.js +1793 -0
  526. package/dist/probe-VsLtK3vQ.js +6328 -0
  527. package/dist/probe-auth-BnsKrQt7.js +38 -0
  528. package/dist/probe-auth-DYdUG8l1.js +48 -0
  529. package/dist/program-8enYYBsc.js +247 -0
  530. package/dist/prompt-select-styled-DxBcUasv.js +2673 -0
  531. package/dist/provider-api-key-auth.runtime-DsLZyt6h.js +116 -0
  532. package/dist/provider-auth-choice-30EvRxqc.js +126 -0
  533. package/dist/provider-auth-choice-preference-DMr1WmRg.js +189 -0
  534. package/dist/provider-auth-choice.runtime-CI98BgQF.js +118 -0
  535. package/dist/provider-auth-guidance-WKDIi_wk.js +34 -0
  536. package/dist/provider-auth-result-Cs8wguSI.d.ts +18 -0
  537. package/dist/provider-models-EOys_Nvi.d.ts +867 -0
  538. package/dist/provider-ollama-setup-D89zlm9C.d.ts +32 -0
  539. package/dist/provider-onboard-BzOpgCLu.d.ts +40 -0
  540. package/dist/provider-runtime.runtime-Cm4as2KG.js +106 -0
  541. package/dist/provider-self-hosted-setup-Bmv_AQmw.d.ts +61 -0
  542. package/dist/provider-self-hosted-setup-CJwFVVB4.js +182 -0
  543. package/dist/provider-usage-CVNyLLDb.js +106 -0
  544. package/dist/provider-usage.types-CdTymHNu.d.ts +16 -0
  545. package/dist/provider-web-search-BJhXD5dH.js +2392 -0
  546. package/dist/provider-wizard-DMMYXjlW.js +152 -0
  547. package/dist/push-apns-BnWTdTEk.js +1038 -0
  548. package/dist/pw-ai-CtK_7Cy2.js +1866 -0
  549. package/dist/qr-cli-CA-BF0--.js +108 -0
  550. package/dist/qr-cli-D18HiUkh.js +369 -0
  551. package/dist/reactions-Df7XG8Uh.js +281 -0
  552. package/dist/read-only-account-inspect.discord.runtime-B-FP0mwb.js +111 -0
  553. package/dist/read-only-account-inspect.slack.runtime-DkWZ2ccW.js +111 -0
  554. package/dist/read-only-account-inspect.telegram.runtime-BnlTkn_e.js +111 -0
  555. package/dist/redact-snapshot-DVdstBvO.js +2661 -0
  556. package/dist/ref-contract-RPkB754Q.js +53 -0
  557. package/dist/register.agent-DVAxXQKW.js +434 -0
  558. package/dist/register.backup-CUuL5KUZ.js +624 -0
  559. package/dist/register.configure-bC0UEwfU.js +247 -0
  560. package/dist/register.maintenance-iIqvl_eT.js +569 -0
  561. package/dist/register.message-CEDd4z07.js +704 -0
  562. package/dist/register.onboard-Cejfnysy.js +187 -0
  563. package/dist/register.setup-DU7uHdYt.js +207 -0
  564. package/dist/register.status-health-sessions-BWphMXNR.js +493 -0
  565. package/dist/register.subclis-DnIweTEG.js +315 -0
  566. package/dist/register.subclis-gJX_Pbub.js +12 -0
  567. package/dist/registry-Dgwc-7eS.js +1183 -0
  568. package/dist/replies-D9PEZ8yn.js +110 -0
  569. package/dist/reply-history-lHgoC4l3.d.ts +1 -0
  570. package/dist/reply-payload-Bd2HuR4g.d.ts +46 -0
  571. package/dist/request-url-BcSJaiiu.d.ts +5 -0
  572. package/dist/resolve-BbsCHGLY.js +660 -0
  573. package/dist/resolve-channels-BtrGC95o.js +262 -0
  574. package/dist/resolve-channels-C1SthO1N.js +226 -0
  575. package/dist/resolve-users-CgSxHrU0.js +143 -0
  576. package/dist/routes-BZtqNrBf.js +7097 -0
  577. package/dist/rpc-D3KMxG4J.js +67 -0
  578. package/dist/run-command-C8b3dCZV.d.ts +16 -0
  579. package/dist/run-main-BlWJVotF.js +423 -0
  580. package/dist/runtime-RWGbO5Qy.d.ts +26 -0
  581. package/dist/runtime-discord-ops.runtime-DUXIYvQr.js +9073 -0
  582. package/dist/runtime-slack-ops.runtime-n1yFfyp1.js +4551 -0
  583. package/dist/runtime-telegram-ops.runtime-PZUWchjT.js +128 -0
  584. package/dist/runtime-whatsapp-login.runtime-xsuNyvGz.js +109 -0
  585. package/dist/runtime-whatsapp-outbound.runtime-5EfEyCsO.js +112 -0
  586. package/dist/sandbox-cli-Dw1nWNmQ.js +530 -0
  587. package/dist/search-manager-BJoRxOaf.js +15 -0
  588. package/dist/search-manager-DxkQvUrW.js +386 -0
  589. package/dist/secret-input-schema-Cp_La9qv.d.ts +19 -0
  590. package/dist/secrets-cli-BPyV2gSq.js +2065 -0
  591. package/dist/security-cli-EK4sSRfG.js +570 -0
  592. package/dist/send-B01Gvh9m.js +629 -0
  593. package/dist/send-B4L4wRJO.js +100 -0
  594. package/dist/send-BDcGrXt0.js +1025 -0
  595. package/dist/send-BRRtHxyR.js +283 -0
  596. package/dist/send-DU6dmMXW.js +631 -0
  597. package/dist/server-CWw5GFEg.js +106 -0
  598. package/dist/server-node-events-92cDVswC.js +501 -0
  599. package/dist/session-key-DbkfhOjM.d.ts +46 -0
  600. package/dist/sessions-B052uHA3.js +218 -0
  601. package/dist/sessions-Cef4dZNP.js +107 -0
  602. package/dist/setup-BlQPyDPy.js +387 -0
  603. package/dist/setup-DcSZ_pTn.d.ts +37 -0
  604. package/dist/setup-core-B9mdZYnU.js +166 -0
  605. package/dist/setup-core-Cj0sLkpP.js +47 -0
  606. package/dist/setup-core-CkZbebOv.js +143 -0
  607. package/dist/setup-core-MRNjnrJl.js +205 -0
  608. package/dist/setup-surface-3ZY0JtWE.js +490 -0
  609. package/dist/setup-wizard-helpers-Dwzb9Dcz.d.ts +203 -0
  610. package/dist/setup.finalize-B5ETm3Ui.js +517 -0
  611. package/dist/setup.gateway-config-C8hdtlbw.js +338 -0
  612. package/dist/setup.secret-input-BZSIeiqy.js +25 -0
  613. package/dist/shared--9_eQ_lc.js +75 -0
  614. package/dist/shared-CxkH3H0U.js +102 -0
  615. package/dist/shared-DTNL0hA9.js +298 -0
  616. package/dist/shared-HSP1OV-Q.js +96 -0
  617. package/dist/shared-UIjWb_3B.js +182 -0
  618. package/dist/signal-CTI6bSmB.js +109 -0
  619. package/dist/skills-4-r1mfJM.js +853 -0
  620. package/dist/skills-RNm54CBO.js +19 -0
  621. package/dist/skills-cli-te7dSs5p.js +291 -0
  622. package/dist/skills-install-Del-Ogv8.js +763 -0
  623. package/dist/skills-status-BZpoMXrR.js +169 -0
  624. package/dist/skills-status-Dq61Sz8U.js +20 -0
  625. package/dist/slack-oc-viUtl.js +109 -0
  626. package/dist/slash-commands.runtime-NdkD2LZV.js +123 -0
  627. package/dist/slash-dispatch.runtime-DQgeaF3J.js +136 -0
  628. package/dist/slash-skill-commands.runtime-DmOl2DnL.js +111 -0
  629. package/dist/src-0wtt7seR.js +1696 -0
  630. package/dist/status-5oR_gqv_.js +121 -0
  631. package/dist/status-BO8LY0hC.js +1599 -0
  632. package/dist/status-D_oHA9yO.js +126 -0
  633. package/dist/status-IrMacJRj.js +606 -0
  634. package/dist/status-Prdeg53E.js +43 -0
  635. package/dist/status-json-Da0hR-1Z.js +286 -0
  636. package/dist/status.link-channel-BgUJEZAz.js +138 -0
  637. package/dist/status.scan.deps.runtime-D9vHTxOW.js +121 -0
  638. package/dist/status.scan.runtime-D-EdD5CW.js +114 -0
  639. package/dist/status.summary--i6xduWH.js +592 -0
  640. package/dist/status.summary.runtime-BqMXjaBc.js +113 -0
  641. package/dist/subagent-orphan-recovery-DiRJcFQc.js +302 -0
  642. package/dist/subagent-registry-runtime-B66EYEYm.js +106 -0
  643. package/dist/synology-chat-BemXqdzG.js +297 -0
  644. package/dist/system-cli-CSuiia4-.js +92 -0
  645. package/dist/telegram/audit.d.ts +2 -0
  646. package/dist/telegram/audit.js +1 -1
  647. package/dist/telegram/token.d.ts +2 -0
  648. package/dist/telegram/token.js +26 -26
  649. package/dist/telegram-DLFcRv5a.js +109 -0
  650. package/dist/testing-DZrulv-n.d.ts +1755 -0
  651. package/dist/text-chunking-BaYBIUoR.d.ts +79 -0
  652. package/dist/text-chunking-C8kmbNfa.js +84 -0
  653. package/dist/thinking-D8aqmr3o.d.ts +13 -0
  654. package/dist/tlon-Bpr4f3yF.js +433 -0
  655. package/dist/tool-send-BHKm5ztm.d.ts +9 -0
  656. package/dist/tui-BY3QRgC1.js +3834 -0
  657. package/dist/tui-cli-CCfZOlV0.js +132 -0
  658. package/dist/types-CKx5nDZB.d.ts +45 -0
  659. package/dist/types-DBhDdMQd.d.ts +22670 -0
  660. package/dist/types.base-B_TkkSS8.d.ts +188 -0
  661. package/dist/types.secrets-Bojc4omL.js +92 -0
  662. package/dist/ui-1UpZZyI3.js +31 -0
  663. package/dist/update-BR4JvFpV.js +1036 -0
  664. package/dist/update-cli-BZv44lFq.js +1498 -0
  665. package/dist/update-offset-store-DGdBotIW.js +107 -0
  666. package/dist/update-runner-D34sooPe.js +1496 -0
  667. package/dist/vllm-defaults-BCGSJ7K0.d.ts +13 -0
  668. package/dist/wait-BU9vJv22.d.ts +4 -0
  669. package/dist/web-CXpU2D41.js +107 -0
  670. package/dist/web-shared-B4sL45ah.d.ts +45 -0
  671. package/dist/webhook-memory-guards-B7oLVseG.d.ts +43 -0
  672. package/dist/webhook-request-guards-CqIH7equ.d.ts +76 -0
  673. package/dist/webhook-targets-CAAGATtk.js +181 -0
  674. package/dist/webhook-targets-oQ0jd4r0.d.ts +106 -0
  675. package/dist/webhooks-cli-B46t2VT5.js +349 -0
  676. package/dist/whatsapp-Dniwd4Rv.js +109 -0
  677. package/dist/whatsapp-actions-fL46PsNs.js +162 -0
  678. package/dist/windows-spawn-DGeE98SH.d.ts +43 -0
  679. package/dist/workspace-dirs-d3Ms_ryk.js +2002 -0
  680. package/dist/zalo-Csulx0XK.d.ts +9 -0
  681. package/dist/zalo-gh0yAWmS.js +415 -0
  682. package/dist/zalouser-CuxRvztM.js +30911 -0
  683. package/dist/zod-schema.agent-runtime-B4MkB-_3.d.ts +10 -0
  684. package/dist/zod-schema.core-D5reNip6.js +541 -0
  685. package/dist/zod-schema.core-DN3RhEUG.d.ts +173 -0
  686. package/docs/SEC1.md +523 -0
  687. package/docs/SEC1_IMPLEMENTATION/CHANNELS_REPORT.md +173 -0
  688. package/docs/SEC1_IMPLEMENTATION/CORE_UTIL_REPORT.md +139 -0
  689. package/docs/SEC1_IMPLEMENTATION/DOCS_REPORT.md +134 -0
  690. package/docs/SEC1_IMPLEMENTATION/ENV_MAP_DRAFT.md +148 -0
  691. package/docs/SEC1_IMPLEMENTATION/INTEGRATION_REPORT.md +170 -0
  692. package/docs/SEC1_IMPLEMENTATION/PROVIDERS_REPORT.md +291 -0
  693. package/docs/SEC1_IMPLEMENTATION/QA_REPORT.md +249 -0
  694. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave1-channels.md +317 -0
  695. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave1-docs.md +212 -0
  696. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave1-security.md +368 -0
  697. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave2-critic-consolidated.md +195 -0
  698. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave3-fix-report.md +105 -0
  699. package/docs/SEC1_IMPLEMENTATION/STRATEGY.md +451 -0
  700. package/docs/SEC1_IMPLEMENTATION/TEST_REPORT.md +156 -0
  701. package/docs/pipeline-sdk/CLI_SPEC.md +609 -0
  702. package/docs/pipeline-sdk/PIPELINE_SDK_DESIGN.md +1372 -0
  703. package/extensions/kakao-talkchannel/MIGRATION_ARCH_ANALYSIS.md +455 -0
  704. package/extensions/kakao-talkchannel/MIGRATION_CODE_ANALYSIS.md +383 -0
  705. package/extensions/kakao-talkchannel/MIGRATION_STRATEGY.md +115 -0
  706. package/extensions/kakao-talkchannel/README.md +50 -0
  707. package/extensions/kakao-talkchannel/index.ts +20 -0
  708. package/extensions/kakao-talkchannel/moldclaw.plugin.json +98 -0
  709. package/extensions/kakao-talkchannel/package.json +12 -0
  710. package/extensions/kakao-talkchannel/src/adapters/config.ts +132 -0
  711. package/extensions/kakao-talkchannel/src/adapters/gateway.ts +974 -0
  712. package/extensions/kakao-talkchannel/src/adapters/outbound.ts +52 -0
  713. package/extensions/kakao-talkchannel/src/adapters/pairing.ts +35 -0
  714. package/extensions/kakao-talkchannel/src/adapters/security.ts +57 -0
  715. package/extensions/kakao-talkchannel/src/adapters/setup.ts +105 -0
  716. package/extensions/kakao-talkchannel/src/adapters/status.ts +117 -0
  717. package/extensions/kakao-talkchannel/src/channel.ts +58 -0
  718. package/extensions/kakao-talkchannel/src/commands/card.ts +413 -0
  719. package/extensions/kakao-talkchannel/src/config/schema.ts +129 -0
  720. package/extensions/kakao-talkchannel/src/kakao/callback.ts +133 -0
  721. package/extensions/kakao-talkchannel/src/kakao/limits.ts +129 -0
  722. package/extensions/kakao-talkchannel/src/kakao/payload.ts +138 -0
  723. package/extensions/kakao-talkchannel/src/kakao/response.ts +373 -0
  724. package/extensions/kakao-talkchannel/src/relay/client.ts +146 -0
  725. package/extensions/kakao-talkchannel/src/relay/session.ts +137 -0
  726. package/extensions/kakao-talkchannel/src/relay/sse.ts +258 -0
  727. package/extensions/kakao-talkchannel/src/relay/stream.ts +149 -0
  728. package/extensions/kakao-talkchannel/src/runtime.ts +21 -0
  729. package/extensions/kakao-talkchannel/src/types.ts +447 -0
  730. package/extensions/kakao-talkchannel/src/version.ts +3 -0
  731. package/extensions/kakao-talkchannel/tsconfig.json +19 -0
  732. package/package.json +23 -8
  733. package/skills/meshy/SKILL.md +69 -0
  734. package/skills/meshy/scripts/__pycache__/check_status.cpython-312.pyc +0 -0
  735. package/skills/meshy/scripts/__pycache__/image_to_3d.cpython-312.pyc +0 -0
  736. package/skills/meshy/scripts/__pycache__/text_to_3d.cpython-312.pyc +0 -0
  737. package/skills/meshy/scripts/check_status.py +147 -0
  738. package/skills/meshy/scripts/image_to_3d.py +229 -0
  739. package/skills/meshy/scripts/text_to_3d.py +214 -0
  740. package/skills/nano-banana-pro/scripts/generate_image.py +1 -1
  741. package/skills/openai-whisper-api/scripts/transcribe.sh +0 -0
  742. package/skills/tavily-search/SKILL.md +61 -0
  743. package/skills/tavily-search/scripts/__pycache__/search.cpython-312.pyc +0 -0
  744. package/skills/tavily-search/scripts/search.py +238 -0
  745. package/skills/video-frames/scripts/frame.sh +0 -0
  746. package/LICENSE +0 -21
  747. package/dist/accounts-UcSvD34O.js +0 -109
  748. package/dist/acp-cli-BPb8PgHP.js +0 -2088
  749. package/dist/actions.runtime-BL5QRooG.js +0 -114
  750. package/dist/actions.runtime-DSdfSo40.js +0 -128
  751. package/dist/agents-CHeX_5-H.js +0 -217
  752. package/dist/agents-DQRL9XKP.js +0 -853
  753. package/dist/allow-list-Boi79v-U.js +0 -81
  754. package/dist/allowlist-B2eBBeMF.js +0 -142
  755. package/dist/api-CFAtRSYL.js +0 -6953
  756. package/dist/api-D5JNJj8n.js +0 -112
  757. package/dist/audit-BM0GsdzV.js +0 -787
  758. package/dist/audit-BqRK9OSj.js +0 -54
  759. package/dist/audit-channel.collect.runtime-BPvDB8aq.js +0 -600
  760. package/dist/audit-channel.runtime-D3fzHiAo.js +0 -116
  761. package/dist/audit-extra.async-NveNIzX0.js +0 -813
  762. package/dist/audit-membership-runtime-mu470WFO.js +0 -157
  763. package/dist/audit.deep.runtime-RdxvW8Tj.js +0 -24
  764. package/dist/audit.nondeep.runtime-DDu8vA9Z.js +0 -831
  765. package/dist/audit.runtime-Y8C9W7s9.js +0 -113
  766. package/dist/auth-choice-C1CIxRsi.js +0 -268
  767. package/dist/auth-choice-CTvqWiDI.js +0 -117
  768. package/dist/auth-choice-Ddzko1B8.js +0 -502
  769. package/dist/auth-choice-options-BIAmAiCe.js +0 -123
  770. package/dist/auth-choice-prompt-B815kArz.js +0 -110
  771. package/dist/auth-choice-prompt-CGhTNCJx.js +0 -36
  772. package/dist/auth-choice.plugin-providers.runtime-AvAZ6S5W.js +0 -114
  773. package/dist/auth-profiles-BJcHzwPy.js +0 -127650
  774. package/dist/auth-profiles.runtime-CieFilK5.js +0 -111
  775. package/dist/bluebubbles-F8FGE9cH.js +0 -64
  776. package/dist/brave-BG5Yopn8.js +0 -24
  777. package/dist/browser-cli-Co7PJGZF.js +0 -1492
  778. package/dist/call-CoaQYq7c.js +0 -639
  779. package/dist/call-D3eu5Jjh.js +0 -37
  780. package/dist/channel-BftWD6yu.js +0 -1321
  781. package/dist/channel-Bub9U5Xg.js +0 -214
  782. package/dist/channel-C0oDs7TO.js +0 -4681
  783. package/dist/channel-C8CnEdkZ.js +0 -352
  784. package/dist/channel-CI-RC-xf.js +0 -497
  785. package/dist/channel-CY-hZCOJ.js +0 -397
  786. package/dist/channel-CbtGJB2x.js +0 -943
  787. package/dist/channel-CcfK3wP8.js +0 -803
  788. package/dist/channel-DBoDIeVj.js +0 -619
  789. package/dist/channel-DEq6Ecs-.js +0 -920
  790. package/dist/channel-DH4dhW1n.js +0 -226
  791. package/dist/channel-DQ_wdKg_.js +0 -575
  792. package/dist/channel-DT6qD1Ic.js +0 -207
  793. package/dist/channel-DZNAyxwr.js +0 -542
  794. package/dist/channel-DtakwAEe.js +0 -538
  795. package/dist/channel-DuYgH6p1.js +0 -562
  796. package/dist/channel-Hn-AN-d52.js +0 -316
  797. package/dist/channel-_R4hbD5h.js +0 -1598
  798. package/dist/channel-account-context-DXq8dlvI.js +0 -103
  799. package/dist/channel-kQmEVn3I.js +0 -306
  800. package/dist/channel-options-DHfxaklg.js +0 -50
  801. package/dist/channel-summary-DUpnoYhI.js +0 -106
  802. package/dist/channel-t-JxCWk6.js +0 -949
  803. package/dist/channel.runtime--GYriaXU.js +0 -213
  804. package/dist/channel.runtime-BJtn3GOH.js +0 -174
  805. package/dist/channel.runtime-BV7t_oNz.js +0 -166
  806. package/dist/channel.runtime-Bi8a3n9S.js +0 -865
  807. package/dist/channel.runtime-BjsYF0NN.js +0 -122
  808. package/dist/channel.runtime-BnI6YtmI.js +0 -413
  809. package/dist/channel.runtime-CQOftcCd.js +0 -194
  810. package/dist/channel.runtime-CuIAcPjZ.js +0 -4006
  811. package/dist/channel.runtime-DH1Q1G4k.js +0 -399
  812. package/dist/channel.runtime-DYYUPKxr.js +0 -236
  813. package/dist/channel.runtime-U5Gszsr5.js +0 -177
  814. package/dist/channel.setup-BQFHmgki.js +0 -9
  815. package/dist/channel.setup-BVoDwklu.js +0 -8
  816. package/dist/channel.setup-Bf73HsXr.js +0 -57
  817. package/dist/channel.setup-CblD4flM.js +0 -11
  818. package/dist/channel.setup-DgxlrPgz.js +0 -6
  819. package/dist/channel.setup-GLIAEVKL.js +0 -8
  820. package/dist/channel.setup-YTy5R1sz.js +0 -9
  821. package/dist/channels-CTL8iR9J.js +0 -404
  822. package/dist/channels-DBGvnjHY.js +0 -1113
  823. package/dist/channels-cli-BmVO5-sq.js +0 -286
  824. package/dist/channels-status-issues-kDtsWzA-.js +0 -16
  825. package/dist/clawbot-cli-DtcMJHqX.js +0 -113
  826. package/dist/cli-BNGECGVY.js +0 -149
  827. package/dist/command-registry-1SDrWgER.js +0 -13
  828. package/dist/command-registry-DNorYU4w.js +0 -212
  829. package/dist/command-secret-gateway-DqDZparO.js +0 -106
  830. package/dist/compact.runtime-C1ZN8UGb.js +0 -111
  831. package/dist/completion-cli-Q_Jt5Foc.js +0 -16
  832. package/dist/completion-cli-QkTXhuJh.js +0 -445
  833. package/dist/config-BbxrRaLf.js +0 -938
  834. package/dist/config-CkD8DJ7L.js +0 -44
  835. package/dist/config-cli-BoPrlYTp.js +0 -428
  836. package/dist/config-guard-CEhCvr_u.js +0 -117
  837. package/dist/config-schema-GQ6uWjXe.js +0 -31
  838. package/dist/config-validation-woE2_LpC.js +0 -262
  839. package/dist/config-value-Dh8m-CFf.js +0 -132
  840. package/dist/config-y4i5g7s4.js +0 -30
  841. package/dist/configure-DGRzwdFN.js +0 -1100
  842. package/dist/configure-S4AHE3k_.js +0 -238
  843. package/dist/control-ui-shared-kLBp4YlS.js +0 -29
  844. package/dist/credentials-D5uBf_C5.js +0 -265
  845. package/dist/cron-cli-lGupeVCW.js +0 -634
  846. package/dist/daemon-cli-Cs_edi0I.js +0 -339
  847. package/dist/daemon-install-DIFpP_qv.js +0 -175
  848. package/dist/deliver-DYa_DFZU.js +0 -106
  849. package/dist/deliver-runtime-DCW_o2Ot.js +0 -106
  850. package/dist/devices-cli-YsGOW2-w.js +0 -340
  851. package/dist/diagnostic-vMghIesG.js +0 -310
  852. package/dist/directory-cli-DtjMQjU5.js +0 -306
  853. package/dist/directory.static-DBZGvsdF.js +0 -44
  854. package/dist/discord-DYCu19HT.js +0 -109
  855. package/dist/discovery-DZYAoDF_.js +0 -48
  856. package/dist/dns-cli-DqW4pNgW.js +0 -216
  857. package/dist/docs-cli-Bu9TBlDU.js +0 -173
  858. package/dist/doctor-completion-B5hcQD5c.js +0 -90
  859. package/dist/doctor-config-flow-BBB2ZKfT.js +0 -107
  860. package/dist/doctor-config-flow-DDBYUS9f.js +0 -2437
  861. package/dist/enable-Tmsp8QuB.js +0 -24
  862. package/dist/env-overrides-BHxqjYZG.js +0 -434
  863. package/dist/env-overrides.runtime-Cz98bf-l.js +0 -17
  864. package/dist/exec-approvals-cli-wO5cYfMa.js +0 -419
  865. package/dist/gateway-cli-CFvDGhB9.js +0 -26429
  866. package/dist/gateway-install-token-CskJfo_N.js +0 -163
  867. package/dist/gateway-rpc-srYfBID9.js +0 -26
  868. package/dist/gateway-runtime-C76hUmUV.js +0 -69
  869. package/dist/googlechat-Cha5utST.js +0 -307
  870. package/dist/health-DDQYYsJy.js +0 -108
  871. package/dist/health-DXZykGaX.js +0 -570
  872. package/dist/hooks-cli-DfkurPYP.js +0 -995
  873. package/dist/imessage-B26k39pl.js +0 -110
  874. package/dist/imessage-Bp1_6cws.js +0 -31
  875. package/dist/inbound-reply-dispatch-DoIJLztA.js +0 -71
  876. package/dist/install-target-BjOuS4I8.js +0 -574
  877. package/dist/installs-Cz4k0W1Y.js +0 -532
  878. package/dist/io-B0OKifLZ.js +0 -28
  879. package/dist/io-DcoxdH6t.js +0 -9570
  880. package/dist/ipv4-CTQQ4_IW.js +0 -82
  881. package/dist/irc-B8vBDigm.js +0 -672
  882. package/dist/library-VCM_cQY4.js +0 -107
  883. package/dist/lifecycle-core-Ctz36PdQ.js +0 -382
  884. package/dist/line-B_uTLrdI.js +0 -530
  885. package/dist/llm-slug-generator-YWg0g2pj.js +0 -67
  886. package/dist/logging-S-5LPdfQ.js +0 -13
  887. package/dist/logging-ueBMCGMR.js +0 -29
  888. package/dist/login-qr-pcACm2Ng.js +0 -107
  889. package/dist/login-qr-pv-kxMfF.js +0 -233
  890. package/dist/logs-cli-RgADgSMO.js +0 -254
  891. package/dist/manager-runtime-BhTkoKmb.js +0 -106
  892. package/dist/manager.runtime-BjHzikoK.js +0 -710
  893. package/dist/matrix-C4EEu2Qp.js +0 -1490
  894. package/dist/matrix-Dfzcc5nV.js +0 -1269
  895. package/dist/mcp-cli-CJmOm9Oj.js +0 -86
  896. package/dist/media-understanding.runtime-DCETFCw_.js +0 -111
  897. package/dist/memory-cli-DFqd6tYx.js +0 -106
  898. package/dist/method-scopes-D-Q9dvbj.js +0 -2586
  899. package/dist/model-picker-Z-CUcuMr.js +0 -390
  900. package/dist/model-picker-v5mUsZ4J.js +0 -107
  901. package/dist/model-picker.runtime-A_z0dHfS.js +0 -120
  902. package/dist/model-suppression.runtime-QVWVJRr-.js +0 -111
  903. package/dist/models-Bbj0xV4F.js +0 -2514
  904. package/dist/models-D-OIjZqU.js +0 -113
  905. package/dist/models-cli-Bpn-5i4h.js +0 -304
  906. package/dist/models-config-Cwa5cJbC.js +0 -106
  907. package/dist/monitor-BchfCAaU.js +0 -6823
  908. package/dist/monitor-BydV44SP.js +0 -3076
  909. package/dist/monitor-CT8axwfm.js +0 -767
  910. package/dist/monitor-CZGWNOvn.js +0 -777
  911. package/dist/monitor-DN62r69g.js +0 -3468
  912. package/dist/monitor-DZ0fzJku.js +0 -110
  913. package/dist/monitor-DvNjzWFu.js +0 -108
  914. package/dist/monitor-shared-B-DBSlkQ.js +0 -444
  915. package/dist/msteams-Bf-wk2Rp.js +0 -852
  916. package/dist/node-cli-kH16TQI7.js +0 -2498
  917. package/dist/node-resolve-DfOpQmxm.js +0 -835
  918. package/dist/nodes-cli-CkAMXW5u.js +0 -1375
  919. package/dist/nostr-B8UGHclZ.js +0 -8744
  920. package/dist/npm-resolution-DmjlifII.js +0 -60
  921. package/dist/onboard-C883nfyw.js +0 -589
  922. package/dist/onboard-channels-Dc-BxN7p.js +0 -200
  923. package/dist/onboard-channels-j5EENtum.js +0 -1241
  924. package/dist/onboard-custom-0atne0C5.js +0 -571
  925. package/dist/onboard-custom-CWMqwjJx.js +0 -109
  926. package/dist/onboard-helpers-D3wWfH8F.js +0 -335
  927. package/dist/onboard-helpers-DZmRCe8l.js +0 -108
  928. package/dist/onboard-remote-Cn6kW-p0.js +0 -112
  929. package/dist/onboard-remote-Cx4w5VAk.js +0 -181
  930. package/dist/onboard-search-Ck9HRh2M.js +0 -297
  931. package/dist/onboard-skills-BtqrGioT.js +0 -133
  932. package/dist/onboard-skills-Dnw19Os8.js +0 -112
  933. package/dist/outbound-media-C5Nv4o18.js +0 -11
  934. package/dist/pairing-cli-Cwy9QZ_4.js +0 -212
  935. package/dist/perplexity-Brhpb45X.js +0 -24
  936. package/dist/pi-model-discovery-runtime-DIOdo6D8.js +0 -106
  937. package/dist/pi-tools.before-tool-call.runtime-CFM4gsDF.js +0 -380
  938. package/dist/plugin-install-BOV00hia.js +0 -112
  939. package/dist/plugin-install-Bak8fUBv.js +0 -184
  940. package/dist/plugin-install-plan-bKkEefRf.js +0 -49
  941. package/dist/plugin-registry-DxAXQUlZ.js +0 -108
  942. package/dist/plugin-registry-n0p3phem.js +0 -49
  943. package/dist/plugins-Ca3RK8Fi.js +0 -106
  944. package/dist/plugins-cli-BnC51H2R.js +0 -912
  945. package/dist/policy-BJv97w9e.js +0 -143
  946. package/dist/preflight-audio.runtime-BrFcf-6_.js +0 -111
  947. package/dist/probe-063xvvZc.js +0 -19
  948. package/dist/probe-BJEb2wGv.js +0 -1793
  949. package/dist/probe-CJQlxgsl.js +0 -47
  950. package/dist/probe-Caa2HznF.js +0 -6328
  951. package/dist/probe-CfL4tnJ6.js +0 -129
  952. package/dist/probe-auth-DN2Ec83-.js +0 -38
  953. package/dist/probe-auth-D_UKzu4m.js +0 -48
  954. package/dist/program-BOMdC7MC.js +0 -247
  955. package/dist/prompt-select-styled-DDnCfM3j.js +0 -2673
  956. package/dist/provider-api-key-auth.runtime-DUns3fwX.js +0 -116
  957. package/dist/provider-auth-choice-B_j1ctT2.js +0 -126
  958. package/dist/provider-auth-choice-preference-BaOBZ_Xn.js +0 -189
  959. package/dist/provider-auth-choice.runtime-DOako_zV.js +0 -118
  960. package/dist/provider-auth-guidance-CrjxnoNZ.js +0 -34
  961. package/dist/provider-runtime.runtime-BkOkgmTw.js +0 -106
  962. package/dist/provider-self-hosted-setup-BFDU6dRa.js +0 -182
  963. package/dist/provider-usage-CaDE0mqq.js +0 -106
  964. package/dist/provider-web-search-BR7etTjJ.js +0 -2392
  965. package/dist/provider-wizard-DCPdKUvb.js +0 -152
  966. package/dist/push-apns-B_OZjm4v.js +0 -1038
  967. package/dist/pw-ai-dG60P0hQ.js +0 -1866
  968. package/dist/qr-cli-DWfiw79I.js +0 -369
  969. package/dist/qr-cli-DwuKtyZQ.js +0 -108
  970. package/dist/reactions-CIGAPBn8.js +0 -281
  971. package/dist/read-only-account-inspect.discord.runtime-D54mnq8l.js +0 -111
  972. package/dist/read-only-account-inspect.slack.runtime-Bxs9ObMC.js +0 -111
  973. package/dist/read-only-account-inspect.telegram.runtime-UoVuf_Yo.js +0 -111
  974. package/dist/redact-snapshot-DZ3Vq-SC.js +0 -2657
  975. package/dist/ref-contract-D96lSYLs.js +0 -53
  976. package/dist/register.agent-2KmeahEL.js +0 -434
  977. package/dist/register.backup-ECBnWVR7.js +0 -624
  978. package/dist/register.configure-Doz1daCp.js +0 -247
  979. package/dist/register.maintenance-C33cV-WM.js +0 -569
  980. package/dist/register.message-CnL0NiF6.js +0 -704
  981. package/dist/register.onboard-BrYGZeQA.js +0 -187
  982. package/dist/register.setup-Bx6gEg6X.js +0 -207
  983. package/dist/register.status-health-sessions-FLb0CUOO.js +0 -493
  984. package/dist/register.subclis-BuqgaeIf.js +0 -12
  985. package/dist/register.subclis-DwdgfdnT.js +0 -315
  986. package/dist/registry-xhgvU89y.js +0 -1107
  987. package/dist/replies-hB2aipLu.js +0 -110
  988. package/dist/resolve-3ErMOltL.js +0 -660
  989. package/dist/resolve-channels-BV8GXuPe.js +0 -226
  990. package/dist/resolve-channels-CTY_XRIP.js +0 -262
  991. package/dist/resolve-users-DQ4Ne4Zc.js +0 -143
  992. package/dist/routes-BNDsNO_e.js +0 -7097
  993. package/dist/rpc-BLGTBWXq.js +0 -67
  994. package/dist/run-main-COAE4GlI.js +0 -423
  995. package/dist/runtime-discord-ops.runtime-Dxg-nlgd.js +0 -9073
  996. package/dist/runtime-slack-ops.runtime-Di474LJr.js +0 -4551
  997. package/dist/runtime-telegram-ops.runtime-Da8vgf3O.js +0 -128
  998. package/dist/runtime-whatsapp-login.runtime-DcouP4iF.js +0 -109
  999. package/dist/runtime-whatsapp-outbound.runtime-CYamaEJX.js +0 -112
  1000. package/dist/sandbox-cli-U5ZTxhxL.js +0 -530
  1001. package/dist/search-manager-CfizyEMk.js +0 -386
  1002. package/dist/search-manager-DaF2QP4s.js +0 -15
  1003. package/dist/secrets-cli-C0gytFip.js +0 -2065
  1004. package/dist/security-cli-C74EuLUO.js +0 -570
  1005. package/dist/send-BTLVBf_E.js +0 -631
  1006. package/dist/send-BlWWCEZE.js +0 -1025
  1007. package/dist/send-CfypD1B_.js +0 -100
  1008. package/dist/send-Cm9v3uhF.js +0 -283
  1009. package/dist/send-g2odQuYI.js +0 -629
  1010. package/dist/server-C8b5QJ2s.js +0 -106
  1011. package/dist/server-node-events-xqQe5xiu.js +0 -501
  1012. package/dist/sessions-CSSzvgPQ.js +0 -107
  1013. package/dist/sessions-z0GIvdKa.js +0 -218
  1014. package/dist/setup-D9XTmlF8.js +0 -387
  1015. package/dist/setup-core-BDrLOwYO.js +0 -143
  1016. package/dist/setup-core-CM7cY7_i.js +0 -166
  1017. package/dist/setup-core-CnmgANY-.js +0 -205
  1018. package/dist/setup-core-DgcjCKmG.js +0 -47
  1019. package/dist/setup-surface-DzRrVKYj.js +0 -490
  1020. package/dist/setup.finalize-UaPu_adv.js +0 -517
  1021. package/dist/setup.gateway-config-Djc1ceEh.js +0 -338
  1022. package/dist/setup.secret-input-BkczghbR.js +0 -25
  1023. package/dist/shared-BHizGoNk.js +0 -298
  1024. package/dist/shared-CUfYhQkP.js +0 -96
  1025. package/dist/shared-DYYqr9EC.js +0 -75
  1026. package/dist/shared-DthOxMRQ.js +0 -182
  1027. package/dist/shared-On_A5_hW.js +0 -102
  1028. package/dist/signal-D6px9PGZ.js +0 -109
  1029. package/dist/skills-B4h1k-SP.js +0 -853
  1030. package/dist/skills-Bto10BGB.js +0 -19
  1031. package/dist/skills-cli-CXGR3Y5j.js +0 -291
  1032. package/dist/skills-install-B1AlkK8C.js +0 -763
  1033. package/dist/skills-status-BsmJ_iSg.js +0 -20
  1034. package/dist/skills-status-DGdxY3OI.js +0 -169
  1035. package/dist/slack-B7vWFmxP.js +0 -109
  1036. package/dist/slash-commands.runtime-DXdAT84n.js +0 -123
  1037. package/dist/slash-dispatch.runtime-CNf2-9Aj.js +0 -136
  1038. package/dist/slash-skill-commands.runtime-CBjffHRX.js +0 -111
  1039. package/dist/src-Cp7P7T08.js +0 -1696
  1040. package/dist/status-158fWh4A.js +0 -43
  1041. package/dist/status-BJIVLJnb.js +0 -1599
  1042. package/dist/status-BQiBI6N9.js +0 -126
  1043. package/dist/status-CZipXGUu.js +0 -121
  1044. package/dist/status-ZZIVFLI-.js +0 -606
  1045. package/dist/status-json-BNUy5Mem.js +0 -286
  1046. package/dist/status.link-channel-B694y1Xu.js +0 -138
  1047. package/dist/status.scan.deps.runtime-BcoKEzQD.js +0 -121
  1048. package/dist/status.scan.runtime-CqScDt-p.js +0 -114
  1049. package/dist/status.summary-AMek7qvI.js +0 -592
  1050. package/dist/status.summary.runtime-XgkcQ_kr.js +0 -113
  1051. package/dist/subagent-orphan-recovery-CrCYTmFC.js +0 -302
  1052. package/dist/subagent-registry-runtime-Cg-YvLx3.js +0 -106
  1053. package/dist/synology-chat-0G85jIqQ.js +0 -297
  1054. package/dist/system-cli-kZtSxKNm.js +0 -92
  1055. package/dist/telegram-DV0Wy89w.js +0 -109
  1056. package/dist/text-chunking-C2J2Oeul.js +0 -84
  1057. package/dist/tlon-DmK1NUVP.js +0 -433
  1058. package/dist/tui-D3bNPLG7.js +0 -3834
  1059. package/dist/tui-cli-DtMp9k_s.js +0 -132
  1060. package/dist/types.secrets-DuSPmmWB.js +0 -80
  1061. package/dist/ui-CeGztSEL.js +0 -31
  1062. package/dist/update-De7VudzP.js +0 -1036
  1063. package/dist/update-cli-BH8Pb-So.js +0 -1498
  1064. package/dist/update-offset-store-syELkdEW.js +0 -107
  1065. package/dist/update-runner-Cq-Q40T9.js +0 -1496
  1066. package/dist/web-CjMtvfSq.js +0 -107
  1067. package/dist/webhook-targets-_jTR0Bb_.js +0 -181
  1068. package/dist/webhooks-cli-DQ6u2Qau.js +0 -349
  1069. package/dist/whatsapp-CyLk16SZ.js +0 -109
  1070. package/dist/whatsapp-actions-Dzr2Wzqw.js +0 -162
  1071. package/dist/workspace-dirs-L1_QQ9mB.js +0 -2002
  1072. package/dist/zalo-CrehfXvK.js +0 -415
  1073. package/dist/zalouser-D1QD-O-I.js +0 -30911
  1074. package/dist/zod-schema.core-CWxzqcUs.js +0 -541
@@ -1,3834 +0,0 @@
1
- import { i as visibleWidth, r as stripAnsi$1 } from "./ansi-BPhP6LBZ.js";
2
- import { Fb as formatToolDetail, Ib as resolveToolDisplay, Tn as listThinkingLevelLabels, fn as listChatCommands, p as formatRawAssistantErrorForUi, pn as listChatCommandsForConfig, wn as formatThinkingLevels } from "./auth-profiles-BJcHzwPy.js";
3
- import { B as normalizeUsageDisplay, H as resolveResponseUsageMode } from "./model-selection-DfA4esOK.js";
4
- import { c as resolveAgentIdByWorkspacePath, m as resolveDefaultAgentId } from "./agent-scope-DA7O8MVG.js";
5
- import { S as parseAgentSessionKey, c as normalizeAgentId, l as normalizeMainKey, r as buildAgentMainSessionKey } from "./session-key-DyhRsRh-.js";
6
- import { s as loadConfig } from "./io-DcoxdH6t.js";
7
- import { n as VERSION } from "./version-rW_3ob2o.js";
8
- import { a as hasConfiguredSecretInput } from "./types.secrets-DuSPmmWB.js";
9
- import { it as resolveConfiguredSecretInputString, st as assertExplicitGatewayAuthModeWhenBothConfigured } from "./routes-BNDsNO_e.js";
10
- import { _ as GATEWAY_CLIENT_MODES, h as GATEWAY_CLIENT_CAPS, v as GATEWAY_CLIENT_NAMES } from "./message-channel-CKeDAoOT.js";
11
- import { u as GatewayClient } from "./method-scopes-D-Q9dvbj.js";
12
- import { s as formatTokenCount, y as stripLeadingInboundMetadata } from "./session-cost-usage-B-57mlS8.js";
13
- import { c as resolveExplicitGatewayAuth, o as ensureExplicitGatewayAuth, t as buildGatewayConnectionDetails } from "./call-CoaQYq7c.js";
14
- import { n as formatTimeAgo, t as formatRelativeTimestamp } from "./format-relative-B7AB_aDW.js";
15
- import { spawn } from "node:child_process";
16
- import chalk from "chalk";
17
- import { randomUUID } from "node:crypto";
18
- import { Box, CombinedAutocompleteProvider, Container, Editor, Input, Key, Loader, Markdown, ProcessTerminal, SelectList, SettingsList, Spacer, TUI, Text, getEditorKeybindings, isKeyRelease, matchesKey, truncateToWidth } from "@mariozechner/pi-tui";
19
- import { highlight, supportsLanguage } from "cli-highlight";
20
- //#region src/tui/commands.ts
21
- const VERBOSE_LEVELS = ["on", "off"];
22
- const FAST_LEVELS = [
23
- "status",
24
- "on",
25
- "off"
26
- ];
27
- const REASONING_LEVELS = ["on", "off"];
28
- const ELEVATED_LEVELS = [
29
- "on",
30
- "off",
31
- "ask",
32
- "full"
33
- ];
34
- const ACTIVATION_LEVELS = ["mention", "always"];
35
- const USAGE_FOOTER_LEVELS = [
36
- "off",
37
- "tokens",
38
- "full"
39
- ];
40
- const COMMAND_ALIASES = { elev: "elevated" };
41
- function createLevelCompletion(levels) {
42
- return (prefix) => levels.filter((value) => value.startsWith(prefix.toLowerCase())).map((value) => ({
43
- value,
44
- label: value
45
- }));
46
- }
47
- function parseCommand(input) {
48
- const trimmed = input.replace(/^\//, "").trim();
49
- if (!trimmed) return {
50
- name: "",
51
- args: ""
52
- };
53
- const [name, ...rest] = trimmed.split(/\s+/);
54
- const normalized = name.toLowerCase();
55
- return {
56
- name: COMMAND_ALIASES[normalized] ?? normalized,
57
- args: rest.join(" ").trim()
58
- };
59
- }
60
- function getSlashCommands(options = {}) {
61
- const thinkLevels = listThinkingLevelLabels(options.provider, options.model);
62
- const verboseCompletions = createLevelCompletion(VERBOSE_LEVELS);
63
- const fastCompletions = createLevelCompletion(FAST_LEVELS);
64
- const reasoningCompletions = createLevelCompletion(REASONING_LEVELS);
65
- const usageCompletions = createLevelCompletion(USAGE_FOOTER_LEVELS);
66
- const elevatedCompletions = createLevelCompletion(ELEVATED_LEVELS);
67
- const activationCompletions = createLevelCompletion(ACTIVATION_LEVELS);
68
- const commands = [
69
- {
70
- name: "help",
71
- description: "Show slash command help"
72
- },
73
- {
74
- name: "status",
75
- description: "Show gateway status summary"
76
- },
77
- {
78
- name: "agent",
79
- description: "Switch agent (or open picker)"
80
- },
81
- {
82
- name: "agents",
83
- description: "Open agent picker"
84
- },
85
- {
86
- name: "session",
87
- description: "Switch session (or open picker)"
88
- },
89
- {
90
- name: "sessions",
91
- description: "Open session picker"
92
- },
93
- {
94
- name: "model",
95
- description: "Set model (or open picker)"
96
- },
97
- {
98
- name: "models",
99
- description: "Open model picker"
100
- },
101
- {
102
- name: "think",
103
- description: "Set thinking level",
104
- getArgumentCompletions: (prefix) => thinkLevels.filter((v) => v.startsWith(prefix.toLowerCase())).map((value) => ({
105
- value,
106
- label: value
107
- }))
108
- },
109
- {
110
- name: "fast",
111
- description: "Set fast mode on/off",
112
- getArgumentCompletions: fastCompletions
113
- },
114
- {
115
- name: "verbose",
116
- description: "Set verbose on/off",
117
- getArgumentCompletions: verboseCompletions
118
- },
119
- {
120
- name: "reasoning",
121
- description: "Set reasoning on/off",
122
- getArgumentCompletions: reasoningCompletions
123
- },
124
- {
125
- name: "usage",
126
- description: "Toggle per-response usage line",
127
- getArgumentCompletions: usageCompletions
128
- },
129
- {
130
- name: "elevated",
131
- description: "Set elevated on/off/ask/full",
132
- getArgumentCompletions: elevatedCompletions
133
- },
134
- {
135
- name: "elev",
136
- description: "Alias for /elevated",
137
- getArgumentCompletions: elevatedCompletions
138
- },
139
- {
140
- name: "activation",
141
- description: "Set group activation",
142
- getArgumentCompletions: activationCompletions
143
- },
144
- {
145
- name: "abort",
146
- description: "Abort active run"
147
- },
148
- {
149
- name: "new",
150
- description: "Reset the session"
151
- },
152
- {
153
- name: "reset",
154
- description: "Reset the session"
155
- },
156
- {
157
- name: "settings",
158
- description: "Open settings"
159
- },
160
- {
161
- name: "exit",
162
- description: "Exit the TUI"
163
- },
164
- {
165
- name: "quit",
166
- description: "Exit the TUI"
167
- }
168
- ];
169
- const seen = new Set(commands.map((command) => command.name));
170
- const gatewayCommands = options.cfg ? listChatCommandsForConfig(options.cfg) : listChatCommands();
171
- for (const command of gatewayCommands) {
172
- const aliases = command.textAliases.length > 0 ? command.textAliases : [`/${command.key}`];
173
- for (const alias of aliases) {
174
- const name = alias.replace(/^\//, "").trim();
175
- if (!name || seen.has(name)) continue;
176
- seen.add(name);
177
- commands.push({
178
- name,
179
- description: command.description
180
- });
181
- }
182
- }
183
- return commands;
184
- }
185
- function helpText(options = {}) {
186
- return [
187
- "Slash commands:",
188
- "/help",
189
- "/commands",
190
- "/status",
191
- "/agent <id> (or /agents)",
192
- "/session <key> (or /sessions)",
193
- "/model <provider/model> (or /models)",
194
- `/think <${formatThinkingLevels(options.provider, options.model, "|")}>`,
195
- "/fast <status|on|off>",
196
- "/verbose <on|off>",
197
- "/reasoning <on|off>",
198
- "/usage <off|tokens|full>",
199
- "/elevated <on|off|ask|full>",
200
- "/elev <on|off|ask|full>",
201
- "/activation <mention|always>",
202
- "/new or /reset",
203
- "/abort",
204
- "/settings",
205
- "/exit"
206
- ].join("\n");
207
- }
208
- //#endregion
209
- //#region src/tui/theme/syntax-theme.ts
210
- /**
211
- * Syntax highlighting theme for code blocks.
212
- * Uses chalk functions to style different token types.
213
- */
214
- function createSyntaxTheme(fallback, light = false) {
215
- if (light) return {
216
- keyword: chalk.hex("#AF00DB"),
217
- built_in: chalk.hex("#267F99"),
218
- type: chalk.hex("#267F99"),
219
- literal: chalk.hex("#0000FF"),
220
- number: chalk.hex("#098658"),
221
- string: chalk.hex("#A31515"),
222
- regexp: chalk.hex("#811F3F"),
223
- symbol: chalk.hex("#098658"),
224
- class: chalk.hex("#267F99"),
225
- function: chalk.hex("#795E26"),
226
- title: chalk.hex("#795E26"),
227
- params: chalk.hex("#001080"),
228
- comment: chalk.hex("#008000"),
229
- doctag: chalk.hex("#008000"),
230
- meta: chalk.hex("#001080"),
231
- "meta-keyword": chalk.hex("#AF00DB"),
232
- "meta-string": chalk.hex("#A31515"),
233
- section: chalk.hex("#795E26"),
234
- tag: chalk.hex("#800000"),
235
- name: chalk.hex("#001080"),
236
- attr: chalk.hex("#C50000"),
237
- attribute: chalk.hex("#C50000"),
238
- variable: chalk.hex("#001080"),
239
- bullet: chalk.hex("#795E26"),
240
- code: chalk.hex("#A31515"),
241
- emphasis: chalk.italic,
242
- strong: chalk.bold,
243
- formula: chalk.hex("#AF00DB"),
244
- link: chalk.hex("#267F99"),
245
- quote: chalk.hex("#008000"),
246
- addition: chalk.hex("#098658"),
247
- deletion: chalk.hex("#A31515"),
248
- "selector-tag": chalk.hex("#800000"),
249
- "selector-id": chalk.hex("#800000"),
250
- "selector-class": chalk.hex("#800000"),
251
- "selector-attr": chalk.hex("#800000"),
252
- "selector-pseudo": chalk.hex("#800000"),
253
- "template-tag": chalk.hex("#AF00DB"),
254
- "template-variable": chalk.hex("#001080"),
255
- default: fallback
256
- };
257
- return {
258
- keyword: chalk.hex("#C586C0"),
259
- built_in: chalk.hex("#4EC9B0"),
260
- type: chalk.hex("#4EC9B0"),
261
- literal: chalk.hex("#569CD6"),
262
- number: chalk.hex("#B5CEA8"),
263
- string: chalk.hex("#CE9178"),
264
- regexp: chalk.hex("#D16969"),
265
- symbol: chalk.hex("#B5CEA8"),
266
- class: chalk.hex("#4EC9B0"),
267
- function: chalk.hex("#DCDCAA"),
268
- title: chalk.hex("#DCDCAA"),
269
- params: chalk.hex("#9CDCFE"),
270
- comment: chalk.hex("#6A9955"),
271
- doctag: chalk.hex("#608B4E"),
272
- meta: chalk.hex("#9CDCFE"),
273
- "meta-keyword": chalk.hex("#C586C0"),
274
- "meta-string": chalk.hex("#CE9178"),
275
- section: chalk.hex("#DCDCAA"),
276
- tag: chalk.hex("#569CD6"),
277
- name: chalk.hex("#9CDCFE"),
278
- attr: chalk.hex("#9CDCFE"),
279
- attribute: chalk.hex("#9CDCFE"),
280
- variable: chalk.hex("#9CDCFE"),
281
- bullet: chalk.hex("#D7BA7D"),
282
- code: chalk.hex("#CE9178"),
283
- emphasis: chalk.italic,
284
- strong: chalk.bold,
285
- formula: chalk.hex("#C586C0"),
286
- link: chalk.hex("#4EC9B0"),
287
- quote: chalk.hex("#6A9955"),
288
- addition: chalk.hex("#B5CEA8"),
289
- deletion: chalk.hex("#F44747"),
290
- "selector-tag": chalk.hex("#D7BA7D"),
291
- "selector-id": chalk.hex("#D7BA7D"),
292
- "selector-class": chalk.hex("#D7BA7D"),
293
- "selector-attr": chalk.hex("#D7BA7D"),
294
- "selector-pseudo": chalk.hex("#D7BA7D"),
295
- "template-tag": chalk.hex("#C586C0"),
296
- "template-variable": chalk.hex("#9CDCFE"),
297
- default: fallback
298
- };
299
- }
300
- //#endregion
301
- //#region src/tui/theme/theme.ts
302
- const DARK_TEXT = "#E8E3D5";
303
- const LIGHT_TEXT = "#1E1E1E";
304
- const XTERM_LEVELS = [
305
- 0,
306
- 95,
307
- 135,
308
- 175,
309
- 215,
310
- 255
311
- ];
312
- function channelToSrgb(value) {
313
- const normalized = value / 255;
314
- return normalized <= .03928 ? normalized / 12.92 : ((normalized + .055) / 1.055) ** 2.4;
315
- }
316
- function relativeLuminanceRgb(r, g, b) {
317
- const red = channelToSrgb(r);
318
- const green = channelToSrgb(g);
319
- const blue = channelToSrgb(b);
320
- return .2126 * red + .7152 * green + .0722 * blue;
321
- }
322
- function relativeLuminanceHex(hex) {
323
- return relativeLuminanceRgb(Number.parseInt(hex.slice(1, 3), 16), Number.parseInt(hex.slice(3, 5), 16), Number.parseInt(hex.slice(5, 7), 16));
324
- }
325
- function contrastRatio(background, foregroundHex) {
326
- const foreground = relativeLuminanceHex(foregroundHex);
327
- const lighter = Math.max(background, foreground);
328
- const darker = Math.min(background, foreground);
329
- return (lighter + .05) / (darker + .05);
330
- }
331
- function pickHigherContrastText(r, g, b) {
332
- const background = relativeLuminanceRgb(r, g, b);
333
- return contrastRatio(background, LIGHT_TEXT) >= contrastRatio(background, DARK_TEXT);
334
- }
335
- function isLightBackground() {
336
- const explicit = process.env.MOLDCLAW_THEME?.toLowerCase();
337
- if (explicit === "light") return true;
338
- if (explicit === "dark") return false;
339
- const colorfgbg = process.env.COLORFGBG;
340
- if (colorfgbg && colorfgbg.length <= 64) {
341
- const sep = colorfgbg.lastIndexOf(";");
342
- const bg = Number.parseInt(sep >= 0 ? colorfgbg.slice(sep + 1) : colorfgbg, 10);
343
- if (bg >= 0 && bg <= 255) {
344
- if (bg <= 15) return bg === 7 || bg === 15;
345
- if (bg >= 232) return bg >= 244;
346
- const cubeIndex = bg - 16;
347
- const bVal = XTERM_LEVELS[cubeIndex % 6];
348
- const gVal = XTERM_LEVELS[Math.floor(cubeIndex / 6) % 6];
349
- const rVal = XTERM_LEVELS[Math.floor(cubeIndex / 36)];
350
- return pickHigherContrastText(rVal, gVal, bVal);
351
- }
352
- }
353
- return false;
354
- }
355
- /** Whether the terminal has a light background. Exported for testing only. */
356
- const lightMode = isLightBackground();
357
- const palette = lightMode ? {
358
- text: "#1E1E1E",
359
- dim: "#5B6472",
360
- accent: "#B45309",
361
- accentSoft: "#C2410C",
362
- border: "#5B6472",
363
- userBg: "#F3F0E8",
364
- userText: "#1E1E1E",
365
- systemText: "#4B5563",
366
- toolPendingBg: "#EFF6FF",
367
- toolSuccessBg: "#ECFDF5",
368
- toolErrorBg: "#FEF2F2",
369
- toolTitle: "#B45309",
370
- toolOutput: "#374151",
371
- quote: "#1D4ED8",
372
- quoteBorder: "#2563EB",
373
- code: "#92400E",
374
- codeBlock: "#F9FAFB",
375
- codeBorder: "#92400E",
376
- link: "#047857",
377
- error: "#DC2626",
378
- success: "#047857"
379
- } : {
380
- text: "#E8E3D5",
381
- dim: "#7B7F87",
382
- accent: "#F6C453",
383
- accentSoft: "#F2A65A",
384
- border: "#3C414B",
385
- userBg: "#2B2F36",
386
- userText: "#F3EEE0",
387
- systemText: "#9BA3B2",
388
- toolPendingBg: "#1F2A2F",
389
- toolSuccessBg: "#1E2D23",
390
- toolErrorBg: "#2F1F1F",
391
- toolTitle: "#F6C453",
392
- toolOutput: "#E1DACB",
393
- quote: "#8CC8FF",
394
- quoteBorder: "#3B4D6B",
395
- code: "#F0C987",
396
- codeBlock: "#1E232A",
397
- codeBorder: "#343A45",
398
- link: "#7DD3A5",
399
- error: "#F97066",
400
- success: "#7DD3A5"
401
- };
402
- const fg = (hex) => (text) => chalk.hex(hex)(text);
403
- const bg = (hex) => (text) => chalk.bgHex(hex)(text);
404
- const syntaxTheme = createSyntaxTheme(fg(palette.code), lightMode);
405
- /**
406
- * Highlight code with syntax coloring.
407
- * Returns an array of lines with ANSI escape codes.
408
- */
409
- function highlightCode(code, lang) {
410
- try {
411
- return highlight(code, {
412
- language: lang && supportsLanguage(lang) ? lang : void 0,
413
- theme: syntaxTheme,
414
- ignoreIllegals: true
415
- }).split("\n");
416
- } catch {
417
- return code.split("\n").map((line) => fg(palette.code)(line));
418
- }
419
- }
420
- const theme = {
421
- fg: fg(palette.text),
422
- assistantText: (text) => text,
423
- dim: fg(palette.dim),
424
- accent: fg(palette.accent),
425
- accentSoft: fg(palette.accentSoft),
426
- success: fg(palette.success),
427
- error: fg(palette.error),
428
- header: (text) => chalk.bold(fg(palette.accent)(text)),
429
- system: fg(palette.systemText),
430
- userBg: bg(palette.userBg),
431
- userText: fg(palette.userText),
432
- toolTitle: fg(palette.toolTitle),
433
- toolOutput: fg(palette.toolOutput),
434
- toolPendingBg: bg(palette.toolPendingBg),
435
- toolSuccessBg: bg(palette.toolSuccessBg),
436
- toolErrorBg: bg(palette.toolErrorBg),
437
- border: fg(palette.border),
438
- bold: (text) => chalk.bold(text),
439
- italic: (text) => chalk.italic(text)
440
- };
441
- const markdownTheme = {
442
- heading: (text) => chalk.bold(fg(palette.accent)(text)),
443
- link: (text) => fg(palette.link)(text),
444
- linkUrl: (text) => chalk.dim(text),
445
- code: (text) => fg(palette.code)(text),
446
- codeBlock: (text) => fg(palette.code)(text),
447
- codeBlockBorder: (text) => fg(palette.codeBorder)(text),
448
- quote: (text) => fg(palette.quote)(text),
449
- quoteBorder: (text) => fg(palette.quoteBorder)(text),
450
- hr: (text) => fg(palette.border)(text),
451
- listBullet: (text) => fg(palette.accentSoft)(text),
452
- bold: (text) => chalk.bold(text),
453
- italic: (text) => chalk.italic(text),
454
- strikethrough: (text) => chalk.strikethrough(text),
455
- underline: (text) => chalk.underline(text),
456
- highlightCode
457
- };
458
- const baseSelectListTheme = {
459
- selectedPrefix: (text) => fg(palette.accent)(text),
460
- selectedText: (text) => chalk.bold(fg(palette.accent)(text)),
461
- description: (text) => fg(palette.dim)(text),
462
- scrollInfo: (text) => fg(palette.dim)(text),
463
- noMatch: (text) => fg(palette.dim)(text)
464
- };
465
- const selectListTheme = baseSelectListTheme;
466
- const filterableSelectListTheme = {
467
- ...baseSelectListTheme,
468
- filterLabel: (text) => fg(palette.dim)(text)
469
- };
470
- const settingsListTheme = {
471
- label: (text, selected) => selected ? chalk.bold(fg(palette.accent)(text)) : fg(palette.text)(text),
472
- value: (text, selected) => selected ? fg(palette.accentSoft)(text) : fg(palette.dim)(text),
473
- description: (text) => fg(palette.systemText)(text),
474
- cursor: fg(palette.accent)("→ "),
475
- hint: (text) => fg(palette.dim)(text)
476
- };
477
- const editorTheme = {
478
- borderColor: (text) => fg(palette.border)(text),
479
- selectList: selectListTheme
480
- };
481
- const searchableSelectListTheme = {
482
- ...baseSelectListTheme,
483
- searchPrompt: (text) => fg(palette.accentSoft)(text),
484
- searchInput: (text) => fg(palette.text)(text),
485
- matchHighlight: (text) => chalk.bold(fg(palette.accent)(text))
486
- };
487
- //#endregion
488
- //#region src/tui/osc8-hyperlinks.ts
489
- const SGR_PATTERN = "\\x1b\\[[0-9;]*m";
490
- const OSC8_PATTERN = "\\x1b\\]8;;.*?(?:\\x07|\\x1b\\\\)";
491
- const ANSI_RE = new RegExp(`${SGR_PATTERN}|${OSC8_PATTERN}`, "g");
492
- const SGR_START_RE = new RegExp(`^${SGR_PATTERN}`);
493
- const OSC8_START_RE = new RegExp(`^${OSC8_PATTERN}`);
494
- /**
495
- * Extract all unique URLs from raw markdown text.
496
- * Finds both bare URLs and markdown link hrefs [text](url).
497
- */
498
- function extractUrls(markdown) {
499
- const urls = /* @__PURE__ */ new Set();
500
- const mdLinkRe = /\[(?:[^\]]*)\]\(\s*<?(https?:\/\/[^)\s>]+)>?(?:\s+["'][^"']*["'])?\s*\)/g;
501
- let m;
502
- while ((m = mdLinkRe.exec(markdown)) !== null) urls.add(m[1]);
503
- const stripped = markdown.replace(/\[(?:[^\]]*)\]\(\s*<?https?:\/\/[^)\s>]+>?(?:\s+["'][^"']*["'])?\s*\)/g, "");
504
- const bareRe = /https?:\/\/[^\s)\]>]+/g;
505
- while ((m = bareRe.exec(stripped)) !== null) urls.add(m[0]);
506
- return [...urls];
507
- }
508
- /** Strip ANSI SGR and OSC 8 sequences to get visible text. */
509
- function stripAnsi(input) {
510
- return input.replace(ANSI_RE, "");
511
- }
512
- /**
513
- * Find URL ranges in a line's visible text, handling cross-line URL splits.
514
- */
515
- function findUrlRanges(visibleText, knownUrls, pending) {
516
- const ranges = [];
517
- let newPending = null;
518
- let searchFrom = 0;
519
- if (pending) {
520
- const remaining = pending.url.slice(pending.consumed);
521
- const trimmed = visibleText.trimStart();
522
- const leadingSpaces = visibleText.length - trimmed.length;
523
- let matchLen = 0;
524
- for (let j = 0; j < remaining.length && j < trimmed.length; j++) if (remaining[j] === trimmed[j]) matchLen++;
525
- else break;
526
- if (matchLen > 0) {
527
- ranges.push({
528
- start: leadingSpaces,
529
- end: leadingSpaces + matchLen,
530
- url: pending.url
531
- });
532
- searchFrom = leadingSpaces + matchLen;
533
- if (pending.consumed + matchLen < pending.url.length) newPending = {
534
- url: pending.url,
535
- consumed: pending.consumed + matchLen
536
- };
537
- }
538
- }
539
- const urlRe = /https?:\/\/[^\s)\]>]+/g;
540
- urlRe.lastIndex = searchFrom;
541
- let match;
542
- while ((match = urlRe.exec(visibleText)) !== null) {
543
- const fragment = match[0];
544
- const start = match.index;
545
- let resolvedUrl = fragment;
546
- let found = false;
547
- for (const known of knownUrls) if (known === fragment) {
548
- resolvedUrl = known;
549
- found = true;
550
- break;
551
- }
552
- if (!found) {
553
- let bestLen = 0;
554
- for (const known of knownUrls) if (known.startsWith(fragment) && known.length > bestLen) {
555
- resolvedUrl = known;
556
- bestLen = known.length;
557
- found = true;
558
- }
559
- }
560
- if (!found) {
561
- let bestLen = 0;
562
- for (const known of knownUrls) if (fragment.startsWith(known) && known.length > bestLen) {
563
- resolvedUrl = known;
564
- bestLen = known.length;
565
- }
566
- }
567
- ranges.push({
568
- start,
569
- end: start + fragment.length,
570
- url: resolvedUrl
571
- });
572
- if (resolvedUrl.length > fragment.length && resolvedUrl.startsWith(fragment)) newPending = {
573
- url: resolvedUrl,
574
- consumed: fragment.length
575
- };
576
- }
577
- return {
578
- ranges,
579
- pending: newPending
580
- };
581
- }
582
- /**
583
- * Apply OSC 8 hyperlink sequences to a line based on visible-text URL ranges.
584
- * Walks through the raw string character by character, inserting OSC 8
585
- * open/close sequences at URL range boundaries while preserving ANSI codes.
586
- */
587
- function applyOsc8Ranges(line, ranges) {
588
- if (ranges.length === 0) return line;
589
- const urlAt = /* @__PURE__ */ new Map();
590
- for (const r of ranges) for (let p = r.start; p < r.end; p++) urlAt.set(p, r.url);
591
- let result = "";
592
- let visiblePos = 0;
593
- let activeUrl = null;
594
- let i = 0;
595
- while (i < line.length) {
596
- if (line.charCodeAt(i) === 27) {
597
- const sgr = line.slice(i).match(SGR_START_RE);
598
- if (sgr) {
599
- result += sgr[0];
600
- i += sgr[0].length;
601
- continue;
602
- }
603
- const osc = line.slice(i).match(OSC8_START_RE);
604
- if (osc) {
605
- result += osc[0];
606
- i += osc[0].length;
607
- continue;
608
- }
609
- }
610
- const targetUrl = urlAt.get(visiblePos) ?? null;
611
- if (targetUrl !== activeUrl) {
612
- if (activeUrl !== null) result += "\x1B]8;;\x07";
613
- if (targetUrl !== null) result += `\x1b]8;;${targetUrl}\x07`;
614
- activeUrl = targetUrl;
615
- }
616
- result += line[i];
617
- visiblePos++;
618
- i++;
619
- }
620
- if (activeUrl !== null) result += "\x1B]8;;\x07";
621
- return result;
622
- }
623
- /**
624
- * Add OSC 8 hyperlinks to rendered lines using a pre-extracted URL list.
625
- *
626
- * For each line, finds URL-like substrings in the visible text, matches them
627
- * against known URLs, and wraps each fragment with OSC 8 escape sequences.
628
- * Handles URLs broken across multiple lines by pi-tui's word wrapping.
629
- */
630
- function addOsc8Hyperlinks(lines, urls) {
631
- if (urls.length === 0) return lines;
632
- let pending = null;
633
- return lines.map((line) => {
634
- const result = findUrlRanges(stripAnsi(line), urls, pending);
635
- pending = result.pending;
636
- return applyOsc8Ranges(line, result.ranges);
637
- });
638
- }
639
- //#endregion
640
- //#region src/tui/components/hyperlink-markdown.ts
641
- /**
642
- * Wrapper around pi-tui's Markdown component that adds OSC 8 terminal
643
- * hyperlinks to rendered output, making URLs clickable even when broken
644
- * across multiple lines by word wrapping.
645
- */
646
- var HyperlinkMarkdown = class {
647
- constructor(text, paddingX, paddingY, theme, options) {
648
- this.inner = new Markdown(text, paddingX, paddingY, theme, options);
649
- this.urls = extractUrls(text);
650
- }
651
- render(width) {
652
- return addOsc8Hyperlinks(this.inner.render(width), this.urls);
653
- }
654
- setText(text) {
655
- this.inner.setText(text);
656
- this.urls = extractUrls(text);
657
- }
658
- invalidate() {
659
- this.inner.invalidate();
660
- }
661
- };
662
- //#endregion
663
- //#region src/tui/components/assistant-message.ts
664
- var AssistantMessageComponent = class extends Container {
665
- constructor(text) {
666
- super();
667
- this.body = new HyperlinkMarkdown(text, 1, 0, markdownTheme, { color: (line) => theme.assistantText(line) });
668
- this.addChild(new Spacer(1));
669
- this.addChild(this.body);
670
- }
671
- setText(text) {
672
- this.body.setText(text);
673
- }
674
- };
675
- //#endregion
676
- //#region src/tui/components/btw-inline-message.ts
677
- var BtwInlineMessage = class extends Container {
678
- constructor(params) {
679
- super();
680
- this.setResult(params);
681
- }
682
- setResult(params) {
683
- this.clear();
684
- this.addChild(new Spacer(1));
685
- this.addChild(new Text(theme.header(`BTW: ${params.question}`), 1, 0));
686
- if (params.isError) this.addChild(new Text(theme.error(params.text), 1, 0));
687
- else this.addChild(new AssistantMessageComponent(params.text));
688
- this.addChild(new Text(theme.dim("Press Enter or Esc to dismiss"), 1, 0));
689
- }
690
- };
691
- //#endregion
692
- //#region src/tui/tui-formatters.ts
693
- const REPLACEMENT_CHAR_RE = /\uFFFD/g;
694
- const MAX_TOKEN_CHARS = 32;
695
- const LONG_TOKEN_RE = /\S{33,}/g;
696
- const LONG_TOKEN_TEST_RE = /\S{33,}/;
697
- const BINARY_LINE_REPLACEMENT_THRESHOLD = 12;
698
- const URL_PREFIX_RE = /^(https?:\/\/|file:\/\/)/i;
699
- const WINDOWS_DRIVE_RE = /^[a-zA-Z]:[\\/]/;
700
- const FILE_LIKE_RE = /^[a-zA-Z0-9._-]+$/;
701
- const EDGE_PUNCTUATION_RE = /^[`"'([{<]+|[`"')\]}>.,:;!?]+$/g;
702
- const TOKENISH_MIN_LENGTH = 24;
703
- const RTL_SCRIPT_RE = /[\u0590-\u08ff\ufb1d-\ufdff\ufe70-\ufefc]/;
704
- const BIDI_CONTROL_RE = /[\u202a-\u202e\u2066-\u2069]/;
705
- const RTL_ISOLATE_START = "⁧";
706
- const RTL_ISOLATE_END = "⁩";
707
- function hasControlChars(text) {
708
- for (const char of text) {
709
- const code = char.charCodeAt(0);
710
- if (code <= 31 && code !== 9 && code !== 10 && code !== 13 || code >= 127 && code <= 159) return true;
711
- }
712
- return false;
713
- }
714
- function stripControlChars(text) {
715
- if (!hasControlChars(text)) return text;
716
- let sanitized = "";
717
- for (const char of text) {
718
- const code = char.charCodeAt(0);
719
- if (!(code <= 31 && code !== 9 && code !== 10 && code !== 13) && !(code >= 127 && code <= 159)) sanitized += char;
720
- }
721
- return sanitized;
722
- }
723
- function chunkToken(token, maxChars) {
724
- if (token.length <= maxChars) return [token];
725
- const chunks = [];
726
- for (let i = 0; i < token.length; i += maxChars) chunks.push(token.slice(i, i + maxChars));
727
- return chunks;
728
- }
729
- function isCopySensitiveToken(token) {
730
- const candidate = token.replace(EDGE_PUNCTUATION_RE, "") || token;
731
- if (URL_PREFIX_RE.test(token)) return true;
732
- if (token.startsWith("/") || token.startsWith("~/") || token.startsWith("./") || token.startsWith("../")) return true;
733
- if (WINDOWS_DRIVE_RE.test(token) || token.startsWith("\\\\")) return true;
734
- if (token.includes("/") || token.includes("\\")) return true;
735
- if (token.includes("_") && FILE_LIKE_RE.test(token)) return true;
736
- if (candidate.length >= TOKENISH_MIN_LENGTH && /[a-z]/i.test(candidate) && /\d/.test(candidate)) return true;
737
- return false;
738
- }
739
- function normalizeLongTokenForDisplay(token) {
740
- if (isCopySensitiveToken(token)) return token;
741
- return chunkToken(token, MAX_TOKEN_CHARS).join(" ");
742
- }
743
- function redactBinaryLikeLine(line) {
744
- const replacementCount = (line.match(REPLACEMENT_CHAR_RE) || []).length;
745
- if (replacementCount >= BINARY_LINE_REPLACEMENT_THRESHOLD && replacementCount * 2 >= line.length) return "[binary data omitted]";
746
- return line;
747
- }
748
- function isolateRtlLine(line) {
749
- if (!RTL_SCRIPT_RE.test(line) || BIDI_CONTROL_RE.test(line)) return line;
750
- return `${RTL_ISOLATE_START}${line}${RTL_ISOLATE_END}`;
751
- }
752
- function applyRtlIsolation(text) {
753
- if (!RTL_SCRIPT_RE.test(text)) return text;
754
- return text.split("\n").map((line) => isolateRtlLine(line)).join("\n");
755
- }
756
- function sanitizeRenderableText(text) {
757
- if (!text) return text;
758
- const hasAnsi = text.includes("\x1B");
759
- const hasReplacementChars = text.includes("�");
760
- const hasLongTokens = LONG_TOKEN_TEST_RE.test(text);
761
- const hasControls = hasControlChars(text);
762
- if (!hasAnsi && !hasReplacementChars && !hasLongTokens && !hasControls) return applyRtlIsolation(text);
763
- const withoutAnsi = hasAnsi ? stripAnsi$1(text) : text;
764
- const withoutControlChars = hasControls ? stripControlChars(withoutAnsi) : withoutAnsi;
765
- const redacted = hasReplacementChars ? withoutControlChars.split("\n").map((line) => redactBinaryLikeLine(line)).join("\n") : withoutControlChars;
766
- return applyRtlIsolation(LONG_TOKEN_TEST_RE.test(redacted) ? redacted.replace(LONG_TOKEN_RE, normalizeLongTokenForDisplay) : redacted);
767
- }
768
- function resolveFinalAssistantText(params) {
769
- const finalText = params.finalText ?? "";
770
- if (finalText.trim()) return finalText;
771
- const streamedText = params.streamedText ?? "";
772
- if (streamedText.trim()) return streamedText;
773
- const errorMessage = params.errorMessage ?? "";
774
- if (errorMessage.trim()) return formatRawAssistantErrorForUi(errorMessage);
775
- return "(no output)";
776
- }
777
- function composeThinkingAndContent(params) {
778
- const thinkingText = params.thinkingText?.trim() ?? "";
779
- const contentText = params.contentText?.trim() ?? "";
780
- const parts = [];
781
- if (params.showThinking && thinkingText) parts.push(`[thinking]\n${thinkingText}`);
782
- if (contentText) parts.push(contentText);
783
- return parts.join("\n\n").trim();
784
- }
785
- function asMessageRecord(message) {
786
- if (!message || typeof message !== "object") return;
787
- return message;
788
- }
789
- function resolveMessageRecord(message) {
790
- const record = asMessageRecord(message);
791
- if (!record) return;
792
- return {
793
- record,
794
- content: record.content
795
- };
796
- }
797
- function formatAssistantErrorFromRecord(record) {
798
- if ((typeof record.stopReason === "string" ? record.stopReason : "") !== "error") return "";
799
- return formatRawAssistantErrorForUi(typeof record.errorMessage === "string" ? record.errorMessage : "");
800
- }
801
- function collectSanitizedBlockStrings(params) {
802
- if (!Array.isArray(params.content)) return [];
803
- const parts = [];
804
- for (const block of params.content) {
805
- if (!block || typeof block !== "object") continue;
806
- const rec = block;
807
- if (rec.type === params.blockType && typeof rec[params.valueKey] === "string") parts.push(sanitizeRenderableText(rec[params.valueKey]));
808
- }
809
- return parts;
810
- }
811
- /**
812
- * Extract ONLY thinking blocks from message content.
813
- * Model-agnostic: returns empty string if no thinking blocks exist.
814
- */
815
- function extractThinkingFromMessage(message) {
816
- const resolved = resolveMessageRecord(message);
817
- if (!resolved) return "";
818
- const { content } = resolved;
819
- if (typeof content === "string") return "";
820
- return collectSanitizedBlockStrings({
821
- content,
822
- blockType: "thinking",
823
- valueKey: "thinking"
824
- }).join("\n").trim();
825
- }
826
- /**
827
- * Extract ONLY text content blocks from message (excludes thinking).
828
- * Model-agnostic: works for any model with text content blocks.
829
- */
830
- function extractContentFromMessage(message) {
831
- const resolved = resolveMessageRecord(message);
832
- if (!resolved) return "";
833
- const { record, content } = resolved;
834
- if (typeof content === "string") return sanitizeRenderableText(content).trim();
835
- const parts = collectSanitizedBlockStrings({
836
- content,
837
- blockType: "text",
838
- valueKey: "text"
839
- });
840
- if (parts.length > 0) return parts.join("\n").trim();
841
- return formatAssistantErrorFromRecord(record);
842
- }
843
- function extractTextBlocks(content, opts) {
844
- if (typeof content === "string") return sanitizeRenderableText(content).trim();
845
- if (!Array.isArray(content)) return "";
846
- const textParts = collectSanitizedBlockStrings({
847
- content,
848
- blockType: "text",
849
- valueKey: "text"
850
- });
851
- return composeThinkingAndContent({
852
- thinkingText: (opts?.includeThinking === true ? collectSanitizedBlockStrings({
853
- content,
854
- blockType: "thinking",
855
- valueKey: "thinking"
856
- }) : []).join("\n").trim(),
857
- contentText: textParts.join("\n").trim(),
858
- showThinking: opts?.includeThinking ?? false
859
- });
860
- }
861
- function extractTextFromMessage(message, opts) {
862
- const record = asMessageRecord(message);
863
- if (!record) return "";
864
- const text = extractTextBlocks(record.content, opts);
865
- if (text) {
866
- if (record.role === "user") return stripLeadingInboundMetadata(text);
867
- return text;
868
- }
869
- const errorText = formatAssistantErrorFromRecord(record);
870
- if (!errorText) return "";
871
- return errorText;
872
- }
873
- function isCommandMessage(message) {
874
- if (!message || typeof message !== "object") return false;
875
- return message.command === true;
876
- }
877
- function formatTokens(total, context) {
878
- if (total == null && context == null) return "tokens ?";
879
- const totalLabel = total == null ? "?" : formatTokenCount(total);
880
- if (context == null) return `tokens ${totalLabel}`;
881
- const pct = typeof total === "number" && context > 0 ? Math.min(999, Math.round(total / context * 100)) : null;
882
- return `tokens ${totalLabel}/${formatTokenCount(context)}${pct !== null ? ` (${pct}%)` : ""}`;
883
- }
884
- function formatContextUsageLine(params) {
885
- const totalLabel = typeof params.total === "number" ? formatTokenCount(params.total) : "?";
886
- const ctxLabel = typeof params.context === "number" ? formatTokenCount(params.context) : "?";
887
- const pct = typeof params.percent === "number" ? Math.min(999, Math.round(params.percent)) : null;
888
- const extra = [typeof params.remaining === "number" ? `${formatTokenCount(params.remaining)} left` : null, pct !== null ? `${pct}%` : null].filter(Boolean).join(", ");
889
- return `tokens ${totalLabel}/${ctxLabel}${extra ? ` (${extra})` : ""}`;
890
- }
891
- function asString(value, fallback = "") {
892
- if (typeof value === "string") return value;
893
- if (typeof value === "number" || typeof value === "boolean") return String(value);
894
- return fallback;
895
- }
896
- //#endregion
897
- //#region src/tui/components/tool-execution.ts
898
- const PREVIEW_LINES = 12;
899
- function formatArgs(toolName, args) {
900
- const detail = formatToolDetail(resolveToolDisplay({
901
- name: toolName,
902
- args
903
- }));
904
- if (detail) return sanitizeRenderableText(detail);
905
- if (!args || typeof args !== "object") return "";
906
- try {
907
- return sanitizeRenderableText(JSON.stringify(args));
908
- } catch {
909
- return "";
910
- }
911
- }
912
- function extractText(result) {
913
- if (!result?.content) return "";
914
- const lines = [];
915
- for (const entry of result.content) if (entry.type === "text" && entry.text) lines.push(sanitizeRenderableText(entry.text));
916
- else if (entry.type === "image") {
917
- const mime = entry.mimeType ?? "image";
918
- const size = entry.bytes ? ` ${Math.round(entry.bytes / 1024)}kb` : "";
919
- const omitted = entry.omitted ? " (omitted)" : "";
920
- lines.push(`[${mime}${size}${omitted}]`);
921
- }
922
- return lines.join("\n").trim();
923
- }
924
- var ToolExecutionComponent = class extends Container {
925
- constructor(toolName, args) {
926
- super();
927
- this.expanded = false;
928
- this.isError = false;
929
- this.isPartial = true;
930
- this.toolName = toolName;
931
- this.args = args;
932
- this.box = new Box(1, 1, (line) => theme.toolPendingBg(line));
933
- this.header = new Text("", 0, 0);
934
- this.argsLine = new Text("", 0, 0);
935
- this.output = new Markdown("", 0, 0, markdownTheme, { color: (line) => theme.toolOutput(line) });
936
- this.addChild(new Spacer(1));
937
- this.addChild(this.box);
938
- this.box.addChild(this.header);
939
- this.box.addChild(this.argsLine);
940
- this.box.addChild(this.output);
941
- this.refresh();
942
- }
943
- setArgs(args) {
944
- this.args = args;
945
- this.refresh();
946
- }
947
- setExpanded(expanded) {
948
- this.expanded = expanded;
949
- this.refresh();
950
- }
951
- setResult(result, opts) {
952
- this.result = result;
953
- this.isPartial = false;
954
- this.isError = Boolean(opts?.isError);
955
- this.refresh();
956
- }
957
- setPartialResult(result) {
958
- this.result = result;
959
- this.isPartial = true;
960
- this.refresh();
961
- }
962
- refresh() {
963
- const bg = this.isPartial ? theme.toolPendingBg : this.isError ? theme.toolErrorBg : theme.toolSuccessBg;
964
- this.box.setBgFn((line) => bg(line));
965
- const display = resolveToolDisplay({
966
- name: this.toolName,
967
- args: this.args
968
- });
969
- const title = `${display.emoji} ${display.label}${this.isPartial ? " (running)" : ""}`;
970
- this.header.setText(theme.toolTitle(theme.bold(title)));
971
- const argLine = formatArgs(this.toolName, this.args);
972
- this.argsLine.setText(argLine ? theme.dim(argLine) : theme.dim(" "));
973
- const text = extractText(this.result) || (this.isPartial ? "…" : "");
974
- if (!this.expanded && text) {
975
- const lines = text.split("\n");
976
- const preview = lines.length > PREVIEW_LINES ? `${lines.slice(0, PREVIEW_LINES).join("\n")}\n…` : text;
977
- this.output.setText(preview);
978
- } else this.output.setText(text);
979
- }
980
- };
981
- //#endregion
982
- //#region src/tui/components/markdown-message.ts
983
- var MarkdownMessageComponent = class extends Container {
984
- constructor(text, y, options) {
985
- super();
986
- this.body = new Markdown(text, 1, y, markdownTheme, options);
987
- this.addChild(new Spacer(1));
988
- this.addChild(this.body);
989
- }
990
- setText(text) {
991
- this.body.setText(text);
992
- }
993
- };
994
- //#endregion
995
- //#region src/tui/components/user-message.ts
996
- var UserMessageComponent = class extends MarkdownMessageComponent {
997
- constructor(text) {
998
- super(text, 1, {
999
- bgColor: (line) => theme.userBg(line),
1000
- color: (line) => theme.userText(line)
1001
- });
1002
- }
1003
- };
1004
- //#endregion
1005
- //#region src/tui/components/chat-log.ts
1006
- var ChatLog = class extends Container {
1007
- constructor(maxComponents = 180) {
1008
- super();
1009
- this.toolById = /* @__PURE__ */ new Map();
1010
- this.streamingRuns = /* @__PURE__ */ new Map();
1011
- this.btwMessage = null;
1012
- this.toolsExpanded = false;
1013
- this.maxComponents = Math.max(20, Math.floor(maxComponents));
1014
- }
1015
- dropComponentReferences(component) {
1016
- for (const [toolId, tool] of this.toolById.entries()) if (tool === component) this.toolById.delete(toolId);
1017
- for (const [runId, message] of this.streamingRuns.entries()) if (message === component) this.streamingRuns.delete(runId);
1018
- if (this.btwMessage === component) this.btwMessage = null;
1019
- }
1020
- pruneOverflow() {
1021
- while (this.children.length > this.maxComponents) {
1022
- const oldest = this.children[0];
1023
- if (!oldest) return;
1024
- this.removeChild(oldest);
1025
- this.dropComponentReferences(oldest);
1026
- }
1027
- }
1028
- append(component) {
1029
- this.addChild(component);
1030
- this.pruneOverflow();
1031
- }
1032
- clearAll() {
1033
- this.clear();
1034
- this.toolById.clear();
1035
- this.streamingRuns.clear();
1036
- this.btwMessage = null;
1037
- }
1038
- addSystem(text) {
1039
- this.append(new Spacer(1));
1040
- this.append(new Text(theme.system(text), 1, 0));
1041
- }
1042
- addUser(text) {
1043
- this.append(new UserMessageComponent(text));
1044
- }
1045
- resolveRunId(runId) {
1046
- return runId ?? "default";
1047
- }
1048
- startAssistant(text, runId) {
1049
- const effectiveRunId = this.resolveRunId(runId);
1050
- const existing = this.streamingRuns.get(effectiveRunId);
1051
- if (existing) {
1052
- existing.setText(text);
1053
- return existing;
1054
- }
1055
- const component = new AssistantMessageComponent(text);
1056
- this.streamingRuns.set(effectiveRunId, component);
1057
- this.append(component);
1058
- return component;
1059
- }
1060
- updateAssistant(text, runId) {
1061
- const effectiveRunId = this.resolveRunId(runId);
1062
- const existing = this.streamingRuns.get(effectiveRunId);
1063
- if (!existing) {
1064
- this.startAssistant(text, runId);
1065
- return;
1066
- }
1067
- existing.setText(text);
1068
- }
1069
- finalizeAssistant(text, runId) {
1070
- const effectiveRunId = this.resolveRunId(runId);
1071
- const existing = this.streamingRuns.get(effectiveRunId);
1072
- if (existing) {
1073
- existing.setText(text);
1074
- this.streamingRuns.delete(effectiveRunId);
1075
- return;
1076
- }
1077
- this.append(new AssistantMessageComponent(text));
1078
- }
1079
- dropAssistant(runId) {
1080
- const effectiveRunId = this.resolveRunId(runId);
1081
- const existing = this.streamingRuns.get(effectiveRunId);
1082
- if (!existing) return;
1083
- this.removeChild(existing);
1084
- this.streamingRuns.delete(effectiveRunId);
1085
- }
1086
- showBtw(params) {
1087
- if (this.btwMessage) {
1088
- this.btwMessage.setResult(params);
1089
- if (this.children[this.children.length - 1] !== this.btwMessage) {
1090
- this.removeChild(this.btwMessage);
1091
- this.append(this.btwMessage);
1092
- }
1093
- return this.btwMessage;
1094
- }
1095
- const component = new BtwInlineMessage(params);
1096
- this.btwMessage = component;
1097
- this.append(component);
1098
- return component;
1099
- }
1100
- dismissBtw() {
1101
- if (!this.btwMessage) return;
1102
- this.removeChild(this.btwMessage);
1103
- this.btwMessage = null;
1104
- }
1105
- hasVisibleBtw() {
1106
- return this.btwMessage !== null;
1107
- }
1108
- startTool(toolCallId, toolName, args) {
1109
- const existing = this.toolById.get(toolCallId);
1110
- if (existing) {
1111
- existing.setArgs(args);
1112
- return existing;
1113
- }
1114
- const component = new ToolExecutionComponent(toolName, args);
1115
- component.setExpanded(this.toolsExpanded);
1116
- this.toolById.set(toolCallId, component);
1117
- this.append(component);
1118
- return component;
1119
- }
1120
- updateToolArgs(toolCallId, args) {
1121
- const existing = this.toolById.get(toolCallId);
1122
- if (!existing) return;
1123
- existing.setArgs(args);
1124
- }
1125
- updateToolResult(toolCallId, result, opts) {
1126
- const existing = this.toolById.get(toolCallId);
1127
- if (!existing) return;
1128
- if (opts?.partial) {
1129
- existing.setPartialResult(result);
1130
- return;
1131
- }
1132
- existing.setResult(result, { isError: opts?.isError });
1133
- }
1134
- setToolsExpanded(expanded) {
1135
- this.toolsExpanded = expanded;
1136
- for (const tool of this.toolById.values()) tool.setExpanded(expanded);
1137
- }
1138
- };
1139
- //#endregion
1140
- //#region src/tui/components/custom-editor.ts
1141
- var CustomEditor = class extends Editor {
1142
- handleInput(data) {
1143
- if (matchesKey(data, Key.alt("enter")) && this.onAltEnter) {
1144
- this.onAltEnter();
1145
- return;
1146
- }
1147
- if (matchesKey(data, Key.ctrl("l")) && this.onCtrlL) {
1148
- this.onCtrlL();
1149
- return;
1150
- }
1151
- if (matchesKey(data, Key.ctrl("o")) && this.onCtrlO) {
1152
- this.onCtrlO();
1153
- return;
1154
- }
1155
- if (matchesKey(data, Key.ctrl("p")) && this.onCtrlP) {
1156
- this.onCtrlP();
1157
- return;
1158
- }
1159
- if (matchesKey(data, Key.ctrl("g")) && this.onCtrlG) {
1160
- this.onCtrlG();
1161
- return;
1162
- }
1163
- if (matchesKey(data, Key.ctrl("t")) && this.onCtrlT) {
1164
- this.onCtrlT();
1165
- return;
1166
- }
1167
- if (matchesKey(data, Key.shift("tab")) && this.onShiftTab) {
1168
- this.onShiftTab();
1169
- return;
1170
- }
1171
- if (matchesKey(data, Key.escape) && this.onEscape && !this.isShowingAutocomplete()) {
1172
- this.onEscape();
1173
- return;
1174
- }
1175
- if (matchesKey(data, Key.ctrl("c")) && this.onCtrlC) {
1176
- this.onCtrlC();
1177
- return;
1178
- }
1179
- if (matchesKey(data, Key.ctrl("d"))) {
1180
- if (this.getText().length === 0 && this.onCtrlD) this.onCtrlD();
1181
- return;
1182
- }
1183
- super.handleInput(data);
1184
- }
1185
- };
1186
- //#endregion
1187
- //#region src/tui/gateway-chat.ts
1188
- function trimToUndefined(value) {
1189
- if (typeof value !== "string") return;
1190
- const trimmed = value.trim();
1191
- return trimmed.length > 0 ? trimmed : void 0;
1192
- }
1193
- function throwGatewayAuthResolutionError(reason) {
1194
- throw new Error([
1195
- reason,
1196
- "Fix: set MOLDCLAW_GATEWAY_TOKEN/MOLDCLAW_GATEWAY_PASSWORD, pass --token/--password,",
1197
- "or resolve the configured secret provider for this credential."
1198
- ].join("\n"));
1199
- }
1200
- var GatewayChatClient = class GatewayChatClient {
1201
- constructor(connection) {
1202
- this.connection = connection;
1203
- this.readyPromise = new Promise((resolve) => {
1204
- this.resolveReady = resolve;
1205
- });
1206
- this.client = new GatewayClient({
1207
- url: connection.url,
1208
- token: connection.token,
1209
- password: connection.password,
1210
- clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
1211
- clientDisplayName: "moldclaw-tui",
1212
- clientVersion: VERSION,
1213
- platform: process.platform,
1214
- mode: GATEWAY_CLIENT_MODES.UI,
1215
- caps: [GATEWAY_CLIENT_CAPS.TOOL_EVENTS],
1216
- instanceId: randomUUID(),
1217
- minProtocol: 3,
1218
- maxProtocol: 3,
1219
- onHelloOk: (hello) => {
1220
- this.hello = hello;
1221
- this.resolveReady?.();
1222
- this.onConnected?.();
1223
- },
1224
- onEvent: (evt) => {
1225
- this.onEvent?.({
1226
- event: evt.event,
1227
- payload: evt.payload,
1228
- seq: evt.seq
1229
- });
1230
- },
1231
- onClose: (_code, reason) => {
1232
- this.readyPromise = new Promise((resolve) => {
1233
- this.resolveReady = resolve;
1234
- });
1235
- this.onDisconnected?.(reason);
1236
- },
1237
- onGap: (info) => {
1238
- this.onGap?.(info);
1239
- }
1240
- });
1241
- }
1242
- static async connect(opts) {
1243
- return new GatewayChatClient(await resolveGatewayConnection(opts));
1244
- }
1245
- start() {
1246
- this.client.start();
1247
- }
1248
- stop() {
1249
- this.client.stop();
1250
- }
1251
- async waitForReady() {
1252
- await this.readyPromise;
1253
- }
1254
- async sendChat(opts) {
1255
- const runId = opts.runId ?? randomUUID();
1256
- await this.client.request("chat.send", {
1257
- sessionKey: opts.sessionKey,
1258
- message: opts.message,
1259
- thinking: opts.thinking,
1260
- deliver: opts.deliver,
1261
- timeoutMs: opts.timeoutMs,
1262
- idempotencyKey: runId
1263
- });
1264
- return { runId };
1265
- }
1266
- async abortChat(opts) {
1267
- return await this.client.request("chat.abort", {
1268
- sessionKey: opts.sessionKey,
1269
- runId: opts.runId
1270
- });
1271
- }
1272
- async loadHistory(opts) {
1273
- return await this.client.request("chat.history", {
1274
- sessionKey: opts.sessionKey,
1275
- limit: opts.limit
1276
- });
1277
- }
1278
- async listSessions(opts) {
1279
- return await this.client.request("sessions.list", {
1280
- limit: opts?.limit,
1281
- activeMinutes: opts?.activeMinutes,
1282
- includeGlobal: opts?.includeGlobal,
1283
- includeUnknown: opts?.includeUnknown,
1284
- includeDerivedTitles: opts?.includeDerivedTitles,
1285
- includeLastMessage: opts?.includeLastMessage,
1286
- agentId: opts?.agentId
1287
- });
1288
- }
1289
- async listAgents() {
1290
- return await this.client.request("agents.list", {});
1291
- }
1292
- async patchSession(opts) {
1293
- return await this.client.request("sessions.patch", opts);
1294
- }
1295
- async resetSession(key, reason) {
1296
- return await this.client.request("sessions.reset", {
1297
- key,
1298
- ...reason ? { reason } : {}
1299
- });
1300
- }
1301
- async getStatus() {
1302
- return await this.client.request("status");
1303
- }
1304
- async listModels() {
1305
- const res = await this.client.request("models.list");
1306
- return Array.isArray(res?.models) ? res.models : [];
1307
- }
1308
- };
1309
- async function resolveGatewayConnection(opts) {
1310
- const config = loadConfig();
1311
- const env = process.env;
1312
- const gatewayAuthMode = config.gateway?.auth?.mode;
1313
- const isRemoteMode = config.gateway?.mode === "remote";
1314
- const remote = config.gateway?.remote;
1315
- const envToken = trimToUndefined(env.MOLDCLAW_GATEWAY_TOKEN);
1316
- const envPassword = trimToUndefined(env.MOLDCLAW_GATEWAY_PASSWORD);
1317
- const urlOverride = typeof opts.url === "string" && opts.url.trim().length > 0 ? opts.url.trim() : void 0;
1318
- const explicitAuth = resolveExplicitGatewayAuth({
1319
- token: opts.token,
1320
- password: opts.password
1321
- });
1322
- ensureExplicitGatewayAuth({
1323
- urlOverride,
1324
- urlOverrideSource: "cli",
1325
- explicitAuth,
1326
- errorHint: "Fix: pass --token or --password when using --url."
1327
- });
1328
- const url = buildGatewayConnectionDetails({
1329
- config,
1330
- ...urlOverride ? { url: urlOverride } : {}
1331
- }).url;
1332
- if (urlOverride) return {
1333
- url,
1334
- token: explicitAuth.token,
1335
- password: explicitAuth.password
1336
- };
1337
- if (isRemoteMode) {
1338
- const remoteToken = explicitAuth.token ? { value: explicitAuth.token } : await resolveConfiguredSecretInputString({
1339
- value: remote?.token,
1340
- path: "gateway.remote.token",
1341
- env,
1342
- config
1343
- });
1344
- const remotePassword = explicitAuth.password || envPassword ? { value: explicitAuth.password ?? envPassword } : await resolveConfiguredSecretInputString({
1345
- value: remote?.password,
1346
- path: "gateway.remote.password",
1347
- env,
1348
- config
1349
- });
1350
- const token = explicitAuth.token ?? remoteToken.value;
1351
- const password = explicitAuth.password ?? envPassword ?? remotePassword.value;
1352
- if (!token && !password) throwGatewayAuthResolutionError(remoteToken.unresolvedRefReason ?? remotePassword.unresolvedRefReason ?? "Missing gateway auth credentials.");
1353
- return {
1354
- url,
1355
- token,
1356
- password
1357
- };
1358
- }
1359
- if (gatewayAuthMode === "none" || gatewayAuthMode === "trusted-proxy") return {
1360
- url,
1361
- token: explicitAuth.token ?? envToken,
1362
- password: explicitAuth.password ?? envPassword
1363
- };
1364
- try {
1365
- assertExplicitGatewayAuthModeWhenBothConfigured(config);
1366
- } catch (err) {
1367
- throwGatewayAuthResolutionError(err instanceof Error ? err.message : String(err));
1368
- }
1369
- const defaults = config.secrets?.defaults;
1370
- const hasConfiguredToken = hasConfiguredSecretInput(config.gateway?.auth?.token, defaults);
1371
- const hasConfiguredPassword = hasConfiguredSecretInput(config.gateway?.auth?.password, defaults);
1372
- if (gatewayAuthMode === "password") {
1373
- const localPassword = explicitAuth.password || envPassword ? { value: explicitAuth.password ?? envPassword } : await resolveConfiguredSecretInputString({
1374
- value: config.gateway?.auth?.password,
1375
- path: "gateway.auth.password",
1376
- env,
1377
- config
1378
- });
1379
- const password = explicitAuth.password ?? envPassword ?? localPassword.value;
1380
- if (!password) throwGatewayAuthResolutionError(localPassword.unresolvedRefReason ?? "Missing gateway auth password.");
1381
- return {
1382
- url,
1383
- token: explicitAuth.token ?? envToken,
1384
- password
1385
- };
1386
- }
1387
- const resolveToken = async () => {
1388
- const localToken = explicitAuth.token ? { value: explicitAuth.token } : await resolveConfiguredSecretInputString({
1389
- value: config.gateway?.auth?.token,
1390
- path: "gateway.auth.token",
1391
- env,
1392
- config
1393
- });
1394
- const token = explicitAuth.token ?? localToken.value ?? envToken;
1395
- if (!token) throwGatewayAuthResolutionError(localToken.unresolvedRefReason ?? "Missing gateway auth token.");
1396
- return token;
1397
- };
1398
- if (gatewayAuthMode === "token") return {
1399
- url,
1400
- token: await resolveToken(),
1401
- password: explicitAuth.password ?? envPassword
1402
- };
1403
- const passwordCandidate = explicitAuth.password ?? envPassword;
1404
- if (Boolean(passwordCandidate) || hasConfiguredPassword && !hasConfiguredToken) {
1405
- const localPassword = passwordCandidate ? { value: passwordCandidate } : await resolveConfiguredSecretInputString({
1406
- value: config.gateway?.auth?.password,
1407
- path: "gateway.auth.password",
1408
- env,
1409
- config
1410
- });
1411
- const password = explicitAuth.password ?? localPassword.value ?? envPassword;
1412
- if (!password) throwGatewayAuthResolutionError(localPassword.unresolvedRefReason ?? "Missing gateway auth password.");
1413
- return {
1414
- url,
1415
- token: explicitAuth.token ?? envToken,
1416
- password
1417
- };
1418
- }
1419
- return {
1420
- url,
1421
- token: await resolveToken(),
1422
- password: explicitAuth.password ?? envPassword
1423
- };
1424
- }
1425
- //#endregion
1426
- //#region src/tui/components/fuzzy-filter.ts
1427
- /**
1428
- * Shared fuzzy filtering utilities for select list components.
1429
- */
1430
- /**
1431
- * Word boundary characters for matching.
1432
- */
1433
- const WORD_BOUNDARY_CHARS = /[\s\-_./:#@]/;
1434
- /**
1435
- * Check if position is at a word boundary.
1436
- */
1437
- function isWordBoundary(text, index) {
1438
- return index === 0 || WORD_BOUNDARY_CHARS.test(text[index - 1] ?? "");
1439
- }
1440
- /**
1441
- * Find index where query matches at a word boundary in text.
1442
- * Returns null if no match.
1443
- */
1444
- function findWordBoundaryIndex(text, query) {
1445
- if (!query) return null;
1446
- const textLower = text.toLowerCase();
1447
- const queryLower = query.toLowerCase();
1448
- const maxIndex = textLower.length - queryLower.length;
1449
- if (maxIndex < 0) return null;
1450
- for (let i = 0; i <= maxIndex; i++) if (textLower.startsWith(queryLower, i) && isWordBoundary(textLower, i)) return i;
1451
- return null;
1452
- }
1453
- /**
1454
- * Fuzzy match with pre-lowercased inputs (avoids toLowerCase on every keystroke).
1455
- * Returns score (lower = better) or null if no match.
1456
- */
1457
- function fuzzyMatchLower(queryLower, textLower) {
1458
- if (queryLower.length === 0) return 0;
1459
- if (queryLower.length > textLower.length) return null;
1460
- let queryIndex = 0;
1461
- let score = 0;
1462
- let lastMatchIndex = -1;
1463
- let consecutiveMatches = 0;
1464
- for (let i = 0; i < textLower.length && queryIndex < queryLower.length; i++) if (textLower[i] === queryLower[queryIndex]) {
1465
- const isAtWordBoundary = isWordBoundary(textLower, i);
1466
- if (lastMatchIndex === i - 1) {
1467
- consecutiveMatches++;
1468
- score -= consecutiveMatches * 5;
1469
- } else {
1470
- consecutiveMatches = 0;
1471
- if (lastMatchIndex >= 0) score += (i - lastMatchIndex - 1) * 2;
1472
- }
1473
- if (isAtWordBoundary) score -= 10;
1474
- score += i * .1;
1475
- lastMatchIndex = i;
1476
- queryIndex++;
1477
- }
1478
- return queryIndex < queryLower.length ? null : score;
1479
- }
1480
- /**
1481
- * Filter items using pre-lowercased searchTextLower field.
1482
- * Supports space-separated tokens (all must match).
1483
- */
1484
- function fuzzyFilterLower(items, queryLower) {
1485
- const trimmed = queryLower.trim();
1486
- if (!trimmed) return items;
1487
- const tokens = trimmed.split(/\s+/).filter((t) => t.length > 0);
1488
- if (tokens.length === 0) return items;
1489
- const results = [];
1490
- for (const item of items) {
1491
- const text = item.searchTextLower ?? "";
1492
- let totalScore = 0;
1493
- let allMatch = true;
1494
- for (const token of tokens) {
1495
- const score = fuzzyMatchLower(token, text);
1496
- if (score !== null) totalScore += score;
1497
- else {
1498
- allMatch = false;
1499
- break;
1500
- }
1501
- }
1502
- if (allMatch) results.push({
1503
- item,
1504
- score: totalScore
1505
- });
1506
- }
1507
- results.sort((a, b) => a.score - b.score);
1508
- return results.map((r) => r.item);
1509
- }
1510
- /**
1511
- * Prepare items for fuzzy filtering by pre-computing lowercase search text.
1512
- */
1513
- function prepareSearchItems(items) {
1514
- return items.map((item) => {
1515
- const parts = [];
1516
- if (item.label) parts.push(item.label);
1517
- if (item.description) parts.push(item.description);
1518
- if (item.searchText) parts.push(item.searchText);
1519
- return {
1520
- ...item,
1521
- searchTextLower: parts.join(" ").toLowerCase()
1522
- };
1523
- });
1524
- }
1525
- //#endregion
1526
- //#region src/tui/components/filterable-select-list.ts
1527
- /**
1528
- * Combines text input filtering with a select list.
1529
- * User types to filter, arrows/j/k to navigate, Enter to select, Escape to clear/cancel.
1530
- */
1531
- var FilterableSelectList = class {
1532
- constructor(items, maxVisible, theme) {
1533
- this.filterText = "";
1534
- this.allItems = prepareSearchItems(items);
1535
- this.maxVisible = maxVisible;
1536
- this.theme = theme;
1537
- this.input = new Input();
1538
- this.selectList = new SelectList(this.allItems, maxVisible, theme);
1539
- }
1540
- applyFilter() {
1541
- const queryLower = this.filterText.toLowerCase();
1542
- if (!queryLower.trim()) {
1543
- this.selectList = new SelectList(this.allItems, this.maxVisible, this.theme);
1544
- return;
1545
- }
1546
- this.selectList = new SelectList(fuzzyFilterLower(this.allItems, queryLower), this.maxVisible, this.theme);
1547
- }
1548
- invalidate() {
1549
- this.input.invalidate();
1550
- this.selectList.invalidate();
1551
- }
1552
- render(width) {
1553
- const lines = [];
1554
- const filterLabel = this.theme.filterLabel("Filter: ");
1555
- const inputText = this.input.render(width - 8)[0] ?? "";
1556
- lines.push(filterLabel + inputText);
1557
- lines.push(chalk.dim("─".repeat(Math.max(0, width))));
1558
- const listLines = this.selectList.render(width);
1559
- lines.push(...listLines);
1560
- return lines;
1561
- }
1562
- handleInput(keyData) {
1563
- const allowVimNav = !this.filterText.trim();
1564
- if (matchesKey(keyData, "up") || matchesKey(keyData, "ctrl+p") || allowVimNav && keyData === "k") {
1565
- this.selectList.handleInput("\x1B[A");
1566
- return;
1567
- }
1568
- if (matchesKey(keyData, "down") || matchesKey(keyData, "ctrl+n") || allowVimNav && keyData === "j") {
1569
- this.selectList.handleInput("\x1B[B");
1570
- return;
1571
- }
1572
- if (matchesKey(keyData, "enter")) {
1573
- const selected = this.selectList.getSelectedItem();
1574
- if (selected) this.onSelect?.(selected);
1575
- return;
1576
- }
1577
- if (getEditorKeybindings().matches(keyData, "selectCancel")) {
1578
- if (this.filterText) {
1579
- this.filterText = "";
1580
- this.input.setValue("");
1581
- this.applyFilter();
1582
- } else this.onCancel?.();
1583
- return;
1584
- }
1585
- const prevValue = this.input.getValue();
1586
- this.input.handleInput(keyData);
1587
- const newValue = this.input.getValue();
1588
- if (newValue !== prevValue) {
1589
- this.filterText = newValue;
1590
- this.applyFilter();
1591
- }
1592
- }
1593
- getSelectedItem() {
1594
- return this.selectList.getSelectedItem();
1595
- }
1596
- getFilterText() {
1597
- return this.filterText;
1598
- }
1599
- };
1600
- //#endregion
1601
- //#region src/tui/components/searchable-select-list.ts
1602
- const ANSI_ESCAPE = String.fromCharCode(27);
1603
- const ANSI_SGR_REGEX = new RegExp(`${ANSI_ESCAPE}\\[[0-9;]*m`, "g");
1604
- /**
1605
- * A select list with a search input at the top for fuzzy filtering.
1606
- */
1607
- var SearchableSelectList = class SearchableSelectList {
1608
- static {
1609
- this.DESCRIPTION_LAYOUT_MIN_WIDTH = 40;
1610
- }
1611
- static {
1612
- this.DESCRIPTION_MIN_WIDTH = 12;
1613
- }
1614
- static {
1615
- this.DESCRIPTION_SPACING_WIDTH = 2;
1616
- }
1617
- static {
1618
- this.RIGHT_MARGIN_WIDTH = 2;
1619
- }
1620
- constructor(items, maxVisible, theme) {
1621
- this.selectedIndex = 0;
1622
- this.regexCache = /* @__PURE__ */ new Map();
1623
- this.compareByScore = (a, b) => {
1624
- if (a.tier !== b.tier) return a.tier - b.tier;
1625
- if (a.score !== b.score) return a.score - b.score;
1626
- return this.getItemLabel(a.item).localeCompare(this.getItemLabel(b.item));
1627
- };
1628
- this.items = items;
1629
- this.filteredItems = items;
1630
- this.maxVisible = maxVisible;
1631
- this.theme = theme;
1632
- this.searchInput = new Input();
1633
- }
1634
- getCachedRegex(pattern) {
1635
- let regex = this.regexCache.get(pattern);
1636
- if (!regex) {
1637
- regex = new RegExp(this.escapeRegex(pattern), "gi");
1638
- this.regexCache.set(pattern, regex);
1639
- }
1640
- return regex;
1641
- }
1642
- updateFilter() {
1643
- const query = this.searchInput.getValue().trim();
1644
- if (!query) this.filteredItems = this.items;
1645
- else this.filteredItems = this.smartFilter(query);
1646
- this.selectedIndex = 0;
1647
- this.notifySelectionChange();
1648
- }
1649
- /**
1650
- * Smart filtering that prioritizes:
1651
- * 1. Exact substring match in label (highest priority)
1652
- * 2. Word-boundary prefix match in label
1653
- * 3. Exact substring in description
1654
- * 4. Fuzzy match (lowest priority)
1655
- */
1656
- smartFilter(query) {
1657
- const q = query.toLowerCase();
1658
- const scoredItems = [];
1659
- const fuzzyCandidates = [];
1660
- for (const item of this.items) {
1661
- const rawLabel = this.getItemLabel(item);
1662
- const rawDesc = item.description ?? "";
1663
- const label = stripAnsi$1(rawLabel).toLowerCase();
1664
- const desc = stripAnsi$1(rawDesc).toLowerCase();
1665
- const labelIndex = label.indexOf(q);
1666
- if (labelIndex !== -1) {
1667
- scoredItems.push({
1668
- item,
1669
- tier: 0,
1670
- score: labelIndex
1671
- });
1672
- continue;
1673
- }
1674
- const wordBoundaryIndex = findWordBoundaryIndex(label, q);
1675
- if (wordBoundaryIndex !== null) {
1676
- scoredItems.push({
1677
- item,
1678
- tier: 1,
1679
- score: wordBoundaryIndex
1680
- });
1681
- continue;
1682
- }
1683
- const descIndex = desc.indexOf(q);
1684
- if (descIndex !== -1) {
1685
- scoredItems.push({
1686
- item,
1687
- tier: 2,
1688
- score: descIndex
1689
- });
1690
- continue;
1691
- }
1692
- const searchText = item.searchText ?? "";
1693
- fuzzyCandidates.push({
1694
- item,
1695
- searchTextLower: [
1696
- rawLabel,
1697
- rawDesc,
1698
- searchText
1699
- ].map((value) => stripAnsi$1(value)).filter(Boolean).join(" ").toLowerCase()
1700
- });
1701
- }
1702
- scoredItems.sort(this.compareByScore);
1703
- const fuzzyMatches = fuzzyFilterLower(fuzzyCandidates, q);
1704
- return [...scoredItems.map((s) => s.item), ...fuzzyMatches.map((entry) => entry.item)];
1705
- }
1706
- escapeRegex(str) {
1707
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1708
- }
1709
- getItemLabel(item) {
1710
- return item.label || item.value;
1711
- }
1712
- splitAnsiParts(text) {
1713
- const parts = [];
1714
- ANSI_SGR_REGEX.lastIndex = 0;
1715
- let lastIndex = 0;
1716
- let match;
1717
- while ((match = ANSI_SGR_REGEX.exec(text)) !== null) {
1718
- if (match.index > lastIndex) parts.push({
1719
- text: text.slice(lastIndex, match.index),
1720
- isAnsi: false
1721
- });
1722
- parts.push({
1723
- text: match[0],
1724
- isAnsi: true
1725
- });
1726
- lastIndex = match.index + match[0].length;
1727
- }
1728
- if (lastIndex < text.length) parts.push({
1729
- text: text.slice(lastIndex),
1730
- isAnsi: false
1731
- });
1732
- return parts;
1733
- }
1734
- highlightMatch(text, query) {
1735
- const tokens = query.trim().split(/\s+/).map((token) => token.toLowerCase()).filter((token) => token.length > 0);
1736
- if (tokens.length === 0) return text;
1737
- const uniqueTokens = Array.from(new Set(tokens)).toSorted((a, b) => b.length - a.length);
1738
- let parts = this.splitAnsiParts(text);
1739
- for (const token of uniqueTokens) {
1740
- const regex = this.getCachedRegex(token);
1741
- const nextParts = [];
1742
- for (const part of parts) {
1743
- if (part.isAnsi) {
1744
- nextParts.push(part);
1745
- continue;
1746
- }
1747
- regex.lastIndex = 0;
1748
- const replaced = part.text.replace(regex, (match) => this.theme.matchHighlight(match));
1749
- if (replaced === part.text) {
1750
- nextParts.push(part);
1751
- continue;
1752
- }
1753
- nextParts.push(...this.splitAnsiParts(replaced));
1754
- }
1755
- parts = nextParts;
1756
- }
1757
- return parts.map((part) => part.text).join("");
1758
- }
1759
- setSelectedIndex(index) {
1760
- this.selectedIndex = Math.max(0, Math.min(index, this.filteredItems.length - 1));
1761
- }
1762
- invalidate() {
1763
- this.searchInput.invalidate();
1764
- }
1765
- render(width) {
1766
- const lines = [];
1767
- const prompt = this.theme.searchPrompt("search: ");
1768
- const inputWidth = Math.max(1, width - visibleWidth(prompt));
1769
- const inputText = this.searchInput.render(inputWidth)[0] ?? "";
1770
- lines.push(`${prompt}${this.theme.searchInput(inputText)}`);
1771
- lines.push("");
1772
- const query = this.searchInput.getValue().trim();
1773
- if (this.filteredItems.length === 0) {
1774
- lines.push(this.theme.noMatch(" No matches"));
1775
- return lines;
1776
- }
1777
- const startIndex = Math.max(0, Math.min(this.selectedIndex - Math.floor(this.maxVisible / 2), this.filteredItems.length - this.maxVisible));
1778
- const endIndex = Math.min(startIndex + this.maxVisible, this.filteredItems.length);
1779
- for (let i = startIndex; i < endIndex; i++) {
1780
- const item = this.filteredItems[i];
1781
- if (!item) continue;
1782
- const isSelected = i === this.selectedIndex;
1783
- lines.push(this.renderItemLine(item, isSelected, width, query));
1784
- }
1785
- if (this.filteredItems.length > this.maxVisible) {
1786
- const scrollInfo = `${this.selectedIndex + 1}/${this.filteredItems.length}`;
1787
- lines.push(this.theme.scrollInfo(` ${scrollInfo}`));
1788
- }
1789
- return lines;
1790
- }
1791
- renderItemLine(item, isSelected, width, query) {
1792
- const prefix = isSelected ? "→ " : " ";
1793
- const prefixWidth = prefix.length;
1794
- const displayValue = this.getItemLabel(item);
1795
- const description = item.description;
1796
- if (description) {
1797
- const descriptionLayout = this.getDescriptionLayout(width, prefixWidth);
1798
- if (descriptionLayout) {
1799
- const truncatedValue = truncateToWidth(displayValue, descriptionLayout.maxValueWidth, "");
1800
- const valueText = this.highlightMatch(truncatedValue, query);
1801
- const usedByValue = visibleWidth(valueText);
1802
- const descriptionWidth = descriptionLayout.availableWidth - usedByValue - descriptionLayout.spacingWidth;
1803
- if (descriptionWidth >= SearchableSelectList.DESCRIPTION_MIN_WIDTH) {
1804
- const spacing = " ".repeat(descriptionLayout.spacingWidth);
1805
- const truncatedDesc = truncateToWidth(description, descriptionWidth, "");
1806
- const highlightedDesc = this.highlightMatch(truncatedDesc, query);
1807
- const line = `${prefix}${valueText}${spacing}${isSelected ? highlightedDesc : this.theme.description(highlightedDesc)}`;
1808
- return isSelected ? this.theme.selectedText(line) : line;
1809
- }
1810
- }
1811
- }
1812
- const truncatedValue = truncateToWidth(displayValue, width - prefixWidth - 2, "");
1813
- const line = `${prefix}${this.highlightMatch(truncatedValue, query)}`;
1814
- return isSelected ? this.theme.selectedText(line) : line;
1815
- }
1816
- getDescriptionLayout(width, prefixWidth) {
1817
- if (width <= SearchableSelectList.DESCRIPTION_LAYOUT_MIN_WIDTH) return null;
1818
- const availableWidth = Math.max(1, width - prefixWidth - SearchableSelectList.RIGHT_MARGIN_WIDTH);
1819
- const maxValueWidth = availableWidth - SearchableSelectList.DESCRIPTION_MIN_WIDTH - SearchableSelectList.DESCRIPTION_SPACING_WIDTH;
1820
- if (maxValueWidth < 1) return null;
1821
- return {
1822
- availableWidth,
1823
- maxValueWidth,
1824
- spacingWidth: SearchableSelectList.DESCRIPTION_SPACING_WIDTH
1825
- };
1826
- }
1827
- handleInput(keyData) {
1828
- if (isKeyRelease(keyData)) return;
1829
- const allowVimNav = !this.searchInput.getValue().trim();
1830
- if (matchesKey(keyData, "up") || matchesKey(keyData, "ctrl+p") || allowVimNav && keyData === "k") {
1831
- this.selectedIndex = Math.max(0, this.selectedIndex - 1);
1832
- this.notifySelectionChange();
1833
- return;
1834
- }
1835
- if (matchesKey(keyData, "down") || matchesKey(keyData, "ctrl+n") || allowVimNav && keyData === "j") {
1836
- this.selectedIndex = Math.min(this.filteredItems.length - 1, this.selectedIndex + 1);
1837
- this.notifySelectionChange();
1838
- return;
1839
- }
1840
- if (matchesKey(keyData, "enter")) {
1841
- const item = this.filteredItems[this.selectedIndex];
1842
- if (item && this.onSelect) this.onSelect(item);
1843
- return;
1844
- }
1845
- if (getEditorKeybindings().matches(keyData, "selectCancel")) {
1846
- if (this.onCancel) this.onCancel();
1847
- return;
1848
- }
1849
- const prevValue = this.searchInput.getValue();
1850
- this.searchInput.handleInput(keyData);
1851
- if (prevValue !== this.searchInput.getValue()) this.updateFilter();
1852
- }
1853
- notifySelectionChange() {
1854
- const item = this.filteredItems[this.selectedIndex];
1855
- if (item && this.onSelectionChange) this.onSelectionChange(item);
1856
- }
1857
- getSelectedItem() {
1858
- return this.filteredItems[this.selectedIndex] ?? null;
1859
- }
1860
- };
1861
- //#endregion
1862
- //#region src/tui/components/selectors.ts
1863
- function createSearchableSelectList(items, maxVisible = 7) {
1864
- return new SearchableSelectList(items, maxVisible, searchableSelectListTheme);
1865
- }
1866
- function createFilterableSelectList(items, maxVisible = 7) {
1867
- return new FilterableSelectList(items, maxVisible, filterableSelectListTheme);
1868
- }
1869
- function createSettingsList(items, onChange, onCancel, maxVisible = 7) {
1870
- return new SettingsList(items, maxVisible, settingsListTheme, onChange, onCancel);
1871
- }
1872
- //#endregion
1873
- //#region src/tui/tui-status-summary.ts
1874
- function formatStatusSummary(summary) {
1875
- const lines = [];
1876
- lines.push("Gateway status");
1877
- if (summary.runtimeVersion) lines.push(`Version: ${summary.runtimeVersion}`);
1878
- if (!summary.linkChannel) lines.push("Link channel: unknown");
1879
- else {
1880
- const linkLabel = summary.linkChannel.label ?? "Link channel";
1881
- const linked = summary.linkChannel.linked === true;
1882
- const authAge = linked && typeof summary.linkChannel.authAgeMs === "number" ? ` (last refreshed ${formatTimeAgo(summary.linkChannel.authAgeMs)})` : "";
1883
- lines.push(`${linkLabel}: ${linked ? "linked" : "not linked"}${authAge}`);
1884
- }
1885
- const providerSummary = Array.isArray(summary.providerSummary) ? summary.providerSummary : [];
1886
- if (providerSummary.length > 0) {
1887
- lines.push("");
1888
- lines.push("System:");
1889
- for (const line of providerSummary) lines.push(` ${line}`);
1890
- }
1891
- const heartbeatAgents = summary.heartbeat?.agents ?? [];
1892
- if (heartbeatAgents.length > 0) {
1893
- const heartbeatParts = heartbeatAgents.map((agent) => {
1894
- const agentId = agent.agentId ?? "unknown";
1895
- if (!agent.enabled || !agent.everyMs) return `disabled (${agentId})`;
1896
- return `${agent.every ?? "unknown"} (${agentId})`;
1897
- });
1898
- lines.push("");
1899
- lines.push(`Heartbeat: ${heartbeatParts.join(", ")}`);
1900
- }
1901
- const sessionPaths = summary.sessions?.paths ?? [];
1902
- if (sessionPaths.length === 1) lines.push(`Session store: ${sessionPaths[0]}`);
1903
- else if (sessionPaths.length > 1) lines.push(`Session stores: ${sessionPaths.length}`);
1904
- const defaults = summary.sessions?.defaults;
1905
- const defaultModel = defaults?.model ?? "unknown";
1906
- const defaultCtx = typeof defaults?.contextTokens === "number" ? ` (${formatTokenCount(defaults.contextTokens)} ctx)` : "";
1907
- lines.push(`Default model: ${defaultModel}${defaultCtx}`);
1908
- const sessionCount = summary.sessions?.count ?? 0;
1909
- lines.push(`Active sessions: ${sessionCount}`);
1910
- const recent = Array.isArray(summary.sessions?.recent) ? summary.sessions?.recent : [];
1911
- if (recent.length > 0) {
1912
- lines.push("Recent sessions:");
1913
- for (const entry of recent) {
1914
- const ageLabel = typeof entry.age === "number" ? formatTimeAgo(entry.age) : "no activity";
1915
- const model = entry.model ?? "unknown";
1916
- const usage = formatContextUsageLine({
1917
- total: entry.totalTokens ?? null,
1918
- context: entry.contextTokens ?? null,
1919
- remaining: entry.remainingTokens ?? null,
1920
- percent: entry.percentUsed ?? null
1921
- });
1922
- const flags = entry.flags?.length ? ` | flags: ${entry.flags.join(", ")}` : "";
1923
- lines.push(`- ${entry.key}${entry.kind ? ` [${entry.kind}]` : ""} | ${ageLabel} | model ${model} | ${usage}${flags}`);
1924
- }
1925
- }
1926
- const queued = Array.isArray(summary.queuedSystemEvents) ? summary.queuedSystemEvents : [];
1927
- if (queued.length > 0) {
1928
- const preview = queued.slice(0, 3).join(" | ");
1929
- lines.push(`Queued system events (${queued.length}): ${preview}`);
1930
- }
1931
- return lines;
1932
- }
1933
- //#endregion
1934
- //#region src/tui/tui-command-handlers.ts
1935
- function isBtwCommand(text) {
1936
- return /^\/btw(?::|\s|$)/i.test(text.trim());
1937
- }
1938
- function createCommandHandlers(context) {
1939
- const { client, chatLog, tui, opts, state, deliverDefault, openOverlay, closeOverlay, refreshSessionInfo, loadHistory, setSession, refreshAgents, abortActive, setActivityStatus, formatSessionKey, applySessionInfoFromPatch, noteLocalRunId, noteLocalBtwRunId, forgetLocalRunId, forgetLocalBtwRunId, requestExit } = context;
1940
- const setAgent = async (id) => {
1941
- state.currentAgentId = normalizeAgentId(id);
1942
- await setSession("");
1943
- };
1944
- const closeOverlayAndRender = () => {
1945
- closeOverlay();
1946
- tui.requestRender();
1947
- };
1948
- const openSelector = (selector, onSelect) => {
1949
- selector.onSelect = (item) => {
1950
- (async () => {
1951
- await onSelect(item.value);
1952
- closeOverlayAndRender();
1953
- })();
1954
- };
1955
- selector.onCancel = closeOverlayAndRender;
1956
- openOverlay(selector);
1957
- tui.requestRender();
1958
- };
1959
- const openModelSelector = async () => {
1960
- try {
1961
- const models = await client.listModels();
1962
- if (models.length === 0) {
1963
- chatLog.addSystem("no models available");
1964
- tui.requestRender();
1965
- return;
1966
- }
1967
- openSelector(createSearchableSelectList(models.map((model) => ({
1968
- value: `${model.provider}/${model.id}`,
1969
- label: `${model.provider}/${model.id}`,
1970
- description: model.name && model.name !== model.id ? model.name : ""
1971
- })), 9), async (value) => {
1972
- try {
1973
- const result = await client.patchSession({
1974
- key: state.currentSessionKey,
1975
- model: value
1976
- });
1977
- chatLog.addSystem(`model set to ${value}`);
1978
- applySessionInfoFromPatch(result);
1979
- await refreshSessionInfo();
1980
- } catch (err) {
1981
- chatLog.addSystem(`model set failed: ${String(err)}`);
1982
- }
1983
- });
1984
- } catch (err) {
1985
- chatLog.addSystem(`model list failed: ${String(err)}`);
1986
- tui.requestRender();
1987
- }
1988
- };
1989
- const openAgentSelector = async () => {
1990
- await refreshAgents();
1991
- if (state.agents.length === 0) {
1992
- chatLog.addSystem("no agents found");
1993
- tui.requestRender();
1994
- return;
1995
- }
1996
- openSelector(createSearchableSelectList(state.agents.map((agent) => ({
1997
- value: agent.id,
1998
- label: agent.name ? `${agent.id} (${agent.name})` : agent.id,
1999
- description: agent.id === state.agentDefaultId ? "default" : ""
2000
- })), 9), async (value) => {
2001
- await setAgent(value);
2002
- });
2003
- };
2004
- const openSessionSelector = async () => {
2005
- try {
2006
- openSelector(createFilterableSelectList((await client.listSessions({
2007
- includeGlobal: false,
2008
- includeUnknown: false,
2009
- includeDerivedTitles: true,
2010
- includeLastMessage: true,
2011
- agentId: state.currentAgentId
2012
- })).sessions.map((session) => {
2013
- const title = session.derivedTitle ?? session.displayName;
2014
- const formattedKey = formatSessionKey(session.key);
2015
- const label = title && title !== formattedKey ? `${title} (${formattedKey})` : formattedKey;
2016
- const timePart = session.updatedAt ? formatRelativeTimestamp(session.updatedAt, {
2017
- dateFallback: true,
2018
- fallback: ""
2019
- }) : "";
2020
- const preview = session.lastMessagePreview?.replace(/\s+/g, " ").trim();
2021
- const description = timePart && preview ? `${timePart} · ${preview}` : preview ?? timePart;
2022
- return {
2023
- value: session.key,
2024
- label,
2025
- description,
2026
- searchText: [
2027
- session.displayName,
2028
- session.label,
2029
- session.subject,
2030
- session.sessionId,
2031
- session.key,
2032
- session.lastMessagePreview
2033
- ].filter(Boolean).join(" ")
2034
- };
2035
- }), 9), async (value) => {
2036
- await setSession(value);
2037
- });
2038
- } catch (err) {
2039
- chatLog.addSystem(`sessions list failed: ${String(err)}`);
2040
- tui.requestRender();
2041
- }
2042
- };
2043
- const openSettings = () => {
2044
- openOverlay(createSettingsList([{
2045
- id: "tools",
2046
- label: "Tool output",
2047
- currentValue: state.toolsExpanded ? "expanded" : "collapsed",
2048
- values: ["collapsed", "expanded"]
2049
- }, {
2050
- id: "thinking",
2051
- label: "Show thinking",
2052
- currentValue: state.showThinking ? "on" : "off",
2053
- values: ["off", "on"]
2054
- }], (id, value) => {
2055
- if (id === "tools") {
2056
- state.toolsExpanded = value === "expanded";
2057
- chatLog.setToolsExpanded(state.toolsExpanded);
2058
- }
2059
- if (id === "thinking") {
2060
- state.showThinking = value === "on";
2061
- loadHistory();
2062
- }
2063
- tui.requestRender();
2064
- }, () => {
2065
- closeOverlay();
2066
- tui.requestRender();
2067
- }));
2068
- tui.requestRender();
2069
- };
2070
- const handleCommand = async (raw) => {
2071
- const { name, args } = parseCommand(raw);
2072
- if (!name) return;
2073
- switch (name) {
2074
- case "help":
2075
- chatLog.addSystem(helpText({
2076
- provider: state.sessionInfo.modelProvider,
2077
- model: state.sessionInfo.model
2078
- }));
2079
- break;
2080
- case "status":
2081
- try {
2082
- const status = await client.getStatus();
2083
- if (typeof status === "string") {
2084
- chatLog.addSystem(status);
2085
- break;
2086
- }
2087
- if (status && typeof status === "object") {
2088
- const lines = formatStatusSummary(status);
2089
- for (const line of lines) chatLog.addSystem(line);
2090
- break;
2091
- }
2092
- chatLog.addSystem("status: unknown response");
2093
- } catch (err) {
2094
- chatLog.addSystem(`status failed: ${String(err)}`);
2095
- }
2096
- break;
2097
- case "agent":
2098
- if (!args) await openAgentSelector();
2099
- else await setAgent(args);
2100
- break;
2101
- case "agents":
2102
- await openAgentSelector();
2103
- break;
2104
- case "session":
2105
- if (!args) await openSessionSelector();
2106
- else await setSession(args);
2107
- break;
2108
- case "sessions":
2109
- await openSessionSelector();
2110
- break;
2111
- case "model":
2112
- if (!args) await openModelSelector();
2113
- else try {
2114
- const result = await client.patchSession({
2115
- key: state.currentSessionKey,
2116
- model: args
2117
- });
2118
- chatLog.addSystem(`model set to ${args}`);
2119
- applySessionInfoFromPatch(result);
2120
- await refreshSessionInfo();
2121
- } catch (err) {
2122
- chatLog.addSystem(`model set failed: ${String(err)}`);
2123
- }
2124
- break;
2125
- case "models":
2126
- await openModelSelector();
2127
- break;
2128
- case "think":
2129
- if (!args) {
2130
- const levels = formatThinkingLevels(state.sessionInfo.modelProvider, state.sessionInfo.model, "|");
2131
- chatLog.addSystem(`usage: /think <${levels}>`);
2132
- break;
2133
- }
2134
- try {
2135
- const result = await client.patchSession({
2136
- key: state.currentSessionKey,
2137
- thinkingLevel: args
2138
- });
2139
- chatLog.addSystem(`thinking set to ${args}`);
2140
- applySessionInfoFromPatch(result);
2141
- await refreshSessionInfo();
2142
- } catch (err) {
2143
- chatLog.addSystem(`think failed: ${String(err)}`);
2144
- }
2145
- break;
2146
- case "verbose":
2147
- if (!args) {
2148
- chatLog.addSystem("usage: /verbose <on|off>");
2149
- break;
2150
- }
2151
- try {
2152
- const result = await client.patchSession({
2153
- key: state.currentSessionKey,
2154
- verboseLevel: args
2155
- });
2156
- chatLog.addSystem(`verbose set to ${args}`);
2157
- applySessionInfoFromPatch(result);
2158
- await loadHistory();
2159
- } catch (err) {
2160
- chatLog.addSystem(`verbose failed: ${String(err)}`);
2161
- }
2162
- break;
2163
- case "fast":
2164
- if (!args || args === "status") {
2165
- chatLog.addSystem(`fast mode: ${state.sessionInfo.fastMode ? "on" : "off"}`);
2166
- break;
2167
- }
2168
- if (args !== "on" && args !== "off") {
2169
- chatLog.addSystem("usage: /fast <status|on|off>");
2170
- break;
2171
- }
2172
- try {
2173
- const result = await client.patchSession({
2174
- key: state.currentSessionKey,
2175
- fastMode: args === "on"
2176
- });
2177
- chatLog.addSystem(`fast mode ${args === "on" ? "enabled" : "disabled"}`);
2178
- applySessionInfoFromPatch(result);
2179
- await refreshSessionInfo();
2180
- } catch (err) {
2181
- chatLog.addSystem(`fast failed: ${String(err)}`);
2182
- }
2183
- break;
2184
- case "reasoning":
2185
- if (!args) {
2186
- chatLog.addSystem("usage: /reasoning <on|off>");
2187
- break;
2188
- }
2189
- try {
2190
- const result = await client.patchSession({
2191
- key: state.currentSessionKey,
2192
- reasoningLevel: args
2193
- });
2194
- chatLog.addSystem(`reasoning set to ${args}`);
2195
- applySessionInfoFromPatch(result);
2196
- await refreshSessionInfo();
2197
- } catch (err) {
2198
- chatLog.addSystem(`reasoning failed: ${String(err)}`);
2199
- }
2200
- break;
2201
- case "usage": {
2202
- const normalized = args ? normalizeUsageDisplay(args) : void 0;
2203
- if (args && !normalized) {
2204
- chatLog.addSystem("usage: /usage <off|tokens|full>");
2205
- break;
2206
- }
2207
- const currentRaw = state.sessionInfo.responseUsage;
2208
- const current = resolveResponseUsageMode(currentRaw);
2209
- const next = normalized ?? (current === "off" ? "tokens" : current === "tokens" ? "full" : "off");
2210
- try {
2211
- const result = await client.patchSession({
2212
- key: state.currentSessionKey,
2213
- responseUsage: next === "off" ? null : next
2214
- });
2215
- chatLog.addSystem(`usage footer: ${next}`);
2216
- applySessionInfoFromPatch(result);
2217
- await refreshSessionInfo();
2218
- } catch (err) {
2219
- chatLog.addSystem(`usage failed: ${String(err)}`);
2220
- }
2221
- break;
2222
- }
2223
- case "elevated":
2224
- if (!args) {
2225
- chatLog.addSystem("usage: /elevated <on|off|ask|full>");
2226
- break;
2227
- }
2228
- if (![
2229
- "on",
2230
- "off",
2231
- "ask",
2232
- "full"
2233
- ].includes(args)) {
2234
- chatLog.addSystem("usage: /elevated <on|off|ask|full>");
2235
- break;
2236
- }
2237
- try {
2238
- const result = await client.patchSession({
2239
- key: state.currentSessionKey,
2240
- elevatedLevel: args
2241
- });
2242
- chatLog.addSystem(`elevated set to ${args}`);
2243
- applySessionInfoFromPatch(result);
2244
- await refreshSessionInfo();
2245
- } catch (err) {
2246
- chatLog.addSystem(`elevated failed: ${String(err)}`);
2247
- }
2248
- break;
2249
- case "activation":
2250
- if (!args) {
2251
- chatLog.addSystem("usage: /activation <mention|always>");
2252
- break;
2253
- }
2254
- try {
2255
- const result = await client.patchSession({
2256
- key: state.currentSessionKey,
2257
- groupActivation: args === "always" ? "always" : "mention"
2258
- });
2259
- chatLog.addSystem(`activation set to ${args}`);
2260
- applySessionInfoFromPatch(result);
2261
- await refreshSessionInfo();
2262
- } catch (err) {
2263
- chatLog.addSystem(`activation failed: ${String(err)}`);
2264
- }
2265
- break;
2266
- case "new":
2267
- try {
2268
- state.sessionInfo.inputTokens = null;
2269
- state.sessionInfo.outputTokens = null;
2270
- state.sessionInfo.totalTokens = null;
2271
- tui.requestRender();
2272
- const uniqueKey = `tui-${randomUUID()}`;
2273
- await setSession(uniqueKey);
2274
- chatLog.addSystem(`new session: ${uniqueKey}`);
2275
- } catch (err) {
2276
- chatLog.addSystem(`new session failed: ${sanitizeRenderableText(String(err))}`);
2277
- }
2278
- break;
2279
- case "reset":
2280
- try {
2281
- state.sessionInfo.inputTokens = null;
2282
- state.sessionInfo.outputTokens = null;
2283
- state.sessionInfo.totalTokens = null;
2284
- tui.requestRender();
2285
- await client.resetSession(state.currentSessionKey, name);
2286
- chatLog.addSystem(`session ${state.currentSessionKey} reset`);
2287
- await loadHistory();
2288
- } catch (err) {
2289
- chatLog.addSystem(`reset failed: ${sanitizeRenderableText(String(err))}`);
2290
- }
2291
- break;
2292
- case "abort":
2293
- await abortActive();
2294
- break;
2295
- case "settings":
2296
- openSettings();
2297
- break;
2298
- case "exit":
2299
- case "quit":
2300
- requestExit();
2301
- break;
2302
- default:
2303
- await sendMessage(raw);
2304
- break;
2305
- }
2306
- tui.requestRender();
2307
- };
2308
- const sendMessage = async (text) => {
2309
- if (!state.isConnected) {
2310
- chatLog.addSystem("not connected to gateway — message not sent");
2311
- setActivityStatus("disconnected");
2312
- tui.requestRender();
2313
- return;
2314
- }
2315
- const isBtw = isBtwCommand(text);
2316
- const runId = randomUUID();
2317
- try {
2318
- if (!isBtw) {
2319
- chatLog.addUser(text);
2320
- noteLocalRunId(runId);
2321
- state.activeChatRunId = runId;
2322
- setActivityStatus("sending");
2323
- } else noteLocalBtwRunId?.(runId);
2324
- tui.requestRender();
2325
- await client.sendChat({
2326
- sessionKey: state.currentSessionKey,
2327
- message: text,
2328
- thinking: opts.thinking,
2329
- deliver: deliverDefault,
2330
- timeoutMs: opts.timeoutMs,
2331
- runId
2332
- });
2333
- if (!isBtw) {
2334
- setActivityStatus("waiting");
2335
- tui.requestRender();
2336
- }
2337
- } catch (err) {
2338
- if (isBtw) forgetLocalBtwRunId?.(runId);
2339
- if (!isBtw && state.activeChatRunId) forgetLocalRunId?.(state.activeChatRunId);
2340
- if (!isBtw) state.activeChatRunId = null;
2341
- chatLog.addSystem(`${isBtw ? "btw failed" : "send failed"}: ${String(err)}`);
2342
- if (!isBtw) setActivityStatus("error");
2343
- tui.requestRender();
2344
- }
2345
- };
2346
- return {
2347
- handleCommand,
2348
- sendMessage,
2349
- openModelSelector,
2350
- openAgentSelector,
2351
- openSessionSelector,
2352
- openSettings,
2353
- setAgent
2354
- };
2355
- }
2356
- //#endregion
2357
- //#region src/tui/tui-stream-assembler.ts
2358
- function extractTextBlocksAndSignals(message) {
2359
- if (!message || typeof message !== "object") return {
2360
- textBlocks: [],
2361
- sawNonTextContentBlocks: false
2362
- };
2363
- const content = message.content;
2364
- if (typeof content === "string") {
2365
- const text = content.trim();
2366
- return {
2367
- textBlocks: text ? [text] : [],
2368
- sawNonTextContentBlocks: false
2369
- };
2370
- }
2371
- if (!Array.isArray(content)) return {
2372
- textBlocks: [],
2373
- sawNonTextContentBlocks: false
2374
- };
2375
- const textBlocks = [];
2376
- let sawNonTextContentBlocks = false;
2377
- for (const block of content) {
2378
- if (!block || typeof block !== "object") continue;
2379
- const rec = block;
2380
- if (rec.type === "text" && typeof rec.text === "string") {
2381
- const text = rec.text.trim();
2382
- if (text) textBlocks.push(text);
2383
- continue;
2384
- }
2385
- if (typeof rec.type === "string" && rec.type !== "thinking") sawNonTextContentBlocks = true;
2386
- }
2387
- return {
2388
- textBlocks,
2389
- sawNonTextContentBlocks
2390
- };
2391
- }
2392
- function isDroppedBoundaryTextBlockSubset(params) {
2393
- const { streamedTextBlocks, finalTextBlocks } = params;
2394
- if (finalTextBlocks.length === 0 || finalTextBlocks.length >= streamedTextBlocks.length) return false;
2395
- if (finalTextBlocks.every((block, index) => streamedTextBlocks[index] === block)) return true;
2396
- const suffixStart = streamedTextBlocks.length - finalTextBlocks.length;
2397
- return finalTextBlocks.every((block, index) => streamedTextBlocks[suffixStart + index] === block);
2398
- }
2399
- function shouldPreserveBoundaryDroppedText(params) {
2400
- if (params.boundaryDropMode === "off") return false;
2401
- if (!(params.boundaryDropMode === "streamed-or-incoming" ? params.streamedSawNonTextContentBlocks || params.incomingSawNonTextContentBlocks : params.streamedSawNonTextContentBlocks)) return false;
2402
- return isDroppedBoundaryTextBlockSubset({
2403
- streamedTextBlocks: params.streamedTextBlocks,
2404
- finalTextBlocks: params.nextContentBlocks
2405
- });
2406
- }
2407
- var TuiStreamAssembler = class {
2408
- constructor() {
2409
- this.runs = /* @__PURE__ */ new Map();
2410
- }
2411
- getOrCreateRun(runId) {
2412
- let state = this.runs.get(runId);
2413
- if (!state) {
2414
- state = {
2415
- thinkingText: "",
2416
- contentText: "",
2417
- contentBlocks: [],
2418
- sawNonTextContentBlocks: false,
2419
- displayText: ""
2420
- };
2421
- this.runs.set(runId, state);
2422
- }
2423
- return state;
2424
- }
2425
- updateRunState(state, message, showThinking, opts) {
2426
- const thinkingText = extractThinkingFromMessage(message);
2427
- const contentText = extractContentFromMessage(message);
2428
- const { textBlocks, sawNonTextContentBlocks } = extractTextBlocksAndSignals(message);
2429
- if (thinkingText) state.thinkingText = thinkingText;
2430
- if (contentText) {
2431
- const nextContentBlocks = textBlocks.length > 0 ? textBlocks : [contentText];
2432
- if (!shouldPreserveBoundaryDroppedText({
2433
- boundaryDropMode: opts?.boundaryDropMode ?? "off",
2434
- streamedSawNonTextContentBlocks: state.sawNonTextContentBlocks,
2435
- incomingSawNonTextContentBlocks: sawNonTextContentBlocks,
2436
- streamedTextBlocks: state.contentBlocks,
2437
- nextContentBlocks
2438
- })) {
2439
- state.contentText = contentText;
2440
- state.contentBlocks = nextContentBlocks;
2441
- }
2442
- }
2443
- if (sawNonTextContentBlocks) state.sawNonTextContentBlocks = true;
2444
- state.displayText = composeThinkingAndContent({
2445
- thinkingText: state.thinkingText,
2446
- contentText: state.contentText,
2447
- showThinking
2448
- });
2449
- }
2450
- ingestDelta(runId, message, showThinking) {
2451
- const state = this.getOrCreateRun(runId);
2452
- const previousDisplayText = state.displayText;
2453
- this.updateRunState(state, message, showThinking, { boundaryDropMode: "streamed-or-incoming" });
2454
- if (!state.displayText || state.displayText === previousDisplayText) return null;
2455
- return state.displayText;
2456
- }
2457
- finalize(runId, message, showThinking, errorMessage) {
2458
- const state = this.getOrCreateRun(runId);
2459
- const streamedDisplayText = state.displayText;
2460
- const streamedTextBlocks = [...state.contentBlocks];
2461
- const streamedSawNonTextContentBlocks = state.sawNonTextContentBlocks;
2462
- this.updateRunState(state, message, showThinking, { boundaryDropMode: "streamed-only" });
2463
- const finalComposed = state.displayText;
2464
- const finalText = resolveFinalAssistantText({
2465
- finalText: streamedSawNonTextContentBlocks && isDroppedBoundaryTextBlockSubset({
2466
- streamedTextBlocks,
2467
- finalTextBlocks: state.contentBlocks
2468
- }) ? streamedDisplayText : finalComposed,
2469
- streamedText: streamedDisplayText,
2470
- errorMessage
2471
- });
2472
- this.runs.delete(runId);
2473
- return finalText;
2474
- }
2475
- drop(runId) {
2476
- this.runs.delete(runId);
2477
- }
2478
- };
2479
- //#endregion
2480
- //#region src/tui/tui-event-handlers.ts
2481
- function createEventHandlers(context) {
2482
- const { chatLog, btw, tui, state, setActivityStatus, refreshSessionInfo, loadHistory, isLocalRunId, forgetLocalRunId, clearLocalRunIds, isLocalBtwRunId, forgetLocalBtwRunId, clearLocalBtwRunIds } = context;
2483
- const finalizedRuns = /* @__PURE__ */ new Map();
2484
- const sessionRuns = /* @__PURE__ */ new Map();
2485
- let streamAssembler = new TuiStreamAssembler();
2486
- let lastSessionKey = state.currentSessionKey;
2487
- const pruneRunMap = (runs) => {
2488
- if (runs.size <= 200) return;
2489
- const keepUntil = Date.now() - 600 * 1e3;
2490
- for (const [key, ts] of runs) {
2491
- if (runs.size <= 150) break;
2492
- if (ts < keepUntil) runs.delete(key);
2493
- }
2494
- if (runs.size > 200) for (const key of runs.keys()) {
2495
- runs.delete(key);
2496
- if (runs.size <= 150) break;
2497
- }
2498
- };
2499
- const syncSessionKey = () => {
2500
- if (state.currentSessionKey === lastSessionKey) return;
2501
- lastSessionKey = state.currentSessionKey;
2502
- finalizedRuns.clear();
2503
- sessionRuns.clear();
2504
- streamAssembler = new TuiStreamAssembler();
2505
- clearLocalRunIds?.();
2506
- clearLocalBtwRunIds?.();
2507
- btw.clear();
2508
- };
2509
- const noteSessionRun = (runId) => {
2510
- sessionRuns.set(runId, Date.now());
2511
- pruneRunMap(sessionRuns);
2512
- };
2513
- const noteFinalizedRun = (runId) => {
2514
- finalizedRuns.set(runId, Date.now());
2515
- sessionRuns.delete(runId);
2516
- streamAssembler.drop(runId);
2517
- pruneRunMap(finalizedRuns);
2518
- };
2519
- const clearActiveRunIfMatch = (runId) => {
2520
- if (state.activeChatRunId === runId) state.activeChatRunId = null;
2521
- };
2522
- const finalizeRun = (params) => {
2523
- noteFinalizedRun(params.runId);
2524
- clearActiveRunIfMatch(params.runId);
2525
- if (params.wasActiveRun) setActivityStatus(params.status);
2526
- refreshSessionInfo?.();
2527
- };
2528
- const terminateRun = (params) => {
2529
- streamAssembler.drop(params.runId);
2530
- sessionRuns.delete(params.runId);
2531
- clearActiveRunIfMatch(params.runId);
2532
- if (params.wasActiveRun) setActivityStatus(params.status);
2533
- refreshSessionInfo?.();
2534
- };
2535
- const hasConcurrentActiveRun = (runId) => {
2536
- const activeRunId = state.activeChatRunId;
2537
- if (!activeRunId || activeRunId === runId) return false;
2538
- return sessionRuns.has(activeRunId);
2539
- };
2540
- const maybeRefreshHistoryForRun = (runId, opts) => {
2541
- if (isLocalRunId?.(runId) ?? false) {
2542
- forgetLocalRunId?.(runId);
2543
- if (!opts?.allowLocalWithoutDisplayableFinal) return;
2544
- }
2545
- if (hasConcurrentActiveRun(runId)) return;
2546
- loadHistory?.();
2547
- };
2548
- const isSameSessionKey = (left, right) => {
2549
- const normalizedLeft = (left ?? "").trim().toLowerCase();
2550
- const normalizedRight = (right ?? "").trim().toLowerCase();
2551
- if (!normalizedLeft || !normalizedRight) return false;
2552
- if (normalizedLeft === normalizedRight) return true;
2553
- const parsedLeft = parseAgentSessionKey(normalizedLeft);
2554
- const parsedRight = parseAgentSessionKey(normalizedRight);
2555
- if (parsedLeft && parsedRight) return parsedLeft.agentId === parsedRight.agentId && parsedLeft.rest === parsedRight.rest;
2556
- if (parsedLeft) return parsedLeft.rest === normalizedRight;
2557
- if (parsedRight) return normalizedLeft === parsedRight.rest;
2558
- return false;
2559
- };
2560
- const handleChatEvent = (payload) => {
2561
- if (!payload || typeof payload !== "object") return;
2562
- const evt = payload;
2563
- syncSessionKey();
2564
- if (!isSameSessionKey(evt.sessionKey, state.currentSessionKey)) return;
2565
- if (finalizedRuns.has(evt.runId)) {
2566
- if (evt.state === "delta") return;
2567
- if (evt.state === "final") return;
2568
- }
2569
- noteSessionRun(evt.runId);
2570
- if (!state.activeChatRunId && !isLocalBtwRunId?.(evt.runId)) state.activeChatRunId = evt.runId;
2571
- if (evt.state === "delta") {
2572
- const displayText = streamAssembler.ingestDelta(evt.runId, evt.message, state.showThinking);
2573
- if (!displayText) return;
2574
- chatLog.updateAssistant(displayText, evt.runId);
2575
- setActivityStatus("streaming");
2576
- }
2577
- if (evt.state === "final") {
2578
- const isLocalBtwRun = isLocalBtwRunId?.(evt.runId) ?? false;
2579
- const wasActiveRun = state.activeChatRunId === evt.runId;
2580
- if (!evt.message && isLocalBtwRun) {
2581
- forgetLocalBtwRunId?.(evt.runId);
2582
- noteFinalizedRun(evt.runId);
2583
- tui.requestRender();
2584
- return;
2585
- }
2586
- if (!evt.message) {
2587
- maybeRefreshHistoryForRun(evt.runId, { allowLocalWithoutDisplayableFinal: true });
2588
- chatLog.dropAssistant(evt.runId);
2589
- finalizeRun({
2590
- runId: evt.runId,
2591
- wasActiveRun,
2592
- status: "idle"
2593
- });
2594
- tui.requestRender();
2595
- return;
2596
- }
2597
- if (isCommandMessage(evt.message)) {
2598
- maybeRefreshHistoryForRun(evt.runId);
2599
- const text = extractTextFromMessage(evt.message);
2600
- if (text) chatLog.addSystem(text);
2601
- finalizeRun({
2602
- runId: evt.runId,
2603
- wasActiveRun,
2604
- status: "idle"
2605
- });
2606
- tui.requestRender();
2607
- return;
2608
- }
2609
- maybeRefreshHistoryForRun(evt.runId);
2610
- const stopReason = evt.message && typeof evt.message === "object" && !Array.isArray(evt.message) ? typeof evt.message.stopReason === "string" ? evt.message.stopReason : "" : "";
2611
- const finalText = streamAssembler.finalize(evt.runId, evt.message, state.showThinking, evt.errorMessage);
2612
- if (finalText === "(no output)" && !isLocalRunId?.(evt.runId)) chatLog.dropAssistant(evt.runId);
2613
- else chatLog.finalizeAssistant(finalText, evt.runId);
2614
- finalizeRun({
2615
- runId: evt.runId,
2616
- wasActiveRun,
2617
- status: stopReason === "error" ? "error" : "idle"
2618
- });
2619
- }
2620
- if (evt.state === "aborted") {
2621
- forgetLocalBtwRunId?.(evt.runId);
2622
- const wasActiveRun = state.activeChatRunId === evt.runId;
2623
- chatLog.addSystem("run aborted");
2624
- terminateRun({
2625
- runId: evt.runId,
2626
- wasActiveRun,
2627
- status: "aborted"
2628
- });
2629
- maybeRefreshHistoryForRun(evt.runId);
2630
- }
2631
- if (evt.state === "error") {
2632
- forgetLocalBtwRunId?.(evt.runId);
2633
- const wasActiveRun = state.activeChatRunId === evt.runId;
2634
- chatLog.addSystem(`run error: ${evt.errorMessage ?? "unknown"}`);
2635
- terminateRun({
2636
- runId: evt.runId,
2637
- wasActiveRun,
2638
- status: "error"
2639
- });
2640
- maybeRefreshHistoryForRun(evt.runId);
2641
- }
2642
- tui.requestRender();
2643
- };
2644
- const handleAgentEvent = (payload) => {
2645
- if (!payload || typeof payload !== "object") return;
2646
- const evt = payload;
2647
- syncSessionKey();
2648
- const isActiveRun = evt.runId === state.activeChatRunId;
2649
- if (!(isActiveRun || sessionRuns.has(evt.runId) || finalizedRuns.has(evt.runId))) return;
2650
- if (evt.stream === "tool") {
2651
- const verbose = state.sessionInfo.verboseLevel ?? "off";
2652
- const allowToolEvents = verbose !== "off";
2653
- const allowToolOutput = verbose === "full";
2654
- if (!allowToolEvents) return;
2655
- const data = evt.data ?? {};
2656
- const phase = asString(data.phase, "");
2657
- const toolCallId = asString(data.toolCallId, "");
2658
- const toolName = asString(data.name, "tool");
2659
- if (!toolCallId) return;
2660
- if (phase === "start") chatLog.startTool(toolCallId, toolName, data.args);
2661
- else if (phase === "update") {
2662
- if (!allowToolOutput) return;
2663
- chatLog.updateToolResult(toolCallId, data.partialResult, { partial: true });
2664
- } else if (phase === "result") if (allowToolOutput) chatLog.updateToolResult(toolCallId, data.result, { isError: Boolean(data.isError) });
2665
- else chatLog.updateToolResult(toolCallId, { content: [] }, { isError: Boolean(data.isError) });
2666
- tui.requestRender();
2667
- return;
2668
- }
2669
- if (evt.stream === "lifecycle") {
2670
- if (!isActiveRun) return;
2671
- const phase = typeof evt.data?.phase === "string" ? evt.data.phase : "";
2672
- if (phase === "start") setActivityStatus("running");
2673
- if (phase === "end") setActivityStatus("idle");
2674
- if (phase === "error") setActivityStatus("error");
2675
- tui.requestRender();
2676
- }
2677
- };
2678
- const handleBtwEvent = (payload) => {
2679
- if (!payload || typeof payload !== "object") return;
2680
- const evt = payload;
2681
- syncSessionKey();
2682
- if (!isSameSessionKey(evt.sessionKey, state.currentSessionKey)) return;
2683
- if (evt.kind !== "btw") return;
2684
- const question = evt.question.trim();
2685
- const text = evt.text.trim();
2686
- if (!question || !text) return;
2687
- btw.showResult({
2688
- question,
2689
- text,
2690
- isError: evt.isError
2691
- });
2692
- tui.requestRender();
2693
- };
2694
- return {
2695
- handleChatEvent,
2696
- handleAgentEvent,
2697
- handleBtwEvent
2698
- };
2699
- }
2700
- //#endregion
2701
- //#region src/tui/tui-local-shell.ts
2702
- function createLocalShellRunner(deps) {
2703
- let localExecAsked = false;
2704
- let localExecAllowed = false;
2705
- const createSelector = deps.createSelector ?? createSearchableSelectList;
2706
- const spawnCommand = deps.spawnCommand ?? spawn;
2707
- const getCwd = deps.getCwd ?? (() => process.cwd());
2708
- const env = deps.env ?? process.env;
2709
- const maxChars = deps.maxOutputChars ?? 4e4;
2710
- const ensureLocalExecAllowed = async () => {
2711
- if (localExecAllowed) return true;
2712
- if (localExecAsked) return false;
2713
- localExecAsked = true;
2714
- return await new Promise((resolve) => {
2715
- deps.chatLog.addSystem("Allow local shell commands for this session?");
2716
- deps.chatLog.addSystem("This runs commands on YOUR machine (not the gateway) and may delete files or reveal secrets.");
2717
- deps.chatLog.addSystem("Select Yes/No (arrows + Enter), Esc to cancel.");
2718
- const selector = createSelector([{
2719
- value: "no",
2720
- label: "No"
2721
- }, {
2722
- value: "yes",
2723
- label: "Yes"
2724
- }], 2);
2725
- selector.onSelect = (item) => {
2726
- deps.closeOverlay();
2727
- if (item.value === "yes") {
2728
- localExecAllowed = true;
2729
- deps.chatLog.addSystem("local shell: enabled for this session");
2730
- resolve(true);
2731
- } else {
2732
- deps.chatLog.addSystem("local shell: not enabled");
2733
- resolve(false);
2734
- }
2735
- deps.tui.requestRender();
2736
- };
2737
- selector.onCancel = () => {
2738
- deps.closeOverlay();
2739
- deps.chatLog.addSystem("local shell: cancelled");
2740
- deps.tui.requestRender();
2741
- resolve(false);
2742
- };
2743
- deps.openOverlay(selector);
2744
- deps.tui.requestRender();
2745
- });
2746
- };
2747
- const runLocalShellLine = async (line) => {
2748
- const cmd = line.slice(1);
2749
- if (cmd === "") return;
2750
- if (localExecAsked && !localExecAllowed) {
2751
- deps.chatLog.addSystem("local shell: not enabled for this session");
2752
- deps.tui.requestRender();
2753
- return;
2754
- }
2755
- if (!await ensureLocalExecAllowed()) return;
2756
- deps.chatLog.addSystem(`[local] $ ${cmd}`);
2757
- deps.tui.requestRender();
2758
- const appendWithCap = (text, chunk) => {
2759
- const combined = text + chunk;
2760
- return combined.length > maxChars ? combined.slice(-maxChars) : combined;
2761
- };
2762
- await new Promise((resolve) => {
2763
- const child = spawnCommand(cmd, {
2764
- shell: true,
2765
- cwd: getCwd(),
2766
- env: {
2767
- ...env,
2768
- MOLDCLAW_SHELL: "tui-local"
2769
- }
2770
- });
2771
- let stdout = "";
2772
- let stderr = "";
2773
- child.stdout.on("data", (buf) => {
2774
- stdout = appendWithCap(stdout, buf.toString("utf8"));
2775
- });
2776
- child.stderr.on("data", (buf) => {
2777
- stderr = appendWithCap(stderr, buf.toString("utf8"));
2778
- });
2779
- child.on("close", (code, signal) => {
2780
- const combined = (stdout + (stderr ? (stdout ? "\n" : "") + stderr : "")).slice(0, maxChars).trimEnd();
2781
- if (combined) for (const line of combined.split("\n")) deps.chatLog.addSystem(`[local] ${line}`);
2782
- deps.chatLog.addSystem(`[local] exit ${code ?? "?"}${signal ? ` (signal ${String(signal)})` : ""}`);
2783
- deps.tui.requestRender();
2784
- resolve();
2785
- });
2786
- child.on("error", (err) => {
2787
- deps.chatLog.addSystem(`[local] error: ${String(err)}`);
2788
- deps.tui.requestRender();
2789
- resolve();
2790
- });
2791
- });
2792
- };
2793
- return { runLocalShellLine };
2794
- }
2795
- //#endregion
2796
- //#region src/tui/tui-overlays.ts
2797
- function createOverlayHandlers(host, fallbackFocus) {
2798
- const openOverlay = (component) => {
2799
- host.showOverlay(component);
2800
- };
2801
- const closeOverlay = () => {
2802
- if (host.hasOverlay()) {
2803
- host.hideOverlay();
2804
- return;
2805
- }
2806
- host.setFocus(fallbackFocus);
2807
- };
2808
- return {
2809
- openOverlay,
2810
- closeOverlay
2811
- };
2812
- }
2813
- //#endregion
2814
- //#region src/tui/tui-session-actions.ts
2815
- function createSessionActions(context) {
2816
- const { client, chatLog, btw, tui, opts, state, agentNames, initialSessionInput, initialSessionAgentId, resolveSessionKey, updateHeader, updateFooter, updateAutocompleteProvider, setActivityStatus, clearLocalRunIds } = context;
2817
- let refreshSessionInfoPromise = Promise.resolve();
2818
- let lastSessionDefaults = null;
2819
- const applyAgentsResult = (result) => {
2820
- state.agentDefaultId = normalizeAgentId(result.defaultId);
2821
- state.sessionMainKey = normalizeMainKey(result.mainKey);
2822
- state.sessionScope = result.scope ?? state.sessionScope;
2823
- state.agents = result.agents.map((agent) => ({
2824
- id: normalizeAgentId(agent.id),
2825
- name: agent.name?.trim() || void 0
2826
- }));
2827
- agentNames.clear();
2828
- for (const agent of state.agents) if (agent.name) agentNames.set(agent.id, agent.name);
2829
- if (!state.initialSessionApplied) {
2830
- if (initialSessionAgentId) {
2831
- if (state.agents.some((agent) => agent.id === initialSessionAgentId)) state.currentAgentId = initialSessionAgentId;
2832
- } else if (!state.agents.some((agent) => agent.id === state.currentAgentId)) state.currentAgentId = state.agents[0]?.id ?? normalizeAgentId(result.defaultId ?? state.currentAgentId);
2833
- const nextSessionKey = resolveSessionKey(initialSessionInput);
2834
- if (nextSessionKey !== state.currentSessionKey) state.currentSessionKey = nextSessionKey;
2835
- state.initialSessionApplied = true;
2836
- } else if (!state.agents.some((agent) => agent.id === state.currentAgentId)) state.currentAgentId = state.agents[0]?.id ?? normalizeAgentId(result.defaultId ?? state.currentAgentId);
2837
- updateHeader();
2838
- updateFooter();
2839
- };
2840
- const refreshAgents = async () => {
2841
- try {
2842
- applyAgentsResult(await client.listAgents());
2843
- } catch (err) {
2844
- chatLog.addSystem(`agents list failed: ${String(err)}`);
2845
- }
2846
- };
2847
- const updateAgentFromSessionKey = (key) => {
2848
- const parsed = parseAgentSessionKey(key);
2849
- if (!parsed) return;
2850
- const next = normalizeAgentId(parsed.agentId);
2851
- if (next !== state.currentAgentId) state.currentAgentId = next;
2852
- };
2853
- const resolveModelSelection = (entry) => {
2854
- if (entry?.modelProvider || entry?.model) return {
2855
- modelProvider: entry.modelProvider ?? state.sessionInfo.modelProvider,
2856
- model: entry.model ?? state.sessionInfo.model
2857
- };
2858
- const overrideModel = entry?.modelOverride?.trim();
2859
- if (overrideModel) return {
2860
- modelProvider: entry?.providerOverride?.trim() || state.sessionInfo.modelProvider,
2861
- model: overrideModel
2862
- };
2863
- return {
2864
- modelProvider: state.sessionInfo.modelProvider,
2865
- model: state.sessionInfo.model
2866
- };
2867
- };
2868
- const applySessionInfo = (params) => {
2869
- const entry = params.entry ?? void 0;
2870
- const defaults = params.defaults ?? lastSessionDefaults ?? void 0;
2871
- const previousDefaults = lastSessionDefaults;
2872
- const defaultsChanged = params.defaults ? previousDefaults?.model !== params.defaults.model || previousDefaults?.modelProvider !== params.defaults.modelProvider || previousDefaults?.contextTokens !== params.defaults.contextTokens : false;
2873
- if (params.defaults) lastSessionDefaults = params.defaults;
2874
- const entryUpdatedAt = entry?.updatedAt ?? null;
2875
- const currentUpdatedAt = state.sessionInfo.updatedAt ?? null;
2876
- if (!params.force && entryUpdatedAt !== null && currentUpdatedAt !== null && entryUpdatedAt < currentUpdatedAt && !defaultsChanged) return;
2877
- const next = { ...state.sessionInfo };
2878
- if (entry?.thinkingLevel !== void 0) next.thinkingLevel = entry.thinkingLevel;
2879
- if (entry?.fastMode !== void 0) next.fastMode = entry.fastMode;
2880
- if (entry?.verboseLevel !== void 0) next.verboseLevel = entry.verboseLevel;
2881
- if (entry?.reasoningLevel !== void 0) next.reasoningLevel = entry.reasoningLevel;
2882
- if (entry?.responseUsage !== void 0) next.responseUsage = entry.responseUsage;
2883
- if (entry?.inputTokens !== void 0) next.inputTokens = entry.inputTokens;
2884
- if (entry?.outputTokens !== void 0) next.outputTokens = entry.outputTokens;
2885
- if (entry?.totalTokens !== void 0) next.totalTokens = entry.totalTokens;
2886
- if (entry?.contextTokens !== void 0 || defaults?.contextTokens !== void 0) next.contextTokens = entry?.contextTokens ?? defaults?.contextTokens ?? state.sessionInfo.contextTokens;
2887
- if (entry?.displayName !== void 0) next.displayName = entry.displayName;
2888
- if (entry?.updatedAt !== void 0) next.updatedAt = entry.updatedAt;
2889
- const selection = resolveModelSelection(entry);
2890
- if (selection.modelProvider !== void 0) next.modelProvider = selection.modelProvider;
2891
- if (selection.model !== void 0) next.model = selection.model;
2892
- state.sessionInfo = next;
2893
- updateAutocompleteProvider();
2894
- updateFooter();
2895
- tui.requestRender();
2896
- };
2897
- const runRefreshSessionInfo = async () => {
2898
- try {
2899
- const resolveListAgentId = () => {
2900
- if (state.currentSessionKey === "global" || state.currentSessionKey === "unknown") return;
2901
- const parsed = parseAgentSessionKey(state.currentSessionKey);
2902
- return parsed?.agentId ? normalizeAgentId(parsed.agentId) : state.currentAgentId;
2903
- };
2904
- const listAgentId = resolveListAgentId();
2905
- const result = await client.listSessions({
2906
- includeGlobal: false,
2907
- includeUnknown: false,
2908
- agentId: listAgentId
2909
- });
2910
- const normalizeMatchKey = (key) => parseAgentSessionKey(key)?.rest ?? key;
2911
- const currentMatchKey = normalizeMatchKey(state.currentSessionKey);
2912
- const entry = result.sessions.find((row) => {
2913
- if (row.key === state.currentSessionKey) return true;
2914
- return normalizeMatchKey(row.key) === currentMatchKey;
2915
- });
2916
- if (entry?.key && entry.key !== state.currentSessionKey) {
2917
- updateAgentFromSessionKey(entry.key);
2918
- state.currentSessionKey = entry.key;
2919
- updateHeader();
2920
- }
2921
- applySessionInfo({
2922
- entry,
2923
- defaults: result.defaults
2924
- });
2925
- } catch (err) {
2926
- chatLog.addSystem(`sessions list failed: ${String(err)}`);
2927
- }
2928
- };
2929
- const refreshSessionInfo = async () => {
2930
- refreshSessionInfoPromise = refreshSessionInfoPromise.then(runRefreshSessionInfo, runRefreshSessionInfo);
2931
- await refreshSessionInfoPromise;
2932
- };
2933
- const applySessionInfoFromPatch = (result) => {
2934
- if (!result?.entry) return;
2935
- if (result.key && result.key !== state.currentSessionKey) {
2936
- updateAgentFromSessionKey(result.key);
2937
- state.currentSessionKey = result.key;
2938
- updateHeader();
2939
- }
2940
- const resolved = result.resolved;
2941
- applySessionInfo({
2942
- entry: resolved && (resolved.modelProvider || resolved.model) ? {
2943
- ...result.entry,
2944
- modelProvider: resolved.modelProvider ?? result.entry.modelProvider,
2945
- model: resolved.model ?? result.entry.model
2946
- } : result.entry,
2947
- force: true
2948
- });
2949
- };
2950
- const loadHistory = async () => {
2951
- try {
2952
- const record = await client.loadHistory({
2953
- sessionKey: state.currentSessionKey,
2954
- limit: opts.historyLimit ?? 200
2955
- });
2956
- state.currentSessionId = typeof record.sessionId === "string" ? record.sessionId : null;
2957
- state.sessionInfo.thinkingLevel = record.thinkingLevel ?? state.sessionInfo.thinkingLevel;
2958
- state.sessionInfo.fastMode = record.fastMode ?? state.sessionInfo.fastMode;
2959
- state.sessionInfo.verboseLevel = record.verboseLevel ?? state.sessionInfo.verboseLevel;
2960
- const showTools = (state.sessionInfo.verboseLevel ?? "off") !== "off";
2961
- chatLog.clearAll();
2962
- btw.clear();
2963
- chatLog.addSystem(`session ${state.currentSessionKey}`);
2964
- for (const entry of record.messages ?? []) {
2965
- if (!entry || typeof entry !== "object") continue;
2966
- const message = entry;
2967
- if (isCommandMessage(message)) {
2968
- const text = extractTextFromMessage(message);
2969
- if (text) chatLog.addSystem(text);
2970
- continue;
2971
- }
2972
- if (message.role === "user") {
2973
- const text = extractTextFromMessage(message);
2974
- if (text) chatLog.addUser(text);
2975
- continue;
2976
- }
2977
- if (message.role === "assistant") {
2978
- const text = extractTextFromMessage(message, { includeThinking: state.showThinking });
2979
- if (text) chatLog.finalizeAssistant(text);
2980
- continue;
2981
- }
2982
- if (message.role === "toolResult") {
2983
- if (!showTools) continue;
2984
- const toolCallId = asString(message.toolCallId, "");
2985
- const toolName = asString(message.toolName, "tool");
2986
- chatLog.startTool(toolCallId, toolName, {}).setResult({
2987
- content: Array.isArray(message.content) ? message.content : [],
2988
- details: typeof message.details === "object" && message.details ? message.details : void 0
2989
- }, { isError: Boolean(message.isError) });
2990
- }
2991
- }
2992
- state.historyLoaded = true;
2993
- } catch (err) {
2994
- chatLog.addSystem(`history failed: ${String(err)}`);
2995
- }
2996
- await refreshSessionInfo();
2997
- tui.requestRender();
2998
- };
2999
- const setSession = async (rawKey) => {
3000
- const nextKey = resolveSessionKey(rawKey);
3001
- updateAgentFromSessionKey(nextKey);
3002
- state.currentSessionKey = nextKey;
3003
- state.activeChatRunId = null;
3004
- state.currentSessionId = null;
3005
- state.sessionInfo.updatedAt = null;
3006
- state.historyLoaded = false;
3007
- clearLocalRunIds?.();
3008
- btw.clear();
3009
- updateHeader();
3010
- updateFooter();
3011
- await loadHistory();
3012
- };
3013
- const abortActive = async () => {
3014
- if (!state.activeChatRunId) {
3015
- chatLog.addSystem("no active run");
3016
- tui.requestRender();
3017
- return;
3018
- }
3019
- try {
3020
- await client.abortChat({
3021
- sessionKey: state.currentSessionKey,
3022
- runId: state.activeChatRunId
3023
- });
3024
- setActivityStatus("aborted");
3025
- } catch (err) {
3026
- chatLog.addSystem(`abort failed: ${String(err)}`);
3027
- setActivityStatus("abort failed");
3028
- }
3029
- tui.requestRender();
3030
- };
3031
- return {
3032
- applyAgentsResult,
3033
- refreshAgents,
3034
- refreshSessionInfo,
3035
- applySessionInfoFromPatch,
3036
- loadHistory,
3037
- setSession,
3038
- abortActive
3039
- };
3040
- }
3041
- //#endregion
3042
- //#region src/tui/tui-waiting.ts
3043
- const defaultWaitingPhrases = [
3044
- "flibbertigibbeting",
3045
- "kerfuffling",
3046
- "dillydallying",
3047
- "twiddling thumbs",
3048
- "noodling",
3049
- "bamboozling",
3050
- "moseying",
3051
- "hobnobbing",
3052
- "pondering",
3053
- "conjuring"
3054
- ];
3055
- function pickWaitingPhrase(tick, phrases = defaultWaitingPhrases) {
3056
- return phrases[Math.floor(tick / 10) % phrases.length] ?? phrases[0] ?? "waiting";
3057
- }
3058
- function shimmerText(theme, text, tick) {
3059
- const width = 6;
3060
- const hi = (ch) => theme.bold(theme.accentSoft(ch));
3061
- const pos = tick % (text.length + width);
3062
- const start = Math.max(0, pos - width);
3063
- const end = Math.min(text.length - 1, pos);
3064
- let out = "";
3065
- for (let i = 0; i < text.length; i++) {
3066
- const ch = text[i];
3067
- out += i >= start && i <= end ? hi(ch) : theme.dim(ch);
3068
- }
3069
- return out;
3070
- }
3071
- function buildWaitingStatusMessage(params) {
3072
- const phrase = pickWaitingPhrase(params.tick, params.phrases);
3073
- return `${shimmerText(params.theme, `${phrase}…`, params.tick)} • ${params.elapsed} | ${params.connectionStatus}`;
3074
- }
3075
- //#endregion
3076
- //#region src/tui/tui.ts
3077
- function createEditorSubmitHandler(params) {
3078
- return (text) => {
3079
- const raw = text;
3080
- const value = raw.trim();
3081
- params.editor.setText("");
3082
- if (!value) return;
3083
- if (raw.startsWith("!") && raw !== "!") {
3084
- params.editor.addToHistory(raw);
3085
- params.handleBangLine(raw);
3086
- return;
3087
- }
3088
- params.editor.addToHistory(value);
3089
- if (value.startsWith("/")) {
3090
- params.handleCommand(value);
3091
- return;
3092
- }
3093
- params.sendMessage(value);
3094
- };
3095
- }
3096
- function shouldEnableWindowsGitBashPasteFallback(params) {
3097
- const platform = params?.platform ?? process.platform;
3098
- const env = params?.env ?? process.env;
3099
- const termProgram = (env.TERM_PROGRAM ?? "").toLowerCase();
3100
- if (platform === "darwin") {
3101
- if (termProgram.includes("iterm") || termProgram.includes("apple_terminal")) return true;
3102
- return false;
3103
- }
3104
- if (platform !== "win32") return false;
3105
- const msystem = (env.MSYSTEM ?? "").toUpperCase();
3106
- const shell = env.SHELL ?? "";
3107
- if (msystem.startsWith("MINGW") || msystem.startsWith("MSYS")) return true;
3108
- if (shell.toLowerCase().includes("bash")) return true;
3109
- return termProgram.includes("mintty");
3110
- }
3111
- function createSubmitBurstCoalescer(params) {
3112
- const windowMs = Math.max(1, params.burstWindowMs ?? 50);
3113
- const now = params.now ?? (() => Date.now());
3114
- const setTimer = params.setTimer ?? setTimeout;
3115
- const clearTimer = params.clearTimer ?? clearTimeout;
3116
- let pending = null;
3117
- let pendingAt = 0;
3118
- let flushTimer = null;
3119
- const clearFlushTimer = () => {
3120
- if (!flushTimer) return;
3121
- clearTimer(flushTimer);
3122
- flushTimer = null;
3123
- };
3124
- const flushPending = () => {
3125
- if (pending === null) return;
3126
- const value = pending;
3127
- pending = null;
3128
- pendingAt = 0;
3129
- clearFlushTimer();
3130
- params.submit(value);
3131
- };
3132
- const scheduleFlush = () => {
3133
- clearFlushTimer();
3134
- flushTimer = setTimer(() => {
3135
- flushPending();
3136
- }, windowMs);
3137
- };
3138
- return (value) => {
3139
- if (!params.enabled) {
3140
- params.submit(value);
3141
- return;
3142
- }
3143
- if (value.includes("\n")) {
3144
- flushPending();
3145
- params.submit(value);
3146
- return;
3147
- }
3148
- const ts = now();
3149
- if (pending === null) {
3150
- pending = value;
3151
- pendingAt = ts;
3152
- scheduleFlush();
3153
- return;
3154
- }
3155
- if (ts - pendingAt <= windowMs) {
3156
- pending = `${pending}\n${value}`;
3157
- pendingAt = ts;
3158
- scheduleFlush();
3159
- return;
3160
- }
3161
- flushPending();
3162
- pending = value;
3163
- pendingAt = ts;
3164
- scheduleFlush();
3165
- };
3166
- }
3167
- function resolveTuiSessionKey(params) {
3168
- const trimmed = (params.raw ?? "").trim();
3169
- if (!trimmed) {
3170
- if (params.sessionScope === "global") return "global";
3171
- return buildAgentMainSessionKey({
3172
- agentId: params.currentAgentId,
3173
- mainKey: params.sessionMainKey
3174
- });
3175
- }
3176
- if (trimmed === "global" || trimmed === "unknown") return trimmed;
3177
- if (trimmed.startsWith("agent:")) return trimmed.toLowerCase();
3178
- return `agent:${params.currentAgentId}:${trimmed.toLowerCase()}`;
3179
- }
3180
- function resolveInitialTuiAgentId(params) {
3181
- const parsed = parseAgentSessionKey((params.initialSessionInput ?? "").trim());
3182
- if (parsed?.agentId) return normalizeAgentId(parsed.agentId);
3183
- const inferredFromWorkspace = resolveAgentIdByWorkspacePath(params.cfg, params.cwd ?? process.cwd());
3184
- if (inferredFromWorkspace) return inferredFromWorkspace;
3185
- return normalizeAgentId(params.fallbackAgentId);
3186
- }
3187
- function resolveGatewayDisconnectState(reason) {
3188
- const reasonLabel = reason?.trim() ? reason.trim() : "closed";
3189
- if (/pairing required/i.test(reasonLabel)) return {
3190
- connectionStatus: `gateway disconnected: ${reasonLabel}`,
3191
- activityStatus: "pairing required: run moldclaw devices list",
3192
- pairingHint: "Pairing required. Run `moldclaw devices list`, approve your request ID, then reconnect."
3193
- };
3194
- return {
3195
- connectionStatus: `gateway disconnected: ${reasonLabel}`,
3196
- activityStatus: "idle"
3197
- };
3198
- }
3199
- function createBackspaceDeduper(params) {
3200
- const dedupeWindowMs = Math.max(0, Math.floor(params?.dedupeWindowMs ?? 8));
3201
- const now = params?.now ?? (() => Date.now());
3202
- let lastBackspaceAt = -1;
3203
- return (data) => {
3204
- if (!matchesKey(data, Key.backspace)) return data;
3205
- const ts = now();
3206
- if (lastBackspaceAt >= 0 && ts - lastBackspaceAt <= dedupeWindowMs) return "";
3207
- lastBackspaceAt = ts;
3208
- return data;
3209
- };
3210
- }
3211
- function isIgnorableTuiStopError(error) {
3212
- if (!error || typeof error !== "object") return false;
3213
- const err = error;
3214
- const code = typeof err.code === "string" ? err.code : "";
3215
- const syscall = typeof err.syscall === "string" ? err.syscall : "";
3216
- const message = typeof err.message === "string" ? err.message : "";
3217
- if (code === "EBADF" && syscall === "setRawMode") return true;
3218
- return /setRawMode/i.test(message) && /EBADF/i.test(message);
3219
- }
3220
- function stopTuiSafely(stop) {
3221
- try {
3222
- stop();
3223
- } catch (error) {
3224
- if (!isIgnorableTuiStopError(error)) throw error;
3225
- }
3226
- }
3227
- function resolveCtrlCAction(params) {
3228
- const exitWindowMs = Math.max(1, Math.floor(params.exitWindowMs ?? 1e3));
3229
- if (params.hasInput) return {
3230
- action: "clear",
3231
- nextLastCtrlCAt: params.now
3232
- };
3233
- if (params.now - params.lastCtrlCAt <= exitWindowMs) return {
3234
- action: "exit",
3235
- nextLastCtrlCAt: params.lastCtrlCAt
3236
- };
3237
- return {
3238
- action: "warn",
3239
- nextLastCtrlCAt: params.now
3240
- };
3241
- }
3242
- async function runTui(opts) {
3243
- const config = loadConfig();
3244
- const initialSessionInput = (opts.session ?? "").trim();
3245
- let sessionScope = config.session?.scope ?? "per-sender";
3246
- let sessionMainKey = normalizeMainKey(config.session?.mainKey);
3247
- let agentDefaultId = resolveDefaultAgentId(config);
3248
- let currentAgentId = resolveInitialTuiAgentId({
3249
- cfg: config,
3250
- fallbackAgentId: agentDefaultId,
3251
- initialSessionInput,
3252
- cwd: process.cwd()
3253
- });
3254
- let agents = [];
3255
- const agentNames = /* @__PURE__ */ new Map();
3256
- let currentSessionKey = "";
3257
- let initialSessionApplied = false;
3258
- let currentSessionId = null;
3259
- let activeChatRunId = null;
3260
- let historyLoaded = false;
3261
- let isConnected = false;
3262
- let wasDisconnected = false;
3263
- let toolsExpanded = false;
3264
- let showThinking = false;
3265
- let pairingHintShown = false;
3266
- const localRunIds = /* @__PURE__ */ new Set();
3267
- const localBtwRunIds = /* @__PURE__ */ new Set();
3268
- const deliverDefault = opts.deliver ?? false;
3269
- const autoMessage = opts.message?.trim();
3270
- let autoMessageSent = false;
3271
- let sessionInfo = {};
3272
- let lastCtrlCAt = 0;
3273
- let exitRequested = false;
3274
- let activityStatus = "idle";
3275
- let connectionStatus = "connecting";
3276
- let statusTimeout = null;
3277
- let statusTimer = null;
3278
- let statusStartedAt = null;
3279
- let lastActivityStatus = activityStatus;
3280
- const state = {
3281
- get agentDefaultId() {
3282
- return agentDefaultId;
3283
- },
3284
- set agentDefaultId(value) {
3285
- agentDefaultId = value;
3286
- },
3287
- get sessionMainKey() {
3288
- return sessionMainKey;
3289
- },
3290
- set sessionMainKey(value) {
3291
- sessionMainKey = value;
3292
- },
3293
- get sessionScope() {
3294
- return sessionScope;
3295
- },
3296
- set sessionScope(value) {
3297
- sessionScope = value;
3298
- },
3299
- get agents() {
3300
- return agents;
3301
- },
3302
- set agents(value) {
3303
- agents = value;
3304
- },
3305
- get currentAgentId() {
3306
- return currentAgentId;
3307
- },
3308
- set currentAgentId(value) {
3309
- currentAgentId = value;
3310
- },
3311
- get currentSessionKey() {
3312
- return currentSessionKey;
3313
- },
3314
- set currentSessionKey(value) {
3315
- currentSessionKey = value;
3316
- },
3317
- get currentSessionId() {
3318
- return currentSessionId;
3319
- },
3320
- set currentSessionId(value) {
3321
- currentSessionId = value;
3322
- },
3323
- get activeChatRunId() {
3324
- return activeChatRunId;
3325
- },
3326
- set activeChatRunId(value) {
3327
- activeChatRunId = value;
3328
- },
3329
- get historyLoaded() {
3330
- return historyLoaded;
3331
- },
3332
- set historyLoaded(value) {
3333
- historyLoaded = value;
3334
- },
3335
- get sessionInfo() {
3336
- return sessionInfo;
3337
- },
3338
- set sessionInfo(value) {
3339
- sessionInfo = value;
3340
- },
3341
- get initialSessionApplied() {
3342
- return initialSessionApplied;
3343
- },
3344
- set initialSessionApplied(value) {
3345
- initialSessionApplied = value;
3346
- },
3347
- get isConnected() {
3348
- return isConnected;
3349
- },
3350
- set isConnected(value) {
3351
- isConnected = value;
3352
- },
3353
- get autoMessageSent() {
3354
- return autoMessageSent;
3355
- },
3356
- set autoMessageSent(value) {
3357
- autoMessageSent = value;
3358
- },
3359
- get toolsExpanded() {
3360
- return toolsExpanded;
3361
- },
3362
- set toolsExpanded(value) {
3363
- toolsExpanded = value;
3364
- },
3365
- get showThinking() {
3366
- return showThinking;
3367
- },
3368
- set showThinking(value) {
3369
- showThinking = value;
3370
- },
3371
- get connectionStatus() {
3372
- return connectionStatus;
3373
- },
3374
- set connectionStatus(value) {
3375
- connectionStatus = value;
3376
- },
3377
- get activityStatus() {
3378
- return activityStatus;
3379
- },
3380
- set activityStatus(value) {
3381
- activityStatus = value;
3382
- },
3383
- get statusTimeout() {
3384
- return statusTimeout;
3385
- },
3386
- set statusTimeout(value) {
3387
- statusTimeout = value;
3388
- },
3389
- get lastCtrlCAt() {
3390
- return lastCtrlCAt;
3391
- },
3392
- set lastCtrlCAt(value) {
3393
- lastCtrlCAt = value;
3394
- }
3395
- };
3396
- const noteLocalRunId = (runId) => {
3397
- if (!runId) return;
3398
- localRunIds.add(runId);
3399
- if (localRunIds.size > 200) {
3400
- const [first] = localRunIds;
3401
- if (first) localRunIds.delete(first);
3402
- }
3403
- };
3404
- const forgetLocalRunId = (runId) => {
3405
- localRunIds.delete(runId);
3406
- };
3407
- const isLocalRunId = (runId) => localRunIds.has(runId);
3408
- const clearLocalRunIds = () => {
3409
- localRunIds.clear();
3410
- };
3411
- const noteLocalBtwRunId = (runId) => {
3412
- if (!runId) return;
3413
- localBtwRunIds.add(runId);
3414
- if (localBtwRunIds.size > 200) {
3415
- const [first] = localBtwRunIds;
3416
- if (first) localBtwRunIds.delete(first);
3417
- }
3418
- };
3419
- const forgetLocalBtwRunId = (runId) => {
3420
- localBtwRunIds.delete(runId);
3421
- };
3422
- const isLocalBtwRunId = (runId) => localBtwRunIds.has(runId);
3423
- const clearLocalBtwRunIds = () => {
3424
- localBtwRunIds.clear();
3425
- };
3426
- const client = await GatewayChatClient.connect({
3427
- url: opts.url,
3428
- token: opts.token,
3429
- password: opts.password
3430
- });
3431
- const tui = new TUI(new ProcessTerminal());
3432
- const dedupeBackspace = createBackspaceDeduper();
3433
- tui.addInputListener((data) => {
3434
- const next = dedupeBackspace(data);
3435
- if (next.length === 0) return { consume: true };
3436
- return { data: next };
3437
- });
3438
- const header = new Text("", 1, 0);
3439
- const statusContainer = new Container();
3440
- const footer = new Text("", 1, 0);
3441
- const chatLog = new ChatLog();
3442
- const editor = new CustomEditor(tui, editorTheme);
3443
- const root = new Container();
3444
- root.addChild(header);
3445
- root.addChild(chatLog);
3446
- root.addChild(statusContainer);
3447
- root.addChild(footer);
3448
- root.addChild(editor);
3449
- const updateAutocompleteProvider = () => {
3450
- editor.setAutocompleteProvider(new CombinedAutocompleteProvider(getSlashCommands({
3451
- cfg: config,
3452
- provider: sessionInfo.modelProvider,
3453
- model: sessionInfo.model
3454
- }), process.cwd()));
3455
- };
3456
- tui.addChild(root);
3457
- tui.setFocus(editor);
3458
- const formatSessionKey = (key) => {
3459
- if (key === "global" || key === "unknown") return key;
3460
- return parseAgentSessionKey(key)?.rest ?? key;
3461
- };
3462
- const formatAgentLabel = (id) => {
3463
- const name = agentNames.get(id);
3464
- return name ? `${id} (${name})` : id;
3465
- };
3466
- const resolveSessionKey = (raw) => {
3467
- return resolveTuiSessionKey({
3468
- raw,
3469
- sessionScope,
3470
- currentAgentId,
3471
- sessionMainKey
3472
- });
3473
- };
3474
- currentSessionKey = resolveSessionKey(initialSessionInput);
3475
- const updateHeader = () => {
3476
- const sessionLabel = formatSessionKey(currentSessionKey);
3477
- const agentLabel = formatAgentLabel(currentAgentId);
3478
- header.setText(theme.header(`moldclaw tui - ${client.connection.url} - agent ${agentLabel} - session ${sessionLabel}`));
3479
- };
3480
- const busyStates = new Set([
3481
- "sending",
3482
- "waiting",
3483
- "streaming",
3484
- "running"
3485
- ]);
3486
- let statusText = null;
3487
- let statusLoader = null;
3488
- const formatElapsed = (startMs) => {
3489
- const totalSeconds = Math.max(0, Math.floor((Date.now() - startMs) / 1e3));
3490
- if (totalSeconds < 60) return `${totalSeconds}s`;
3491
- return `${Math.floor(totalSeconds / 60)}m ${totalSeconds % 60}s`;
3492
- };
3493
- const ensureStatusText = () => {
3494
- if (statusText) return;
3495
- statusContainer.clear();
3496
- statusLoader?.stop();
3497
- statusLoader = null;
3498
- statusText = new Text("", 1, 0);
3499
- statusContainer.addChild(statusText);
3500
- };
3501
- const ensureStatusLoader = () => {
3502
- if (statusLoader) return;
3503
- statusContainer.clear();
3504
- statusText = null;
3505
- statusLoader = new Loader(tui, (spinner) => theme.accent(spinner), (text) => theme.bold(theme.accentSoft(text)), "");
3506
- statusContainer.addChild(statusLoader);
3507
- };
3508
- let waitingTick = 0;
3509
- let waitingTimer = null;
3510
- let waitingPhrase = null;
3511
- const updateBusyStatusMessage = () => {
3512
- if (!statusLoader || !statusStartedAt) return;
3513
- const elapsed = formatElapsed(statusStartedAt);
3514
- if (activityStatus === "waiting") {
3515
- waitingTick++;
3516
- statusLoader.setMessage(buildWaitingStatusMessage({
3517
- theme,
3518
- tick: waitingTick,
3519
- elapsed,
3520
- connectionStatus,
3521
- phrases: waitingPhrase ? [waitingPhrase] : void 0
3522
- }));
3523
- return;
3524
- }
3525
- statusLoader.setMessage(`${activityStatus} • ${elapsed} | ${connectionStatus}`);
3526
- };
3527
- const startStatusTimer = () => {
3528
- if (statusTimer) return;
3529
- statusTimer = setInterval(() => {
3530
- if (!busyStates.has(activityStatus)) return;
3531
- updateBusyStatusMessage();
3532
- }, 1e3);
3533
- };
3534
- const stopStatusTimer = () => {
3535
- if (!statusTimer) return;
3536
- clearInterval(statusTimer);
3537
- statusTimer = null;
3538
- };
3539
- const startWaitingTimer = () => {
3540
- if (waitingTimer) return;
3541
- if (!waitingPhrase) waitingPhrase = defaultWaitingPhrases[Math.floor(Math.random() * defaultWaitingPhrases.length)] ?? defaultWaitingPhrases[0] ?? "waiting";
3542
- waitingTick = 0;
3543
- waitingTimer = setInterval(() => {
3544
- if (activityStatus !== "waiting") return;
3545
- updateBusyStatusMessage();
3546
- }, 120);
3547
- };
3548
- const stopWaitingTimer = () => {
3549
- if (!waitingTimer) return;
3550
- clearInterval(waitingTimer);
3551
- waitingTimer = null;
3552
- waitingPhrase = null;
3553
- };
3554
- const renderStatus = () => {
3555
- if (busyStates.has(activityStatus)) {
3556
- if (!statusStartedAt || lastActivityStatus !== activityStatus) statusStartedAt = Date.now();
3557
- ensureStatusLoader();
3558
- if (activityStatus === "waiting") {
3559
- stopStatusTimer();
3560
- startWaitingTimer();
3561
- } else {
3562
- stopWaitingTimer();
3563
- startStatusTimer();
3564
- }
3565
- updateBusyStatusMessage();
3566
- } else {
3567
- statusStartedAt = null;
3568
- stopStatusTimer();
3569
- stopWaitingTimer();
3570
- statusLoader?.stop();
3571
- statusLoader = null;
3572
- ensureStatusText();
3573
- const text = activityStatus ? `${connectionStatus} | ${activityStatus}` : connectionStatus;
3574
- statusText?.setText(theme.dim(text));
3575
- }
3576
- lastActivityStatus = activityStatus;
3577
- };
3578
- const setConnectionStatus = (text, ttlMs) => {
3579
- connectionStatus = text;
3580
- renderStatus();
3581
- if (statusTimeout) clearTimeout(statusTimeout);
3582
- if (ttlMs && ttlMs > 0) statusTimeout = setTimeout(() => {
3583
- connectionStatus = isConnected ? "connected" : "disconnected";
3584
- renderStatus();
3585
- }, ttlMs);
3586
- };
3587
- const setActivityStatus = (text) => {
3588
- activityStatus = text;
3589
- renderStatus();
3590
- };
3591
- const updateFooter = () => {
3592
- const sessionKeyLabel = formatSessionKey(currentSessionKey);
3593
- const sessionLabel = sessionInfo.displayName ? `${sessionKeyLabel} (${sessionInfo.displayName})` : sessionKeyLabel;
3594
- const agentLabel = formatAgentLabel(currentAgentId);
3595
- const modelLabel = sessionInfo.model ? sessionInfo.modelProvider ? `${sessionInfo.modelProvider}/${sessionInfo.model}` : sessionInfo.model : "unknown";
3596
- const tokens = formatTokens(sessionInfo.totalTokens ?? null, sessionInfo.contextTokens ?? null);
3597
- const think = sessionInfo.thinkingLevel ?? "off";
3598
- const fast = sessionInfo.fastMode === true;
3599
- const verbose = sessionInfo.verboseLevel ?? "off";
3600
- const reasoning = sessionInfo.reasoningLevel ?? "off";
3601
- const reasoningLabel = reasoning === "on" ? "reasoning" : reasoning === "stream" ? "reasoning:stream" : null;
3602
- const footerParts = [
3603
- `agent ${agentLabel}`,
3604
- `session ${sessionLabel}`,
3605
- modelLabel,
3606
- think !== "off" ? `think ${think}` : null,
3607
- fast ? "fast" : null,
3608
- verbose !== "off" ? `verbose ${verbose}` : null,
3609
- reasoningLabel,
3610
- tokens
3611
- ].filter(Boolean);
3612
- footer.setText(theme.dim(footerParts.join(" | ")));
3613
- };
3614
- const { openOverlay, closeOverlay } = createOverlayHandlers(tui, editor);
3615
- const btw = {
3616
- showResult: (params) => {
3617
- chatLog.showBtw(params);
3618
- },
3619
- clear: () => {
3620
- chatLog.dismissBtw();
3621
- }
3622
- };
3623
- const { refreshAgents, refreshSessionInfo, applySessionInfoFromPatch, loadHistory, setSession, abortActive } = createSessionActions({
3624
- client,
3625
- chatLog,
3626
- btw,
3627
- tui,
3628
- opts,
3629
- state,
3630
- agentNames,
3631
- initialSessionInput,
3632
- initialSessionAgentId: (() => {
3633
- if (!initialSessionInput) return null;
3634
- const parsed = parseAgentSessionKey(initialSessionInput);
3635
- return parsed ? normalizeAgentId(parsed.agentId) : null;
3636
- })(),
3637
- resolveSessionKey,
3638
- updateHeader,
3639
- updateFooter,
3640
- updateAutocompleteProvider,
3641
- setActivityStatus,
3642
- clearLocalRunIds
3643
- });
3644
- const { handleChatEvent, handleAgentEvent, handleBtwEvent } = createEventHandlers({
3645
- chatLog,
3646
- btw,
3647
- tui,
3648
- state,
3649
- setActivityStatus,
3650
- refreshSessionInfo,
3651
- loadHistory,
3652
- isLocalRunId,
3653
- forgetLocalRunId,
3654
- clearLocalRunIds,
3655
- isLocalBtwRunId,
3656
- forgetLocalBtwRunId,
3657
- clearLocalBtwRunIds
3658
- });
3659
- const requestExit = () => {
3660
- if (exitRequested) return;
3661
- exitRequested = true;
3662
- client.stop();
3663
- stopTuiSafely(() => tui.stop());
3664
- process.exit(0);
3665
- };
3666
- const { handleCommand, sendMessage, openModelSelector, openAgentSelector, openSessionSelector } = createCommandHandlers({
3667
- client,
3668
- chatLog,
3669
- tui,
3670
- opts,
3671
- state,
3672
- deliverDefault,
3673
- openOverlay,
3674
- closeOverlay,
3675
- refreshSessionInfo,
3676
- applySessionInfoFromPatch,
3677
- loadHistory,
3678
- setSession,
3679
- refreshAgents,
3680
- abortActive,
3681
- setActivityStatus,
3682
- formatSessionKey,
3683
- noteLocalRunId,
3684
- noteLocalBtwRunId,
3685
- forgetLocalRunId,
3686
- forgetLocalBtwRunId,
3687
- requestExit
3688
- });
3689
- const { runLocalShellLine } = createLocalShellRunner({
3690
- chatLog,
3691
- tui,
3692
- openOverlay,
3693
- closeOverlay
3694
- });
3695
- updateAutocompleteProvider();
3696
- editor.onSubmit = createSubmitBurstCoalescer({
3697
- submit: createEditorSubmitHandler({
3698
- editor,
3699
- handleCommand,
3700
- sendMessage,
3701
- handleBangLine: runLocalShellLine
3702
- }),
3703
- enabled: shouldEnableWindowsGitBashPasteFallback()
3704
- });
3705
- editor.onEscape = () => {
3706
- if (chatLog.hasVisibleBtw()) {
3707
- chatLog.dismissBtw();
3708
- tui.requestRender();
3709
- return;
3710
- }
3711
- abortActive();
3712
- };
3713
- const handleCtrlC = () => {
3714
- const now = Date.now();
3715
- const decision = resolveCtrlCAction({
3716
- hasInput: editor.getText().trim().length > 0,
3717
- now,
3718
- lastCtrlCAt
3719
- });
3720
- lastCtrlCAt = decision.nextLastCtrlCAt;
3721
- if (decision.action === "clear") {
3722
- editor.setText("");
3723
- setActivityStatus("cleared input; press ctrl+c again to exit");
3724
- tui.requestRender();
3725
- return;
3726
- }
3727
- if (decision.action === "exit") {
3728
- requestExit();
3729
- return;
3730
- }
3731
- setActivityStatus("press ctrl+c again to exit");
3732
- tui.requestRender();
3733
- };
3734
- editor.onCtrlC = () => {
3735
- handleCtrlC();
3736
- };
3737
- editor.onCtrlD = () => {
3738
- requestExit();
3739
- };
3740
- editor.onCtrlO = () => {
3741
- toolsExpanded = !toolsExpanded;
3742
- chatLog.setToolsExpanded(toolsExpanded);
3743
- setActivityStatus(toolsExpanded ? "tools expanded" : "tools collapsed");
3744
- tui.requestRender();
3745
- };
3746
- editor.onCtrlL = () => {
3747
- openModelSelector();
3748
- };
3749
- editor.onCtrlG = () => {
3750
- openAgentSelector();
3751
- };
3752
- editor.onCtrlP = () => {
3753
- openSessionSelector();
3754
- };
3755
- editor.onCtrlT = () => {
3756
- showThinking = !showThinking;
3757
- loadHistory();
3758
- };
3759
- tui.addInputListener((data) => {
3760
- if (!chatLog.hasVisibleBtw()) return;
3761
- if (editor.getText().length > 0) return;
3762
- if (matchesKey(data, "enter")) {
3763
- chatLog.dismissBtw();
3764
- tui.requestRender();
3765
- return { consume: true };
3766
- }
3767
- });
3768
- client.onEvent = (evt) => {
3769
- if (evt.event === "chat") handleChatEvent(evt.payload);
3770
- if (evt.event === "chat.side_result") handleBtwEvent(evt.payload);
3771
- if (evt.event === "agent") handleAgentEvent(evt.payload);
3772
- };
3773
- client.onConnected = () => {
3774
- isConnected = true;
3775
- pairingHintShown = false;
3776
- const reconnected = wasDisconnected;
3777
- wasDisconnected = false;
3778
- setConnectionStatus("connected");
3779
- (async () => {
3780
- await refreshAgents();
3781
- updateHeader();
3782
- await loadHistory();
3783
- setConnectionStatus(reconnected ? "gateway reconnected" : "gateway connected", 4e3);
3784
- tui.requestRender();
3785
- if (!autoMessageSent && autoMessage) {
3786
- autoMessageSent = true;
3787
- await sendMessage(autoMessage);
3788
- }
3789
- updateFooter();
3790
- tui.requestRender();
3791
- })();
3792
- };
3793
- client.onDisconnected = (reason) => {
3794
- isConnected = false;
3795
- wasDisconnected = true;
3796
- historyLoaded = false;
3797
- const disconnectState = resolveGatewayDisconnectState(reason);
3798
- setConnectionStatus(disconnectState.connectionStatus, 5e3);
3799
- setActivityStatus(disconnectState.activityStatus);
3800
- if (disconnectState.pairingHint && !pairingHintShown) {
3801
- pairingHintShown = true;
3802
- chatLog.addSystem(disconnectState.pairingHint);
3803
- }
3804
- updateFooter();
3805
- tui.requestRender();
3806
- };
3807
- client.onGap = (info) => {
3808
- setConnectionStatus(`event gap: expected ${info.expected}, got ${info.received}`, 5e3);
3809
- tui.requestRender();
3810
- };
3811
- updateHeader();
3812
- setConnectionStatus("connecting");
3813
- updateFooter();
3814
- const sigintHandler = () => {
3815
- handleCtrlC();
3816
- };
3817
- const sigtermHandler = () => {
3818
- requestExit();
3819
- };
3820
- process.on("SIGINT", sigintHandler);
3821
- process.on("SIGTERM", sigtermHandler);
3822
- tui.start();
3823
- client.start();
3824
- await new Promise((resolve) => {
3825
- const finish = () => {
3826
- process.removeListener("SIGINT", sigintHandler);
3827
- process.removeListener("SIGTERM", sigtermHandler);
3828
- resolve();
3829
- };
3830
- process.once("exit", finish);
3831
- });
3832
- }
3833
- //#endregion
3834
- export { runTui as t };