@spacebar_ai/moldclaw-core 2026.3.41 → 2026.3.44

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 (1144) hide show
  1. package/dist/accounts-5qY-dKca.d.ts +103 -0
  2. package/dist/accounts-SqdHz2ZP.js +114 -0
  3. package/dist/acp-cli-E6bcNqiE.js +2093 -0
  4. package/dist/actions.runtime-BU_XMuLk.js +119 -0
  5. package/dist/actions.runtime-CY5h8lqH.js +133 -0
  6. package/dist/agent-scope-lZlwP1At.js +208 -0
  7. package/dist/agents-C4SkadR1.js +853 -0
  8. package/dist/agents-RfwqGCzE.js +222 -0
  9. package/dist/agents.config-CX9CPNfP.js +17 -0
  10. package/dist/agents.config-DF9Zwn9n.js +121 -0
  11. package/dist/allow-list-3WSjz1zl.js +81 -0
  12. package/dist/allowlist-DNbDjFjw.js +142 -0
  13. package/dist/api-BEOpJ7dR.js +117 -0
  14. package/dist/audit-CpJz_eu6.js +787 -0
  15. package/dist/audit-CpfSjvyo.js +54 -0
  16. package/dist/audit-channel.collect.runtime-BeGotloZ.js +605 -0
  17. package/dist/audit-channel.runtime-BJDZ7ETt.js +121 -0
  18. package/dist/audit-extra.async-C2G0mqmk.js +813 -0
  19. package/dist/audit-membership-runtime-B1FqJsPV.js +162 -0
  20. package/dist/audit.deep.runtime-DyL9O_sU.js +25 -0
  21. package/dist/audit.nondeep.runtime-C6jFgJfH.js +832 -0
  22. package/dist/audit.runtime-Dnlsn23e.js +118 -0
  23. package/dist/auth-Ch3Rchm4.js +101 -0
  24. package/dist/auth-choice-CEFSlnLT.js +122 -0
  25. package/dist/auth-choice-CVCef-eU.js +268 -0
  26. package/dist/auth-choice-Cez-pXrg.js +507 -0
  27. package/dist/auth-choice-options-DO78mvPe.js +123 -0
  28. package/dist/auth-choice-prompt-CUkC7Mmb.js +36 -0
  29. package/dist/auth-choice-prompt-DCuQRiVl.js +115 -0
  30. package/dist/auth-choice.apply-helpers-BhbNIV8X.js +66 -0
  31. package/dist/auth-choice.plugin-providers.runtime-4BhqvEw_.js +119 -0
  32. package/dist/auth-profiles-smABVXzp.js +128040 -0
  33. package/dist/auth-profiles.runtime-Cr-ojtTc.js +116 -0
  34. package/dist/banner-CojBHPWr.js +342 -0
  35. package/dist/bluebubbles-BnLsj2Fy.d.ts +6 -0
  36. package/dist/bluebubbles-CVk7M3Bl.js +64 -0
  37. package/dist/bot-DdyrB2z9.d.ts +478 -0
  38. package/dist/brave-w4Fo8WZ3.js +24 -0
  39. package/dist/browser-cli-DWFs3P_i.js +1494 -0
  40. package/dist/build-info.json +3 -3
  41. package/dist/bundled/boot-md/handler.d.ts +1 -1
  42. package/dist/bundled/boot-md/handler.js +35 -35
  43. package/dist/bundled/bootstrap-extra-files/handler.d.ts +1 -1
  44. package/dist/bundled/bootstrap-extra-files/handler.js +1 -1
  45. package/dist/bundled/command-logger/handler.d.ts +1 -1
  46. package/dist/bundled/session-memory/handler.d.ts +1 -1
  47. package/dist/bundled/session-memory/handler.js +36 -36
  48. package/dist/call-Do7wTSr7.js +39 -0
  49. package/dist/call-gdDAt07d.js +640 -0
  50. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  51. package/dist/channel-B26pkce0.js +214 -0
  52. package/dist/channel-BJHp0AQC.js +352 -0
  53. package/dist/channel-BKFOv51P.js +4681 -0
  54. package/dist/channel-BNgpOY8v.js +538 -0
  55. package/dist/channel-BcQAAo2P.js +226 -0
  56. package/dist/channel-BvNdnhbx.js +1598 -0
  57. package/dist/channel-C1Rda3Jd.js +306 -0
  58. package/dist/channel-C87DG-F7.js +803 -0
  59. package/dist/channel-CIip0kvZ.js +619 -0
  60. package/dist/channel-CTPxoT_E2.js +316 -0
  61. package/dist/channel-CklaCzUG.js +562 -0
  62. package/dist/channel-CoJnAdLs.js +920 -0
  63. package/dist/channel-D3tafL1_.js +949 -0
  64. package/dist/channel-DFMrP2uu.js +542 -0
  65. package/dist/channel-DMd5cJQe.js +397 -0
  66. package/dist/channel-Dm34kxAJ.js +207 -0
  67. package/dist/channel-DmwF9udn.js +1321 -0
  68. package/dist/channel-account-context-Bjur9nlh.js +103 -0
  69. package/dist/channel-bGnST659.js +943 -0
  70. package/dist/channel-hIgbkTZf.js +575 -0
  71. package/dist/channel-m_TGrDKo.js +497 -0
  72. package/dist/channel-options-DoUPBMa8.js +50 -0
  73. package/dist/channel-plugin-ids-TZIY4hFs.js +26 -0
  74. package/dist/channel-summary-qD54bOBO.js +111 -0
  75. package/dist/channel.runtime-B0H04Dkk.js +199 -0
  76. package/dist/channel.runtime-BU1f3NkV.js +418 -0
  77. package/dist/channel.runtime-Bj1sfLep.js +4011 -0
  78. package/dist/channel.runtime-BtPAAJc3.js +870 -0
  79. package/dist/channel.runtime-Bx-10m_j.js +171 -0
  80. package/dist/channel.runtime-CI_TBywQ.js +179 -0
  81. package/dist/channel.runtime-CSLj14-Z.js +182 -0
  82. package/dist/channel.runtime-D-lTSYAd.js +404 -0
  83. package/dist/channel.runtime-DJqIOSji.js +127 -0
  84. package/dist/channel.runtime-Ec8aQ9V2.js +241 -0
  85. package/dist/channel.runtime-ax5a1jBm.js +218 -0
  86. package/dist/channel.setup-B-ncdYLT.js +9 -0
  87. package/dist/channel.setup-BY4bh5dm.js +9 -0
  88. package/dist/channel.setup-BovsdMnL.js +57 -0
  89. package/dist/channel.setup-CXzXA25h.js +6 -0
  90. package/dist/channel.setup-DcZUEufN.js +8 -0
  91. package/dist/channel.setup-E6zceRsE.js +8 -0
  92. package/dist/channel.setup-Pc7nGbdX.js +11 -0
  93. package/dist/channels/plugins/actions/discord.d.ts +2 -2
  94. package/dist/channels/plugins/actions/discord.js +35 -35
  95. package/dist/channels/plugins/actions/signal.d.ts +1 -1
  96. package/dist/channels/plugins/actions/signal.js +35 -35
  97. package/dist/channels/plugins/actions/telegram.d.ts +2 -2
  98. package/dist/channels/plugins/actions/telegram.js +35 -35
  99. package/dist/channels/plugins/agent-tools/whatsapp-login.d.ts +3 -3
  100. package/dist/channels/plugins/agent-tools/whatsapp-login.js +35 -35
  101. package/dist/channels-CPtE5ND6.js +404 -0
  102. package/dist/channels-Cj8ZolHI.js +1118 -0
  103. package/dist/channels-cli-D2sKrntt.js +291 -0
  104. package/dist/channels-status-issues-CzIHODg2.js +16 -0
  105. package/dist/clawbot-cli-BcwEDmUn.js +118 -0
  106. package/dist/cleanup-utils-D0L17RsX.js +96 -0
  107. package/dist/cli/daemon-cli.js +1 -1
  108. package/dist/cli-BvGVPKnD.js +154 -0
  109. package/dist/command-registry-CADQzTAg.js +14 -0
  110. package/dist/command-registry-ktiJNAJd.js +242 -0
  111. package/dist/command-secret-gateway-CXp10RTM.js +111 -0
  112. package/dist/compact.runtime-DyKL-Iar.js +116 -0
  113. package/dist/completion-cli-Bz4STrpt.js +17 -0
  114. package/dist/completion-cli-pVda2OFb.js +445 -0
  115. package/dist/config-BbvDRSYp.js +31 -0
  116. package/dist/config-CwBv71QC.js +44 -0
  117. package/dist/config-cli-Y0uXHbOw.js +678 -0
  118. package/dist/config-guard-BpW5g7JE.js +118 -0
  119. package/dist/config-validation-B-vLIsbo.js +262 -0
  120. package/dist/config-value-DT3-5958.js +132 -0
  121. package/dist/configure-B9U-jCqP.js +1100 -0
  122. package/dist/configure-BJ3Wrs5b.js +243 -0
  123. package/dist/control-ui-assets-C1YDYi82.js +232 -0
  124. package/dist/control-ui-shared-Dm5Dh0Lo.js +29 -0
  125. package/dist/core-BwKq3krw.js +150 -0
  126. package/dist/core-hjBwfDsW.d.ts +87 -0
  127. package/dist/cron-cli-DTDgfoMh.js +639 -0
  128. package/dist/daemon-cli-C-dkAXR1.js +339 -0
  129. package/dist/daemon-install-Oy0Q5pMF.js +180 -0
  130. package/dist/deliver-DNGnDqF9.js +111 -0
  131. package/dist/deliver-runtime-CCNZIhET.js +111 -0
  132. package/dist/device-id-cli-XvwZbIyC.js +52 -0
  133. package/dist/device-identity-IG5DngWM.js +365 -0
  134. package/dist/devices-cli-DIsxj4xp.js +342 -0
  135. package/dist/diagnostic-DTPopFvh.js +310 -0
  136. package/dist/directory-cli-DTSY3Ktr.js +311 -0
  137. package/dist/directory-config-helpers-DpFcAbmo.d.ts +38 -0
  138. package/dist/directory.static-CBRAUwUW.js +44 -0
  139. package/dist/discord-CrgxhEWw.js +114 -0
  140. package/dist/discovery-DrG7wmAR.js +48 -0
  141. package/dist/dm-policy-shared-DKoGdUpY.d.ts +95 -0
  142. package/dist/dns-cli-BJiz6CLK.js +217 -0
  143. package/dist/docs-cli-Dq2Yi5qO.js +174 -0
  144. package/dist/doctor-completion-D3GeVcFP.js +90 -0
  145. package/dist/doctor-config-flow-B1cMjr8h.js +112 -0
  146. package/dist/doctor-config-flow-BUe7JpV3.js +2437 -0
  147. package/dist/enable-Bc8bCuVe.js +24 -0
  148. package/dist/entry.js +4 -4
  149. package/dist/exec-approvals-cli-kLAev6bP.js +421 -0
  150. package/dist/extensions/acpx/index.d.ts +1 -1
  151. package/dist/extensions/amazon-bedrock/index.d.ts +1 -1
  152. package/dist/extensions/amazon-bedrock/index.js +4 -4
  153. package/dist/extensions/anthropic/index.d.ts +1 -1
  154. package/dist/extensions/anthropic/index.js +35 -35
  155. package/dist/extensions/bluebubbles/index.d.ts +1 -1
  156. package/dist/extensions/bluebubbles/index.js +39 -39
  157. package/dist/extensions/bluebubbles/setup-entry.d.ts +2 -2
  158. package/dist/extensions/bluebubbles/setup-entry.js +39 -39
  159. package/dist/extensions/brave/index.d.ts +1 -1
  160. package/dist/extensions/brave/index.js +5 -5
  161. package/dist/extensions/byteplus/index.d.ts +1 -1
  162. package/dist/extensions/byteplus/index.js +35 -35
  163. package/dist/extensions/cloudflare-ai-gateway/index.d.ts +1 -1
  164. package/dist/extensions/cloudflare-ai-gateway/index.js +36 -36
  165. package/dist/extensions/copilot-proxy/index.d.ts +1 -1
  166. package/dist/extensions/copilot-proxy/index.js +4 -4
  167. package/dist/extensions/device-pair/index.d.ts +1 -1
  168. package/dist/extensions/device-pair/index.js +4 -4
  169. package/dist/extensions/diagnostics-otel/index.d.ts +1 -1
  170. package/dist/extensions/diagnostics-otel/index.js +4 -4
  171. package/dist/extensions/diffs/index.d.ts +1 -1
  172. package/dist/extensions/discord/index.d.ts +1 -1
  173. package/dist/extensions/discord/index.js +40 -40
  174. package/dist/extensions/discord/setup-entry.d.ts +1 -1
  175. package/dist/extensions/discord/setup-entry.js +38 -38
  176. package/dist/extensions/elevenlabs/index.d.ts +1 -1
  177. package/dist/extensions/elevenlabs/index.js +35 -35
  178. package/dist/extensions/feishu/index.d.ts +2 -2
  179. package/dist/extensions/feishu/index.js +40 -40
  180. package/dist/extensions/feishu/setup-entry.d.ts +2 -2
  181. package/dist/extensions/feishu/setup-entry.js +37 -37
  182. package/dist/extensions/firecrawl/index.d.ts +1 -1
  183. package/dist/extensions/firecrawl/index.js +35 -35
  184. package/dist/extensions/github-copilot/index.d.ts +1 -1
  185. package/dist/extensions/github-copilot/index.js +35 -35
  186. package/dist/extensions/google/index.d.ts +1 -1
  187. package/dist/extensions/google/index.js +35 -35
  188. package/dist/extensions/googlechat/index.d.ts +1 -1
  189. package/dist/extensions/googlechat/index.js +38 -38
  190. package/dist/extensions/googlechat/setup-entry.d.ts +1 -1
  191. package/dist/extensions/googlechat/setup-entry.js +38 -38
  192. package/dist/extensions/huggingface/index.d.ts +1 -1
  193. package/dist/extensions/huggingface/index.js +35 -35
  194. package/dist/extensions/imessage/index.d.ts +1 -1
  195. package/dist/extensions/imessage/index.js +39 -39
  196. package/dist/extensions/imessage/setup-entry.d.ts +1 -1
  197. package/dist/extensions/imessage/setup-entry.js +39 -39
  198. package/dist/extensions/irc/index.d.ts +1 -1
  199. package/dist/extensions/irc/index.js +38 -38
  200. package/dist/extensions/irc/setup-entry.d.ts +2 -2
  201. package/dist/extensions/irc/setup-entry.js +38 -38
  202. package/dist/extensions/kakao-talkchannel/index.d.ts +1 -1
  203. package/dist/extensions/kakao-talkchannel/index.js +4 -4
  204. package/dist/extensions/kilocode/index.d.ts +1 -1
  205. package/dist/extensions/kilocode/index.js +35 -35
  206. package/dist/extensions/kimi-coding/index.d.ts +1 -1
  207. package/dist/extensions/kimi-coding/index.js +35 -35
  208. package/dist/extensions/line/index.d.ts +1 -1
  209. package/dist/extensions/line/index.js +37 -37
  210. package/dist/extensions/line/setup-entry.d.ts +1 -1
  211. package/dist/extensions/line/setup-entry.js +37 -37
  212. package/dist/extensions/llm-task/index.d.ts +1 -1
  213. package/dist/extensions/llm-task/index.js +35 -35
  214. package/dist/extensions/lobster/index.d.ts +1 -1
  215. package/dist/extensions/lobster/index.js +4 -4
  216. package/dist/extensions/matrix/index.d.ts +1 -1
  217. package/dist/extensions/matrix/index.js +40 -40
  218. package/dist/extensions/matrix/setup-entry.d.ts +2 -2
  219. package/dist/extensions/matrix/setup-entry.js +40 -40
  220. package/dist/extensions/mattermost/index.d.ts +1 -1
  221. package/dist/extensions/mattermost/index.js +37 -37
  222. package/dist/extensions/mattermost/setup-entry.d.ts +2 -2
  223. package/dist/extensions/mattermost/setup-entry.js +37 -37
  224. package/dist/extensions/memory-core/index.d.ts +1 -1
  225. package/dist/extensions/memory-core/index.js +4 -4
  226. package/dist/extensions/memory-lancedb/index.d.ts +1 -1
  227. package/dist/extensions/memory-lancedb/index.js +4 -4
  228. package/dist/extensions/microsoft/index.d.ts +1 -1
  229. package/dist/extensions/microsoft/index.js +35 -35
  230. package/dist/extensions/minimax/index.d.ts +1 -1
  231. package/dist/extensions/minimax/index.js +35 -35
  232. package/dist/extensions/mistral/index.d.ts +1 -1
  233. package/dist/extensions/mistral/index.js +35 -35
  234. package/dist/extensions/modelstudio/index.d.ts +1 -1
  235. package/dist/extensions/modelstudio/index.js +35 -35
  236. package/dist/extensions/moonshot/index.d.ts +1 -1
  237. package/dist/extensions/moonshot/index.js +35 -35
  238. package/dist/extensions/msteams/index.d.ts +1 -1
  239. package/dist/extensions/msteams/index.js +40 -40
  240. package/dist/extensions/msteams/setup-entry.d.ts +1 -1
  241. package/dist/extensions/msteams/setup-entry.js +40 -40
  242. package/dist/extensions/nextcloud-talk/index.d.ts +1 -1
  243. package/dist/extensions/nextcloud-talk/index.js +37 -37
  244. package/dist/extensions/nextcloud-talk/setup-entry.d.ts +2 -2
  245. package/dist/extensions/nextcloud-talk/setup-entry.js +37 -37
  246. package/dist/extensions/nostr/index.d.ts +1 -1
  247. package/dist/extensions/nostr/index.js +37 -37
  248. package/dist/extensions/nostr/setup-entry.d.ts +1 -1
  249. package/dist/extensions/nostr/setup-entry.js +37 -37
  250. package/dist/extensions/nvidia/index.d.ts +1 -1
  251. package/dist/extensions/nvidia/index.js +4 -4
  252. package/dist/extensions/ollama/index.d.ts +1 -1
  253. package/dist/extensions/ollama/index.js +7 -7
  254. package/dist/extensions/open-prose/index.d.ts +1 -1
  255. package/dist/extensions/open-prose/index.js +4 -4
  256. package/dist/extensions/openai/index.d.ts +1 -1
  257. package/dist/extensions/openai/index.js +35 -35
  258. package/dist/extensions/opencode/index.d.ts +1 -1
  259. package/dist/extensions/opencode/index.js +35 -35
  260. package/dist/extensions/opencode-go/index.d.ts +1 -1
  261. package/dist/extensions/opencode-go/index.js +35 -35
  262. package/dist/extensions/openrouter/index.d.ts +1 -1
  263. package/dist/extensions/openrouter/index.js +35 -35
  264. package/dist/extensions/openshell/index.d.ts +1 -1
  265. package/dist/extensions/openshell/index.js +35 -35
  266. package/dist/extensions/perplexity/index.d.ts +1 -1
  267. package/dist/extensions/perplexity/index.js +5 -5
  268. package/dist/extensions/phone-control/index.d.ts +1 -1
  269. package/dist/extensions/phone-control/index.js +4 -4
  270. package/dist/extensions/qianfan/index.d.ts +1 -1
  271. package/dist/extensions/qianfan/index.js +35 -35
  272. package/dist/extensions/qwen-portal-auth/index.d.ts +1 -1
  273. package/dist/extensions/qwen-portal-auth/index.js +35 -35
  274. package/dist/extensions/sglang/index.d.ts +1 -1
  275. package/dist/extensions/sglang/index.js +35 -35
  276. package/dist/extensions/signal/index.d.ts +1 -1
  277. package/dist/extensions/signal/index.js +38 -38
  278. package/dist/extensions/signal/setup-entry.d.ts +1 -1
  279. package/dist/extensions/signal/setup-entry.js +38 -38
  280. package/dist/extensions/slack/index.d.ts +1 -1
  281. package/dist/extensions/slack/index.js +39 -39
  282. package/dist/extensions/slack/setup-entry.d.ts +1 -1
  283. package/dist/extensions/slack/setup-entry.js +38 -38
  284. package/dist/extensions/synology-chat/index.d.ts +1 -1
  285. package/dist/extensions/synology-chat/index.js +37 -37
  286. package/dist/extensions/synology-chat/setup-entry.d.ts +1 -1
  287. package/dist/extensions/synology-chat/setup-entry.js +37 -37
  288. package/dist/extensions/synthetic/index.d.ts +1 -1
  289. package/dist/extensions/synthetic/index.js +35 -35
  290. package/dist/extensions/talk-voice/index.d.ts +1 -1
  291. package/dist/extensions/talk-voice/index.js +35 -35
  292. package/dist/extensions/telegram/index.d.ts +1 -1
  293. package/dist/extensions/telegram/index.js +38 -38
  294. package/dist/extensions/telegram/setup-entry.d.ts +1 -1
  295. package/dist/extensions/telegram/setup-entry.js +37 -37
  296. package/dist/extensions/thread-ownership/index.d.ts +1 -1
  297. package/dist/extensions/thread-ownership/index.js +4 -4
  298. package/dist/extensions/tlon/index.d.ts +1 -1
  299. package/dist/extensions/tlon/index.js +37 -37
  300. package/dist/extensions/tlon/setup-entry.d.ts +1 -1
  301. package/dist/extensions/tlon/setup-entry.js +37 -37
  302. package/dist/extensions/together/index.d.ts +1 -1
  303. package/dist/extensions/together/index.js +35 -35
  304. package/dist/extensions/twitch/index.d.ts +2 -2
  305. package/dist/extensions/twitch/index.js +37 -37
  306. package/dist/extensions/venice/index.d.ts +1 -1
  307. package/dist/extensions/venice/index.js +35 -35
  308. package/dist/extensions/vercel-ai-gateway/index.d.ts +1 -1
  309. package/dist/extensions/vercel-ai-gateway/index.js +36 -36
  310. package/dist/extensions/vllm/index.d.ts +1 -1
  311. package/dist/extensions/vllm/index.js +35 -35
  312. package/dist/extensions/voice-call/index.d.ts +1 -1
  313. package/dist/extensions/voice-call/index.js +35 -35
  314. package/dist/extensions/volcengine/index.d.ts +1 -1
  315. package/dist/extensions/volcengine/index.js +35 -35
  316. package/dist/extensions/whatsapp/index.d.ts +1 -1
  317. package/dist/extensions/whatsapp/index.js +38 -38
  318. package/dist/extensions/whatsapp/setup-entry.d.ts +1 -1
  319. package/dist/extensions/whatsapp/setup-entry.js +38 -38
  320. package/dist/extensions/xai/index.d.ts +1 -1
  321. package/dist/extensions/xai/index.js +35 -35
  322. package/dist/extensions/xiaomi/index.d.ts +1 -1
  323. package/dist/extensions/xiaomi/index.js +35 -35
  324. package/dist/extensions/zai/index.d.ts +1 -1
  325. package/dist/extensions/zai/index.js +35 -35
  326. package/dist/extensions/zalo/index.d.ts +1 -1
  327. package/dist/extensions/zalo/index.js +39 -39
  328. package/dist/extensions/zalo/setup-entry.d.ts +1 -1
  329. package/dist/extensions/zalo/setup-entry.js +39 -39
  330. package/dist/extensions/zalouser/index.d.ts +1 -1
  331. package/dist/extensions/zalouser/index.js +40 -40
  332. package/dist/extensions/zalouser/setup-entry.d.ts +1 -1
  333. package/dist/extensions/zalouser/setup-entry.js +40 -40
  334. package/dist/feishu-fIcnHDTd.d.ts +36 -0
  335. package/dist/gateway-cli-0c-8h93_.js +26437 -0
  336. package/dist/gateway-install-token-1PwJvrBY.js +163 -0
  337. package/dist/gateway-rpc-C0Vk51W7.js +26 -0
  338. package/dist/gateway-runtime-CBm3CCoA.js +69 -0
  339. package/dist/git-commit-BTWXFY41.js +177 -0
  340. package/dist/git-commit-D6GTN5Yt.js +2 -0
  341. package/dist/googlechat-BQr4xgoZ.js +307 -0
  342. package/dist/googlechat-BvwsCVKl.d.ts +12 -0
  343. package/dist/group-access-DpiQnd-G.d.ts +61 -0
  344. package/dist/health-6yZQGADY.js +113 -0
  345. package/dist/health-C9DYGyRe.js +570 -0
  346. package/dist/heartbeat-summary-Dct2lqJj.js +57 -0
  347. package/dist/help-CtwSApfq.js +81 -0
  348. package/dist/hooks-9gokOxZ5.d.ts +6 -0
  349. package/dist/hooks-cli-BegKzHZT.js +1000 -0
  350. package/dist/hooks-status-Bm_pGORf.js +78 -0
  351. package/dist/http-registry-D-S6a1Na.d.ts +20 -0
  352. package/dist/identity-file-Diub2a0t.js +60 -0
  353. package/dist/image-generation-CbIVzmAR.d.ts +9 -0
  354. package/dist/imessage-Bgok9kfl.js +31 -0
  355. package/dist/imessage-VIHePprL.js +115 -0
  356. package/dist/inbound-reply-dispatch-B53GAGWq.js +71 -0
  357. package/dist/inbound-reply-dispatch-n7U3qg15.d.ts +72 -0
  358. package/dist/index.js +2 -2
  359. package/dist/install-target-oz1pjfHH.js +574 -0
  360. package/dist/installs-CUFm5V8a.js +532 -0
  361. package/dist/io-BaBxjB1v.js +9739 -0
  362. package/dist/io-CgHb1Jld.js +29 -0
  363. package/dist/irc-CaRKzGvW.js +672 -0
  364. package/dist/library-C5SNBCMb.js +112 -0
  365. package/dist/lifecycle-core-Dn8PK6nk.js +382 -0
  366. package/dist/line/accounts.d.ts +2 -2
  367. package/dist/line/send.d.ts +1 -1
  368. package/dist/line/send.js +7 -7
  369. package/dist/line/template-messages.d.ts +1 -1
  370. package/dist/line-B5QFpgN_.d.ts +75 -0
  371. package/dist/line-fePrrQOD.js +530 -0
  372. package/dist/llm-slug-generator-hKae3XDA.js +67 -0
  373. package/dist/llm-slug-generator.d.ts +1 -1
  374. package/dist/llm-slug-generator.js +36 -36
  375. package/dist/logging-CdisccbY.js +13 -0
  376. package/dist/logging-LKQSgX1d.js +30 -0
  377. package/dist/login-qr-C1YWh4nE.js +233 -0
  378. package/dist/login-qr-WFluMDMb.js +112 -0
  379. package/dist/logs-cli-CNzOvZ2d.js +256 -0
  380. package/dist/manager-runtime-DgMhLTkR.js +111 -0
  381. package/dist/manager.runtime-hUWgpPt2.js +715 -0
  382. package/dist/manifest-registry-CS_p1OBQ.js +1329 -0
  383. package/dist/matrix-43_RGLZN.d.ts +68 -0
  384. package/dist/matrix-CCFxHfxa.js +1269 -0
  385. package/dist/matrix-DWs_qIkJ.js +1495 -0
  386. package/dist/mcp-cli-Ci2jvv3s.js +87 -0
  387. package/dist/media-understanding.runtime-Cdr6iTW6.js +116 -0
  388. package/dist/memory-cli-LZbyF0Iu.js +111 -0
  389. package/dist/memory-search-BHhETk6u.js +17 -0
  390. package/dist/memory-search-tTD5o_rU.js +204 -0
  391. package/dist/method-scopes-B2ZKSsxQ.js +2452 -0
  392. package/dist/model-auth-markers-LqZ4qhrZ.d.ts +20 -0
  393. package/dist/model-picker-CTR5mo4v.js +112 -0
  394. package/dist/model-picker-DG4z_dBs.js +390 -0
  395. package/dist/model-picker.runtime-DMQ9Pj9_.js +125 -0
  396. package/dist/model-selection-bBBxfXdb.js +653 -0
  397. package/dist/model-suppression.runtime-BVG75tZ7.js +116 -0
  398. package/dist/models-BjkVLfgw.js +2514 -0
  399. package/dist/models-ZO01Q4cx.js +118 -0
  400. package/dist/models-cli-DemdF-bm.js +309 -0
  401. package/dist/models-config-B2Jja8ua.js +111 -0
  402. package/dist/models-config.providers.discovery-puxTsH39.d.ts +18 -0
  403. package/dist/moldclaw-root-Cb6HRlUO.js +92 -0
  404. package/dist/monitor-BP4idxJD.js +782 -0
  405. package/dist/monitor-B_eP8Eim.js +772 -0
  406. package/dist/monitor-CRHYNl5J.js +3468 -0
  407. package/dist/monitor-Ci1Xg4g3.js +113 -0
  408. package/dist/monitor-DEodDl3z.js +6823 -0
  409. package/dist/monitor-DJlNKuMz.js +115 -0
  410. package/dist/monitor-DvFwDS9w.js +3076 -0
  411. package/dist/monitor-shared--cEjSf8s.js +444 -0
  412. package/dist/msteams-CV2a8uE8.js +852 -0
  413. package/dist/node-cli-Of2g7DSd.js +2503 -0
  414. package/dist/node-resolve-BYC2FbO2.js +835 -0
  415. package/dist/nodes-cli-CPHM6Upj.js +1380 -0
  416. package/dist/nostr-BFKRoOlz.d.ts +7 -0
  417. package/dist/nostr-lHpcBzz4.js +8744 -0
  418. package/dist/npm-resolution-kqHN85wB.js +60 -0
  419. package/dist/oauth-env-CLG8KOrz.js +10 -0
  420. package/dist/onboard-BON0C360.js +48 -0
  421. package/dist/onboard-CRkIBgOI.js +589 -0
  422. package/dist/onboard-DsKI17iq.js +25 -0
  423. package/dist/onboard-channels-BY3IbBBf.js +1241 -0
  424. package/dist/onboard-channels-CLKdRxvW.js +205 -0
  425. package/dist/onboard-custom-BjPrMo_R.js +571 -0
  426. package/dist/onboard-custom-DqcPiZBN.js +114 -0
  427. package/dist/onboard-helpers-BkrOY5OE.js +113 -0
  428. package/dist/onboard-helpers-DiSRTpZC.js +335 -0
  429. package/dist/onboard-hooks-pzEPZAvl.js +72 -0
  430. package/dist/onboard-remote-ChyLC6Dk.js +181 -0
  431. package/dist/onboard-remote-DHmK9ntl.js +117 -0
  432. package/dist/onboard-search-BgA3jEMW.js +302 -0
  433. package/dist/onboard-skills-BMo_NvnW.js +133 -0
  434. package/dist/onboard-skills-Bba-Z2p8.js +117 -0
  435. package/dist/outbound-media-BHD4aJEX.d.ts +11 -0
  436. package/dist/outbound-media-DSno0N82.js +11 -0
  437. package/dist/pairing-access-CzHpaM0R.d.ts +21 -0
  438. package/dist/pairing-cli-CmklqK0q.js +217 -0
  439. package/dist/perplexity-CXwMDD3u.js +24 -0
  440. package/dist/persistent-dedupe-B9vrAf8t.d.ts +26 -0
  441. package/dist/pi-model-discovery-runtime-BrK7tcaO.js +111 -0
  442. package/dist/pi-tools.before-tool-call.runtime-C5yLUogH.js +381 -0
  443. package/dist/plugin-install-C4AWJIFP.js +117 -0
  444. package/dist/plugin-install-CB3J1hfV.js +184 -0
  445. package/dist/plugin-install-plan-7itZiegi.js +49 -0
  446. package/dist/plugin-registry-DX_GFoiz.js +113 -0
  447. package/dist/plugin-registry-e3cxTtvb.js +49 -0
  448. package/dist/plugin-sdk/account-resolution.js +35 -35
  449. package/dist/plugin-sdk/acp-runtime.js +35 -35
  450. package/dist/plugin-sdk/agent-runtime.js +35 -35
  451. package/dist/plugin-sdk/bluebubbles.js +37 -37
  452. package/dist/plugin-sdk/channel-config-helpers.js +35 -35
  453. package/dist/plugin-sdk/channel-policy.js +35 -35
  454. package/dist/plugin-sdk/channel-runtime.js +35 -35
  455. package/dist/plugin-sdk/compat.js +36 -36
  456. package/dist/plugin-sdk/config-runtime.js +35 -35
  457. package/dist/plugin-sdk/conversation-runtime.js +35 -35
  458. package/dist/plugin-sdk/copilot-proxy.js +4 -4
  459. package/dist/plugin-sdk/core.js +4 -4
  460. package/dist/plugin-sdk/device-pair.js +4 -4
  461. package/dist/plugin-sdk/discord.js +35 -35
  462. package/dist/plugin-sdk/feishu.js +35 -35
  463. package/dist/plugin-sdk/gateway-runtime.js +10 -10
  464. package/dist/plugin-sdk/googlechat.js +37 -37
  465. package/dist/plugin-sdk/image-generation-runtime.js +35 -35
  466. package/dist/plugin-sdk/image-generation.js +35 -35
  467. package/dist/plugin-sdk/imessage.js +36 -36
  468. package/dist/plugin-sdk/index.js +35 -35
  469. package/dist/plugin-sdk/infra-runtime.js +35 -35
  470. package/dist/plugin-sdk/irc.js +37 -37
  471. package/dist/plugin-sdk/line.js +36 -36
  472. package/dist/plugin-sdk/llm-task.js +35 -35
  473. package/dist/plugin-sdk/lobster.js +4 -4
  474. package/dist/plugin-sdk/matrix.js +37 -37
  475. package/dist/plugin-sdk/mattermost.js +36 -36
  476. package/dist/plugin-sdk/media-runtime.js +35 -35
  477. package/dist/plugin-sdk/media-understanding-runtime.js +35 -35
  478. package/dist/plugin-sdk/media-understanding.js +35 -35
  479. package/dist/plugin-sdk/memory-lancedb.js +4 -4
  480. package/dist/plugin-sdk/minimax-portal-auth.js +4 -4
  481. package/dist/plugin-sdk/msteams.js +38 -38
  482. package/dist/plugin-sdk/nextcloud-talk.js +36 -36
  483. package/dist/plugin-sdk/nostr.js +36 -36
  484. package/dist/plugin-sdk/ollama-setup.js +9 -9
  485. package/dist/plugin-sdk/open-prose.js +4 -4
  486. package/dist/plugin-sdk/phone-control.js +4 -4
  487. package/dist/plugin-sdk/plugin-runtime.js +35 -35
  488. package/dist/plugin-sdk/provider-auth.js +35 -35
  489. package/dist/plugin-sdk/provider-models.js +5 -5
  490. package/dist/plugin-sdk/provider-onboard.js +4 -4
  491. package/dist/plugin-sdk/provider-setup.js +39 -39
  492. package/dist/plugin-sdk/provider-stream.js +4 -4
  493. package/dist/plugin-sdk/provider-usage.js +4 -4
  494. package/dist/plugin-sdk/qwen-portal-auth.js +35 -35
  495. package/dist/plugin-sdk/reply-history.js +35 -35
  496. package/dist/plugin-sdk/reply-runtime.js +35 -35
  497. package/dist/plugin-sdk/routing.js +3 -3
  498. package/dist/plugin-sdk/sandbox.js +35 -35
  499. package/dist/plugin-sdk/security-runtime.js +35 -35
  500. package/dist/plugin-sdk/self-hosted-provider-setup.js +37 -37
  501. package/dist/plugin-sdk/setup.js +35 -35
  502. package/dist/plugin-sdk/signal.js +35 -35
  503. package/dist/plugin-sdk/slack.js +35 -35
  504. package/dist/plugin-sdk/speech-runtime.js +35 -35
  505. package/dist/plugin-sdk/speech.js +35 -35
  506. package/dist/plugin-sdk/src/secrets/secure-file-store.d.ts +26 -0
  507. package/dist/plugin-sdk/src/subscription/provider.d.ts +5 -3
  508. package/dist/plugin-sdk/synology-chat.js +36 -36
  509. package/dist/plugin-sdk/talk-voice.js +4 -4
  510. package/dist/plugin-sdk/telegram.js +35 -35
  511. package/dist/plugin-sdk/text-runtime.js +7 -7
  512. package/dist/plugin-sdk/thread-ownership.js +4 -4
  513. package/dist/plugin-sdk/tlon.js +36 -36
  514. package/dist/plugin-sdk/twitch.js +35 -35
  515. package/dist/plugin-sdk/voice-call.js +35 -35
  516. package/dist/plugin-sdk/whatsapp.js +35 -35
  517. package/dist/plugin-sdk/zalo.js +38 -38
  518. package/dist/plugin-sdk/zalouser.js +38 -38
  519. package/dist/plugins/runtime/index.d.ts +1 -1
  520. package/dist/plugins/runtime/index.js +35 -35
  521. package/dist/plugins-DF5FaTO0.js +111 -0
  522. package/dist/plugins-cli-CvTJemqC.js +917 -0
  523. package/dist/policy-CNXISK_a.js +143 -0
  524. package/dist/preflight-audio.runtime-RP000oxo.js +116 -0
  525. package/dist/probe-BkM5pykD.js +21 -0
  526. package/dist/probe-DKbRTJv5.js +1793 -0
  527. package/dist/probe-DkrfRsjU.js +47 -0
  528. package/dist/probe-DpcJ0WeP.js +129 -0
  529. package/dist/probe-auth-BcNjX8hy.js +40 -0
  530. package/dist/probe-auth-DhuAb8ls.js +48 -0
  531. package/dist/probe-wciBj-aL.js +6329 -0
  532. package/dist/program-C8-p0mW5.js +253 -0
  533. package/dist/prompt-select-styled-DH0pVoc0.js +2673 -0
  534. package/dist/provider-api-key-auth.runtime-CAFeIQ1u.js +121 -0
  535. package/dist/provider-auth-choice-CB_HzdTl.js +126 -0
  536. package/dist/provider-auth-choice-helpers-hzDkh3f1.js +48 -0
  537. package/dist/provider-auth-choice-preference-BHCXvNSE.js +189 -0
  538. package/dist/provider-auth-choice.runtime-Dx4ms2C5.js +123 -0
  539. package/dist/provider-auth-choices-0KaDNPBQ.js +57 -0
  540. package/dist/provider-auth-guidance-BaAUiNr_.js +34 -0
  541. package/dist/provider-auth-result-Bto1bYtS.d.ts +18 -0
  542. package/dist/provider-models-DxOmeToO.d.ts +867 -0
  543. package/dist/provider-models-xnyxy6mO.js +2113 -0
  544. package/dist/provider-ollama-setup-DBYK__ov.d.ts +32 -0
  545. package/dist/provider-ollama-setup-QzgCxj44.js +314 -0
  546. package/dist/provider-onboard-B9ionepI.js +139 -0
  547. package/dist/provider-onboard-CURxJ_UX.d.ts +40 -0
  548. package/dist/provider-runtime.runtime-4xwmsl5L.js +111 -0
  549. package/dist/provider-self-hosted-setup-BHd24EDG.js +182 -0
  550. package/dist/provider-self-hosted-setup-qeY8BYSy.d.ts +61 -0
  551. package/dist/provider-stream-Chz_EFw3.js +512 -0
  552. package/dist/provider-usage-C11Q7UwS.js +111 -0
  553. package/dist/provider-usage-kxemdMp2.js +633 -0
  554. package/dist/provider-wizard-CanJoxNC.js +152 -0
  555. package/dist/push-apns-Dsajnm8C.js +1038 -0
  556. package/dist/pw-ai-DUe4BbH2.js +1867 -0
  557. package/dist/qmd-manager-CAAFp7qK.js +1570 -0
  558. package/dist/qr-cli-Bu2jqTPY.js +113 -0
  559. package/dist/qr-cli-Bu9Z-X48.js +369 -0
  560. package/dist/reactions-Cpfum4iU.js +281 -0
  561. package/dist/read-only-account-inspect.discord.runtime-BK0LaMgC.js +116 -0
  562. package/dist/read-only-account-inspect.slack.runtime-DgKiC5wT.js +116 -0
  563. package/dist/read-only-account-inspect.telegram.runtime-mxfgFVOU.js +116 -0
  564. package/dist/redact-snapshot-DD8A4tdd.js +2663 -0
  565. package/dist/register.agent-DU4FtrU2.js +439 -0
  566. package/dist/register.backup-8nOYtJqg.js +625 -0
  567. package/dist/register.configure-DmtecqIH.js +252 -0
  568. package/dist/register.maintenance-Dir3ulKP.js +574 -0
  569. package/dist/register.message-Cfl-f3Ju.js +709 -0
  570. package/dist/register.onboard-Bv7WVzEi.js +192 -0
  571. package/dist/register.setup-BIyeI8RY.js +212 -0
  572. package/dist/register.status-health-sessions-C69WQcF4.js +498 -0
  573. package/dist/register.subclis-B_4KCgTd.js +315 -0
  574. package/dist/register.subclis-BeXsmgBL.js +13 -0
  575. package/dist/replies-DdcFUmki.js +110 -0
  576. package/dist/resolve-channels-DRZqPV5o.js +226 -0
  577. package/dist/resolve-channels-DxW1kqxA.js +262 -0
  578. package/dist/resolve-route-DdX-HBVt.js +538 -0
  579. package/dist/resolve-users-rgCQvkLs.js +143 -0
  580. package/dist/root-help-QAkoA7GD.js +32 -0
  581. package/dist/routes-CcJNnwTF.js +7097 -0
  582. package/dist/rpc-DDUAlBbH.js +67 -0
  583. package/dist/run-main-D9ci5pn7.js +424 -0
  584. package/dist/runtime-Bitmi8Er.d.ts +26 -0
  585. package/dist/runtime-discord-ops.runtime-T4sf7aRB.js +9078 -0
  586. package/dist/runtime-slack-ops.runtime-BQpP48mC.js +4556 -0
  587. package/dist/runtime-telegram-ops.runtime-cVO5dqOp.js +133 -0
  588. package/dist/runtime-whatsapp-login.runtime-DtNx0dSY.js +114 -0
  589. package/dist/runtime-whatsapp-outbound.runtime-Bw47QbFK.js +117 -0
  590. package/dist/sandbox-cli-DsFwjbjC.js +535 -0
  591. package/dist/search-manager-BRAK8fEe.js +16 -0
  592. package/dist/search-manager-BS5Db0A6.js +386 -0
  593. package/dist/secrets-cli-D3J46TJp.js +2070 -0
  594. package/dist/security-cli-B866M9cB.js +575 -0
  595. package/dist/send-B1pX9_Oc.js +283 -0
  596. package/dist/send-B2RrLg83.js +100 -0
  597. package/dist/send-DFnV__Aq.js +1025 -0
  598. package/dist/send-DZIH6CJt.js +629 -0
  599. package/dist/send-sl9WnKbW.js +631 -0
  600. package/dist/server-node-events-BT6egg20.js +506 -0
  601. package/dist/server-zI_K-D05.js +107 -0
  602. package/dist/sessions-C8kiAcoJ.js +112 -0
  603. package/dist/sessions-DLBpp52_.js +218 -0
  604. package/dist/setup-C7eOzMiC.js +387 -0
  605. package/dist/setup-CFIMq-Pz.d.ts +37 -0
  606. package/dist/setup-binary-CcAv8NXz.js +406 -0
  607. package/dist/setup-browser-C4eRV3h6.js +70 -0
  608. package/dist/setup-core-BnR486P-.js +143 -0
  609. package/dist/setup-core-CIswIiu5.js +166 -0
  610. package/dist/setup-core-CcbcrXXg.js +47 -0
  611. package/dist/setup-core-nZSw5BSv.js +205 -0
  612. package/dist/setup-surface-C5iSpT4M.js +490 -0
  613. package/dist/setup-wizard-helpers-r0J6l8ST.d.ts +203 -0
  614. package/dist/setup.finalize-adiRfo0U.js +522 -0
  615. package/dist/setup.gateway-config-BwFWKDfT.js +343 -0
  616. package/dist/shared-12TimyeF.js +182 -0
  617. package/dist/shared-9EWO34-k.js +298 -0
  618. package/dist/shared-B4vUbaRR.js +75 -0
  619. package/dist/shared-bNWpW3Dd.js +96 -0
  620. package/dist/shared-lU1y5dvS.js +102 -0
  621. package/dist/signal-DBlETRu9.js +114 -0
  622. package/dist/skills-Bio8GwTE.js +20 -0
  623. package/dist/skills-DE_MXFSN.js +853 -0
  624. package/dist/skills-cli-BGuW-tKw.js +292 -0
  625. package/dist/skills-install--rnorIoJ.js +763 -0
  626. package/dist/skills-status-B08PtBc_.js +21 -0
  627. package/dist/skills-status-CzM008aB.js +169 -0
  628. package/dist/slack-C4T53Nc-.js +114 -0
  629. package/dist/slash-commands.runtime-B7fsD8Be.js +128 -0
  630. package/dist/slash-dispatch.runtime-t0PAX4vQ.js +141 -0
  631. package/dist/slash-skill-commands.runtime-DIhPnEfR.js +116 -0
  632. package/dist/src-DrDirlvw.js +1701 -0
  633. package/dist/status-Bld14WSA.js +131 -0
  634. package/dist/status-CgeO4RuH.js +43 -0
  635. package/dist/status-HlvixAOq.js +606 -0
  636. package/dist/status-Rom_Lf3c.js +1599 -0
  637. package/dist/status-TwbMH6Am.js +126 -0
  638. package/dist/status-json-DMW7cmuK.js +288 -0
  639. package/dist/status.link-channel-V4LkB6Gq.js +143 -0
  640. package/dist/status.scan.deps.runtime-BE3X-dcP.js +126 -0
  641. package/dist/status.scan.runtime-BxVY4mty.js +119 -0
  642. package/dist/status.summary-CzLM0vVr.js +592 -0
  643. package/dist/status.summary.runtime-BSBnHZ1Q.js +118 -0
  644. package/dist/status.update-BxblMS7P.js +77 -0
  645. package/dist/subagent-orphan-recovery-BpRPryEj.js +307 -0
  646. package/dist/subagent-registry-runtime-DYYU5p3X.js +111 -0
  647. package/dist/subscription-CpFdxuFS.js +33 -0
  648. package/dist/subscription-DaA1urx-.js +102 -0
  649. package/dist/subscription-cli-Bvto9EmO.js +134 -0
  650. package/dist/synology-chat-3nwk-Nj0.js +297 -0
  651. package/dist/system-cli-BvNps8sl.js +94 -0
  652. package/dist/telegram/audit.d.ts +1 -1
  653. package/dist/telegram/audit.js +1 -1
  654. package/dist/telegram/token.d.ts +1 -1
  655. package/dist/telegram/token.js +35 -35
  656. package/dist/telegram-RtKXoEsF.js +114 -0
  657. package/dist/text-chunking-BD5mQe2R.js +84 -0
  658. package/dist/text-chunking-DDUU_vAF.d.ts +79 -0
  659. package/dist/tlon-z-kYmJE-.js +433 -0
  660. package/dist/tui-cli-CzSK08Rh.js +137 -0
  661. package/dist/tui-wV7R1Tlc.js +3834 -0
  662. package/dist/types-2H_e7eWT.d.ts +45 -0
  663. package/dist/types-ZKnGUchG.d.ts +22692 -0
  664. package/dist/types.base-BFiQZ4J9.d.ts +188 -0
  665. package/dist/ui-BWVHreeR.js +31 -0
  666. package/dist/update-D1Wgh1Tj.js +1036 -0
  667. package/dist/update-cli-CZh99uyY.js +1503 -0
  668. package/dist/update-offset-store-D5xTdUr0.js +112 -0
  669. package/dist/update-runner-GbKfoCHs.js +1496 -0
  670. package/dist/upsert-with-lock-BZU7Le8n.js +33 -0
  671. package/dist/usage-Czgwvg0h.js +115 -0
  672. package/dist/web-CMczmL90.js +112 -0
  673. package/dist/web-shared-B5Q0mIJq.d.ts +45 -0
  674. package/dist/webhook-request-guards-CsKDhZJr.d.ts +76 -0
  675. package/dist/webhook-targets-BSmFtesN.js +181 -0
  676. package/dist/webhook-targets-CjxuEE9C.d.ts +106 -0
  677. package/dist/webhooks-cli-Wl9y6AWW.js +350 -0
  678. package/dist/whatsapp-VzRW8MdR.js +114 -0
  679. package/dist/whatsapp-actions-Cg1Wxv8W.js +167 -0
  680. package/dist/workspace-DJ_S272u.js +484 -0
  681. package/dist/workspace-DbZSqjw0.js +289 -0
  682. package/dist/workspace-cli-D93DLmAh.js +154 -0
  683. package/dist/workspace-dirs-CGeIPpGN.js +2003 -0
  684. package/dist/zalo-CK2dlGmu.d.ts +9 -0
  685. package/dist/zalo-Db7s2boL.js +415 -0
  686. package/dist/zalouser-Jh5YTJX3.js +30911 -0
  687. package/docs/reference/templates/AGENTS.dev.md +83 -0
  688. package/docs/reference/templates/AGENTS.md +219 -0
  689. package/docs/reference/templates/BOOT.md +11 -0
  690. package/docs/reference/templates/BOOTSTRAP.md +62 -0
  691. package/docs/reference/templates/HEARTBEAT.md +12 -0
  692. package/docs/reference/templates/IDENTITY.dev.md +47 -0
  693. package/docs/reference/templates/IDENTITY.md +29 -0
  694. package/docs/reference/templates/SOUL.dev.md +76 -0
  695. package/docs/reference/templates/SOUL.md +43 -0
  696. package/docs/reference/templates/TOOLS.dev.md +24 -0
  697. package/docs/reference/templates/TOOLS.md +47 -0
  698. package/docs/reference/templates/USER.dev.md +18 -0
  699. package/docs/reference/templates/USER.md +23 -0
  700. package/extensions/discord/src/monitor/allow-list.ts +8 -1
  701. package/extensions/discord/src/monitor/message-handler.preflight.ts +4 -1
  702. package/package.json +2 -1
  703. package/dist/accounts-CDr-lDaV.d.ts +0 -103
  704. package/dist/accounts-CS8U4v8C.js +0 -114
  705. package/dist/acp-cli-BGT0jXcC.js +0 -2093
  706. package/dist/actions.runtime-BfckTw6c.js +0 -119
  707. package/dist/actions.runtime-Cl9mBfqH.js +0 -133
  708. package/dist/agent-scope-C-YmLnnb.js +0 -208
  709. package/dist/agents-CydD54p8.js +0 -222
  710. package/dist/agents-DpQsZO6O.js +0 -853
  711. package/dist/agents.config-XU7IsYE-.js +0 -121
  712. package/dist/agents.config-ssoQXuvF.js +0 -17
  713. package/dist/allow-list-Cfn6lmMK.js +0 -81
  714. package/dist/allowlist-CCYXVpM9.js +0 -142
  715. package/dist/api-BoXoFKxy.js +0 -117
  716. package/dist/audit-Bv05N5o9.js +0 -787
  717. package/dist/audit-CIWW1Aqm.js +0 -54
  718. package/dist/audit-channel.collect.runtime-Bi7yrdcO.js +0 -605
  719. package/dist/audit-channel.runtime-C_NDweiW.js +0 -121
  720. package/dist/audit-extra.async-Dp7OKSXg.js +0 -813
  721. package/dist/audit-membership-runtime-B8FQ6VtN.js +0 -162
  722. package/dist/audit.deep.runtime-CXhobL6b.js +0 -25
  723. package/dist/audit.nondeep.runtime-CrEm3T16.js +0 -832
  724. package/dist/audit.runtime-CJPKj1Zg.js +0 -118
  725. package/dist/auth-Byfp0flq.js +0 -101
  726. package/dist/auth-choice-BgOjdeXN.js +0 -507
  727. package/dist/auth-choice-CD1Heq0M.js +0 -122
  728. package/dist/auth-choice-ePNfg0iQ.js +0 -268
  729. package/dist/auth-choice-options-BlewQWI0.js +0 -123
  730. package/dist/auth-choice-prompt-BP2b6aXz.js +0 -36
  731. package/dist/auth-choice-prompt-Cmwl4n97.js +0 -115
  732. package/dist/auth-choice.apply-helpers-Dq-nxuuX.js +0 -66
  733. package/dist/auth-choice.plugin-providers.runtime-B23kOUzQ.js +0 -119
  734. package/dist/auth-profiles-1kPLbBwI.js +0 -127823
  735. package/dist/auth-profiles.runtime-DAfSjku1.js +0 -116
  736. package/dist/banner-DeOsobLO.js +0 -342
  737. package/dist/bluebubbles-BsLGedBM.js +0 -64
  738. package/dist/bluebubbles-CnT9wiS4.d.ts +0 -6
  739. package/dist/bot-CuzVYwa_.d.ts +0 -478
  740. package/dist/brave-BoWimrLe.js +0 -24
  741. package/dist/browser-cli-D_S3wEYE.js +0 -1494
  742. package/dist/call-ByEzDJ1_.js +0 -640
  743. package/dist/call-CHCWVg-O.js +0 -39
  744. package/dist/channel-3VC0oOMu.js +0 -214
  745. package/dist/channel-B9fCBPiS.js +0 -207
  746. package/dist/channel-B9q775cM.js +0 -562
  747. package/dist/channel-BG3UK54j.js +0 -803
  748. package/dist/channel-BRQAdMML.js +0 -352
  749. package/dist/channel-BmlLp933.js +0 -1321
  750. package/dist/channel-By6KvdTG.js +0 -920
  751. package/dist/channel-C8rRsdf6.js +0 -226
  752. package/dist/channel-CLEDBbXE.js +0 -943
  753. package/dist/channel-CMvBAG7o.js +0 -306
  754. package/dist/channel-CmlxxjHY.js +0 -1598
  755. package/dist/channel-CqG6_xN0.js +0 -949
  756. package/dist/channel-DNueHKs92.js +0 -316
  757. package/dist/channel-DUtyN7BX.js +0 -4681
  758. package/dist/channel-DWD6GrfZ.js +0 -538
  759. package/dist/channel-DaRYMYzj.js +0 -619
  760. package/dist/channel-Dj6BgLp8.js +0 -575
  761. package/dist/channel-account-context-Ba3u5D21.js +0 -103
  762. package/dist/channel-crabk6Em.js +0 -542
  763. package/dist/channel-i8uqQaK2.js +0 -497
  764. package/dist/channel-options-xljvwHS2.js +0 -50
  765. package/dist/channel-plugin-ids-DAgknSG4.js +0 -26
  766. package/dist/channel-summary-dHTMCG75.js +0 -111
  767. package/dist/channel-xVWQ96Ni.js +0 -397
  768. package/dist/channel.runtime-B6PoZ4BV.js +0 -182
  769. package/dist/channel.runtime-BPZmo57e.js +0 -404
  770. package/dist/channel.runtime-B_1uGR-U.js +0 -199
  771. package/dist/channel.runtime-BiXnPU0d.js +0 -218
  772. package/dist/channel.runtime-BpvDc9sv.js +0 -870
  773. package/dist/channel.runtime-CUua3W80.js +0 -418
  774. package/dist/channel.runtime-CaCBTd0A.js +0 -179
  775. package/dist/channel.runtime-D0FfYvUj.js +0 -4011
  776. package/dist/channel.runtime-DhoJtpvJ.js +0 -241
  777. package/dist/channel.runtime-Kj9EXNE0.js +0 -127
  778. package/dist/channel.runtime-r4tPuPyh.js +0 -171
  779. package/dist/channel.setup-B7d_grfe.js +0 -6
  780. package/dist/channel.setup-C0vu1fhi.js +0 -9
  781. package/dist/channel.setup-CAI0FNHj.js +0 -11
  782. package/dist/channel.setup-CkDVwv5R.js +0 -57
  783. package/dist/channel.setup-Cpd00YqQ.js +0 -8
  784. package/dist/channel.setup-DbBz1-WT.js +0 -9
  785. package/dist/channel.setup-GZnAvD9g.js +0 -8
  786. package/dist/channels-5H484RSw.js +0 -1118
  787. package/dist/channels-BnPudfyx.js +0 -404
  788. package/dist/channels-cli-WIC-QeH_.js +0 -291
  789. package/dist/channels-status-issues-RDmzovJU.js +0 -16
  790. package/dist/clawbot-cli-BgutNwf8.js +0 -118
  791. package/dist/cleanup-utils-DBl1Aij1.js +0 -96
  792. package/dist/cli-1P7u6zqu.js +0 -154
  793. package/dist/command-registry-B8jovrws.js +0 -232
  794. package/dist/command-registry-DtDl1FVm.js +0 -14
  795. package/dist/command-secret-gateway-BgUo3FxJ.js +0 -111
  796. package/dist/compact.runtime-CXbXM0AU.js +0 -116
  797. package/dist/completion-cli-Cik_owAE.js +0 -17
  798. package/dist/completion-cli-RU3P2RSl.js +0 -445
  799. package/dist/config-5HUpB1L1.js +0 -31
  800. package/dist/config-cli-QHaUHoZI.js +0 -433
  801. package/dist/config-guard-C9Sn3pE-.js +0 -118
  802. package/dist/config-sW57gztj.js +0 -44
  803. package/dist/config-validation-5LkjIKNt.js +0 -262
  804. package/dist/config-value-CtTWALxG.js +0 -132
  805. package/dist/configure-BmR2TPLf.js +0 -243
  806. package/dist/configure-DaLN-5xM.js +0 -1100
  807. package/dist/control-ui-assets-CH3MYmAo.js +0 -232
  808. package/dist/control-ui-shared-CA77PTml.js +0 -29
  809. package/dist/core-CvDzLs7B.js +0 -150
  810. package/dist/core-jm751KJ9.d.ts +0 -87
  811. package/dist/cron-cli-tguLpzyq.js +0 -639
  812. package/dist/daemon-cli-ptosOkL8.js +0 -339
  813. package/dist/daemon-install-DzU4EnVa.js +0 -180
  814. package/dist/deliver-DwxFoHM3.js +0 -111
  815. package/dist/deliver-runtime-DOdDyaPI.js +0 -111
  816. package/dist/device-id-cli-GopvlxxZ.js +0 -52
  817. package/dist/device-identity-CRfhC3_s.js +0 -365
  818. package/dist/devices-cli-ain7ESqU.js +0 -342
  819. package/dist/diagnostic-D96Xaqrj.js +0 -310
  820. package/dist/directory-cli-fh1UxGgY.js +0 -311
  821. package/dist/directory-config-helpers-Coivm0Mt.d.ts +0 -38
  822. package/dist/directory.static-CKjJUNGl.js +0 -44
  823. package/dist/discord-CflhwDEM.js +0 -114
  824. package/dist/discovery-x0ZqY4AB.js +0 -48
  825. package/dist/dm-policy-shared-DKzsSLlO.d.ts +0 -95
  826. package/dist/dns-cli-DCHyKjGf.js +0 -217
  827. package/dist/docs-cli-D3OoqYSP.js +0 -174
  828. package/dist/doctor-completion-Bq2eP87s.js +0 -90
  829. package/dist/doctor-config-flow-D8XRG9Ku.js +0 -2437
  830. package/dist/doctor-config-flow-DGiF1HGc.js +0 -112
  831. package/dist/enable-0QSF4YGH.js +0 -24
  832. package/dist/exec-approvals-cli-Bncym0Gd.js +0 -421
  833. package/dist/feishu-C1dM8pl2.d.ts +0 -36
  834. package/dist/gateway-cli-DYscsmA-.js +0 -26437
  835. package/dist/gateway-install-token-CNv17ac9.js +0 -163
  836. package/dist/gateway-rpc-BGC1Rxvg.js +0 -26
  837. package/dist/gateway-runtime-D89mSQPB.js +0 -69
  838. package/dist/git-commit-CeLH5Ozm.js +0 -2
  839. package/dist/git-commit-DUKRiCP-.js +0 -177
  840. package/dist/googlechat-BgXeXjd1.js +0 -307
  841. package/dist/googlechat-CNZQb1jd.d.ts +0 -12
  842. package/dist/group-access-Deh1tVNr.d.ts +0 -61
  843. package/dist/health-BEjzWwaB.js +0 -570
  844. package/dist/health-FjqrWQL6.js +0 -113
  845. package/dist/heartbeat-summary-CfdSA9M1.js +0 -57
  846. package/dist/help-BZeVprq1.js +0 -81
  847. package/dist/hooks-06OUQvAV.d.ts +0 -6
  848. package/dist/hooks-cli-B7uGJs2O.js +0 -1000
  849. package/dist/hooks-status-CfceaUSg.js +0 -78
  850. package/dist/http-registry-DYskWhOr.d.ts +0 -20
  851. package/dist/identity-file-sshkKKIr.js +0 -60
  852. package/dist/image-generation-D4o3j8o6.d.ts +0 -9
  853. package/dist/imessage-BcV3WGx_.js +0 -31
  854. package/dist/imessage-Dhje7Ty-.js +0 -115
  855. package/dist/inbound-reply-dispatch-C73_7SOl.js +0 -71
  856. package/dist/inbound-reply-dispatch-D6_HNqH8.d.ts +0 -72
  857. package/dist/install-target-D7NRhfzc.js +0 -574
  858. package/dist/installs-Bj6jblqc.js +0 -532
  859. package/dist/io-CMfWWPXQ.js +0 -9738
  860. package/dist/io-CV844hAM.js +0 -29
  861. package/dist/irc-DKi1fDYI.js +0 -672
  862. package/dist/library-rygTG3oA.js +0 -112
  863. package/dist/lifecycle-core-BPlvShWY.js +0 -382
  864. package/dist/line-B8gTtl3Y.d.ts +0 -75
  865. package/dist/line-CGsemKWJ.js +0 -530
  866. package/dist/llm-slug-generator-DlhVyMqT.js +0 -67
  867. package/dist/logging-5wu9k6w4.js +0 -30
  868. package/dist/logging-CxP9suT8.js +0 -13
  869. package/dist/login-qr-BcDsiwHs.js +0 -233
  870. package/dist/login-qr-Y8pJ5yV4.js +0 -112
  871. package/dist/logs-cli-XI9oVXpH.js +0 -256
  872. package/dist/manager-runtime-DkIlXBhD.js +0 -111
  873. package/dist/manager.runtime-Q0q2rJCC.js +0 -715
  874. package/dist/manifest-registry-DAd0SRAP.js +0 -1329
  875. package/dist/matrix-BI0DBBrG.js +0 -1495
  876. package/dist/matrix-D2JoHzb4.d.ts +0 -68
  877. package/dist/matrix-DiABGjJR.js +0 -1269
  878. package/dist/mcp-cli-BOyn_DLL.js +0 -87
  879. package/dist/media-understanding.runtime-DjUa7Dka.js +0 -116
  880. package/dist/memory-cli-CJd_vl-Y.js +0 -111
  881. package/dist/memory-search-CEEItIFR.js +0 -17
  882. package/dist/memory-search-Cv1SBrn7.js +0 -204
  883. package/dist/method-scopes-CQE7-bZ-.js +0 -2452
  884. package/dist/model-auth-markers-BFoM4IPf.d.ts +0 -20
  885. package/dist/model-picker-D6_89XHg.js +0 -112
  886. package/dist/model-picker-Svaw-APs.js +0 -390
  887. package/dist/model-picker.runtime-Chi9nV7A.js +0 -125
  888. package/dist/model-selection-hL8i1Jbs.js +0 -653
  889. package/dist/model-suppression.runtime-DjWJZ0X-.js +0 -116
  890. package/dist/models-7qj1dG_W.js +0 -118
  891. package/dist/models-BPOB_xJF.js +0 -2514
  892. package/dist/models-cli-DdlOVUjS.js +0 -309
  893. package/dist/models-config-CBqUS-jX.js +0 -111
  894. package/dist/models-config.providers.discovery-Dc905FWG.d.ts +0 -18
  895. package/dist/moldclaw-root-D6PbhbZk.js +0 -88
  896. package/dist/monitor-BPYhkEqF.js +0 -782
  897. package/dist/monitor-BuTcQ24j.js +0 -3468
  898. package/dist/monitor-CuXvNhFh.js +0 -113
  899. package/dist/monitor-D-TqSIHF.js +0 -6823
  900. package/dist/monitor-DRSgo9u2.js +0 -3076
  901. package/dist/monitor-DcHch39z.js +0 -772
  902. package/dist/monitor-DsHBMrXp.js +0 -115
  903. package/dist/monitor-shared-CL8T4gt1.js +0 -444
  904. package/dist/msteams-7FMwTvQG.js +0 -852
  905. package/dist/node-cli-BCjaSCZM.js +0 -2503
  906. package/dist/node-resolve-D5Hvcgyx.js +0 -835
  907. package/dist/nodes-cli-Dd_SNbkt.js +0 -1380
  908. package/dist/nostr-DBTFTxKs.js +0 -8744
  909. package/dist/nostr-DLqaIuZx.d.ts +0 -7
  910. package/dist/npm-resolution-CYfb3MHG.js +0 -60
  911. package/dist/oauth-env-zPt5RywA.js +0 -10
  912. package/dist/onboard-BEFQQeig.js +0 -25
  913. package/dist/onboard-CJHNyxJh.js +0 -48
  914. package/dist/onboard-D_3UeLEN.js +0 -589
  915. package/dist/onboard-channels-B_JL0Djc.js +0 -1241
  916. package/dist/onboard-channels-CqZzHt2C.js +0 -205
  917. package/dist/onboard-custom-CER3Ggbq.js +0 -571
  918. package/dist/onboard-custom-bNRdGECb.js +0 -114
  919. package/dist/onboard-helpers-BK0Hsb7Y.js +0 -335
  920. package/dist/onboard-helpers-CXZ5RPoR.js +0 -113
  921. package/dist/onboard-hooks-1NsxEDjH.js +0 -72
  922. package/dist/onboard-remote-DuKhC_7W.js +0 -117
  923. package/dist/onboard-remote-OwRcDuB3.js +0 -181
  924. package/dist/onboard-search-Cy8dOq2W.js +0 -302
  925. package/dist/onboard-skills-D5phRa6r.js +0 -117
  926. package/dist/onboard-skills-c9qWCNe9.js +0 -133
  927. package/dist/outbound-media-CXKqTh2X.d.ts +0 -11
  928. package/dist/outbound-media-DYRO2vTD.js +0 -11
  929. package/dist/pairing-access-BwJu1mkk.d.ts +0 -21
  930. package/dist/pairing-cli-BOnv0TYn.js +0 -217
  931. package/dist/perplexity-EZwC3y2b.js +0 -24
  932. package/dist/persistent-dedupe-hNES5tS1.d.ts +0 -26
  933. package/dist/pi-model-discovery-runtime-BToY3A6K.js +0 -111
  934. package/dist/pi-tools.before-tool-call.runtime-D_acPtld.js +0 -381
  935. package/dist/plugin-install-CgJpSjYd.js +0 -184
  936. package/dist/plugin-install-Cl1A4EF6.js +0 -117
  937. package/dist/plugin-install-plan-Dc2Z4DeU.js +0 -49
  938. package/dist/plugin-registry-B1UaWrQD.js +0 -49
  939. package/dist/plugin-registry-Cy8biwnn.js +0 -113
  940. package/dist/plugins-CXwvg50F.js +0 -111
  941. package/dist/plugins-cli-Uvzp2aYV.js +0 -917
  942. package/dist/policy-DsMBbEe7.js +0 -143
  943. package/dist/preflight-audio.runtime-hWsZIYvc.js +0 -116
  944. package/dist/probe-CNsSf1Uf.js +0 -6329
  945. package/dist/probe-CqOIrPhb.js +0 -47
  946. package/dist/probe-DH6gDw-h.js +0 -129
  947. package/dist/probe-DM16PLf4.js +0 -21
  948. package/dist/probe-DvAEEWYr.js +0 -1793
  949. package/dist/probe-auth-COfgCble.js +0 -48
  950. package/dist/probe-auth-I_5TX1Eh.js +0 -40
  951. package/dist/program-Dz80sgTU.js +0 -253
  952. package/dist/prompt-select-styled-wQehwFxK.js +0 -2673
  953. package/dist/provider-api-key-auth.runtime-BR9GU4ya.js +0 -121
  954. package/dist/provider-auth-choice-CdhA84kr.js +0 -126
  955. package/dist/provider-auth-choice-helpers-kabp_0zA.js +0 -48
  956. package/dist/provider-auth-choice-preference-se3zAM_2.js +0 -189
  957. package/dist/provider-auth-choice.runtime-BMc8-xNQ.js +0 -123
  958. package/dist/provider-auth-choices-CYsCViGi.js +0 -57
  959. package/dist/provider-auth-guidance-CMjUWlNf.js +0 -34
  960. package/dist/provider-auth-result-5xgWoVGi.d.ts +0 -18
  961. package/dist/provider-models-BCId_Lfu.js +0 -2113
  962. package/dist/provider-models-D-eFl9oH.d.ts +0 -867
  963. package/dist/provider-ollama-setup-B6XJZ0So.js +0 -314
  964. package/dist/provider-ollama-setup-BF1vhob8.d.ts +0 -32
  965. package/dist/provider-onboard-BjXHP3IZ.d.ts +0 -40
  966. package/dist/provider-onboard-Ca0TaNud.js +0 -139
  967. package/dist/provider-runtime.runtime-DwwkHw_7.js +0 -111
  968. package/dist/provider-self-hosted-setup-BEKLVGpj.js +0 -182
  969. package/dist/provider-self-hosted-setup-BQ5BIlpi.d.ts +0 -61
  970. package/dist/provider-stream-DrUD69ai.js +0 -512
  971. package/dist/provider-usage-BgKHCnjr.js +0 -111
  972. package/dist/provider-usage-D8EZpFz9.js +0 -633
  973. package/dist/provider-wizard-DMdb-zj_.js +0 -152
  974. package/dist/push-apns-BPH6d4VV.js +0 -1038
  975. package/dist/pw-ai-DttfldtL.js +0 -1867
  976. package/dist/qmd-manager-CybcDUfk.js +0 -1570
  977. package/dist/qr-cli-8NcmJ8Ft.js +0 -369
  978. package/dist/qr-cli-DWe0Our3.js +0 -113
  979. package/dist/reactions-D6N0LR16.js +0 -281
  980. package/dist/read-only-account-inspect.discord.runtime-CqUWTRfl.js +0 -116
  981. package/dist/read-only-account-inspect.slack.runtime-9-jpln3q.js +0 -116
  982. package/dist/read-only-account-inspect.telegram.runtime-EKPI1D7n.js +0 -116
  983. package/dist/redact-snapshot-DwJEIVk9.js +0 -2663
  984. package/dist/register.agent-D3YdDirP.js +0 -439
  985. package/dist/register.backup-dR27qCuo.js +0 -625
  986. package/dist/register.configure-BjFhkkka.js +0 -252
  987. package/dist/register.maintenance-DiMQJIOa.js +0 -574
  988. package/dist/register.message-CdZsKYH1.js +0 -709
  989. package/dist/register.onboard-B0rV1eaO.js +0 -192
  990. package/dist/register.setup-wKMvohzo.js +0 -212
  991. package/dist/register.status-health-sessions-BJ68m6pt.js +0 -498
  992. package/dist/register.subclis-CnnrWt2a.js +0 -315
  993. package/dist/register.subclis-lSvTkC6z.js +0 -13
  994. package/dist/replies-BABt9b48.js +0 -110
  995. package/dist/resolve-channels-BqZFl2Ux.js +0 -262
  996. package/dist/resolve-channels-DjQLXb7B.js +0 -226
  997. package/dist/resolve-route-CSHDsa_m.js +0 -538
  998. package/dist/resolve-users-BG6HaSR5.js +0 -143
  999. package/dist/root-help-ohmaCyC_.js +0 -32
  1000. package/dist/routes-4k2kpvoT.js +0 -7097
  1001. package/dist/rpc-Cnwn4Q6L.js +0 -67
  1002. package/dist/run-main-VYlacKA0.js +0 -424
  1003. package/dist/runtime-Cy8pqYUB.d.ts +0 -26
  1004. package/dist/runtime-discord-ops.runtime-DafrU-rI.js +0 -9078
  1005. package/dist/runtime-slack-ops.runtime-CdXBKXwd.js +0 -4556
  1006. package/dist/runtime-telegram-ops.runtime-B12sF7gE.js +0 -133
  1007. package/dist/runtime-whatsapp-login.runtime-CqEudH37.js +0 -114
  1008. package/dist/runtime-whatsapp-outbound.runtime-D5m2qyn-.js +0 -117
  1009. package/dist/sandbox-cli-CHJiEWXB.js +0 -535
  1010. package/dist/search-manager-BtNC3-i_.js +0 -16
  1011. package/dist/search-manager-C7J7B3_a.js +0 -386
  1012. package/dist/secrets-cli-C6yIWBbN.js +0 -2070
  1013. package/dist/security-cli-BVu9BkjD.js +0 -575
  1014. package/dist/send-BSreC7rr.js +0 -631
  1015. package/dist/send-BsLHQG_B.js +0 -1025
  1016. package/dist/send-BuNhp8PH.js +0 -283
  1017. package/dist/send-DOCswVar.js +0 -100
  1018. package/dist/send-Dl0LLErk.js +0 -629
  1019. package/dist/server-node-events-Bq2067EG.js +0 -506
  1020. package/dist/server-y38L7N5H.js +0 -107
  1021. package/dist/sessions-BV8gXURR.js +0 -112
  1022. package/dist/sessions-dl1Kc-Ci.js +0 -218
  1023. package/dist/setup-DGszQH0_.js +0 -387
  1024. package/dist/setup-DR5rRw9y.d.ts +0 -37
  1025. package/dist/setup-binary-C17YnmA8.js +0 -406
  1026. package/dist/setup-browser-CPx-nEsr.js +0 -70
  1027. package/dist/setup-core-BByHN1ME.js +0 -143
  1028. package/dist/setup-core-C0KPlBmL.js +0 -47
  1029. package/dist/setup-core-Cq37G6of.js +0 -166
  1030. package/dist/setup-core-uO84_Y75.js +0 -205
  1031. package/dist/setup-surface-BEMi7Rmb.js +0 -490
  1032. package/dist/setup-wizard-helpers-BtuGx_gN.d.ts +0 -203
  1033. package/dist/setup.finalize-BzPBa8zW.js +0 -522
  1034. package/dist/setup.gateway-config-DdwkF-8e.js +0 -343
  1035. package/dist/shared-BCw4SKjB.js +0 -96
  1036. package/dist/shared-CjNzsULP.js +0 -75
  1037. package/dist/shared-Cu1BE7ZE.js +0 -298
  1038. package/dist/shared-DSClmyUn.js +0 -182
  1039. package/dist/shared-DyJdGH6y.js +0 -102
  1040. package/dist/signal-Dyv4NZsB.js +0 -114
  1041. package/dist/skills-CbB5b27M.js +0 -853
  1042. package/dist/skills-CnfI7Szw.js +0 -20
  1043. package/dist/skills-cli-CavB1f_3.js +0 -292
  1044. package/dist/skills-install-B1OBdgd0.js +0 -763
  1045. package/dist/skills-status-B3gAmIbW.js +0 -169
  1046. package/dist/skills-status-DrHhFgU9.js +0 -21
  1047. package/dist/slack-BRzqnoAz.js +0 -114
  1048. package/dist/slash-commands.runtime-BK88kgds.js +0 -128
  1049. package/dist/slash-dispatch.runtime-COGywwJE.js +0 -141
  1050. package/dist/slash-skill-commands.runtime-Ti4brxgh.js +0 -116
  1051. package/dist/src-DUR6OQxI.js +0 -1701
  1052. package/dist/status-C6dgQY9a.js +0 -131
  1053. package/dist/status-CNK0Q7QH.js +0 -606
  1054. package/dist/status-DBcX0DSC.js +0 -43
  1055. package/dist/status-DKgFgbwv.js +0 -1599
  1056. package/dist/status-Wn5lhNAc.js +0 -126
  1057. package/dist/status-json-D2EkWqAl.js +0 -288
  1058. package/dist/status.link-channel-D3ULIdEa.js +0 -143
  1059. package/dist/status.scan.deps.runtime-BsjWTAm4.js +0 -126
  1060. package/dist/status.scan.runtime-D4HbzROD.js +0 -119
  1061. package/dist/status.summary-C3YxPrDK.js +0 -592
  1062. package/dist/status.summary.runtime-DAkXPSaK.js +0 -118
  1063. package/dist/status.update-B4NnN9P1.js +0 -77
  1064. package/dist/subagent-orphan-recovery-QiQEBv36.js +0 -307
  1065. package/dist/subagent-registry-runtime-BJatPQFK.js +0 -111
  1066. package/dist/subscription-BhZORXN9.js +0 -100
  1067. package/dist/subscription-QEUjQRMv.js +0 -33
  1068. package/dist/subscription-cli-HrULlAgc.js +0 -134
  1069. package/dist/synology-chat-DB76GWMN.js +0 -297
  1070. package/dist/system-cli-D8jDwWuL.js +0 -94
  1071. package/dist/telegram-BHiiqKkQ.js +0 -114
  1072. package/dist/text-chunking-Baonm9Lu.js +0 -84
  1073. package/dist/text-chunking-Y3dPBOuZ.d.ts +0 -79
  1074. package/dist/tlon-DLESxNgD.js +0 -433
  1075. package/dist/tui-C75zi2Cl.js +0 -3834
  1076. package/dist/tui-cli-DFwx5e6i.js +0 -137
  1077. package/dist/types-BBJ3Qz7j.d.ts +0 -45
  1078. package/dist/types-Ckufs_BY.d.ts +0 -22692
  1079. package/dist/types.base-Cw0-zIvE.d.ts +0 -188
  1080. package/dist/ui-B55NOIB6.js +0 -31
  1081. package/dist/update--ojavYQ4.js +0 -1036
  1082. package/dist/update-cli-Cvj5aWYM.js +0 -1503
  1083. package/dist/update-offset-store-upatuWwX.js +0 -112
  1084. package/dist/update-runner-DHkY_-76.js +0 -1496
  1085. package/dist/upsert-with-lock-C171GLaR.js +0 -33
  1086. package/dist/usage-N3bxnbmt.js +0 -115
  1087. package/dist/web-RdvT7gKa.js +0 -112
  1088. package/dist/web-shared-HSGD3yGt.d.ts +0 -45
  1089. package/dist/webhook-request-guards-CosLyl01.d.ts +0 -76
  1090. package/dist/webhook-targets-Bfnag-du.js +0 -181
  1091. package/dist/webhook-targets-Di17rt8e.d.ts +0 -106
  1092. package/dist/webhooks-cli-ZpnXrq7G.js +0 -350
  1093. package/dist/whatsapp-DNTAyZHt.js +0 -114
  1094. package/dist/whatsapp-actions-o1zKQzKZ.js +0 -167
  1095. package/dist/workspace-CpWi5wPr.js +0 -479
  1096. package/dist/workspace-Ii7aRS7c.js +0 -289
  1097. package/dist/workspace-dirs-x10McA9t.js +0 -2003
  1098. package/dist/zalo-BN3VCrRY.d.ts +0 -9
  1099. package/dist/zalo-zm_bYCKg.js +0 -415
  1100. package/dist/zalouser-CvVEUvc5.js +0 -30911
  1101. /package/dist/{account-id-B3YSn4hl.d.ts → account-id-B8ce6G_4.d.ts} +0 -0
  1102. /package/dist/{acpx-CnNv70m2.d.ts → acpx-Ci50I9T2.d.ts} +0 -0
  1103. /package/dist/{agent-media-payload-DE2pEcsz.d.ts → agent-media-payload-en-gS5p6.d.ts} +0 -0
  1104. /package/dist/{allow-from-DPpHnT2A.d.ts → allow-from-cMeQ47Ot.d.ts} +0 -0
  1105. /package/dist/{allowlist-resolution-CLFiZ6nE.d.ts → allowlist-resolution-DoAWbfXV.d.ts} +0 -0
  1106. /package/dist/{bluebubbles-Duhu-Jer.d.ts → bluebubbles-C6yYmUl0.d.ts} +0 -0
  1107. /package/dist/{boolean-param-BhFjB3gp.d.ts → boolean-param-CdO2TFTk.d.ts} +0 -0
  1108. /package/dist/{channel-config-schema-DnnVMdjR.d.ts → channel-config-schema-Chp38wel.d.ts} +0 -0
  1109. /package/dist/{channel-policy-Baq-Z06b.d.ts → channel-policy-g2h6AbYQ.d.ts} +0 -0
  1110. /package/dist/{chat-type-DpiBgwuG.d.ts → chat-type-BLt59pPT.d.ts} +0 -0
  1111. /package/dist/{command-format-vi4xq8e8.d.ts → command-format-BDJC05Jp.d.ts} +0 -0
  1112. /package/dist/{diffs-DK7fVSDo.d.ts → diffs-D_iNKCyn.d.ts} +0 -0
  1113. /package/dist/{directory-runtime-BTLPaysA.d.ts → directory-runtime-DhMex6HY.d.ts} +0 -0
  1114. /package/dist/{exec-C01wtBHu.d.ts → exec-pjfUY4KM.d.ts} +0 -0
  1115. /package/dist/{gaxios-fetch-compat-wZ38b3w3.js → gaxios-fetch-compat-B_vtINdV.js} +0 -0
  1116. /package/dist/{history-CwXuP2TW.d.ts → history-aqSS5VGQ.d.ts} +0 -0
  1117. /package/dist/{inbound-envelope-SggrBs9m.d.ts → inbound-envelope-C5hWuZod.d.ts} +0 -0
  1118. /package/dist/{index-apAZHsDo.d.ts → index-DXVQFYGX.d.ts} +0 -0
  1119. /package/dist/{json-store-r75IZGk9.d.ts → json-store-UnqQ5aV3.d.ts} +0 -0
  1120. /package/dist/{keyed-async-queue-DHIr7yNe.d.ts → keyed-async-queue-guucpLw3.d.ts} +0 -0
  1121. /package/dist/{links-HeQ3r_L0.d.ts → links-Bar0meEK.d.ts} +0 -0
  1122. /package/dist/{markdown-to-line-CDb4Jy3V.d.ts → markdown-to-line-D8uH_KOj.d.ts} +0 -0
  1123. /package/dist/{mattermost-DtCsxpgg.d.ts → mattermost-xl7jAFJL.d.ts} +0 -0
  1124. /package/dist/{net-BATPDwdQ.d.ts → net-rGOKGds6.d.ts} +0 -0
  1125. /package/dist/{nextcloud-talk-Bb2wHOwp.d.ts → nextcloud-talk-De2CZ9dV.d.ts} +0 -0
  1126. /package/dist/{oauth-utils-u567CLT0.d.ts → oauth-utils-DzN1AlEH.d.ts} +0 -0
  1127. /package/dist/{parse-finite-number-l3tNlrZh.d.ts → parse-finite-number-odgyqhi0.d.ts} +0 -0
  1128. /package/dist/{provider-usage.types-C6061OVN.d.ts → provider-usage.types-EDE9o-H_.d.ts} +0 -0
  1129. /package/dist/{reply-history-BDsFnZFl.d.ts → reply-history-CVuU31xe.d.ts} +0 -0
  1130. /package/dist/{reply-payload-CCvM4W9u.d.ts → reply-payload-CHkpBYwL.d.ts} +0 -0
  1131. /package/dist/{request-url-C54l4-xC.d.ts → request-url-DHisbiHY.d.ts} +0 -0
  1132. /package/dist/{run-command-D3RqWcHu.d.ts → run-command-y0Cndsb1.d.ts} +0 -0
  1133. /package/dist/{secret-input-schema-BLBt-NAP.d.ts → secret-input-schema-b1vpYDQN.d.ts} +0 -0
  1134. /package/dist/{session-key-BQ2-bR-9.d.ts → session-key-DTHQl57f.d.ts} +0 -0
  1135. /package/dist/{ssh-config-C4mcH9Ly.js → ssh-config-hEHBfU2_.js} +0 -0
  1136. /package/dist/{testing-DLkhGsoz.d.ts → testing-DszuZXgK.d.ts} +0 -0
  1137. /package/dist/{thinking-DRkjX18p.d.ts → thinking-IwXTGSeT.d.ts} +0 -0
  1138. /package/dist/{tool-send-CMMD1uDu.d.ts → tool-send-DWHRmKpz.d.ts} +0 -0
  1139. /package/dist/{vllm-defaults-CcGuf4hL.d.ts → vllm-defaults-CrxZgE6-.d.ts} +0 -0
  1140. /package/dist/{wait-Daog8bxM.d.ts → wait-wDWw_MTI.d.ts} +0 -0
  1141. /package/dist/{webhook-memory-guards-C5MrExwT.d.ts → webhook-memory-guards-DreORuJy.d.ts} +0 -0
  1142. /package/dist/{windows-spawn-j2l-dqu8.d.ts → windows-spawn-BIzH92x2.d.ts} +0 -0
  1143. /package/dist/{zod-schema.agent-runtime-krMrBnIn.d.ts → zod-schema.agent-runtime-CP2rmis3.d.ts} +0 -0
  1144. /package/dist/{zod-schema.core-BNDieZDZ.d.ts → zod-schema.core-Foi1tYwi.d.ts} +0 -0
@@ -0,0 +1,3834 @@
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-smABVXzp.js";
3
+ import { B as normalizeUsageDisplay, H as resolveResponseUsageMode } from "./model-selection-bBBxfXdb.js";
4
+ import { c as resolveAgentIdByWorkspacePath, m as resolveDefaultAgentId } from "./agent-scope-lZlwP1At.js";
5
+ import { S as parseAgentSessionKey, c as normalizeAgentId, l as normalizeMainKey, r as buildAgentMainSessionKey } from "./session-key-UoG7Kfw5.js";
6
+ import { c as loadConfig } from "./io-BaBxjB1v.js";
7
+ import { n as VERSION } from "./version-T8nMYUnU.js";
8
+ import { a as hasConfiguredSecretInput } from "./types.secrets-Ca-9L8vU.js";
9
+ import { it as resolveConfiguredSecretInputString, st as assertExplicitGatewayAuthModeWhenBothConfigured } from "./routes-CcJNnwTF.js";
10
+ import { _ as GATEWAY_CLIENT_MODES, h as GATEWAY_CLIENT_CAPS, v as GATEWAY_CLIENT_NAMES } from "./message-channel-DFE4FuE_.js";
11
+ import { u as GatewayClient } from "./method-scopes-B2ZKSsxQ.js";
12
+ import { s as formatTokenCount, y as stripLeadingInboundMetadata } from "./session-cost-usage-DWgQk6XT.js";
13
+ import { c as resolveExplicitGatewayAuth, o as ensureExplicitGatewayAuth, t as buildGatewayConnectionDetails } from "./call-gdDAt07d.js";
14
+ import { n as formatTimeAgo, t as formatRelativeTimestamp } from "./format-relative-B1Jfwsqe.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 };