@spacebar_ai/moldclaw-core 2026.3.14 → 2026.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1074) hide show
  1. package/README.md +108 -3
  2. package/dist/account-id-plS5L20e.d.ts +1 -0
  3. package/dist/accounts-BAYVGC2k.js +109 -0
  4. package/dist/accounts-DrjRgReV.d.ts +103 -0
  5. package/dist/acp-cli-at_UYEOS.js +2088 -0
  6. package/dist/acpx-Chy1GQ_k.d.ts +5 -0
  7. package/dist/actions.runtime-C0F7dMfO.js +114 -0
  8. package/dist/actions.runtime-caI2LG9o.js +128 -0
  9. package/dist/agent-media-payload-CkpAqaOh.d.ts +16 -0
  10. package/dist/agents-B98yPGc5.js +853 -0
  11. package/dist/agents-BrLr08L3.js +217 -0
  12. package/dist/allow-from-BIwT4dl7.d.ts +42 -0
  13. package/dist/allow-list-CHt7yvAf.js +81 -0
  14. package/dist/allowlist-CxQo2wQc.js +142 -0
  15. package/dist/allowlist-resolution-B7ib7gye.d.ts +17 -0
  16. package/dist/api-Co7TNHbL.js +6953 -0
  17. package/dist/api-cEQ_ql_8.js +112 -0
  18. package/dist/audit-AnKnnlaZ.js +787 -0
  19. package/dist/audit-channel.collect.runtime-CAk1DFQ3.js +600 -0
  20. package/dist/audit-channel.runtime-5phdZp_m.js +116 -0
  21. package/dist/audit-extra.async-B8ZXFxic.js +813 -0
  22. package/dist/audit-hdKa3D-u.js +54 -0
  23. package/dist/audit-membership-runtime-CJV5XvGU.js +157 -0
  24. package/dist/audit.deep.runtime-DNMcRQrp.js +24 -0
  25. package/dist/audit.nondeep.runtime-DhNDL6yM.js +831 -0
  26. package/dist/audit.runtime-Bx7uWEh8.js +113 -0
  27. package/dist/auth-choice-C37W9MA7.js +268 -0
  28. package/dist/auth-choice-CNppOY_V.js +117 -0
  29. package/dist/auth-choice-XYFnp6fI.js +502 -0
  30. package/dist/auth-choice-options-D6oZY4Xo.js +123 -0
  31. package/dist/auth-choice-prompt-BhRqchJx.js +110 -0
  32. package/dist/auth-choice-prompt-C1xv0N08.js +36 -0
  33. package/dist/auth-choice.plugin-providers.runtime-DhLEtbmR.js +114 -0
  34. package/dist/auth-profiles-9zZdaXJK.js +127756 -0
  35. package/dist/auth-profiles.runtime-HONFDgiu.js +111 -0
  36. package/dist/bluebubbles-BY8JhO4y.js +64 -0
  37. package/dist/bluebubbles-CQjEnzK_.d.ts +6 -0
  38. package/dist/bluebubbles-RmcKgkBa.d.ts +45 -0
  39. package/dist/boolean-param-F1sMwnPu.d.ts +5 -0
  40. package/dist/bot-BGh-ATV7.d.ts +478 -0
  41. package/dist/brave-CljenznH.js +24 -0
  42. package/dist/browser-cli-CX8i0wf0.js +1492 -0
  43. package/dist/build-info.json +3 -3
  44. package/dist/bundled/boot-md/handler.d.ts +6 -0
  45. package/dist/bundled/boot-md/handler.js +26 -26
  46. package/dist/bundled/bootstrap-extra-files/handler.d.ts +6 -0
  47. package/dist/bundled/command-logger/handler.d.ts +9 -0
  48. package/dist/bundled/session-memory/handler.d.ts +9 -0
  49. package/dist/bundled/session-memory/handler.js +27 -27
  50. package/dist/call-Bc257L16.js +37 -0
  51. package/dist/call-DYFR7oGy.js +639 -0
  52. package/dist/canvas-host/a2ui/.bundle.hash +1 -1
  53. package/dist/channel-Bd-igGEW.js +803 -0
  54. package/dist/channel-BgRMb6bZ.js +575 -0
  55. package/dist/channel-BtcLrU6J.js +1598 -0
  56. package/dist/channel-Bwf6m_hD.js +538 -0
  57. package/dist/channel-C7-kgDBd.js +562 -0
  58. package/dist/channel-CEXOAxIc.js +949 -0
  59. package/dist/channel-CpZ3p9MJ.js +226 -0
  60. package/dist/channel-CqBlN6A2.js +619 -0
  61. package/dist/channel-DKhfHW4U.js +352 -0
  62. package/dist/channel-DS3t_KdJ2.js +316 -0
  63. package/dist/channel-DY24FA1v.js +4681 -0
  64. package/dist/channel-DYFGmImJ.js +542 -0
  65. package/dist/channel-DcyIqX5p.js +207 -0
  66. package/dist/channel-J-2XcAli.js +214 -0
  67. package/dist/channel-N616f4gZ.js +306 -0
  68. package/dist/channel-NY7aU2Gj.js +397 -0
  69. package/dist/channel-PNI8BOmm.js +1321 -0
  70. package/dist/channel-UcXepDJs.js +943 -0
  71. package/dist/channel-account-context-CL3hEq1j.js +103 -0
  72. package/dist/channel-config-schema-Q2nzcCCR.d.ts +1 -0
  73. package/dist/channel-jA_jodJo.js +920 -0
  74. package/dist/channel-options-CtgU5qkG.js +50 -0
  75. package/dist/channel-policy-7wXDp6d3.d.ts +1 -0
  76. package/dist/channel-rGI8uig4.js +497 -0
  77. package/dist/channel-summary-DGJZXo0r.js +106 -0
  78. package/dist/channel.runtime--WZvlNJM.js +413 -0
  79. package/dist/channel.runtime-B0ct42DL.js +122 -0
  80. package/dist/channel.runtime-BEZUZrYB.js +177 -0
  81. package/dist/channel.runtime-BMuWmsIC.js +166 -0
  82. package/dist/channel.runtime-BtvHP0po.js +4006 -0
  83. package/dist/channel.runtime-Cwf993pX.js +194 -0
  84. package/dist/channel.runtime-Cy4lEpTX.js +174 -0
  85. package/dist/channel.runtime-DAz6axda.js +865 -0
  86. package/dist/channel.runtime-DdQ2mOVh.js +236 -0
  87. package/dist/channel.runtime-Dy3HPgOU.js +399 -0
  88. package/dist/channel.runtime-iqfC25k7.js +213 -0
  89. package/dist/channel.setup-B4VYMZlQ.js +9 -0
  90. package/dist/channel.setup-BohGbCbI.js +57 -0
  91. package/dist/channel.setup-Bq2AQqqc.js +6 -0
  92. package/dist/channel.setup-BxiSfLp1.js +8 -0
  93. package/dist/channel.setup-DOUS6fjO.js +8 -0
  94. package/dist/channel.setup-DXhdYU3g.js +9 -0
  95. package/dist/channel.setup-N51CgfNy.js +11 -0
  96. package/dist/channels/plugins/actions/discord.d.ts +3 -0
  97. package/dist/channels/plugins/actions/discord.js +26 -26
  98. package/dist/channels/plugins/actions/signal.d.ts +2 -0
  99. package/dist/channels/plugins/actions/signal.js +26 -26
  100. package/dist/channels/plugins/actions/telegram.d.ts +3 -0
  101. package/dist/channels/plugins/actions/telegram.js +26 -26
  102. package/dist/channels/plugins/agent-tools/whatsapp-login.d.ts +4 -0
  103. package/dist/channels/plugins/agent-tools/whatsapp-login.js +26 -26
  104. package/dist/channels-CueeFf0q.js +404 -0
  105. package/dist/channels-PheAd73E.js +1113 -0
  106. package/dist/channels-cli-CXzVF84v.js +286 -0
  107. package/dist/channels-status-issues-BjWBQHhU.js +16 -0
  108. package/dist/chat-type-BlSN0vo4.d.ts +5 -0
  109. package/dist/clawbot-cli-BBehDXW1.js +113 -0
  110. package/dist/cli/daemon-cli.d.ts +58 -0
  111. package/dist/cli/daemon-cli.js +1 -1
  112. package/dist/cli-CIm7d5Id.js +149 -0
  113. package/dist/command-format-pq3tS8t2.d.ts +4 -0
  114. package/dist/command-registry-CDkp__KH.js +13 -0
  115. package/dist/command-registry-DSEkUBW1.js +212 -0
  116. package/dist/command-secret-gateway-CqP_o0n8.js +106 -0
  117. package/dist/compact.runtime-Qm_csEtG.js +111 -0
  118. package/dist/completion-cli-Ch1sgSLQ.js +445 -0
  119. package/dist/completion-cli-vF067Tso.js +16 -0
  120. package/dist/config-B2W1zTP1.js +44 -0
  121. package/dist/config-CMhKplgO.js +938 -0
  122. package/dist/config-DchtRsvs.js +30 -0
  123. package/dist/config-cli-C41d88_c.js +428 -0
  124. package/dist/config-guard-B_vjkXCQ.js +117 -0
  125. package/dist/config-schema-pPBCF4hz.js +31 -0
  126. package/dist/config-validation-6om9cBUx.js +262 -0
  127. package/dist/config-value-Dl3XEpA6.js +132 -0
  128. package/dist/configure-BxzvDSzu.js +1100 -0
  129. package/dist/configure-CLMLoWAn.js +238 -0
  130. package/dist/control-ui-shared-E8Nz6uKZ.js +29 -0
  131. package/dist/core-Cd3fMFKq.d.ts +87 -0
  132. package/dist/credentials-yYt6VWCq.js +268 -0
  133. package/dist/cron-cli-CA3lV3kh.js +634 -0
  134. package/dist/daemon-cli-BtQuIXEk.js +339 -0
  135. package/dist/daemon-install-BWKGzgMm.js +175 -0
  136. package/dist/deliver-CgMNmfTy.js +106 -0
  137. package/dist/deliver-runtime-Bn1KWoiQ.js +106 -0
  138. package/dist/devices-cli-D601npiL.js +340 -0
  139. package/dist/diagnostic-CkiYEGqt.js +310 -0
  140. package/dist/diffs-B5tZ8Coj.d.ts +1 -0
  141. package/dist/directory-cli-skEV8MT7.js +306 -0
  142. package/dist/directory-config-helpers-B-tiBKIv.d.ts +38 -0
  143. package/dist/directory-runtime-BEJ2fCIR.d.ts +1 -0
  144. package/dist/directory.static-CnyzoWbV.js +44 -0
  145. package/dist/discord-B_gbzPti.js +109 -0
  146. package/dist/discovery-CqI-e_Mv.js +48 -0
  147. package/dist/dm-policy-shared-nybkS1uP.d.ts +95 -0
  148. package/dist/dns-cli-Cjes3Ruw.js +216 -0
  149. package/dist/docs-cli-C3g3Gi_d.js +173 -0
  150. package/dist/doctor-completion-TvgV4SZH.js +90 -0
  151. package/dist/doctor-config-flow-0w9Ux7V8.js +107 -0
  152. package/dist/doctor-config-flow-DLzr8W7Y.js +2437 -0
  153. package/dist/enable-VYzv8b2z.js +24 -0
  154. package/dist/entry.d.ts +7 -0
  155. package/dist/entry.js +1 -1
  156. package/dist/env-overrides-DYVIkuvN.js +434 -0
  157. package/dist/env-overrides.runtime-6kijpIuu.js +17 -0
  158. package/dist/exec-approvals-cli-D_lkTG-l.js +419 -0
  159. package/dist/exec-sVmouhA9.d.ts +39 -0
  160. package/dist/extensions/acpx/index.d.ts +11 -0
  161. package/dist/extensions/acpx/index.js +1 -1
  162. package/dist/extensions/amazon-bedrock/index.d.ts +11 -0
  163. package/dist/extensions/anthropic/index.d.ts +11 -0
  164. package/dist/extensions/anthropic/index.js +26 -26
  165. package/dist/extensions/bluebubbles/index.d.ts +11 -0
  166. package/dist/extensions/bluebubbles/index.js +30 -30
  167. package/dist/extensions/bluebubbles/setup-entry.d.ts +59 -0
  168. package/dist/extensions/bluebubbles/setup-entry.js +30 -30
  169. package/dist/extensions/brave/index.d.ts +11 -0
  170. package/dist/extensions/brave/index.js +2 -2
  171. package/dist/extensions/byteplus/index.d.ts +11 -0
  172. package/dist/extensions/byteplus/index.js +26 -26
  173. package/dist/extensions/cloudflare-ai-gateway/index.d.ts +11 -0
  174. package/dist/extensions/cloudflare-ai-gateway/index.js +27 -27
  175. package/dist/extensions/copilot-proxy/index.d.ts +11 -0
  176. package/dist/extensions/device-pair/index.d.ts +12 -0
  177. package/dist/extensions/diagnostics-otel/index.d.ts +11 -0
  178. package/dist/extensions/diffs/index.d.ts +11 -0
  179. package/dist/extensions/discord/index.d.ts +11 -0
  180. package/dist/extensions/discord/index.js +31 -31
  181. package/dist/extensions/discord/setup-entry.d.ts +7 -0
  182. package/dist/extensions/discord/setup-entry.js +29 -29
  183. package/dist/extensions/elevenlabs/index.d.ts +11 -0
  184. package/dist/extensions/elevenlabs/index.js +26 -26
  185. package/dist/extensions/feishu/index.d.ts +229 -0
  186. package/dist/extensions/feishu/index.js +31 -31
  187. package/dist/extensions/feishu/setup-entry.d.ts +9 -0
  188. package/dist/extensions/feishu/setup-entry.js +28 -28
  189. package/dist/extensions/firecrawl/index.d.ts +11 -0
  190. package/dist/extensions/firecrawl/index.js +26 -26
  191. package/dist/extensions/github-copilot/index.d.ts +11 -0
  192. package/dist/extensions/github-copilot/index.js +27 -27
  193. package/dist/extensions/google/index.d.ts +11 -0
  194. package/dist/extensions/google/index.js +26 -26
  195. package/dist/extensions/googlechat/index.d.ts +11 -0
  196. package/dist/extensions/googlechat/index.js +30 -30
  197. package/dist/extensions/googlechat/setup-entry.d.ts +19 -0
  198. package/dist/extensions/googlechat/setup-entry.js +30 -30
  199. package/dist/extensions/huggingface/index.d.ts +11 -0
  200. package/dist/extensions/huggingface/index.js +26 -26
  201. package/dist/extensions/imessage/index.d.ts +11 -0
  202. package/dist/extensions/imessage/index.js +30 -30
  203. package/dist/extensions/imessage/setup-entry.d.ts +7 -0
  204. package/dist/extensions/imessage/setup-entry.js +30 -30
  205. package/dist/extensions/irc/index.d.ts +11 -0
  206. package/dist/extensions/irc/index.js +29 -29
  207. package/dist/extensions/irc/setup-entry.d.ts +8 -0
  208. package/dist/extensions/irc/setup-entry.js +29 -29
  209. package/dist/extensions/kakao-talkchannel/index.d.ts +19 -0
  210. package/dist/extensions/kakao-talkchannel/index.js +1762 -0
  211. package/dist/extensions/kakao-talkchannel/moldclaw.plugin.json +111 -0
  212. package/dist/extensions/kakao-talkchannel/package.json +12 -0
  213. package/dist/extensions/kilocode/index.d.ts +11 -0
  214. package/dist/extensions/kilocode/index.js +26 -26
  215. package/dist/extensions/kimi-coding/index.d.ts +11 -0
  216. package/dist/extensions/kimi-coding/index.js +26 -26
  217. package/dist/extensions/line/index.d.ts +11 -0
  218. package/dist/extensions/line/index.js +28 -28
  219. package/dist/extensions/line/setup-entry.d.ts +7 -0
  220. package/dist/extensions/line/setup-entry.js +28 -28
  221. package/dist/extensions/llm-task/index.d.ts +11 -0
  222. package/dist/extensions/llm-task/index.js +28 -28
  223. package/dist/extensions/lobster/index.d.ts +11 -0
  224. package/dist/extensions/matrix/index.d.ts +11 -0
  225. package/dist/extensions/matrix/index.js +31 -31
  226. package/dist/extensions/matrix/setup-entry.d.ts +20 -0
  227. package/dist/extensions/matrix/setup-entry.js +31 -31
  228. package/dist/extensions/mattermost/index.d.ts +11 -0
  229. package/dist/extensions/mattermost/index.js +28 -28
  230. package/dist/extensions/mattermost/setup-entry.d.ts +88 -0
  231. package/dist/extensions/mattermost/setup-entry.js +28 -28
  232. package/dist/extensions/memory-core/index.d.ts +11 -0
  233. package/dist/extensions/memory-lancedb/index.d.ts +25 -0
  234. package/dist/extensions/microsoft/index.d.ts +11 -0
  235. package/dist/extensions/microsoft/index.js +26 -26
  236. package/dist/extensions/minimax/index.d.ts +11 -0
  237. package/dist/extensions/minimax/index.js +26 -26
  238. package/dist/extensions/mistral/index.d.ts +11 -0
  239. package/dist/extensions/mistral/index.js +26 -26
  240. package/dist/extensions/modelstudio/index.d.ts +11 -0
  241. package/dist/extensions/modelstudio/index.js +26 -26
  242. package/dist/extensions/moonshot/index.d.ts +11 -0
  243. package/dist/extensions/moonshot/index.js +26 -26
  244. package/dist/extensions/msteams/index.d.ts +11 -0
  245. package/dist/extensions/msteams/index.js +31 -31
  246. package/dist/extensions/msteams/setup-entry.d.ts +11 -0
  247. package/dist/extensions/msteams/setup-entry.js +31 -31
  248. package/dist/extensions/nextcloud-talk/index.d.ts +11 -0
  249. package/dist/extensions/nextcloud-talk/index.js +28 -28
  250. package/dist/extensions/nextcloud-talk/setup-entry.d.ts +60 -0
  251. package/dist/extensions/nextcloud-talk/setup-entry.js +28 -28
  252. package/dist/extensions/nostr/index.d.ts +11 -0
  253. package/dist/extensions/nostr/index.js +28 -28
  254. package/dist/extensions/nostr/setup-entry.d.ts +49 -0
  255. package/dist/extensions/nostr/setup-entry.js +28 -28
  256. package/dist/extensions/nvidia/index.d.ts +11 -0
  257. package/dist/extensions/ollama/index.d.ts +11 -0
  258. package/dist/extensions/open-prose/index.d.ts +11 -0
  259. package/dist/extensions/openai/index.d.ts +11 -0
  260. package/dist/extensions/openai/index.js +26 -26
  261. package/dist/extensions/opencode/index.d.ts +11 -0
  262. package/dist/extensions/opencode/index.js +26 -26
  263. package/dist/extensions/opencode-go/index.d.ts +11 -0
  264. package/dist/extensions/opencode-go/index.js +26 -26
  265. package/dist/extensions/openrouter/index.d.ts +11 -0
  266. package/dist/extensions/openrouter/index.js +26 -26
  267. package/dist/extensions/openshell/index.d.ts +11 -0
  268. package/dist/extensions/openshell/index.js +26 -26
  269. package/dist/extensions/perplexity/index.d.ts +11 -0
  270. package/dist/extensions/perplexity/index.js +2 -2
  271. package/dist/extensions/phone-control/index.d.ts +12 -0
  272. package/dist/extensions/qianfan/index.d.ts +11 -0
  273. package/dist/extensions/qianfan/index.js +26 -26
  274. package/dist/extensions/qwen-portal-auth/index.d.ts +12 -0
  275. package/dist/extensions/qwen-portal-auth/index.js +26 -26
  276. package/dist/extensions/sglang/index.d.ts +11 -0
  277. package/dist/extensions/sglang/index.js +26 -26
  278. package/dist/extensions/signal/index.d.ts +11 -0
  279. package/dist/extensions/signal/index.js +29 -29
  280. package/dist/extensions/signal/setup-entry.d.ts +7 -0
  281. package/dist/extensions/signal/setup-entry.js +29 -29
  282. package/dist/extensions/slack/index.d.ts +11 -0
  283. package/dist/extensions/slack/index.js +30 -30
  284. package/dist/extensions/slack/setup-entry.d.ts +7 -0
  285. package/dist/extensions/slack/setup-entry.js +29 -29
  286. package/dist/extensions/synology-chat/index.d.ts +11 -0
  287. package/dist/extensions/synology-chat/index.js +28 -28
  288. package/dist/extensions/synology-chat/setup-entry.d.ts +138 -0
  289. package/dist/extensions/synology-chat/setup-entry.js +28 -28
  290. package/dist/extensions/synthetic/index.d.ts +11 -0
  291. package/dist/extensions/synthetic/index.js +26 -26
  292. package/dist/extensions/talk-voice/index.d.ts +12 -0
  293. package/dist/extensions/talk-voice/index.js +26 -26
  294. package/dist/extensions/telegram/index.d.ts +11 -0
  295. package/dist/extensions/telegram/index.js +29 -29
  296. package/dist/extensions/telegram/setup-entry.d.ts +7 -0
  297. package/dist/extensions/telegram/setup-entry.js +28 -28
  298. package/dist/extensions/thread-ownership/index.d.ts +12 -0
  299. package/dist/extensions/tlon/index.d.ts +11 -0
  300. package/dist/extensions/tlon/index.js +28 -28
  301. package/dist/extensions/tlon/setup-entry.d.ts +7 -0
  302. package/dist/extensions/tlon/setup-entry.js +28 -28
  303. package/dist/extensions/together/index.d.ts +11 -0
  304. package/dist/extensions/together/index.js +26 -26
  305. package/dist/extensions/twitch/index.d.ts +39 -0
  306. package/dist/extensions/twitch/index.js +28 -28
  307. package/dist/extensions/venice/index.d.ts +11 -0
  308. package/dist/extensions/venice/index.js +26 -26
  309. package/dist/extensions/vercel-ai-gateway/index.d.ts +11 -0
  310. package/dist/extensions/vercel-ai-gateway/index.js +26 -26
  311. package/dist/extensions/vllm/index.d.ts +11 -0
  312. package/dist/extensions/vllm/index.js +26 -26
  313. package/dist/extensions/voice-call/index.d.ts +11 -0
  314. package/dist/extensions/voice-call/index.js +26 -26
  315. package/dist/extensions/volcengine/index.d.ts +11 -0
  316. package/dist/extensions/volcengine/index.js +26 -26
  317. package/dist/extensions/whatsapp/index.d.ts +11 -0
  318. package/dist/extensions/whatsapp/index.js +29 -29
  319. package/dist/extensions/whatsapp/setup-entry.d.ts +7 -0
  320. package/dist/extensions/whatsapp/setup-entry.js +29 -29
  321. package/dist/extensions/xai/index.d.ts +11 -0
  322. package/dist/extensions/xai/index.js +26 -26
  323. package/dist/extensions/xiaomi/index.d.ts +11 -0
  324. package/dist/extensions/xiaomi/index.js +26 -26
  325. package/dist/extensions/zai/index.d.ts +11 -0
  326. package/dist/extensions/zai/index.js +26 -26
  327. package/dist/extensions/zalo/index.d.ts +11 -0
  328. package/dist/extensions/zalo/index.js +30 -30
  329. package/dist/extensions/zalo/setup-entry.d.ts +34 -0
  330. package/dist/extensions/zalo/setup-entry.js +30 -30
  331. package/dist/extensions/zalouser/index.d.ts +11 -0
  332. package/dist/extensions/zalouser/index.js +31 -31
  333. package/dist/extensions/zalouser/setup-entry.d.ts +42 -0
  334. package/dist/extensions/zalouser/setup-entry.js +31 -31
  335. package/dist/feishu-DCKEC3ao.d.ts +36 -0
  336. package/dist/gateway-cli-DN1Ii6J-.js +26432 -0
  337. package/dist/gateway-install-token-CJYFJBaC.js +163 -0
  338. package/dist/gateway-rpc-CroQg9MB.js +26 -0
  339. package/dist/gateway-runtime-D9FRZqKP.js +69 -0
  340. package/dist/googlechat-CBCkerAy.js +307 -0
  341. package/dist/googlechat-CSUNieHX.d.ts +12 -0
  342. package/dist/group-access-rSvkIglb.d.ts +61 -0
  343. package/dist/health-B6WwLJp4.js +570 -0
  344. package/dist/health-CAlJydXv.js +108 -0
  345. package/dist/history-BwNxb0sJ.d.ts +75 -0
  346. package/dist/hooks-BYlfU3Nf.d.ts +6 -0
  347. package/dist/hooks-cli-DuKmdo_H.js +995 -0
  348. package/dist/http-registry-DX_LVtuK.d.ts +20 -0
  349. package/dist/image-generation-DKkdRpve.d.ts +9 -0
  350. package/dist/imessage-7abjbe2Q.js +31 -0
  351. package/dist/imessage-DOH1yaDE.js +110 -0
  352. package/dist/inbound-envelope-CmvweL6U.d.ts +78 -0
  353. package/dist/inbound-reply-dispatch-BvnKTOec.js +71 -0
  354. package/dist/inbound-reply-dispatch-C7LjHRZN.d.ts +72 -0
  355. package/dist/index-DTQqfqj9.d.ts +1 -0
  356. package/dist/index.d.ts +27 -0
  357. package/dist/index.js +2 -2
  358. package/dist/infra/warning-filter.d.ts +10 -0
  359. package/dist/install-target-tXRD7VkM.js +574 -0
  360. package/dist/installs-C8fz8sm3.js +532 -0
  361. package/dist/io-C6XifaT4.js +9737 -0
  362. package/dist/io-C8awRnSW.js +28 -0
  363. package/dist/ipv4-d88_Jn2p.js +82 -0
  364. package/dist/irc-DpR6FXjN.js +672 -0
  365. package/dist/json-store-Sr_kk-II.d.ts +14 -0
  366. package/dist/keyed-async-queue-BA3BKukE.d.ts +19 -0
  367. package/dist/library-DOwowAGN.js +107 -0
  368. package/dist/lifecycle-core-BHHBoRTY.js +382 -0
  369. package/dist/line/accounts.d.ts +3 -0
  370. package/dist/line/send.d.ts +2 -0
  371. package/dist/line/send.js +4 -4
  372. package/dist/line/template-messages.d.ts +2 -0
  373. package/dist/line-8rsNbJCP.js +530 -0
  374. package/dist/line-D_cvIf6B.d.ts +75 -0
  375. package/dist/links-BOnvOj1z.d.ts +7 -0
  376. package/dist/llm-slug-generator-D9HjWtJT.js +67 -0
  377. package/dist/llm-slug-generator.d.ts +12 -0
  378. package/dist/llm-slug-generator.js +27 -27
  379. package/dist/logging-BhqLWxTD.js +13 -0
  380. package/dist/logging-DfaiL4OX.js +29 -0
  381. package/dist/login-qr-COBYR52w.js +233 -0
  382. package/dist/login-qr-xK4QIpPc.js +107 -0
  383. package/dist/logs-cli-RSSTw8L_.js +254 -0
  384. package/dist/manager-runtime-DL6JoSj9.js +106 -0
  385. package/dist/manager.runtime-Cbyhg1vB.js +710 -0
  386. package/dist/markdown-to-line-BTlEkOls.d.ts +91 -0
  387. package/dist/matrix-DX-jaB88.js +1490 -0
  388. package/dist/matrix-H6Yyj1QZ.d.ts +68 -0
  389. package/dist/matrix-J8s45tRw.js +1269 -0
  390. package/dist/mattermost-D75n6bRI.d.ts +6 -0
  391. package/dist/mcp-cli-CLc3_yCO.js +86 -0
  392. package/dist/media-understanding.runtime-BI0Lljbl.js +111 -0
  393. package/dist/memory-cli-CTp2cYrf.js +106 -0
  394. package/dist/method-scopes-Du8ODGFW.js +2586 -0
  395. package/dist/model-auth-markers-DEDakSUW.d.ts +20 -0
  396. package/dist/model-picker-CDBs7LJF.js +390 -0
  397. package/dist/model-picker-CRix4Wwv.js +107 -0
  398. package/dist/model-picker.runtime-CITyy3Rn.js +120 -0
  399. package/dist/model-suppression.runtime-Ce7D6QUT.js +111 -0
  400. package/dist/models-BK1eanuP.js +113 -0
  401. package/dist/models-X4Czy3uE.js +2514 -0
  402. package/dist/models-cli-C79Ulviy.js +304 -0
  403. package/dist/models-config-DALlu3S9.js +106 -0
  404. package/dist/models-config.providers.discovery-CSJ1STM1.d.ts +18 -0
  405. package/dist/monitor-B45a_RpX.js +3468 -0
  406. package/dist/monitor-C8KbJ-i0.js +767 -0
  407. package/dist/monitor-CIhrvegZ.js +3076 -0
  408. package/dist/monitor-CQut7klP.js +6823 -0
  409. package/dist/monitor-DZb5IJle.js +777 -0
  410. package/dist/monitor-DaFkdD27.js +108 -0
  411. package/dist/monitor-Do9Tp2Ii.js +110 -0
  412. package/dist/monitor-shared-CMK9cDOb.js +444 -0
  413. package/dist/msteams-A6H_wv5F.js +852 -0
  414. package/dist/net-DpMJgN-o.d.ts +19 -0
  415. package/dist/nextcloud-talk-f1pZ5Bge.d.ts +1 -0
  416. package/dist/node-cli-BXnmsjzL.js +2498 -0
  417. package/dist/node-resolve-CupmrA0Y.js +835 -0
  418. package/dist/nodes-cli-DZVrah_8.js +1375 -0
  419. package/dist/nostr-DMV534Ks.d.ts +7 -0
  420. package/dist/nostr-SAk3tjtR.js +8744 -0
  421. package/dist/npm-resolution-Dr9wssCY.js +60 -0
  422. package/dist/oauth-utils-DnyXdWU9.d.ts +10 -0
  423. package/dist/onboard-BE5pmb1g.js +589 -0
  424. package/dist/onboard-channels-3hNVY0E7.js +1241 -0
  425. package/dist/onboard-channels-vaO3nWLL.js +200 -0
  426. package/dist/onboard-custom-CI5uFyWH.js +571 -0
  427. package/dist/onboard-custom-eIvRswgv.js +109 -0
  428. package/dist/onboard-helpers-ChMWfUnl.js +335 -0
  429. package/dist/onboard-helpers-DRFi9oaD.js +108 -0
  430. package/dist/onboard-remote-BTspTgA4.js +112 -0
  431. package/dist/onboard-remote-so38yXlX.js +181 -0
  432. package/dist/onboard-search-DS0tZS24.js +297 -0
  433. package/dist/onboard-skills-B9DxCCiU.js +133 -0
  434. package/dist/onboard-skills-so0a_BJV.js +112 -0
  435. package/dist/outbound-media-BiJscGlR.js +11 -0
  436. package/dist/outbound-media-DJF-TuJu.d.ts +11 -0
  437. package/dist/pairing-access-CuiJP9xN.d.ts +21 -0
  438. package/dist/pairing-cli-DN0u1Cez.js +212 -0
  439. package/dist/parse-finite-number-B3FJTjyQ.d.ts +5 -0
  440. package/dist/perplexity-Bw1u3CAF.js +24 -0
  441. package/dist/persistent-dedupe-DR5Ka6BX.d.ts +26 -0
  442. package/dist/pi-model-discovery-runtime-iwKNCaYu.js +106 -0
  443. package/dist/pi-tools.before-tool-call.runtime-BM_N-JZe.js +380 -0
  444. package/dist/plugin-install--KVul05Z.js +184 -0
  445. package/dist/plugin-install-DVpPsLkS.js +112 -0
  446. package/dist/plugin-install-plan-Dwc6-coz.js +49 -0
  447. package/dist/plugin-registry-XRswugE9.js +108 -0
  448. package/dist/plugin-registry-jozQafRo.js +49 -0
  449. package/dist/plugin-sdk/account-resolution.js +26 -26
  450. package/dist/plugin-sdk/acp-runtime.js +26 -26
  451. package/dist/plugin-sdk/acpx.js +1 -1
  452. package/dist/plugin-sdk/agent-runtime.js +26 -26
  453. package/dist/plugin-sdk/bluebubbles.js +29 -29
  454. package/dist/plugin-sdk/channel-config-helpers.js +26 -26
  455. package/dist/plugin-sdk/channel-config-schema.js +2 -2
  456. package/dist/plugin-sdk/channel-policy.js +26 -26
  457. package/dist/plugin-sdk/channel-runtime.js +26 -26
  458. package/dist/plugin-sdk/compat.js +27 -27
  459. package/dist/plugin-sdk/config-runtime.js +28 -28
  460. package/dist/plugin-sdk/conversation-runtime.js +26 -26
  461. package/dist/plugin-sdk/discord.js +26 -26
  462. package/dist/plugin-sdk/feishu.js +27 -27
  463. package/dist/plugin-sdk/gateway-runtime.js +8 -8
  464. package/dist/plugin-sdk/googlechat.js +29 -29
  465. package/dist/plugin-sdk/image-generation-runtime.js +26 -26
  466. package/dist/plugin-sdk/image-generation.js +26 -26
  467. package/dist/plugin-sdk/imessage.js +27 -27
  468. package/dist/plugin-sdk/index.js +26 -26
  469. package/dist/plugin-sdk/infra-runtime.js +26 -26
  470. package/dist/plugin-sdk/irc.js +29 -29
  471. package/dist/plugin-sdk/line.js +27 -27
  472. package/dist/plugin-sdk/llm-task.js +26 -26
  473. package/dist/plugin-sdk/matrix.js +29 -29
  474. package/dist/plugin-sdk/mattermost.js +28 -28
  475. package/dist/plugin-sdk/media-runtime.js +26 -26
  476. package/dist/plugin-sdk/media-understanding-runtime.js +26 -26
  477. package/dist/plugin-sdk/media-understanding.js +26 -26
  478. package/dist/plugin-sdk/msteams.js +30 -30
  479. package/dist/plugin-sdk/nextcloud-talk.js +28 -28
  480. package/dist/plugin-sdk/nostr.js +27 -27
  481. package/dist/plugin-sdk/plugin-runtime.js +26 -26
  482. package/dist/plugin-sdk/provider-auth.js +28 -28
  483. package/dist/plugin-sdk/provider-setup.js +27 -27
  484. package/dist/plugin-sdk/provider-web-search.js +1 -1
  485. package/dist/plugin-sdk/qwen-portal-auth.js +26 -26
  486. package/dist/plugin-sdk/reply-history.js +26 -26
  487. package/dist/plugin-sdk/reply-runtime.js +26 -26
  488. package/dist/plugin-sdk/sandbox.js +26 -26
  489. package/dist/plugin-sdk/security-runtime.js +26 -26
  490. package/dist/plugin-sdk/self-hosted-provider-setup.js +27 -27
  491. package/dist/plugin-sdk/setup.js +27 -27
  492. package/dist/plugin-sdk/signal.js +26 -26
  493. package/dist/plugin-sdk/slack.js +26 -26
  494. package/dist/plugin-sdk/speech-runtime.js +26 -26
  495. package/dist/plugin-sdk/speech.js +26 -26
  496. package/dist/plugin-sdk/src/channels/plugins/setup-wizard-helpers.d.ts +3 -0
  497. package/dist/plugin-sdk/src/config/config-lock.d.ts +38 -0
  498. package/dist/plugin-sdk/src/config/config.d.ts +1 -1
  499. package/dist/plugin-sdk/src/config/io.d.ts +39 -0
  500. package/dist/plugin-sdk/src/config/types.gateway.d.ts +12 -0
  501. package/dist/plugin-sdk/src/config/types.secrets.d.ts +10 -0
  502. package/dist/plugin-sdk/src/config/zod-schema.d.ts +2 -0
  503. package/dist/plugin-sdk/src/gateway/credential-planner.d.ts +3 -1
  504. package/dist/plugin-sdk/src/secrets/provider-env-vars.d.ts +61 -0
  505. package/dist/plugin-sdk/src/secrets/sec1-placeholder.d.ts +181 -0
  506. package/dist/plugin-sdk/src/secrets/sec1-utils.d.ts +57 -0
  507. package/dist/plugin-sdk/synology-chat.js +27 -27
  508. package/dist/plugin-sdk/telegram.js +26 -26
  509. package/dist/plugin-sdk/text-runtime.js +4 -4
  510. package/dist/plugin-sdk/tlon.js +27 -27
  511. package/dist/plugin-sdk/twitch.js +26 -26
  512. package/dist/plugin-sdk/voice-call.js +26 -26
  513. package/dist/plugin-sdk/whatsapp.js +26 -26
  514. package/dist/plugin-sdk/zalo.js +30 -30
  515. package/dist/plugin-sdk/zalouser.js +29 -29
  516. package/dist/plugins/runtime/index.d.ts +22 -0
  517. package/dist/plugins/runtime/index.js +26 -26
  518. package/dist/plugins-C4PiDdjc.js +106 -0
  519. package/dist/plugins-cli-zhmliYNU.js +912 -0
  520. package/dist/policy-CcSolumc.js +143 -0
  521. package/dist/preflight-audio.runtime-BAbfqqzW.js +111 -0
  522. package/dist/probe-Bgt5c-cr.js +129 -0
  523. package/dist/probe-CPk5iGcg.js +47 -0
  524. package/dist/probe-DR4KRKXz.js +19 -0
  525. package/dist/probe-DnoCyJ_m.js +1793 -0
  526. package/dist/probe-VsLtK3vQ.js +6328 -0
  527. package/dist/probe-auth-BnsKrQt7.js +38 -0
  528. package/dist/probe-auth-DYdUG8l1.js +48 -0
  529. package/dist/program-8enYYBsc.js +247 -0
  530. package/dist/prompt-select-styled-DxBcUasv.js +2673 -0
  531. package/dist/provider-api-key-auth.runtime-DsLZyt6h.js +116 -0
  532. package/dist/provider-auth-choice-30EvRxqc.js +126 -0
  533. package/dist/provider-auth-choice-preference-DMr1WmRg.js +189 -0
  534. package/dist/provider-auth-choice.runtime-CI98BgQF.js +118 -0
  535. package/dist/provider-auth-guidance-WKDIi_wk.js +34 -0
  536. package/dist/provider-auth-result-Cs8wguSI.d.ts +18 -0
  537. package/dist/provider-models-EOys_Nvi.d.ts +867 -0
  538. package/dist/provider-ollama-setup-D89zlm9C.d.ts +32 -0
  539. package/dist/provider-onboard-BzOpgCLu.d.ts +40 -0
  540. package/dist/provider-runtime.runtime-Cm4as2KG.js +106 -0
  541. package/dist/provider-self-hosted-setup-Bmv_AQmw.d.ts +61 -0
  542. package/dist/provider-self-hosted-setup-CJwFVVB4.js +182 -0
  543. package/dist/provider-usage-CVNyLLDb.js +106 -0
  544. package/dist/provider-usage.types-CdTymHNu.d.ts +16 -0
  545. package/dist/provider-web-search-BJhXD5dH.js +2392 -0
  546. package/dist/provider-wizard-DMMYXjlW.js +152 -0
  547. package/dist/push-apns-BnWTdTEk.js +1038 -0
  548. package/dist/pw-ai-CtK_7Cy2.js +1866 -0
  549. package/dist/qr-cli-CA-BF0--.js +108 -0
  550. package/dist/qr-cli-D18HiUkh.js +369 -0
  551. package/dist/reactions-Df7XG8Uh.js +281 -0
  552. package/dist/read-only-account-inspect.discord.runtime-B-FP0mwb.js +111 -0
  553. package/dist/read-only-account-inspect.slack.runtime-DkWZ2ccW.js +111 -0
  554. package/dist/read-only-account-inspect.telegram.runtime-BnlTkn_e.js +111 -0
  555. package/dist/redact-snapshot-DVdstBvO.js +2661 -0
  556. package/dist/ref-contract-RPkB754Q.js +53 -0
  557. package/dist/register.agent-DVAxXQKW.js +434 -0
  558. package/dist/register.backup-CUuL5KUZ.js +624 -0
  559. package/dist/register.configure-bC0UEwfU.js +247 -0
  560. package/dist/register.maintenance-iIqvl_eT.js +569 -0
  561. package/dist/register.message-CEDd4z07.js +704 -0
  562. package/dist/register.onboard-Cejfnysy.js +187 -0
  563. package/dist/register.setup-DU7uHdYt.js +207 -0
  564. package/dist/register.status-health-sessions-BWphMXNR.js +493 -0
  565. package/dist/register.subclis-DnIweTEG.js +315 -0
  566. package/dist/register.subclis-gJX_Pbub.js +12 -0
  567. package/dist/registry-Dgwc-7eS.js +1183 -0
  568. package/dist/replies-D9PEZ8yn.js +110 -0
  569. package/dist/reply-history-lHgoC4l3.d.ts +1 -0
  570. package/dist/reply-payload-Bd2HuR4g.d.ts +46 -0
  571. package/dist/request-url-BcSJaiiu.d.ts +5 -0
  572. package/dist/resolve-BbsCHGLY.js +660 -0
  573. package/dist/resolve-channels-BtrGC95o.js +262 -0
  574. package/dist/resolve-channels-C1SthO1N.js +226 -0
  575. package/dist/resolve-users-CgSxHrU0.js +143 -0
  576. package/dist/routes-BZtqNrBf.js +7097 -0
  577. package/dist/rpc-D3KMxG4J.js +67 -0
  578. package/dist/run-command-C8b3dCZV.d.ts +16 -0
  579. package/dist/run-main-BlWJVotF.js +423 -0
  580. package/dist/runtime-RWGbO5Qy.d.ts +26 -0
  581. package/dist/runtime-discord-ops.runtime-DUXIYvQr.js +9073 -0
  582. package/dist/runtime-slack-ops.runtime-n1yFfyp1.js +4551 -0
  583. package/dist/runtime-telegram-ops.runtime-PZUWchjT.js +128 -0
  584. package/dist/runtime-whatsapp-login.runtime-xsuNyvGz.js +109 -0
  585. package/dist/runtime-whatsapp-outbound.runtime-5EfEyCsO.js +112 -0
  586. package/dist/sandbox-cli-Dw1nWNmQ.js +530 -0
  587. package/dist/search-manager-BJoRxOaf.js +15 -0
  588. package/dist/search-manager-DxkQvUrW.js +386 -0
  589. package/dist/secret-input-schema-Cp_La9qv.d.ts +19 -0
  590. package/dist/secrets-cli-BPyV2gSq.js +2065 -0
  591. package/dist/security-cli-EK4sSRfG.js +570 -0
  592. package/dist/send-B01Gvh9m.js +629 -0
  593. package/dist/send-B4L4wRJO.js +100 -0
  594. package/dist/send-BDcGrXt0.js +1025 -0
  595. package/dist/send-BRRtHxyR.js +283 -0
  596. package/dist/send-DU6dmMXW.js +631 -0
  597. package/dist/server-CWw5GFEg.js +106 -0
  598. package/dist/server-node-events-92cDVswC.js +501 -0
  599. package/dist/session-key-DbkfhOjM.d.ts +46 -0
  600. package/dist/sessions-B052uHA3.js +218 -0
  601. package/dist/sessions-Cef4dZNP.js +107 -0
  602. package/dist/setup-BlQPyDPy.js +387 -0
  603. package/dist/setup-DcSZ_pTn.d.ts +37 -0
  604. package/dist/setup-core-B9mdZYnU.js +166 -0
  605. package/dist/setup-core-Cj0sLkpP.js +47 -0
  606. package/dist/setup-core-CkZbebOv.js +143 -0
  607. package/dist/setup-core-MRNjnrJl.js +205 -0
  608. package/dist/setup-surface-3ZY0JtWE.js +490 -0
  609. package/dist/setup-wizard-helpers-Dwzb9Dcz.d.ts +203 -0
  610. package/dist/setup.finalize-B5ETm3Ui.js +517 -0
  611. package/dist/setup.gateway-config-C8hdtlbw.js +338 -0
  612. package/dist/setup.secret-input-BZSIeiqy.js +25 -0
  613. package/dist/shared--9_eQ_lc.js +75 -0
  614. package/dist/shared-CxkH3H0U.js +102 -0
  615. package/dist/shared-DTNL0hA9.js +298 -0
  616. package/dist/shared-HSP1OV-Q.js +96 -0
  617. package/dist/shared-UIjWb_3B.js +182 -0
  618. package/dist/signal-CTI6bSmB.js +109 -0
  619. package/dist/skills-4-r1mfJM.js +853 -0
  620. package/dist/skills-RNm54CBO.js +19 -0
  621. package/dist/skills-cli-te7dSs5p.js +291 -0
  622. package/dist/skills-install-Del-Ogv8.js +763 -0
  623. package/dist/skills-status-BZpoMXrR.js +169 -0
  624. package/dist/skills-status-Dq61Sz8U.js +20 -0
  625. package/dist/slack-oc-viUtl.js +109 -0
  626. package/dist/slash-commands.runtime-NdkD2LZV.js +123 -0
  627. package/dist/slash-dispatch.runtime-DQgeaF3J.js +136 -0
  628. package/dist/slash-skill-commands.runtime-DmOl2DnL.js +111 -0
  629. package/dist/src-0wtt7seR.js +1696 -0
  630. package/dist/status-5oR_gqv_.js +121 -0
  631. package/dist/status-BO8LY0hC.js +1599 -0
  632. package/dist/status-D_oHA9yO.js +126 -0
  633. package/dist/status-IrMacJRj.js +606 -0
  634. package/dist/status-Prdeg53E.js +43 -0
  635. package/dist/status-json-Da0hR-1Z.js +286 -0
  636. package/dist/status.link-channel-BgUJEZAz.js +138 -0
  637. package/dist/status.scan.deps.runtime-D9vHTxOW.js +121 -0
  638. package/dist/status.scan.runtime-D-EdD5CW.js +114 -0
  639. package/dist/status.summary--i6xduWH.js +592 -0
  640. package/dist/status.summary.runtime-BqMXjaBc.js +113 -0
  641. package/dist/subagent-orphan-recovery-DiRJcFQc.js +302 -0
  642. package/dist/subagent-registry-runtime-B66EYEYm.js +106 -0
  643. package/dist/synology-chat-BemXqdzG.js +297 -0
  644. package/dist/system-cli-CSuiia4-.js +92 -0
  645. package/dist/telegram/audit.d.ts +2 -0
  646. package/dist/telegram/audit.js +1 -1
  647. package/dist/telegram/token.d.ts +2 -0
  648. package/dist/telegram/token.js +26 -26
  649. package/dist/telegram-DLFcRv5a.js +109 -0
  650. package/dist/testing-DZrulv-n.d.ts +1755 -0
  651. package/dist/text-chunking-BaYBIUoR.d.ts +79 -0
  652. package/dist/text-chunking-C8kmbNfa.js +84 -0
  653. package/dist/thinking-D8aqmr3o.d.ts +13 -0
  654. package/dist/tlon-Bpr4f3yF.js +433 -0
  655. package/dist/tool-send-BHKm5ztm.d.ts +9 -0
  656. package/dist/tui-BY3QRgC1.js +3834 -0
  657. package/dist/tui-cli-CCfZOlV0.js +132 -0
  658. package/dist/types-CKx5nDZB.d.ts +45 -0
  659. package/dist/types-DBhDdMQd.d.ts +22670 -0
  660. package/dist/types.base-B_TkkSS8.d.ts +188 -0
  661. package/dist/types.secrets-Bojc4omL.js +92 -0
  662. package/dist/ui-1UpZZyI3.js +31 -0
  663. package/dist/update-BR4JvFpV.js +1036 -0
  664. package/dist/update-cli-BZv44lFq.js +1498 -0
  665. package/dist/update-offset-store-DGdBotIW.js +107 -0
  666. package/dist/update-runner-D34sooPe.js +1496 -0
  667. package/dist/vllm-defaults-BCGSJ7K0.d.ts +13 -0
  668. package/dist/wait-BU9vJv22.d.ts +4 -0
  669. package/dist/web-CXpU2D41.js +107 -0
  670. package/dist/web-shared-B4sL45ah.d.ts +45 -0
  671. package/dist/webhook-memory-guards-B7oLVseG.d.ts +43 -0
  672. package/dist/webhook-request-guards-CqIH7equ.d.ts +76 -0
  673. package/dist/webhook-targets-CAAGATtk.js +181 -0
  674. package/dist/webhook-targets-oQ0jd4r0.d.ts +106 -0
  675. package/dist/webhooks-cli-B46t2VT5.js +349 -0
  676. package/dist/whatsapp-Dniwd4Rv.js +109 -0
  677. package/dist/whatsapp-actions-fL46PsNs.js +162 -0
  678. package/dist/windows-spawn-DGeE98SH.d.ts +43 -0
  679. package/dist/workspace-dirs-d3Ms_ryk.js +2002 -0
  680. package/dist/zalo-Csulx0XK.d.ts +9 -0
  681. package/dist/zalo-gh0yAWmS.js +415 -0
  682. package/dist/zalouser-CuxRvztM.js +30911 -0
  683. package/dist/zod-schema.agent-runtime-B4MkB-_3.d.ts +10 -0
  684. package/dist/zod-schema.core-D5reNip6.js +541 -0
  685. package/dist/zod-schema.core-DN3RhEUG.d.ts +173 -0
  686. package/docs/SEC1.md +523 -0
  687. package/docs/SEC1_IMPLEMENTATION/CHANNELS_REPORT.md +173 -0
  688. package/docs/SEC1_IMPLEMENTATION/CORE_UTIL_REPORT.md +139 -0
  689. package/docs/SEC1_IMPLEMENTATION/DOCS_REPORT.md +134 -0
  690. package/docs/SEC1_IMPLEMENTATION/ENV_MAP_DRAFT.md +148 -0
  691. package/docs/SEC1_IMPLEMENTATION/INTEGRATION_REPORT.md +170 -0
  692. package/docs/SEC1_IMPLEMENTATION/PROVIDERS_REPORT.md +291 -0
  693. package/docs/SEC1_IMPLEMENTATION/QA_REPORT.md +249 -0
  694. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave1-channels.md +317 -0
  695. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave1-docs.md +212 -0
  696. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave1-security.md +368 -0
  697. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave2-critic-consolidated.md +195 -0
  698. package/docs/SEC1_IMPLEMENTATION/RECURSIVE_QA/wave3-fix-report.md +105 -0
  699. package/docs/SEC1_IMPLEMENTATION/STRATEGY.md +451 -0
  700. package/docs/SEC1_IMPLEMENTATION/TEST_REPORT.md +156 -0
  701. package/docs/pipeline-sdk/CLI_SPEC.md +609 -0
  702. package/docs/pipeline-sdk/PIPELINE_SDK_DESIGN.md +1372 -0
  703. package/extensions/kakao-talkchannel/MIGRATION_ARCH_ANALYSIS.md +455 -0
  704. package/extensions/kakao-talkchannel/MIGRATION_CODE_ANALYSIS.md +383 -0
  705. package/extensions/kakao-talkchannel/MIGRATION_STRATEGY.md +115 -0
  706. package/extensions/kakao-talkchannel/README.md +50 -0
  707. package/extensions/kakao-talkchannel/index.ts +20 -0
  708. package/extensions/kakao-talkchannel/moldclaw.plugin.json +98 -0
  709. package/extensions/kakao-talkchannel/package.json +12 -0
  710. package/extensions/kakao-talkchannel/src/adapters/config.ts +132 -0
  711. package/extensions/kakao-talkchannel/src/adapters/gateway.ts +974 -0
  712. package/extensions/kakao-talkchannel/src/adapters/outbound.ts +52 -0
  713. package/extensions/kakao-talkchannel/src/adapters/pairing.ts +35 -0
  714. package/extensions/kakao-talkchannel/src/adapters/security.ts +57 -0
  715. package/extensions/kakao-talkchannel/src/adapters/setup.ts +105 -0
  716. package/extensions/kakao-talkchannel/src/adapters/status.ts +117 -0
  717. package/extensions/kakao-talkchannel/src/channel.ts +58 -0
  718. package/extensions/kakao-talkchannel/src/commands/card.ts +413 -0
  719. package/extensions/kakao-talkchannel/src/config/schema.ts +129 -0
  720. package/extensions/kakao-talkchannel/src/kakao/callback.ts +133 -0
  721. package/extensions/kakao-talkchannel/src/kakao/limits.ts +129 -0
  722. package/extensions/kakao-talkchannel/src/kakao/payload.ts +138 -0
  723. package/extensions/kakao-talkchannel/src/kakao/response.ts +373 -0
  724. package/extensions/kakao-talkchannel/src/relay/client.ts +146 -0
  725. package/extensions/kakao-talkchannel/src/relay/session.ts +137 -0
  726. package/extensions/kakao-talkchannel/src/relay/sse.ts +258 -0
  727. package/extensions/kakao-talkchannel/src/relay/stream.ts +149 -0
  728. package/extensions/kakao-talkchannel/src/runtime.ts +21 -0
  729. package/extensions/kakao-talkchannel/src/types.ts +447 -0
  730. package/extensions/kakao-talkchannel/src/version.ts +3 -0
  731. package/extensions/kakao-talkchannel/tsconfig.json +19 -0
  732. package/package.json +23 -8
  733. package/skills/meshy/SKILL.md +69 -0
  734. package/skills/meshy/scripts/__pycache__/check_status.cpython-312.pyc +0 -0
  735. package/skills/meshy/scripts/__pycache__/image_to_3d.cpython-312.pyc +0 -0
  736. package/skills/meshy/scripts/__pycache__/text_to_3d.cpython-312.pyc +0 -0
  737. package/skills/meshy/scripts/check_status.py +147 -0
  738. package/skills/meshy/scripts/image_to_3d.py +229 -0
  739. package/skills/meshy/scripts/text_to_3d.py +214 -0
  740. package/skills/nano-banana-pro/scripts/generate_image.py +1 -1
  741. package/skills/openai-whisper-api/scripts/transcribe.sh +0 -0
  742. package/skills/tavily-search/SKILL.md +61 -0
  743. package/skills/tavily-search/scripts/__pycache__/search.cpython-312.pyc +0 -0
  744. package/skills/tavily-search/scripts/search.py +238 -0
  745. package/skills/video-frames/scripts/frame.sh +0 -0
  746. package/LICENSE +0 -21
  747. package/dist/accounts-UcSvD34O.js +0 -109
  748. package/dist/acp-cli-BPb8PgHP.js +0 -2088
  749. package/dist/actions.runtime-BL5QRooG.js +0 -114
  750. package/dist/actions.runtime-DSdfSo40.js +0 -128
  751. package/dist/agents-CHeX_5-H.js +0 -217
  752. package/dist/agents-DQRL9XKP.js +0 -853
  753. package/dist/allow-list-Boi79v-U.js +0 -81
  754. package/dist/allowlist-B2eBBeMF.js +0 -142
  755. package/dist/api-CFAtRSYL.js +0 -6953
  756. package/dist/api-D5JNJj8n.js +0 -112
  757. package/dist/audit-BM0GsdzV.js +0 -787
  758. package/dist/audit-BqRK9OSj.js +0 -54
  759. package/dist/audit-channel.collect.runtime-BPvDB8aq.js +0 -600
  760. package/dist/audit-channel.runtime-D3fzHiAo.js +0 -116
  761. package/dist/audit-extra.async-NveNIzX0.js +0 -813
  762. package/dist/audit-membership-runtime-mu470WFO.js +0 -157
  763. package/dist/audit.deep.runtime-RdxvW8Tj.js +0 -24
  764. package/dist/audit.nondeep.runtime-DDu8vA9Z.js +0 -831
  765. package/dist/audit.runtime-Y8C9W7s9.js +0 -113
  766. package/dist/auth-choice-C1CIxRsi.js +0 -268
  767. package/dist/auth-choice-CTvqWiDI.js +0 -117
  768. package/dist/auth-choice-Ddzko1B8.js +0 -502
  769. package/dist/auth-choice-options-BIAmAiCe.js +0 -123
  770. package/dist/auth-choice-prompt-B815kArz.js +0 -110
  771. package/dist/auth-choice-prompt-CGhTNCJx.js +0 -36
  772. package/dist/auth-choice.plugin-providers.runtime-AvAZ6S5W.js +0 -114
  773. package/dist/auth-profiles-BJcHzwPy.js +0 -127650
  774. package/dist/auth-profiles.runtime-CieFilK5.js +0 -111
  775. package/dist/bluebubbles-F8FGE9cH.js +0 -64
  776. package/dist/brave-BG5Yopn8.js +0 -24
  777. package/dist/browser-cli-Co7PJGZF.js +0 -1492
  778. package/dist/call-CoaQYq7c.js +0 -639
  779. package/dist/call-D3eu5Jjh.js +0 -37
  780. package/dist/channel-BftWD6yu.js +0 -1321
  781. package/dist/channel-Bub9U5Xg.js +0 -214
  782. package/dist/channel-C0oDs7TO.js +0 -4681
  783. package/dist/channel-C8CnEdkZ.js +0 -352
  784. package/dist/channel-CI-RC-xf.js +0 -497
  785. package/dist/channel-CY-hZCOJ.js +0 -397
  786. package/dist/channel-CbtGJB2x.js +0 -943
  787. package/dist/channel-CcfK3wP8.js +0 -803
  788. package/dist/channel-DBoDIeVj.js +0 -619
  789. package/dist/channel-DEq6Ecs-.js +0 -920
  790. package/dist/channel-DH4dhW1n.js +0 -226
  791. package/dist/channel-DQ_wdKg_.js +0 -575
  792. package/dist/channel-DT6qD1Ic.js +0 -207
  793. package/dist/channel-DZNAyxwr.js +0 -542
  794. package/dist/channel-DtakwAEe.js +0 -538
  795. package/dist/channel-DuYgH6p1.js +0 -562
  796. package/dist/channel-Hn-AN-d52.js +0 -316
  797. package/dist/channel-_R4hbD5h.js +0 -1598
  798. package/dist/channel-account-context-DXq8dlvI.js +0 -103
  799. package/dist/channel-kQmEVn3I.js +0 -306
  800. package/dist/channel-options-DHfxaklg.js +0 -50
  801. package/dist/channel-summary-DUpnoYhI.js +0 -106
  802. package/dist/channel-t-JxCWk6.js +0 -949
  803. package/dist/channel.runtime--GYriaXU.js +0 -213
  804. package/dist/channel.runtime-BJtn3GOH.js +0 -174
  805. package/dist/channel.runtime-BV7t_oNz.js +0 -166
  806. package/dist/channel.runtime-Bi8a3n9S.js +0 -865
  807. package/dist/channel.runtime-BjsYF0NN.js +0 -122
  808. package/dist/channel.runtime-BnI6YtmI.js +0 -413
  809. package/dist/channel.runtime-CQOftcCd.js +0 -194
  810. package/dist/channel.runtime-CuIAcPjZ.js +0 -4006
  811. package/dist/channel.runtime-DH1Q1G4k.js +0 -399
  812. package/dist/channel.runtime-DYYUPKxr.js +0 -236
  813. package/dist/channel.runtime-U5Gszsr5.js +0 -177
  814. package/dist/channel.setup-BQFHmgki.js +0 -9
  815. package/dist/channel.setup-BVoDwklu.js +0 -8
  816. package/dist/channel.setup-Bf73HsXr.js +0 -57
  817. package/dist/channel.setup-CblD4flM.js +0 -11
  818. package/dist/channel.setup-DgxlrPgz.js +0 -6
  819. package/dist/channel.setup-GLIAEVKL.js +0 -8
  820. package/dist/channel.setup-YTy5R1sz.js +0 -9
  821. package/dist/channels-CTL8iR9J.js +0 -404
  822. package/dist/channels-DBGvnjHY.js +0 -1113
  823. package/dist/channels-cli-BmVO5-sq.js +0 -286
  824. package/dist/channels-status-issues-kDtsWzA-.js +0 -16
  825. package/dist/clawbot-cli-DtcMJHqX.js +0 -113
  826. package/dist/cli-BNGECGVY.js +0 -149
  827. package/dist/command-registry-1SDrWgER.js +0 -13
  828. package/dist/command-registry-DNorYU4w.js +0 -212
  829. package/dist/command-secret-gateway-DqDZparO.js +0 -106
  830. package/dist/compact.runtime-C1ZN8UGb.js +0 -111
  831. package/dist/completion-cli-Q_Jt5Foc.js +0 -16
  832. package/dist/completion-cli-QkTXhuJh.js +0 -445
  833. package/dist/config-BbxrRaLf.js +0 -938
  834. package/dist/config-CkD8DJ7L.js +0 -44
  835. package/dist/config-cli-BoPrlYTp.js +0 -428
  836. package/dist/config-guard-CEhCvr_u.js +0 -117
  837. package/dist/config-schema-GQ6uWjXe.js +0 -31
  838. package/dist/config-validation-woE2_LpC.js +0 -262
  839. package/dist/config-value-Dh8m-CFf.js +0 -132
  840. package/dist/config-y4i5g7s4.js +0 -30
  841. package/dist/configure-DGRzwdFN.js +0 -1100
  842. package/dist/configure-S4AHE3k_.js +0 -238
  843. package/dist/control-ui-shared-kLBp4YlS.js +0 -29
  844. package/dist/credentials-D5uBf_C5.js +0 -265
  845. package/dist/cron-cli-lGupeVCW.js +0 -634
  846. package/dist/daemon-cli-Cs_edi0I.js +0 -339
  847. package/dist/daemon-install-DIFpP_qv.js +0 -175
  848. package/dist/deliver-DYa_DFZU.js +0 -106
  849. package/dist/deliver-runtime-DCW_o2Ot.js +0 -106
  850. package/dist/devices-cli-YsGOW2-w.js +0 -340
  851. package/dist/diagnostic-vMghIesG.js +0 -310
  852. package/dist/directory-cli-DtjMQjU5.js +0 -306
  853. package/dist/directory.static-DBZGvsdF.js +0 -44
  854. package/dist/discord-DYCu19HT.js +0 -109
  855. package/dist/discovery-DZYAoDF_.js +0 -48
  856. package/dist/dns-cli-DqW4pNgW.js +0 -216
  857. package/dist/docs-cli-Bu9TBlDU.js +0 -173
  858. package/dist/doctor-completion-B5hcQD5c.js +0 -90
  859. package/dist/doctor-config-flow-BBB2ZKfT.js +0 -107
  860. package/dist/doctor-config-flow-DDBYUS9f.js +0 -2437
  861. package/dist/enable-Tmsp8QuB.js +0 -24
  862. package/dist/env-overrides-BHxqjYZG.js +0 -434
  863. package/dist/env-overrides.runtime-Cz98bf-l.js +0 -17
  864. package/dist/exec-approvals-cli-wO5cYfMa.js +0 -419
  865. package/dist/gateway-cli-CFvDGhB9.js +0 -26429
  866. package/dist/gateway-install-token-CskJfo_N.js +0 -163
  867. package/dist/gateway-rpc-srYfBID9.js +0 -26
  868. package/dist/gateway-runtime-C76hUmUV.js +0 -69
  869. package/dist/googlechat-Cha5utST.js +0 -307
  870. package/dist/health-DDQYYsJy.js +0 -108
  871. package/dist/health-DXZykGaX.js +0 -570
  872. package/dist/hooks-cli-DfkurPYP.js +0 -995
  873. package/dist/imessage-B26k39pl.js +0 -110
  874. package/dist/imessage-Bp1_6cws.js +0 -31
  875. package/dist/inbound-reply-dispatch-DoIJLztA.js +0 -71
  876. package/dist/install-target-BjOuS4I8.js +0 -574
  877. package/dist/installs-Cz4k0W1Y.js +0 -532
  878. package/dist/io-B0OKifLZ.js +0 -28
  879. package/dist/io-DcoxdH6t.js +0 -9570
  880. package/dist/ipv4-CTQQ4_IW.js +0 -82
  881. package/dist/irc-B8vBDigm.js +0 -672
  882. package/dist/library-VCM_cQY4.js +0 -107
  883. package/dist/lifecycle-core-Ctz36PdQ.js +0 -382
  884. package/dist/line-B_uTLrdI.js +0 -530
  885. package/dist/llm-slug-generator-YWg0g2pj.js +0 -67
  886. package/dist/logging-S-5LPdfQ.js +0 -13
  887. package/dist/logging-ueBMCGMR.js +0 -29
  888. package/dist/login-qr-pcACm2Ng.js +0 -107
  889. package/dist/login-qr-pv-kxMfF.js +0 -233
  890. package/dist/logs-cli-RgADgSMO.js +0 -254
  891. package/dist/manager-runtime-BhTkoKmb.js +0 -106
  892. package/dist/manager.runtime-BjHzikoK.js +0 -710
  893. package/dist/matrix-C4EEu2Qp.js +0 -1490
  894. package/dist/matrix-Dfzcc5nV.js +0 -1269
  895. package/dist/mcp-cli-CJmOm9Oj.js +0 -86
  896. package/dist/media-understanding.runtime-DCETFCw_.js +0 -111
  897. package/dist/memory-cli-DFqd6tYx.js +0 -106
  898. package/dist/method-scopes-D-Q9dvbj.js +0 -2586
  899. package/dist/model-picker-Z-CUcuMr.js +0 -390
  900. package/dist/model-picker-v5mUsZ4J.js +0 -107
  901. package/dist/model-picker.runtime-A_z0dHfS.js +0 -120
  902. package/dist/model-suppression.runtime-QVWVJRr-.js +0 -111
  903. package/dist/models-Bbj0xV4F.js +0 -2514
  904. package/dist/models-D-OIjZqU.js +0 -113
  905. package/dist/models-cli-Bpn-5i4h.js +0 -304
  906. package/dist/models-config-Cwa5cJbC.js +0 -106
  907. package/dist/monitor-BchfCAaU.js +0 -6823
  908. package/dist/monitor-BydV44SP.js +0 -3076
  909. package/dist/monitor-CT8axwfm.js +0 -767
  910. package/dist/monitor-CZGWNOvn.js +0 -777
  911. package/dist/monitor-DN62r69g.js +0 -3468
  912. package/dist/monitor-DZ0fzJku.js +0 -110
  913. package/dist/monitor-DvNjzWFu.js +0 -108
  914. package/dist/monitor-shared-B-DBSlkQ.js +0 -444
  915. package/dist/msteams-Bf-wk2Rp.js +0 -852
  916. package/dist/node-cli-kH16TQI7.js +0 -2498
  917. package/dist/node-resolve-DfOpQmxm.js +0 -835
  918. package/dist/nodes-cli-CkAMXW5u.js +0 -1375
  919. package/dist/nostr-B8UGHclZ.js +0 -8744
  920. package/dist/npm-resolution-DmjlifII.js +0 -60
  921. package/dist/onboard-C883nfyw.js +0 -589
  922. package/dist/onboard-channels-Dc-BxN7p.js +0 -200
  923. package/dist/onboard-channels-j5EENtum.js +0 -1241
  924. package/dist/onboard-custom-0atne0C5.js +0 -571
  925. package/dist/onboard-custom-CWMqwjJx.js +0 -109
  926. package/dist/onboard-helpers-D3wWfH8F.js +0 -335
  927. package/dist/onboard-helpers-DZmRCe8l.js +0 -108
  928. package/dist/onboard-remote-Cn6kW-p0.js +0 -112
  929. package/dist/onboard-remote-Cx4w5VAk.js +0 -181
  930. package/dist/onboard-search-Ck9HRh2M.js +0 -297
  931. package/dist/onboard-skills-BtqrGioT.js +0 -133
  932. package/dist/onboard-skills-Dnw19Os8.js +0 -112
  933. package/dist/outbound-media-C5Nv4o18.js +0 -11
  934. package/dist/pairing-cli-Cwy9QZ_4.js +0 -212
  935. package/dist/perplexity-Brhpb45X.js +0 -24
  936. package/dist/pi-model-discovery-runtime-DIOdo6D8.js +0 -106
  937. package/dist/pi-tools.before-tool-call.runtime-CFM4gsDF.js +0 -380
  938. package/dist/plugin-install-BOV00hia.js +0 -112
  939. package/dist/plugin-install-Bak8fUBv.js +0 -184
  940. package/dist/plugin-install-plan-bKkEefRf.js +0 -49
  941. package/dist/plugin-registry-DxAXQUlZ.js +0 -108
  942. package/dist/plugin-registry-n0p3phem.js +0 -49
  943. package/dist/plugins-Ca3RK8Fi.js +0 -106
  944. package/dist/plugins-cli-BnC51H2R.js +0 -912
  945. package/dist/policy-BJv97w9e.js +0 -143
  946. package/dist/preflight-audio.runtime-BrFcf-6_.js +0 -111
  947. package/dist/probe-063xvvZc.js +0 -19
  948. package/dist/probe-BJEb2wGv.js +0 -1793
  949. package/dist/probe-CJQlxgsl.js +0 -47
  950. package/dist/probe-Caa2HznF.js +0 -6328
  951. package/dist/probe-CfL4tnJ6.js +0 -129
  952. package/dist/probe-auth-DN2Ec83-.js +0 -38
  953. package/dist/probe-auth-D_UKzu4m.js +0 -48
  954. package/dist/program-BOMdC7MC.js +0 -247
  955. package/dist/prompt-select-styled-DDnCfM3j.js +0 -2673
  956. package/dist/provider-api-key-auth.runtime-DUns3fwX.js +0 -116
  957. package/dist/provider-auth-choice-B_j1ctT2.js +0 -126
  958. package/dist/provider-auth-choice-preference-BaOBZ_Xn.js +0 -189
  959. package/dist/provider-auth-choice.runtime-DOako_zV.js +0 -118
  960. package/dist/provider-auth-guidance-CrjxnoNZ.js +0 -34
  961. package/dist/provider-runtime.runtime-BkOkgmTw.js +0 -106
  962. package/dist/provider-self-hosted-setup-BFDU6dRa.js +0 -182
  963. package/dist/provider-usage-CaDE0mqq.js +0 -106
  964. package/dist/provider-web-search-BR7etTjJ.js +0 -2392
  965. package/dist/provider-wizard-DCPdKUvb.js +0 -152
  966. package/dist/push-apns-B_OZjm4v.js +0 -1038
  967. package/dist/pw-ai-dG60P0hQ.js +0 -1866
  968. package/dist/qr-cli-DWfiw79I.js +0 -369
  969. package/dist/qr-cli-DwuKtyZQ.js +0 -108
  970. package/dist/reactions-CIGAPBn8.js +0 -281
  971. package/dist/read-only-account-inspect.discord.runtime-D54mnq8l.js +0 -111
  972. package/dist/read-only-account-inspect.slack.runtime-Bxs9ObMC.js +0 -111
  973. package/dist/read-only-account-inspect.telegram.runtime-UoVuf_Yo.js +0 -111
  974. package/dist/redact-snapshot-DZ3Vq-SC.js +0 -2657
  975. package/dist/ref-contract-D96lSYLs.js +0 -53
  976. package/dist/register.agent-2KmeahEL.js +0 -434
  977. package/dist/register.backup-ECBnWVR7.js +0 -624
  978. package/dist/register.configure-Doz1daCp.js +0 -247
  979. package/dist/register.maintenance-C33cV-WM.js +0 -569
  980. package/dist/register.message-CnL0NiF6.js +0 -704
  981. package/dist/register.onboard-BrYGZeQA.js +0 -187
  982. package/dist/register.setup-Bx6gEg6X.js +0 -207
  983. package/dist/register.status-health-sessions-FLb0CUOO.js +0 -493
  984. package/dist/register.subclis-BuqgaeIf.js +0 -12
  985. package/dist/register.subclis-DwdgfdnT.js +0 -315
  986. package/dist/registry-xhgvU89y.js +0 -1107
  987. package/dist/replies-hB2aipLu.js +0 -110
  988. package/dist/resolve-3ErMOltL.js +0 -660
  989. package/dist/resolve-channels-BV8GXuPe.js +0 -226
  990. package/dist/resolve-channels-CTY_XRIP.js +0 -262
  991. package/dist/resolve-users-DQ4Ne4Zc.js +0 -143
  992. package/dist/routes-BNDsNO_e.js +0 -7097
  993. package/dist/rpc-BLGTBWXq.js +0 -67
  994. package/dist/run-main-COAE4GlI.js +0 -423
  995. package/dist/runtime-discord-ops.runtime-Dxg-nlgd.js +0 -9073
  996. package/dist/runtime-slack-ops.runtime-Di474LJr.js +0 -4551
  997. package/dist/runtime-telegram-ops.runtime-Da8vgf3O.js +0 -128
  998. package/dist/runtime-whatsapp-login.runtime-DcouP4iF.js +0 -109
  999. package/dist/runtime-whatsapp-outbound.runtime-CYamaEJX.js +0 -112
  1000. package/dist/sandbox-cli-U5ZTxhxL.js +0 -530
  1001. package/dist/search-manager-CfizyEMk.js +0 -386
  1002. package/dist/search-manager-DaF2QP4s.js +0 -15
  1003. package/dist/secrets-cli-C0gytFip.js +0 -2065
  1004. package/dist/security-cli-C74EuLUO.js +0 -570
  1005. package/dist/send-BTLVBf_E.js +0 -631
  1006. package/dist/send-BlWWCEZE.js +0 -1025
  1007. package/dist/send-CfypD1B_.js +0 -100
  1008. package/dist/send-Cm9v3uhF.js +0 -283
  1009. package/dist/send-g2odQuYI.js +0 -629
  1010. package/dist/server-C8b5QJ2s.js +0 -106
  1011. package/dist/server-node-events-xqQe5xiu.js +0 -501
  1012. package/dist/sessions-CSSzvgPQ.js +0 -107
  1013. package/dist/sessions-z0GIvdKa.js +0 -218
  1014. package/dist/setup-D9XTmlF8.js +0 -387
  1015. package/dist/setup-core-BDrLOwYO.js +0 -143
  1016. package/dist/setup-core-CM7cY7_i.js +0 -166
  1017. package/dist/setup-core-CnmgANY-.js +0 -205
  1018. package/dist/setup-core-DgcjCKmG.js +0 -47
  1019. package/dist/setup-surface-DzRrVKYj.js +0 -490
  1020. package/dist/setup.finalize-UaPu_adv.js +0 -517
  1021. package/dist/setup.gateway-config-Djc1ceEh.js +0 -338
  1022. package/dist/setup.secret-input-BkczghbR.js +0 -25
  1023. package/dist/shared-BHizGoNk.js +0 -298
  1024. package/dist/shared-CUfYhQkP.js +0 -96
  1025. package/dist/shared-DYYqr9EC.js +0 -75
  1026. package/dist/shared-DthOxMRQ.js +0 -182
  1027. package/dist/shared-On_A5_hW.js +0 -102
  1028. package/dist/signal-D6px9PGZ.js +0 -109
  1029. package/dist/skills-B4h1k-SP.js +0 -853
  1030. package/dist/skills-Bto10BGB.js +0 -19
  1031. package/dist/skills-cli-CXGR3Y5j.js +0 -291
  1032. package/dist/skills-install-B1AlkK8C.js +0 -763
  1033. package/dist/skills-status-BsmJ_iSg.js +0 -20
  1034. package/dist/skills-status-DGdxY3OI.js +0 -169
  1035. package/dist/slack-B7vWFmxP.js +0 -109
  1036. package/dist/slash-commands.runtime-DXdAT84n.js +0 -123
  1037. package/dist/slash-dispatch.runtime-CNf2-9Aj.js +0 -136
  1038. package/dist/slash-skill-commands.runtime-CBjffHRX.js +0 -111
  1039. package/dist/src-Cp7P7T08.js +0 -1696
  1040. package/dist/status-158fWh4A.js +0 -43
  1041. package/dist/status-BJIVLJnb.js +0 -1599
  1042. package/dist/status-BQiBI6N9.js +0 -126
  1043. package/dist/status-CZipXGUu.js +0 -121
  1044. package/dist/status-ZZIVFLI-.js +0 -606
  1045. package/dist/status-json-BNUy5Mem.js +0 -286
  1046. package/dist/status.link-channel-B694y1Xu.js +0 -138
  1047. package/dist/status.scan.deps.runtime-BcoKEzQD.js +0 -121
  1048. package/dist/status.scan.runtime-CqScDt-p.js +0 -114
  1049. package/dist/status.summary-AMek7qvI.js +0 -592
  1050. package/dist/status.summary.runtime-XgkcQ_kr.js +0 -113
  1051. package/dist/subagent-orphan-recovery-CrCYTmFC.js +0 -302
  1052. package/dist/subagent-registry-runtime-Cg-YvLx3.js +0 -106
  1053. package/dist/synology-chat-0G85jIqQ.js +0 -297
  1054. package/dist/system-cli-kZtSxKNm.js +0 -92
  1055. package/dist/telegram-DV0Wy89w.js +0 -109
  1056. package/dist/text-chunking-C2J2Oeul.js +0 -84
  1057. package/dist/tlon-DmK1NUVP.js +0 -433
  1058. package/dist/tui-D3bNPLG7.js +0 -3834
  1059. package/dist/tui-cli-DtMp9k_s.js +0 -132
  1060. package/dist/types.secrets-DuSPmmWB.js +0 -80
  1061. package/dist/ui-CeGztSEL.js +0 -31
  1062. package/dist/update-De7VudzP.js +0 -1036
  1063. package/dist/update-cli-BH8Pb-So.js +0 -1498
  1064. package/dist/update-offset-store-syELkdEW.js +0 -107
  1065. package/dist/update-runner-Cq-Q40T9.js +0 -1496
  1066. package/dist/web-CjMtvfSq.js +0 -107
  1067. package/dist/webhook-targets-_jTR0Bb_.js +0 -181
  1068. package/dist/webhooks-cli-DQ6u2Qau.js +0 -349
  1069. package/dist/whatsapp-CyLk16SZ.js +0 -109
  1070. package/dist/whatsapp-actions-Dzr2Wzqw.js +0 -162
  1071. package/dist/workspace-dirs-L1_QQ9mB.js +0 -2002
  1072. package/dist/zalo-CrehfXvK.js +0 -415
  1073. package/dist/zalouser-D1QD-O-I.js +0 -30911
  1074. package/dist/zod-schema.core-CWxzqcUs.js +0 -541
@@ -1,2673 +0,0 @@
1
- import { o as getResolvedLoggerSettings } from "./logger-BFfIIIKH.js";
2
- import { _ as resolveStateDir, d as resolveIsNixMode, h as resolveOAuthDir, t as CONFIG_PATH, u as resolveGatewayPort, x as resolveRequiredHomeDir } from "./paths-D6AgsMTU.js";
3
- import { m as defaultRuntime } from "./subsystem-S4LNMNHd.js";
4
- import { t as isTruthyEnvValue$1 } from "./env-Dgex_t9p.js";
5
- import { C as sleep, S as shortenHomePath, y as resolveUserPath } from "./utils-rjVNXUns.js";
6
- import { h as isWSLEnv, p as isWSL } from "./setup-binary-Fw3cCSWL.js";
7
- import { $a as DEFAULT_OAUTH_WARN_MS, AE as updateAuthProfileStoreWithLock, Ad as resolveDmAllowState, Fn as loadmoldClawPlugins, LC as loadCronStore, Pn as resolvePluginProviders, RC as resolveCronStorePath, T as listChannelPlugins, Vb as loadModelCatalog, Xc as analyzeBootstrapBudget, Zc as buildBootstrapInjectionStats, ch as hasConfiguredMemorySecretInput, d as resolveProfileUnusableUntilForDisplay, eo as buildAuthHealthSummary, fE as resolveBootstrapMaxChars, hE as repairOAuthProfileIdMismatch, km as noteOpenAIOAuthTlsPrerequisites, mE as resolveApiKeyForProfile, mf as resolveBootstrapContextForRun, pE as resolveBootstrapTotalMaxChars, rC as loadSessionStore, sx as resolveApiKeyForProvider, to as formatRemainingShort, wE as ensureAuthProfileStore, y as resolveAgentSessionDirs, zC as saveCronStore } from "./auth-profiles-BJcHzwPy.js";
8
- import { O as DEFAULT_MODEL, g as resolveHooksGmailModel, i as getModelRefStatus, k as DEFAULT_PROVIDER, m as resolveConfiguredModelRef } from "./model-selection-DfA4esOK.js";
9
- import { a as resolveAgentDir, m as resolveDefaultAgentId, p as resolveAgentWorkspaceDir } from "./agent-scope-DA7O8MVG.js";
10
- import { S as parseAgentSessionKey } from "./session-key-DyhRsRh-.js";
11
- import { n as runCommandWithTimeout, r as runExec } from "./exec-CoBTyh8B.js";
12
- import { t as resolvemoldClawPackageRoot } from "./moldclaw-root-vgfzPuAl.js";
13
- import { t as DEFAULT_AGENTS_FILENAME } from "./workspace-CxNKYS0V.js";
14
- import { d as readConfigFileSnapshot, g as writeConfigFile } from "./io-DcoxdH6t.js";
15
- import { a as hasConfiguredSecretInput, d as resolveSecretInputRef } from "./types.secrets-DuSPmmWB.js";
16
- import { P as cleanStaleLockFiles, at as DEFAULT_SANDBOX_IMAGE, rt as DEFAULT_SANDBOX_BROWSER_IMAGE, z as resolveSandboxScope } from "./workspace-dirs-L1_QQ9mB.js";
17
- import { m as resolveGatewayAuth } from "./config-BbxrRaLf.js";
18
- import { t as formatCliCommand } from "./command-format-DIDjlImI.js";
19
- import { r as isLoopbackHost, u as resolveGatewayBindHost } from "./net-B_Iq_SVP.js";
20
- import { d as readGatewayTokenEnv } from "./credentials-D5uBf_C5.js";
21
- import { C as parseBrowserMajorVersion, T as resolveGoogleChromeExecutableForPlatform, at as resolveConfiguredSecretInputWithFallback, ct as hasAmbiguousGatewayAuthModeConfig, w as readBrowserVersion } from "./routes-BNDsNO_e.js";
22
- import { a as inspectPortUsage, c as formatPortDiagnostics } from "./ports-BVwQuCIR.js";
23
- import { n as isPrimarySessionTranscriptFileName, t as formatSessionArchiveTimestamp } from "./artifacts-B5Zkf6S0.js";
24
- import { f as resolveMainSessionKey } from "./lazy-runtime-DdzFA4b9.js";
25
- import { c as resolveSessionTranscriptsDirForAgent, i as resolveSessionFilePathOptions, l as resolveStorePath, r as resolveSessionFilePath } from "./paths-CDWV-9nX.js";
26
- import { n as callGateway, t as buildGatewayConnectionDetails } from "./call-CoaQYq7c.js";
27
- import { t as resolveMemorySearchConfig } from "./memory-search-BBG2BKIh.js";
28
- import { r as resolveMemoryBackendConfig } from "./search-manager-CfizyEMk.js";
29
- import { n as logConfigUpdated } from "./logging-S-5LPdfQ.js";
30
- import { i as stylePromptTitle, n as stylePromptHint, r as stylePromptMessage, t as note$1 } from "./note-z78_JyNp.js";
31
- import { f as resolveGatewaySystemdServiceName, h as resolveNodeLaunchAgentLabel, l as resolveGatewayLaunchAgentLabel, p as resolveGatewayWindowsTaskName } from "./constants-WvU01Mp_.js";
32
- import { a as resolveSystemNodeInfo, r as renderSystemNodeWarning } from "./runtime-paths-DPdaWILN.js";
33
- import { n as buildGatewayInstallPlan, r as gatewayInstallErrorHint, t as resolveGatewayInstallToken } from "./gateway-install-token-CskJfo_N.js";
34
- import { n as GATEWAY_DAEMON_RUNTIME_OPTIONS, t as DEFAULT_GATEWAY_DAEMON_RUNTIME } from "./daemon-runtime-BPknjyQD.js";
35
- import { f as printWizardHeader, m as randomToken, n as applyWizardMetadata, s as guardCancel } from "./onboard-helpers-D3wWfH8F.js";
36
- import { i as launchAgentPlistExists, n as isLaunchAgentListed, r as isLaunchAgentLoaded, s as repairLaunchAgentBootstrap } from "./launchd-C1YgvbKp.js";
37
- import { n as resolveGatewayService, t as describeGatewayServiceRestart } from "./service-DLhEn8sS.js";
38
- import { i as isSystemdUserServiceAvailable, u as uninstallLegacySystemdUnits } from "./systemd-BD-XXrY3.js";
39
- import { c as buildPlatformRuntimeLogHints, i as auditGatewayServiceConfig, n as renderSystemdUnavailableHints, o as needsNodeRuntimeMigration, r as SERVICE_AUDIT_CODES, s as readEmbeddedGatewayToken, t as isSystemdUnavailableDetail, u as formatRuntimeStatus } from "./systemd-hints-LWwXTYeY.js";
40
- import { t as readLastGatewayErrorLine } from "./diagnostics-Ct6HBGrk.js";
41
- import { n as renderGatewayServiceCleanupHints, t as findExtraGatewayServices } from "./inspect-BryOMVYx.js";
42
- import { t as buildWorkspaceSkillStatus } from "./skills-status-DGdxY3OI.js";
43
- import { r as healthCommand } from "./health-DXZykGaX.js";
44
- import { i as resolveControlUiDistIndexPathForRoot, r as resolveControlUiDistIndexHealth } from "./control-ui-assets-Bwqp8PYM.js";
45
- import { p as normalizeStoredCronJobs, t as runGatewayUpdate } from "./update-runner-Cq-Q40T9.js";
46
- import { t as collectChannelStatusIssues } from "./channels-status-issues-kDtsWzA-.js";
47
- import { n as resolveProviderAuthLoginCommand, t as buildProviderAuthRecoveryHint } from "./provider-auth-guidance-CrjxnoNZ.js";
48
- import { t as ensureSystemdUserLingerInteractive } from "./systemd-linger-B_ndoLL9.js";
49
- import { t as formatHealthCheckFailure } from "./health-format-D2gwr1bv.js";
50
- import { n as doctorShellCompletion } from "./doctor-completion-B5hcQD5c.js";
51
- import { a as runLegacyStateMigrations, i as detectLegacyStateMigrations, r as loadAndMaybeMigrateDoctorConfig } from "./doctor-config-flow-DDBYUS9f.js";
52
- import { t as resolveDefaultChannelAccountContext } from "./channel-account-context-DXq8dlvI.js";
53
- import fs from "node:fs";
54
- import path from "node:path";
55
- import { execFile } from "node:child_process";
56
- import os from "node:os";
57
- import { promisify } from "node:util";
58
- import fs$1 from "node:fs/promises";
59
- import { confirm, intro, outro, select } from "@clack/prompts";
60
- //#region src/commands/doctor-auth.ts
61
- async function maybeRepairAnthropicOAuthProfileId(cfg, prompter) {
62
- const repair = repairOAuthProfileIdMismatch({
63
- cfg,
64
- store: ensureAuthProfileStore(),
65
- provider: "anthropic",
66
- legacyProfileId: "anthropic:default"
67
- });
68
- if (!repair.migrated || repair.changes.length === 0) return cfg;
69
- note$1(repair.changes.map((c) => `- ${c}`).join("\n"), "Auth profiles");
70
- if (!await prompter.confirm({
71
- message: "Update Anthropic OAuth profile id in config now?",
72
- initialValue: true
73
- })) return cfg;
74
- return repair.config;
75
- }
76
- function pruneAuthOrder(order, profileIds) {
77
- if (!order) return {
78
- next: order,
79
- changed: false
80
- };
81
- let changed = false;
82
- const next = {};
83
- for (const [provider, list] of Object.entries(order)) {
84
- const filtered = list.filter((id) => !profileIds.has(id));
85
- if (filtered.length !== list.length) changed = true;
86
- if (filtered.length > 0) next[provider] = filtered;
87
- }
88
- return {
89
- next: Object.keys(next).length > 0 ? next : void 0,
90
- changed
91
- };
92
- }
93
- function pruneAuthProfiles(cfg, profileIds) {
94
- const profiles = cfg.auth?.profiles;
95
- const order = cfg.auth?.order;
96
- const nextProfiles = profiles ? { ...profiles } : void 0;
97
- let changed = false;
98
- if (nextProfiles) {
99
- for (const id of profileIds) if (id in nextProfiles) {
100
- delete nextProfiles[id];
101
- changed = true;
102
- }
103
- }
104
- const prunedOrder = pruneAuthOrder(order, profileIds);
105
- if (prunedOrder.changed) changed = true;
106
- if (!changed) return {
107
- next: cfg,
108
- changed: false
109
- };
110
- const nextAuth = nextProfiles || prunedOrder.next ? {
111
- ...cfg.auth,
112
- profiles: nextProfiles && Object.keys(nextProfiles).length > 0 ? nextProfiles : void 0,
113
- order: prunedOrder.next
114
- } : void 0;
115
- return {
116
- next: {
117
- ...cfg,
118
- auth: nextAuth
119
- },
120
- changed: true
121
- };
122
- }
123
- async function maybeRemoveDeprecatedCliAuthProfiles(cfg, prompter) {
124
- const store = ensureAuthProfileStore(void 0, { allowKeychainPrompt: false });
125
- const deprecatedEntries = resolvePluginProviders({
126
- config: cfg,
127
- env: process.env,
128
- bundledProviderAllowlistCompat: true,
129
- bundledProviderVitestCompat: true
130
- }).flatMap((provider) => (provider.deprecatedProfileIds ?? []).filter((profileId) => store.profiles[profileId] || cfg.auth?.profiles?.[profileId]).map((profileId) => ({
131
- profileId,
132
- providerId: provider.id,
133
- providerLabel: provider.label
134
- })));
135
- const deprecated = new Set(deprecatedEntries.map((entry) => entry.profileId));
136
- if (deprecated.size === 0) return cfg;
137
- const lines = ["Deprecated external CLI auth profiles detected (no longer supported):"];
138
- for (const entry of deprecatedEntries) {
139
- const authCommand = resolveProviderAuthLoginCommand({
140
- provider: entry.providerId,
141
- config: cfg,
142
- env: process.env
143
- }) ?? formatCliCommand("moldclaw configure");
144
- lines.push(`- ${entry.profileId} (${entry.providerLabel}): use ${authCommand}`);
145
- }
146
- note$1(lines.join("\n"), "Auth profiles");
147
- if (!await prompter.confirmRepair({
148
- message: "Remove deprecated CLI auth profiles now?",
149
- initialValue: true
150
- })) return cfg;
151
- await updateAuthProfileStoreWithLock({ updater: (nextStore) => {
152
- let mutated = false;
153
- for (const id of deprecated) {
154
- if (nextStore.profiles[id]) {
155
- delete nextStore.profiles[id];
156
- mutated = true;
157
- }
158
- if (nextStore.usageStats?.[id]) {
159
- delete nextStore.usageStats[id];
160
- mutated = true;
161
- }
162
- }
163
- if (nextStore.order) for (const [provider, list] of Object.entries(nextStore.order)) {
164
- const filtered = list.filter((id) => !deprecated.has(id));
165
- if (filtered.length !== list.length) {
166
- mutated = true;
167
- if (filtered.length > 0) nextStore.order[provider] = filtered;
168
- else delete nextStore.order[provider];
169
- }
170
- }
171
- if (nextStore.lastGood) {
172
- for (const [provider, profileId] of Object.entries(nextStore.lastGood)) if (deprecated.has(profileId)) {
173
- delete nextStore.lastGood[provider];
174
- mutated = true;
175
- }
176
- }
177
- return mutated;
178
- } });
179
- const pruned = pruneAuthProfiles(cfg, deprecated);
180
- if (pruned.changed) note$1(Array.from(deprecated.values()).map((id) => `- removed ${id} from config`).join("\n"), "Doctor changes");
181
- return pruned.next;
182
- }
183
- function resolveUnusableProfileHint(params) {
184
- if (params.kind === "disabled") {
185
- if (params.reason === "billing") return "Top up credits (provider billing) or switch provider.";
186
- if (params.reason === "auth_permanent" || params.reason === "auth") return "Refresh or replace credentials, then retry.";
187
- }
188
- return "Wait for cooldown or switch provider.";
189
- }
190
- function formatAuthIssueHint(issue) {
191
- if (issue.reasonCode === "invalid_expires") return "Invalid token expires metadata. Set a future Unix ms timestamp or remove expires.";
192
- if (issue.provider === "anthropic" && issue.profileId === "anthropic:claude-cli") return `Deprecated profile. ${buildProviderAuthRecoveryHint({ provider: "anthropic" })}`;
193
- if (issue.provider === "openai-codex" && issue.profileId === "openai-codex:codex-cli") return `Deprecated profile. ${buildProviderAuthRecoveryHint({ provider: "openai-codex" })}`;
194
- return buildProviderAuthRecoveryHint({ provider: issue.provider }).replace(/^Run /, "Re-auth via ");
195
- }
196
- function formatAuthIssueLine(issue) {
197
- const remaining = issue.remainingMs !== void 0 ? ` (${formatRemainingShort(issue.remainingMs)})` : "";
198
- const hint = formatAuthIssueHint(issue);
199
- const reason = issue.reasonCode ? ` [${issue.reasonCode}]` : "";
200
- return `- ${issue.profileId}: ${issue.status}${reason}${remaining}${hint ? ` — ${hint}` : ""}`;
201
- }
202
- async function noteAuthProfileHealth(params) {
203
- const store = ensureAuthProfileStore(void 0, { allowKeychainPrompt: params.allowKeychainPrompt });
204
- const unusable = (() => {
205
- const now = Date.now();
206
- const out = [];
207
- for (const profileId of Object.keys(store.usageStats ?? {})) {
208
- const until = resolveProfileUnusableUntilForDisplay(store, profileId);
209
- if (!until || now >= until) continue;
210
- const stats = store.usageStats?.[profileId];
211
- const remaining = formatRemainingShort(until - now);
212
- const disabledActive = typeof stats?.disabledUntil === "number" && now < stats.disabledUntil;
213
- const kind = disabledActive ? `disabled${stats.disabledReason ? `:${stats.disabledReason}` : ""}` : "cooldown";
214
- const hint = resolveUnusableProfileHint({
215
- kind: disabledActive ? "disabled" : "cooldown",
216
- reason: stats?.disabledReason
217
- });
218
- out.push(`- ${profileId}: ${kind} (${remaining})${hint ? ` — ${hint}` : ""}`);
219
- }
220
- return out;
221
- })();
222
- if (unusable.length > 0) note$1(unusable.join("\n"), "Auth profile cooldowns");
223
- let summary = buildAuthHealthSummary({
224
- store,
225
- cfg: params.cfg,
226
- warnAfterMs: DEFAULT_OAUTH_WARN_MS
227
- });
228
- const findIssues = () => summary.profiles.filter((profile) => (profile.type === "oauth" || profile.type === "token") && (profile.status === "expired" || profile.status === "expiring" || profile.status === "missing"));
229
- let issues = findIssues();
230
- if (issues.length === 0) return;
231
- if (await params.prompter.confirmRepair({
232
- message: "Refresh expiring OAuth tokens now? (static tokens need re-auth)",
233
- initialValue: true
234
- })) {
235
- const refreshTargets = issues.filter((issue) => issue.type === "oauth" && [
236
- "expired",
237
- "expiring",
238
- "missing"
239
- ].includes(issue.status));
240
- const errors = [];
241
- for (const profile of refreshTargets) try {
242
- await resolveApiKeyForProfile({
243
- cfg: params.cfg,
244
- store,
245
- profileId: profile.profileId
246
- });
247
- } catch (err) {
248
- errors.push(`- ${profile.profileId}: ${err instanceof Error ? err.message : String(err)}`);
249
- }
250
- if (errors.length > 0) note$1(errors.join("\n"), "OAuth refresh errors");
251
- summary = buildAuthHealthSummary({
252
- store: ensureAuthProfileStore(void 0, { allowKeychainPrompt: false }),
253
- cfg: params.cfg,
254
- warnAfterMs: DEFAULT_OAUTH_WARN_MS
255
- });
256
- issues = findIssues();
257
- }
258
- if (issues.length > 0) note$1(issues.map((issue) => formatAuthIssueLine({
259
- profileId: issue.profileId,
260
- provider: issue.provider,
261
- status: issue.status,
262
- reasonCode: issue.reasonCode,
263
- remainingMs: issue.remainingMs
264
- })).join("\n"), "Model auth");
265
- }
266
- //#endregion
267
- //#region src/commands/doctor-bootstrap-size.ts
268
- function formatInt(value) {
269
- return new Intl.NumberFormat("en-US").format(Math.max(0, Math.floor(value)));
270
- }
271
- function formatPercent(numerator, denominator) {
272
- if (!Number.isFinite(denominator) || denominator <= 0) return "0%";
273
- return `${Math.min(100, Math.max(0, Math.round(numerator / denominator * 100)))}%`;
274
- }
275
- function formatCauses(causes) {
276
- if (causes.length === 0) return "unknown";
277
- return causes.map((cause) => cause === "per-file-limit" ? "max/file" : "max/total").join(", ");
278
- }
279
- async function noteBootstrapFileSize(cfg) {
280
- const workspaceDir = resolveAgentWorkspaceDir(cfg, resolveDefaultAgentId(cfg));
281
- const bootstrapMaxChars = resolveBootstrapMaxChars(cfg);
282
- const bootstrapTotalMaxChars = resolveBootstrapTotalMaxChars(cfg);
283
- const { bootstrapFiles, contextFiles } = await resolveBootstrapContextForRun({
284
- workspaceDir,
285
- config: cfg
286
- });
287
- const analysis = analyzeBootstrapBudget({
288
- files: buildBootstrapInjectionStats({
289
- bootstrapFiles,
290
- injectedFiles: contextFiles
291
- }),
292
- bootstrapMaxChars,
293
- bootstrapTotalMaxChars
294
- });
295
- if (!analysis.hasTruncation && analysis.nearLimitFiles.length === 0 && !analysis.totalNearLimit) return analysis;
296
- const lines = [];
297
- if (analysis.hasTruncation) {
298
- lines.push("Workspace bootstrap files exceed limits and will be truncated:");
299
- for (const file of analysis.truncatedFiles) {
300
- const truncatedChars = Math.max(0, file.rawChars - file.injectedChars);
301
- lines.push(`- ${file.name}: ${formatInt(file.rawChars)} raw / ${formatInt(file.injectedChars)} injected (${formatPercent(truncatedChars, file.rawChars)} truncated; ${formatCauses(file.causes)})`);
302
- }
303
- } else lines.push("Workspace bootstrap files are near configured limits:");
304
- const nonTruncatedNearLimit = analysis.nearLimitFiles.filter((file) => !file.truncated);
305
- if (nonTruncatedNearLimit.length > 0) for (const file of nonTruncatedNearLimit) lines.push(`- ${file.name}: ${formatInt(file.rawChars)} chars (${formatPercent(file.rawChars, bootstrapMaxChars)} of max/file ${formatInt(bootstrapMaxChars)})`);
306
- lines.push(`Total bootstrap injected chars: ${formatInt(analysis.totals.injectedChars)} (${formatPercent(analysis.totals.injectedChars, bootstrapTotalMaxChars)} of max/total ${formatInt(bootstrapTotalMaxChars)}).`);
307
- lines.push(`Total bootstrap raw chars (before truncation): ${formatInt(analysis.totals.rawChars)}.`);
308
- const needsPerFileTip = analysis.truncatedFiles.some((file) => file.causes.includes("per-file-limit")) || analysis.nearLimitFiles.length > 0;
309
- const needsTotalTip = analysis.truncatedFiles.some((file) => file.causes.includes("total-limit")) || analysis.totalNearLimit;
310
- if (needsPerFileTip || needsTotalTip) lines.push("");
311
- if (needsPerFileTip) lines.push("- Tip: tune `agents.defaults.bootstrapMaxChars` for per-file limits.");
312
- if (needsTotalTip) lines.push("- Tip: tune `agents.defaults.bootstrapTotalMaxChars` for total-budget limits.");
313
- note$1(lines.join("\n"), "Bootstrap file size");
314
- return analysis;
315
- }
316
- //#endregion
317
- //#region src/commands/doctor-browser.ts
318
- const CHROME_MCP_MIN_MAJOR = 144;
319
- const REMOTE_DEBUGGING_PAGES = [
320
- "chrome://inspect/#remote-debugging",
321
- "brave://inspect/#remote-debugging",
322
- "edge://inspect/#remote-debugging"
323
- ].join(", ");
324
- function asRecord(value) {
325
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
326
- }
327
- function collectChromeMcpProfiles(cfg) {
328
- const browser = asRecord(cfg.browser);
329
- if (!browser) return [];
330
- const profiles = /* @__PURE__ */ new Map();
331
- if ((typeof browser.defaultProfile === "string" ? browser.defaultProfile.trim() : "") === "user") profiles.set("user", { name: "user" });
332
- const configuredProfiles = asRecord(browser.profiles);
333
- if (!configuredProfiles) return [...profiles.values()].toSorted((a, b) => a.name.localeCompare(b.name));
334
- for (const [profileName, rawProfile] of Object.entries(configuredProfiles)) {
335
- const profile = asRecord(rawProfile);
336
- if ((typeof profile?.driver === "string" ? profile.driver.trim() : "") === "existing-session") {
337
- const userDataDir = typeof profile?.userDataDir === "string" ? profile.userDataDir.trim() : void 0;
338
- profiles.set(profileName, {
339
- name: profileName,
340
- userDataDir: userDataDir || void 0
341
- });
342
- }
343
- }
344
- return [...profiles.values()].toSorted((a, b) => a.name.localeCompare(b.name));
345
- }
346
- async function noteChromeMcpBrowserReadiness(cfg, deps) {
347
- const profiles = collectChromeMcpProfiles(cfg);
348
- if (profiles.length === 0) return;
349
- const noteFn = deps?.noteFn ?? note$1;
350
- const platform = deps?.platform ?? process.platform;
351
- const resolveChromeExecutable = deps?.resolveChromeExecutable ?? resolveGoogleChromeExecutableForPlatform;
352
- const readVersion = deps?.readVersion ?? readBrowserVersion;
353
- const explicitProfiles = profiles.filter((profile) => profile.userDataDir);
354
- const autoConnectProfiles = profiles.filter((profile) => !profile.userDataDir);
355
- const profileLabel = profiles.map((profile) => profile.name).join(", ");
356
- if (autoConnectProfiles.length === 0) {
357
- noteFn([
358
- `- Chrome MCP existing-session is configured for profile(s): ${profileLabel}.`,
359
- "- These profiles use an explicit Chromium user data directory instead of Chrome's default auto-connect path.",
360
- `- Verify the matching Chromium-based browser is version ${CHROME_MCP_MIN_MAJOR}+ on the same host as the Gateway or node.`,
361
- `- Enable remote debugging in that browser's inspect page (${REMOTE_DEBUGGING_PAGES}).`,
362
- "- Keep the browser running and accept the attach consent prompt the first time moldClaw connects."
363
- ].join("\n"), "Browser");
364
- return;
365
- }
366
- const chrome = resolveChromeExecutable(platform);
367
- const autoProfileLabel = autoConnectProfiles.map((profile) => profile.name).join(", ");
368
- if (!chrome) {
369
- const lines = [
370
- `- Chrome MCP existing-session is configured for profile(s): ${profileLabel}.`,
371
- `- Google Chrome was not found on this host for auto-connect profile(s): ${autoProfileLabel}. moldClaw does not bundle Chrome.`,
372
- `- Install Google Chrome ${CHROME_MCP_MIN_MAJOR}+ on the same host as the Gateway or node, or set browser.profiles.<name>.userDataDir for a different Chromium-based browser.`,
373
- `- Enable remote debugging in the browser inspect page (${REMOTE_DEBUGGING_PAGES}).`,
374
- "- Keep the browser running and accept the attach consent prompt the first time moldClaw connects.",
375
- "- Docker, headless, and sandbox browser flows stay on raw CDP; this check only applies to host-local Chrome MCP attach."
376
- ];
377
- if (explicitProfiles.length > 0) lines.push(`- Profiles with explicit userDataDir skip Chrome auto-detection: ${explicitProfiles.map((profile) => profile.name).join(", ")}.`);
378
- noteFn(lines.join("\n"), "Browser");
379
- return;
380
- }
381
- const versionRaw = readVersion(chrome.path);
382
- const major = parseBrowserMajorVersion(versionRaw);
383
- const lines = [`- Chrome MCP existing-session is configured for profile(s): ${profileLabel}.`, `- Chrome path: ${chrome.path}`];
384
- if (!versionRaw || major === null) lines.push(`- Could not determine the installed Chrome version. Chrome MCP requires Google Chrome ${CHROME_MCP_MIN_MAJOR}+ on this host.`);
385
- else if (major < CHROME_MCP_MIN_MAJOR) lines.push(`- Detected Chrome ${versionRaw}, which is too old for Chrome MCP existing-session attach. Upgrade to Chrome ${CHROME_MCP_MIN_MAJOR}+.`);
386
- else lines.push(`- Detected Chrome ${versionRaw}.`);
387
- lines.push(`- Enable remote debugging in the browser inspect page (${REMOTE_DEBUGGING_PAGES}).`);
388
- lines.push("- Keep the browser running and accept the attach consent prompt the first time moldClaw connects.");
389
- if (explicitProfiles.length > 0) lines.push(`- Profiles with explicit userDataDir still need manual validation of the matching Chromium-based browser: ${explicitProfiles.map((profile) => profile.name).join(", ")}.`);
390
- noteFn(lines.join("\n"), "Browser");
391
- }
392
- //#endregion
393
- //#region src/commands/doctor-cron.ts
394
- function pluralize(count, noun) {
395
- return `${count} ${noun}${count === 1 ? "" : "s"}`;
396
- }
397
- function formatLegacyIssuePreview(issues) {
398
- const lines = [];
399
- if (issues.jobId) lines.push(`- ${pluralize(issues.jobId, "job")} still uses legacy \`jobId\``);
400
- if (issues.legacyScheduleString) lines.push(`- ${pluralize(issues.legacyScheduleString, "job")} stores schedule as a bare string`);
401
- if (issues.legacyScheduleCron) lines.push(`- ${pluralize(issues.legacyScheduleCron, "job")} still uses \`schedule.cron\``);
402
- if (issues.legacyPayloadKind) lines.push(`- ${pluralize(issues.legacyPayloadKind, "job")} needs payload kind normalization`);
403
- if (issues.legacyPayloadProvider) lines.push(`- ${pluralize(issues.legacyPayloadProvider, "job")} still uses payload \`provider\` as a delivery alias`);
404
- if (issues.legacyTopLevelPayloadFields) lines.push(`- ${pluralize(issues.legacyTopLevelPayloadFields, "job")} still uses top-level payload fields`);
405
- if (issues.legacyTopLevelDeliveryFields) lines.push(`- ${pluralize(issues.legacyTopLevelDeliveryFields, "job")} still uses top-level delivery fields`);
406
- if (issues.legacyDeliveryMode) lines.push(`- ${pluralize(issues.legacyDeliveryMode, "job")} still uses delivery mode \`deliver\``);
407
- return lines;
408
- }
409
- function trimString(value) {
410
- return typeof value === "string" && value.trim() ? value.trim() : void 0;
411
- }
412
- function migrateLegacyNotifyFallback(params) {
413
- let changed = false;
414
- const warnings = [];
415
- for (const raw of params.jobs) {
416
- if (!("notify" in raw)) continue;
417
- const jobName = trimString(raw.name) ?? trimString(raw.id) ?? "<unnamed>";
418
- if (!(raw.notify === true)) {
419
- delete raw.notify;
420
- changed = true;
421
- continue;
422
- }
423
- const delivery = raw.delivery && typeof raw.delivery === "object" && !Array.isArray(raw.delivery) ? raw.delivery : null;
424
- const mode = trimString(delivery?.mode)?.toLowerCase();
425
- const to = trimString(delivery?.to);
426
- if (mode === "webhook" && to) {
427
- delete raw.notify;
428
- changed = true;
429
- continue;
430
- }
431
- if ((mode === void 0 || mode === "none" || mode === "webhook") && params.legacyWebhook) {
432
- raw.delivery = {
433
- ...delivery,
434
- mode: "webhook",
435
- to: mode === "none" ? params.legacyWebhook : to ?? params.legacyWebhook
436
- };
437
- delete raw.notify;
438
- changed = true;
439
- continue;
440
- }
441
- if (!params.legacyWebhook) {
442
- warnings.push(`Cron job "${jobName}" still uses legacy notify fallback, but cron.webhook is unset so doctor cannot migrate it automatically.`);
443
- continue;
444
- }
445
- warnings.push(`Cron job "${jobName}" uses legacy notify fallback alongside delivery mode "${mode}". Migrate it manually so webhook delivery does not replace existing announce behavior.`);
446
- }
447
- return {
448
- changed,
449
- warnings
450
- };
451
- }
452
- async function maybeRepairLegacyCronStore(params) {
453
- const storePath = resolveCronStorePath(params.cfg.cron?.store);
454
- const rawJobs = (await loadCronStore(storePath)).jobs ?? [];
455
- if (rawJobs.length === 0) return;
456
- const normalized = normalizeStoredCronJobs(rawJobs);
457
- const legacyWebhook = trimString(params.cfg.cron?.webhook);
458
- const notifyCount = rawJobs.filter((job) => job.notify === true).length;
459
- const previewLines = formatLegacyIssuePreview(normalized.issues);
460
- if (notifyCount > 0) previewLines.push(`- ${pluralize(notifyCount, "job")} still uses legacy \`notify: true\` webhook fallback`);
461
- if (previewLines.length === 0) return;
462
- note$1([
463
- `Legacy cron job storage detected at ${shortenHomePath(storePath)}.`,
464
- ...previewLines,
465
- `Repair with ${formatCliCommand("moldclaw doctor --fix")} to normalize the store before the next scheduler run.`
466
- ].join("\n"), "Cron");
467
- if (!await params.prompter.confirm({
468
- message: "Repair legacy cron jobs now?",
469
- initialValue: true
470
- })) return;
471
- const notifyMigration = migrateLegacyNotifyFallback({
472
- jobs: rawJobs,
473
- legacyWebhook
474
- });
475
- const changed = normalized.mutated || notifyMigration.changed;
476
- if (!changed && notifyMigration.warnings.length === 0) return;
477
- if (changed) {
478
- await saveCronStore(storePath, {
479
- version: 1,
480
- jobs: rawJobs
481
- });
482
- note$1(`Cron store normalized at ${shortenHomePath(storePath)}.`, "Doctor changes");
483
- }
484
- if (notifyMigration.warnings.length > 0) note$1(notifyMigration.warnings.join("\n"), "Doctor warnings");
485
- }
486
- //#endregion
487
- //#region src/commands/doctor-format.ts
488
- function formatGatewayRuntimeSummary(runtime) {
489
- return formatRuntimeStatus(runtime);
490
- }
491
- function buildGatewayRuntimeHints(runtime, options = {}) {
492
- const hints = [];
493
- if (!runtime) return hints;
494
- const platform = options.platform ?? process.platform;
495
- const env = options.env ?? process.env;
496
- const fileLog = (() => {
497
- try {
498
- return getResolvedLoggerSettings().file;
499
- } catch {
500
- return null;
501
- }
502
- })();
503
- if (platform === "linux" && isSystemdUnavailableDetail(runtime.detail)) {
504
- hints.push(...renderSystemdUnavailableHints({ wsl: isWSLEnv() }));
505
- if (fileLog) hints.push(`File logs: ${fileLog}`);
506
- return hints;
507
- }
508
- if (runtime.cachedLabel && platform === "darwin") {
509
- const label = resolveGatewayLaunchAgentLabel(env.MOLDCLAW_PROFILE);
510
- hints.push(`LaunchAgent label cached but plist missing. Clear with: launchctl bootout gui/$UID/${label}`);
511
- hints.push(`Then reinstall: ${formatCliCommand("moldclaw gateway install", env)}`);
512
- }
513
- if (runtime.missingUnit) {
514
- hints.push(`Service not installed. Run: ${formatCliCommand("moldclaw gateway install", env)}`);
515
- if (fileLog) hints.push(`File logs: ${fileLog}`);
516
- return hints;
517
- }
518
- if (runtime.status === "stopped") {
519
- hints.push("Service is loaded but not running (likely exited immediately).");
520
- if (fileLog) hints.push(`File logs: ${fileLog}`);
521
- hints.push(...buildPlatformRuntimeLogHints({
522
- platform,
523
- env,
524
- systemdServiceName: resolveGatewaySystemdServiceName(env.MOLDCLAW_PROFILE),
525
- windowsTaskName: resolveGatewayWindowsTaskName(env.MOLDCLAW_PROFILE)
526
- }));
527
- }
528
- return hints;
529
- }
530
- //#endregion
531
- //#region src/commands/doctor-gateway-daemon-flow.ts
532
- async function maybeRepairLaunchAgentBootstrap(params) {
533
- if (process.platform !== "darwin") return false;
534
- if (!await isLaunchAgentListed({ env: params.env })) return false;
535
- if (await isLaunchAgentLoaded({ env: params.env })) return false;
536
- if (!await launchAgentPlistExists(params.env)) return false;
537
- note$1("LaunchAgent is listed but not loaded in launchd.", `${params.title} LaunchAgent`);
538
- if (!await params.prompter.confirmSkipInNonInteractive({
539
- message: `Repair ${params.title} LaunchAgent bootstrap now?`,
540
- initialValue: true
541
- })) return false;
542
- params.runtime.log(`Bootstrapping ${params.title} LaunchAgent...`);
543
- const repair = await repairLaunchAgentBootstrap({ env: params.env });
544
- if (!repair.ok) {
545
- params.runtime.error(`${params.title} LaunchAgent bootstrap failed: ${repair.detail ?? "unknown error"}`);
546
- return false;
547
- }
548
- if (!await isLaunchAgentLoaded({ env: params.env })) {
549
- params.runtime.error(`${params.title} LaunchAgent still not loaded after repair.`);
550
- return false;
551
- }
552
- note$1(`${params.title} LaunchAgent repaired.`, `${params.title} LaunchAgent`);
553
- return true;
554
- }
555
- async function maybeRepairGatewayDaemon(params) {
556
- if (params.healthOk) return;
557
- const service = resolveGatewayService();
558
- let loaded = false;
559
- try {
560
- loaded = await service.isLoaded({ env: process.env });
561
- } catch {
562
- loaded = false;
563
- }
564
- let serviceRuntime;
565
- if (loaded) serviceRuntime = await service.readRuntime(process.env).catch(() => void 0);
566
- if (process.platform === "darwin" && params.cfg.gateway?.mode !== "remote") {
567
- const gatewayRepaired = await maybeRepairLaunchAgentBootstrap({
568
- env: process.env,
569
- title: "Gateway",
570
- runtime: params.runtime,
571
- prompter: params.prompter
572
- });
573
- await maybeRepairLaunchAgentBootstrap({
574
- env: {
575
- ...process.env,
576
- MOLDCLAW_LAUNCHD_LABEL: resolveNodeLaunchAgentLabel()
577
- },
578
- title: "Node",
579
- runtime: params.runtime,
580
- prompter: params.prompter
581
- });
582
- if (gatewayRepaired) {
583
- loaded = await service.isLoaded({ env: process.env });
584
- if (loaded) serviceRuntime = await service.readRuntime(process.env).catch(() => void 0);
585
- }
586
- }
587
- if (params.cfg.gateway?.mode !== "remote") {
588
- const diagnostics = await inspectPortUsage(resolveGatewayPort(params.cfg, process.env));
589
- if (diagnostics.status === "busy") note$1(formatPortDiagnostics(diagnostics).join("\n"), "Gateway port");
590
- else if (loaded && serviceRuntime?.status === "running") {
591
- const lastError = await readLastGatewayErrorLine(process.env);
592
- if (lastError) note$1(`Last gateway error: ${lastError}`, "Gateway");
593
- }
594
- }
595
- if (!loaded) {
596
- if (process.platform === "linux") {
597
- if (!await isSystemdUserServiceAvailable().catch(() => false)) {
598
- note$1(renderSystemdUnavailableHints({ wsl: await isWSL() }).join("\n"), "Gateway");
599
- return;
600
- }
601
- }
602
- note$1("Gateway service not installed.", "Gateway");
603
- if (params.cfg.gateway?.mode !== "remote") {
604
- if (await params.prompter.confirmSkipInNonInteractive({
605
- message: "Install gateway service now?",
606
- initialValue: true
607
- })) {
608
- const daemonRuntime = await params.prompter.select({
609
- message: "Gateway service runtime",
610
- options: GATEWAY_DAEMON_RUNTIME_OPTIONS,
611
- initialValue: DEFAULT_GATEWAY_DAEMON_RUNTIME
612
- }, DEFAULT_GATEWAY_DAEMON_RUNTIME);
613
- const tokenResolution = await resolveGatewayInstallToken({
614
- config: params.cfg,
615
- env: process.env
616
- });
617
- for (const warning of tokenResolution.warnings) note$1(warning, "Gateway");
618
- if (tokenResolution.unavailableReason) {
619
- note$1([
620
- "Gateway service install aborted.",
621
- tokenResolution.unavailableReason,
622
- "Fix gateway auth config/token input and rerun doctor."
623
- ].join("\n"), "Gateway");
624
- return;
625
- }
626
- const port = resolveGatewayPort(params.cfg, process.env);
627
- const { programArguments, workingDirectory, environment } = await buildGatewayInstallPlan({
628
- env: process.env,
629
- port,
630
- runtime: daemonRuntime,
631
- warn: (message, title) => note$1(message, title),
632
- config: params.cfg
633
- });
634
- try {
635
- await service.install({
636
- env: process.env,
637
- stdout: process.stdout,
638
- programArguments,
639
- workingDirectory,
640
- environment
641
- });
642
- } catch (err) {
643
- note$1(`Gateway service install failed: ${String(err)}`, "Gateway");
644
- note$1(gatewayInstallErrorHint(), "Gateway");
645
- }
646
- }
647
- }
648
- return;
649
- }
650
- const summary = formatGatewayRuntimeSummary(serviceRuntime);
651
- const hints = buildGatewayRuntimeHints(serviceRuntime, {
652
- platform: process.platform,
653
- env: process.env
654
- });
655
- if (summary || hints.length > 0) {
656
- const lines = [];
657
- if (summary) lines.push(`Runtime: ${summary}`);
658
- lines.push(...hints);
659
- note$1(lines.join("\n"), "Gateway");
660
- }
661
- if (serviceRuntime?.status !== "running") {
662
- if (await params.prompter.confirmSkipInNonInteractive({
663
- message: "Start gateway service now?",
664
- initialValue: true
665
- })) {
666
- const restartStatus = describeGatewayServiceRestart("Gateway", await service.restart({
667
- env: process.env,
668
- stdout: process.stdout
669
- }));
670
- if (!restartStatus.scheduled) await sleep(1500);
671
- else note$1(restartStatus.message, "Gateway");
672
- }
673
- }
674
- if (process.platform === "darwin") {
675
- const label = resolveGatewayLaunchAgentLabel(process.env.MOLDCLAW_PROFILE);
676
- note$1(`LaunchAgent loaded; stopping requires "${formatCliCommand("moldclaw gateway stop")}" or launchctl bootout gui/$UID/${label}.`, "Gateway");
677
- }
678
- if (serviceRuntime?.status === "running") {
679
- if (await params.prompter.confirmSkipInNonInteractive({
680
- message: "Restart gateway service now?",
681
- initialValue: true
682
- })) {
683
- const restartStatus = describeGatewayServiceRestart("Gateway", await service.restart({
684
- env: process.env,
685
- stdout: process.stdout
686
- }));
687
- if (restartStatus.scheduled) {
688
- note$1(restartStatus.message, "Gateway");
689
- return;
690
- }
691
- await sleep(1500);
692
- try {
693
- await healthCommand({
694
- json: false,
695
- timeoutMs: 1e4
696
- }, params.runtime);
697
- } catch (err) {
698
- if (String(err).includes("gateway closed")) {
699
- note$1("Gateway not running.", "Gateway");
700
- note$1(params.gatewayDetailsMessage, "Gateway connection");
701
- } else params.runtime.error(formatHealthCheckFailure(err));
702
- }
703
- }
704
- }
705
- }
706
- //#endregion
707
- //#region src/commands/doctor-gateway-health.ts
708
- async function checkGatewayHealth(params) {
709
- const gatewayDetails = buildGatewayConnectionDetails({ config: params.cfg });
710
- const timeoutMs = typeof params.timeoutMs === "number" && params.timeoutMs > 0 ? params.timeoutMs : 1e4;
711
- let healthOk = false;
712
- try {
713
- await healthCommand({
714
- json: false,
715
- timeoutMs,
716
- config: params.cfg
717
- }, params.runtime);
718
- healthOk = true;
719
- } catch (err) {
720
- if (String(err).includes("gateway closed")) {
721
- note$1("Gateway not running.", "Gateway");
722
- note$1(gatewayDetails.message, "Gateway connection");
723
- } else params.runtime.error(formatHealthCheckFailure(err));
724
- }
725
- if (healthOk) try {
726
- const issues = collectChannelStatusIssues(await callGateway({
727
- method: "channels.status",
728
- params: {
729
- probe: true,
730
- timeoutMs: 5e3
731
- },
732
- timeoutMs: 6e3
733
- }));
734
- if (issues.length > 0) note$1(issues.map((issue) => `- ${issue.channel} ${issue.accountId}: ${issue.message}${issue.fix ? ` (${issue.fix})` : ""}`).join("\n"), "Channel warnings");
735
- } catch {}
736
- return { healthOk };
737
- }
738
- async function probeGatewayMemoryStatus(params) {
739
- const timeoutMs = typeof params.timeoutMs === "number" && params.timeoutMs > 0 ? params.timeoutMs : 8e3;
740
- try {
741
- const payload = await callGateway({
742
- method: "doctor.memory.status",
743
- timeoutMs,
744
- config: params.cfg
745
- });
746
- return {
747
- checked: true,
748
- ready: payload.embedding.ok,
749
- error: payload.embedding.error
750
- };
751
- } catch (err) {
752
- return {
753
- checked: true,
754
- ready: false,
755
- error: `gateway memory probe unavailable: ${err instanceof Error ? err.message : String(err)}`
756
- };
757
- }
758
- }
759
- //#endregion
760
- //#region src/commands/doctor-gateway-auth-token.ts
761
- async function resolveGatewayAuthTokenForService(cfg, env) {
762
- const resolved = await resolveConfiguredSecretInputWithFallback({
763
- config: cfg,
764
- env,
765
- value: cfg.gateway?.auth?.token,
766
- path: "gateway.auth.token",
767
- unresolvedReasonStyle: "detailed",
768
- readFallback: () => readGatewayTokenEnv(env)
769
- });
770
- if (resolved.value) return { token: resolved.value };
771
- if (!resolved.secretRefConfigured) return {};
772
- if (resolved.unresolvedRefReason?.includes("resolved to an empty value")) return { unavailableReason: resolved.unresolvedRefReason };
773
- return { unavailableReason: `gateway.auth.token SecretRef is configured but unresolved (${resolved.unresolvedRefReason ?? "unknown reason"}).` };
774
- }
775
- //#endregion
776
- //#region src/commands/doctor-gateway-services.ts
777
- const execFileAsync$1 = promisify(execFile);
778
- function detectGatewayRuntime(programArguments) {
779
- const first = programArguments?.[0];
780
- if (first) {
781
- const base = path.basename(first).toLowerCase();
782
- if (base === "bun" || base === "bun.exe") return "bun";
783
- if (base === "node" || base === "node.exe") return "node";
784
- }
785
- return DEFAULT_GATEWAY_DAEMON_RUNTIME;
786
- }
787
- function findGatewayEntrypoint(programArguments) {
788
- if (!programArguments || programArguments.length === 0) return null;
789
- const gatewayIndex = programArguments.indexOf("gateway");
790
- if (gatewayIndex <= 0) return null;
791
- return programArguments[gatewayIndex - 1] ?? null;
792
- }
793
- async function normalizeExecutablePath(value) {
794
- const resolvedPath = path.resolve(value);
795
- try {
796
- return await fs$1.realpath(resolvedPath);
797
- } catch {
798
- return resolvedPath;
799
- }
800
- }
801
- function extractDetailPath(detail, prefix) {
802
- if (!detail.startsWith(prefix)) return null;
803
- const value = detail.slice(prefix.length).trim();
804
- return value.length > 0 ? value : null;
805
- }
806
- async function cleanupLegacyLaunchdService(params) {
807
- if (typeof process.getuid !== "function") return null;
808
- await execFileAsync$1("launchctl", [
809
- "bootout",
810
- `gui/${process.getuid()}`,
811
- params.plistPath
812
- ]).catch(() => void 0);
813
- await execFileAsync$1("launchctl", ["unload", params.plistPath]).catch(() => void 0);
814
- const trashDir = path.join(os.homedir(), ".Trash");
815
- try {
816
- await fs$1.mkdir(trashDir, { recursive: true });
817
- } catch {}
818
- try {
819
- await fs$1.access(params.plistPath);
820
- } catch {
821
- return null;
822
- }
823
- const dest = path.join(trashDir, `${params.label}-${Date.now()}.plist`);
824
- try {
825
- await fs$1.rename(params.plistPath, dest);
826
- return dest;
827
- } catch {
828
- return null;
829
- }
830
- }
831
- function classifyLegacyServices(legacyServices) {
832
- const darwinUserServices = [];
833
- const linuxUserServices = [];
834
- const failed = [];
835
- for (const svc of legacyServices) {
836
- if (svc.platform === "darwin") {
837
- if (svc.scope === "user") darwinUserServices.push(svc);
838
- else failed.push(`${svc.label} (${svc.scope})`);
839
- continue;
840
- }
841
- if (svc.platform === "linux") {
842
- if (svc.scope === "user") linuxUserServices.push(svc);
843
- else failed.push(`${svc.label} (${svc.scope})`);
844
- continue;
845
- }
846
- failed.push(`${svc.label} (${svc.platform})`);
847
- }
848
- return {
849
- darwinUserServices,
850
- linuxUserServices,
851
- failed
852
- };
853
- }
854
- async function cleanupLegacyDarwinServices(services) {
855
- const removed = [];
856
- const failed = [];
857
- for (const svc of services) {
858
- const plistPath = extractDetailPath(svc.detail, "plist:");
859
- if (!plistPath) {
860
- failed.push(`${svc.label} (missing plist path)`);
861
- continue;
862
- }
863
- const dest = await cleanupLegacyLaunchdService({
864
- label: svc.label,
865
- plistPath
866
- });
867
- removed.push(dest ? `${svc.label} -> ${dest}` : svc.label);
868
- }
869
- return {
870
- removed,
871
- failed
872
- };
873
- }
874
- async function cleanupLegacyLinuxUserServices(services, runtime) {
875
- const removed = [];
876
- const failed = [];
877
- try {
878
- const removedUnits = await uninstallLegacySystemdUnits({
879
- env: process.env,
880
- stdout: process.stdout
881
- });
882
- const removedByLabel = new Map(removedUnits.map((unit) => [`${unit.name}.service`, unit]));
883
- for (const svc of services) {
884
- const removedUnit = removedByLabel.get(svc.label);
885
- if (!removedUnit) {
886
- failed.push(`${svc.label} (legacy unit name not recognized)`);
887
- continue;
888
- }
889
- removed.push(`${svc.label} -> ${removedUnit.unitPath}`);
890
- }
891
- } catch (err) {
892
- runtime.error(`Legacy Linux gateway cleanup failed: ${String(err)}`);
893
- for (const svc of services) failed.push(`${svc.label} (linux cleanup failed)`);
894
- }
895
- return {
896
- removed,
897
- failed
898
- };
899
- }
900
- async function maybeRepairGatewayServiceConfig(cfg, mode, runtime, prompter) {
901
- if (resolveIsNixMode(process.env)) {
902
- note$1("Nix mode detected; skip service updates.", "Gateway");
903
- return;
904
- }
905
- if (mode === "remote") {
906
- note$1("Gateway mode is remote; skipped local service audit.", "Gateway");
907
- return;
908
- }
909
- const service = resolveGatewayService();
910
- let command = null;
911
- try {
912
- command = await service.readCommand(process.env);
913
- } catch {
914
- command = null;
915
- }
916
- if (!command) return;
917
- const tokenRefConfigured = Boolean(resolveSecretInputRef({
918
- value: cfg.gateway?.auth?.token,
919
- defaults: cfg.secrets?.defaults
920
- }).ref);
921
- const gatewayTokenResolution = await resolveGatewayAuthTokenForService(cfg, process.env);
922
- if (gatewayTokenResolution.unavailableReason) note$1(`Unable to verify gateway service token drift: ${gatewayTokenResolution.unavailableReason}`, "Gateway service config");
923
- const expectedGatewayToken = tokenRefConfigured ? void 0 : gatewayTokenResolution.token;
924
- const audit = await auditGatewayServiceConfig({
925
- env: process.env,
926
- command,
927
- expectedGatewayToken
928
- });
929
- const serviceToken = readEmbeddedGatewayToken(command);
930
- if (tokenRefConfigured && serviceToken) audit.issues.push({
931
- code: SERVICE_AUDIT_CODES.gatewayTokenMismatch,
932
- message: "Gateway service MOLDCLAW_GATEWAY_TOKEN should be unset when gateway.auth.token is SecretRef-managed",
933
- detail: "service token is stale",
934
- level: "recommended"
935
- });
936
- const needsNodeRuntime = needsNodeRuntimeMigration(audit.issues);
937
- const systemNodeInfo = needsNodeRuntime ? await resolveSystemNodeInfo({ env: process.env }) : null;
938
- const systemNodePath = systemNodeInfo?.supported ? systemNodeInfo.path : null;
939
- if (needsNodeRuntime && !systemNodePath) {
940
- const warning = renderSystemNodeWarning(systemNodeInfo);
941
- if (warning) note$1(warning, "Gateway runtime");
942
- note$1("System Node 22 LTS (22.16+) or Node 24 not found. Install via Homebrew/apt/choco and rerun doctor to migrate off Bun/version managers.", "Gateway runtime");
943
- }
944
- const port = resolveGatewayPort(cfg, process.env);
945
- const runtimeChoice = detectGatewayRuntime(command.programArguments);
946
- const { programArguments } = await buildGatewayInstallPlan({
947
- env: process.env,
948
- port,
949
- runtime: needsNodeRuntime && systemNodePath ? "node" : runtimeChoice,
950
- nodePath: systemNodePath ?? void 0,
951
- warn: (message, title) => note$1(message, title),
952
- config: cfg
953
- });
954
- const expectedEntrypoint = findGatewayEntrypoint(programArguments);
955
- const currentEntrypoint = findGatewayEntrypoint(command.programArguments);
956
- const normalizedExpectedEntrypoint = expectedEntrypoint ? await normalizeExecutablePath(expectedEntrypoint) : null;
957
- const normalizedCurrentEntrypoint = currentEntrypoint ? await normalizeExecutablePath(currentEntrypoint) : null;
958
- if (normalizedExpectedEntrypoint && normalizedCurrentEntrypoint && normalizedExpectedEntrypoint !== normalizedCurrentEntrypoint) audit.issues.push({
959
- code: SERVICE_AUDIT_CODES.gatewayEntrypointMismatch,
960
- message: "Gateway service entrypoint does not match the current install.",
961
- detail: `${currentEntrypoint} -> ${expectedEntrypoint}`,
962
- level: "recommended"
963
- });
964
- if (audit.issues.length === 0) return;
965
- note$1(audit.issues.map((issue) => issue.detail ? `- ${issue.message} (${issue.detail})` : `- ${issue.message}`).join("\n"), "Gateway service config");
966
- const needsAggressive = audit.issues.filter((issue) => issue.level === "aggressive").length > 0;
967
- if (needsAggressive && !prompter.shouldForce) note$1("Custom or unexpected service edits detected. Rerun with --force to overwrite.", "Gateway service config");
968
- if (!(needsAggressive ? await prompter.confirmAggressive({
969
- message: "Overwrite gateway service config with current defaults now?",
970
- initialValue: Boolean(prompter.shouldForce)
971
- }) : await prompter.confirmRepair({
972
- message: "Update gateway service config to the recommended defaults now?",
973
- initialValue: true
974
- }))) return;
975
- const serviceEmbeddedToken = readEmbeddedGatewayToken(command);
976
- const gatewayTokenForRepair = expectedGatewayToken ?? serviceEmbeddedToken;
977
- const configuredGatewayToken = typeof cfg.gateway?.auth?.token === "string" ? cfg.gateway.auth.token.trim() || void 0 : void 0;
978
- let cfgForServiceInstall = cfg;
979
- if (!tokenRefConfigured && !configuredGatewayToken && gatewayTokenForRepair) {
980
- const nextCfg = {
981
- ...cfg,
982
- gateway: {
983
- ...cfg.gateway,
984
- auth: {
985
- ...cfg.gateway?.auth,
986
- mode: cfg.gateway?.auth?.mode ?? "token",
987
- token: gatewayTokenForRepair
988
- }
989
- }
990
- };
991
- try {
992
- await writeConfigFile(nextCfg);
993
- cfgForServiceInstall = nextCfg;
994
- note$1(expectedGatewayToken ? "Persisted gateway.auth.token from environment before reinstalling service." : "Persisted gateway.auth.token from existing service definition before reinstalling service.", "Gateway");
995
- } catch (err) {
996
- runtime.error(`Failed to persist gateway.auth.token before service repair: ${String(err)}`);
997
- return;
998
- }
999
- }
1000
- const updatedPort = resolveGatewayPort(cfgForServiceInstall, process.env);
1001
- const updatedPlan = await buildGatewayInstallPlan({
1002
- env: process.env,
1003
- port: updatedPort,
1004
- runtime: needsNodeRuntime && systemNodePath ? "node" : runtimeChoice,
1005
- nodePath: systemNodePath ?? void 0,
1006
- warn: (message, title) => note$1(message, title),
1007
- config: cfgForServiceInstall
1008
- });
1009
- try {
1010
- await service.install({
1011
- env: process.env,
1012
- stdout: process.stdout,
1013
- programArguments: updatedPlan.programArguments,
1014
- workingDirectory: updatedPlan.workingDirectory,
1015
- environment: updatedPlan.environment
1016
- });
1017
- } catch (err) {
1018
- runtime.error(`Gateway service update failed: ${String(err)}`);
1019
- }
1020
- }
1021
- async function maybeScanExtraGatewayServices(options, runtime, prompter) {
1022
- const extraServices = await findExtraGatewayServices(process.env, { deep: options.deep });
1023
- if (extraServices.length === 0) return;
1024
- note$1(extraServices.map((svc) => `- ${svc.label} (${svc.scope}, ${svc.detail})`).join("\n"), "Other gateway-like services detected");
1025
- const legacyServices = extraServices.filter((svc) => svc.legacy === true);
1026
- if (legacyServices.length > 0) {
1027
- if (await prompter.confirmSkipInNonInteractive({
1028
- message: "Remove legacy gateway services (clawdbot/moltbot) now?",
1029
- initialValue: true
1030
- })) {
1031
- const removed = [];
1032
- const { darwinUserServices, linuxUserServices, failed } = classifyLegacyServices(legacyServices);
1033
- if (darwinUserServices.length > 0) {
1034
- const result = await cleanupLegacyDarwinServices(darwinUserServices);
1035
- removed.push(...result.removed);
1036
- failed.push(...result.failed);
1037
- }
1038
- if (linuxUserServices.length > 0) {
1039
- const result = await cleanupLegacyLinuxUserServices(linuxUserServices, runtime);
1040
- removed.push(...result.removed);
1041
- failed.push(...result.failed);
1042
- }
1043
- if (removed.length > 0) note$1(removed.map((line) => `- ${line}`).join("\n"), "Legacy gateway removed");
1044
- if (failed.length > 0) note$1(failed.map((line) => `- ${line}`).join("\n"), "Legacy gateway cleanup skipped");
1045
- if (removed.length > 0) runtime.log("Legacy gateway services removed. Installing moldClaw gateway next.");
1046
- }
1047
- }
1048
- const cleanupHints = renderGatewayServiceCleanupHints();
1049
- if (cleanupHints.length > 0) note$1(cleanupHints.map((hint) => `- ${hint}`).join("\n"), "Cleanup hints");
1050
- note$1([
1051
- "Recommendation: run a single gateway per machine for most setups.",
1052
- "One gateway supports multiple agents.",
1053
- "If you need multiple gateways (e.g., a rescue bot on the same host), isolate ports + config/state (see docs: /gateway#multiple-gateways-same-host)."
1054
- ].join("\n"), "Gateway recommendation");
1055
- }
1056
- //#endregion
1057
- //#region src/commands/doctor-install.ts
1058
- function noteSourceInstallIssues(root) {
1059
- if (!root) return;
1060
- const workspaceMarker = path.join(root, "pnpm-workspace.yaml");
1061
- if (!fs.existsSync(workspaceMarker)) return;
1062
- const warnings = [];
1063
- const nodeModules = path.join(root, "node_modules");
1064
- const pnpmStore = path.join(nodeModules, ".pnpm");
1065
- const tsxBin = path.join(nodeModules, ".bin", "tsx");
1066
- const srcEntry = path.join(root, "src", "entry.ts");
1067
- if (fs.existsSync(nodeModules) && !fs.existsSync(pnpmStore)) warnings.push("- node_modules was not installed by pnpm (missing node_modules/.pnpm). Run: pnpm install");
1068
- if (fs.existsSync(path.join(root, "package-lock.json"))) warnings.push("- package-lock.json present in a pnpm workspace. If you ran npm install, remove it and reinstall with pnpm.");
1069
- if (fs.existsSync(srcEntry) && !fs.existsSync(tsxBin)) warnings.push("- tsx binary is missing for source runs. Run: pnpm install");
1070
- if (warnings.length > 0) note$1(warnings.join("\n"), "Install");
1071
- }
1072
- //#endregion
1073
- //#region src/commands/doctor-memory-search.ts
1074
- /**
1075
- * Check whether memory search has a usable embedding provider.
1076
- * Runs as part of `moldclaw doctor` — config-only, no network calls.
1077
- */
1078
- async function noteMemorySearchHealth(cfg, opts) {
1079
- const agentId = resolveDefaultAgentId(cfg);
1080
- const agentDir = resolveAgentDir(cfg, agentId);
1081
- const resolved = resolveMemorySearchConfig(cfg, agentId);
1082
- const hasRemoteApiKey = hasConfiguredMemorySecretInput(resolved?.remote?.apiKey);
1083
- if (!resolved) {
1084
- note$1("Memory search is explicitly disabled (enabled: false).", "Memory search");
1085
- return;
1086
- }
1087
- if (resolveMemoryBackendConfig({
1088
- cfg,
1089
- agentId
1090
- }).backend === "qmd") return;
1091
- if (resolved.provider !== "auto") {
1092
- if (resolved.provider === "local") {
1093
- if (hasLocalEmbeddings(resolved.local, true)) {
1094
- if (opts?.gatewayMemoryProbe?.checked && !opts.gatewayMemoryProbe.ready) {
1095
- const detail = opts.gatewayMemoryProbe.error?.trim();
1096
- note$1([
1097
- "Memory search provider is set to \"local\" and a model path is configured,",
1098
- "but the gateway reports local embeddings are not ready.",
1099
- detail ? `Gateway probe: ${detail}` : null,
1100
- "",
1101
- `Verify: ${formatCliCommand("moldclaw memory status --deep")}`
1102
- ].filter(Boolean).join("\n"), "Memory search");
1103
- }
1104
- return;
1105
- }
1106
- note$1([
1107
- "Memory search provider is set to \"local\" but no local model file was found.",
1108
- "",
1109
- "Fix (pick one):",
1110
- `- Install node-llama-cpp and set a local model path in config`,
1111
- `- Switch to a remote provider: ${formatCliCommand("moldclaw config set agents.defaults.memorySearch.provider openai")}`,
1112
- "",
1113
- `Verify: ${formatCliCommand("moldclaw memory status --deep")}`
1114
- ].join("\n"), "Memory search");
1115
- return;
1116
- }
1117
- if (hasRemoteApiKey || await hasApiKeyForProvider(resolved.provider, cfg, agentDir)) return;
1118
- if (opts?.gatewayMemoryProbe?.checked && opts.gatewayMemoryProbe.ready) {
1119
- note$1([
1120
- `Memory search provider is set to "${resolved.provider}" but the API key was not found in the CLI environment.`,
1121
- "The running gateway reports memory embeddings are ready for the default agent.",
1122
- `Verify: ${formatCliCommand("moldclaw memory status --deep")}`
1123
- ].join("\n"), "Memory search");
1124
- return;
1125
- }
1126
- const gatewayProbeWarning = buildGatewayProbeWarning(opts?.gatewayMemoryProbe);
1127
- const envVar = providerEnvVar(resolved.provider);
1128
- note$1([
1129
- `Memory search provider is set to "${resolved.provider}" but no API key was found.`,
1130
- `Semantic recall will not work without a valid API key.`,
1131
- gatewayProbeWarning ? gatewayProbeWarning : null,
1132
- "",
1133
- "Fix (pick one):",
1134
- `- Set ${envVar} in your environment`,
1135
- `- Configure credentials: ${formatCliCommand("moldclaw configure --section model")}`,
1136
- `- To disable: ${formatCliCommand("moldclaw config set agents.defaults.memorySearch.enabled false")}`,
1137
- "",
1138
- `Verify: ${formatCliCommand("moldclaw memory status --deep")}`
1139
- ].join("\n"), "Memory search");
1140
- return;
1141
- }
1142
- if (hasLocalEmbeddings(resolved.local)) return;
1143
- for (const provider of [
1144
- "openai",
1145
- "gemini",
1146
- "voyage",
1147
- "mistral"
1148
- ]) if (hasRemoteApiKey || await hasApiKeyForProvider(provider, cfg, agentDir)) return;
1149
- if (opts?.gatewayMemoryProbe?.checked && opts.gatewayMemoryProbe.ready) {
1150
- note$1([
1151
- "Memory search provider is set to \"auto\" but the API key was not found in the CLI environment.",
1152
- "The running gateway reports memory embeddings are ready for the default agent.",
1153
- `Verify: ${formatCliCommand("moldclaw memory status --deep")}`
1154
- ].join("\n"), "Memory search");
1155
- return;
1156
- }
1157
- const gatewayProbeWarning = buildGatewayProbeWarning(opts?.gatewayMemoryProbe);
1158
- note$1([
1159
- "Memory search is enabled but no embedding provider is configured.",
1160
- "Semantic recall will not work without an embedding provider.",
1161
- gatewayProbeWarning ? gatewayProbeWarning : null,
1162
- "",
1163
- "Fix (pick one):",
1164
- "- Set OPENAI_API_KEY, GEMINI_API_KEY, VOYAGE_API_KEY, or MISTRAL_API_KEY in your environment",
1165
- `- Configure credentials: ${formatCliCommand("moldclaw configure --section model")}`,
1166
- `- For local embeddings: configure agents.defaults.memorySearch.provider and local model path`,
1167
- `- To disable: ${formatCliCommand("moldclaw config set agents.defaults.memorySearch.enabled false")}`,
1168
- "",
1169
- `Verify: ${formatCliCommand("moldclaw memory status --deep")}`
1170
- ].join("\n"), "Memory search");
1171
- }
1172
- /**
1173
- * Check whether local embeddings are available.
1174
- *
1175
- * When `useDefaultFallback` is true (explicit `provider: "local"`), an empty
1176
- * modelPath is treated as available because the runtime falls back to
1177
- * DEFAULT_LOCAL_MODEL (an auto-downloaded HuggingFace model).
1178
- *
1179
- * When false (provider: "auto"), we only consider local available if the user
1180
- * explicitly configured a local file path — matching `canAutoSelectLocal()`
1181
- * in the runtime, which skips local for empty/hf: model paths.
1182
- */
1183
- function hasLocalEmbeddings(local, useDefaultFallback = false) {
1184
- const modelPath = local.modelPath?.trim() || (useDefaultFallback ? "hf:ggml-org/embeddinggemma-300m-qat-q8_0-GGUF/embeddinggemma-300m-qat-Q8_0.gguf" : void 0);
1185
- if (!modelPath) return false;
1186
- if (/^(hf:|https?:)/i.test(modelPath)) return true;
1187
- const resolved = resolveUserPath(modelPath);
1188
- try {
1189
- return fs.statSync(resolved).isFile();
1190
- } catch {
1191
- return false;
1192
- }
1193
- }
1194
- async function hasApiKeyForProvider(provider, cfg, agentDir) {
1195
- const authProvider = provider === "gemini" ? "google" : provider;
1196
- try {
1197
- await resolveApiKeyForProvider({
1198
- provider: authProvider,
1199
- cfg,
1200
- agentDir
1201
- });
1202
- return true;
1203
- } catch {
1204
- return false;
1205
- }
1206
- }
1207
- function providerEnvVar(provider) {
1208
- switch (provider) {
1209
- case "openai": return "OPENAI_API_KEY";
1210
- case "gemini": return "GEMINI_API_KEY";
1211
- case "voyage": return "VOYAGE_API_KEY";
1212
- default: return `${provider.toUpperCase()}_API_KEY`;
1213
- }
1214
- }
1215
- function buildGatewayProbeWarning(probe) {
1216
- if (!probe?.checked || probe.ready) return null;
1217
- const detail = probe.error?.trim();
1218
- return detail ? `Gateway memory probe for default agent is not ready: ${detail}` : "Gateway memory probe for default agent is not ready.";
1219
- }
1220
- //#endregion
1221
- //#region src/commands/doctor-platform-notes.ts
1222
- const execFileAsync = promisify(execFile);
1223
- function resolveHomeDir() {
1224
- return process.env.HOME ?? os.homedir();
1225
- }
1226
- async function noteMacLaunchAgentOverrides() {
1227
- if (process.platform !== "darwin") return;
1228
- const home = resolveHomeDir();
1229
- const markerPath = [path.join(home, ".moldclaw", "disable-launchagent")].find((candidate) => fs.existsSync(candidate));
1230
- if (!markerPath) return;
1231
- const displayMarkerPath = shortenHomePath(markerPath);
1232
- note$1([
1233
- `- LaunchAgent writes are disabled via ${displayMarkerPath}.`,
1234
- "- To restore default behavior:",
1235
- ` rm ${displayMarkerPath}`
1236
- ].filter((line) => Boolean(line)).join("\n"), "Gateway (macOS)");
1237
- }
1238
- async function launchctlGetenv(name) {
1239
- try {
1240
- const result = await execFileAsync("/bin/launchctl", ["getenv", name], { encoding: "utf8" });
1241
- const value = String(result.stdout ?? "").trim();
1242
- return value.length > 0 ? value : void 0;
1243
- } catch {
1244
- return;
1245
- }
1246
- }
1247
- function hasConfigGatewayCreds(cfg) {
1248
- const localPassword = cfg.gateway?.auth?.password;
1249
- const remoteToken = cfg.gateway?.remote?.token;
1250
- const remotePassword = cfg.gateway?.remote?.password;
1251
- return Boolean(hasConfiguredSecretInput(cfg.gateway?.auth?.token, cfg.secrets?.defaults) || hasConfiguredSecretInput(localPassword, cfg.secrets?.defaults) || hasConfiguredSecretInput(remoteToken, cfg.secrets?.defaults) || hasConfiguredSecretInput(remotePassword, cfg.secrets?.defaults));
1252
- }
1253
- async function noteMacLaunchctlGatewayEnvOverrides(cfg, deps) {
1254
- if ((deps?.platform ?? process.platform) !== "darwin") return;
1255
- if (!hasConfigGatewayCreds(cfg)) return;
1256
- const getenv = deps?.getenv ?? launchctlGetenv;
1257
- const deprecatedLaunchctlEntries = [["MOLDCLAW_GATEWAY_TOKEN", await getenv("MOLDCLAW_GATEWAY_TOKEN")], ["MOLDCLAW_GATEWAY_PASSWORD", await getenv("MOLDCLAW_GATEWAY_PASSWORD")]].filter((entry) => Boolean(entry[1]?.trim()));
1258
- if (deprecatedLaunchctlEntries.length > 0) {
1259
- const lines = ["- Deprecated launchctl environment variables detected (ignored).", ...deprecatedLaunchctlEntries.map(([key]) => `- \`${key}\` is set; use \`MOLDCLAW_${key.slice(key.indexOf("_") + 1)}\` instead.`)];
1260
- (deps?.noteFn ?? note$1)(lines.join("\n"), "Gateway (macOS)");
1261
- }
1262
- const tokenEntries = [["MOLDCLAW_GATEWAY_TOKEN", await getenv("MOLDCLAW_GATEWAY_TOKEN")]];
1263
- const passwordEntries = [["MOLDCLAW_GATEWAY_PASSWORD", await getenv("MOLDCLAW_GATEWAY_PASSWORD")]];
1264
- const tokenEntry = tokenEntries.find(([, value]) => value?.trim());
1265
- const passwordEntry = passwordEntries.find(([, value]) => value?.trim());
1266
- const envToken = tokenEntry?.[1]?.trim() ?? "";
1267
- const envPassword = passwordEntry?.[1]?.trim() ?? "";
1268
- const envTokenKey = tokenEntry?.[0];
1269
- const envPasswordKey = passwordEntry?.[0];
1270
- if (!envToken && !envPassword) return;
1271
- const lines = [
1272
- "- launchctl environment overrides detected (can cause confusing unauthorized errors).",
1273
- envToken && envTokenKey ? `- \`${envTokenKey}\` is set; it overrides config tokens.` : void 0,
1274
- envPassword ? `- \`${envPasswordKey ?? "MOLDCLAW_GATEWAY_PASSWORD"}\` is set; it overrides config passwords.` : void 0,
1275
- "- Clear overrides and restart the app/gateway:",
1276
- envTokenKey ? ` launchctl unsetenv ${envTokenKey}` : void 0,
1277
- envPasswordKey ? ` launchctl unsetenv ${envPasswordKey}` : void 0
1278
- ].filter((line) => Boolean(line));
1279
- (deps?.noteFn ?? note$1)(lines.join("\n"), "Gateway (macOS)");
1280
- }
1281
- function noteDeprecatedLegacyEnvVars(env = process.env, deps) {
1282
- const entries = Object.entries(env).filter(([key, value]) => key.startsWith("MOLDCLAW_") && value?.trim()).map(([key]) => key);
1283
- if (entries.length === 0) return;
1284
- const lines = [
1285
- "- Deprecated legacy environment variables detected (ignored).",
1286
- "- Use MOLDCLAW_* equivalents instead:",
1287
- ...entries.map((key) => {
1288
- return ` ${key} -> MOLDCLAW_${key.slice(key.indexOf("_") + 1)}`;
1289
- })
1290
- ];
1291
- (deps?.noteFn ?? note$1)(lines.join("\n"), "Environment");
1292
- }
1293
- function isTruthyEnvValue(value) {
1294
- return typeof value === "string" && value.trim().length > 0;
1295
- }
1296
- function isTmpCompileCachePath(cachePath) {
1297
- const normalized = cachePath.trim().replace(/\/+$/, "");
1298
- return normalized === "/tmp" || normalized.startsWith("/tmp/") || normalized === "/private/tmp" || normalized.startsWith("/private/tmp/");
1299
- }
1300
- function noteStartupOptimizationHints(env = process.env, deps) {
1301
- const platform = deps?.platform ?? process.platform;
1302
- if (platform === "win32") return;
1303
- const arch = deps?.arch ?? os.arch();
1304
- const totalMemBytes = deps?.totalMemBytes ?? os.totalmem();
1305
- if (!(platform === "linux" && (arch === "arm" || arch === "arm64" || platform === "linux" && totalMemBytes > 0 && totalMemBytes <= 8 * 1024 ** 3))) return;
1306
- const noteFn = deps?.noteFn ?? note$1;
1307
- const compileCache = env.NODE_COMPILE_CACHE?.trim() ?? "";
1308
- const disableCompileCache = env.NODE_DISABLE_COMPILE_CACHE?.trim() ?? "";
1309
- const noRespawn = env.MOLDCLAW_NO_RESPAWN?.trim() ?? "";
1310
- const lines = [];
1311
- if (!compileCache) lines.push("- NODE_COMPILE_CACHE is not set; repeated CLI runs can be slower on small hosts (Pi/VM).");
1312
- else if (isTmpCompileCachePath(compileCache)) lines.push("- NODE_COMPILE_CACHE points to /tmp; use /var/tmp so cache survives reboots and warms startup reliably.");
1313
- if (isTruthyEnvValue(disableCompileCache)) lines.push("- NODE_DISABLE_COMPILE_CACHE is set; startup compile cache is disabled.");
1314
- if (noRespawn !== "1") lines.push("- MOLDCLAW_NO_RESPAWN is not set to 1; set it to avoid extra startup overhead from self-respawn.");
1315
- if (lines.length === 0) return;
1316
- const suggestions = [
1317
- "- Suggested env for low-power hosts:",
1318
- " export NODE_COMPILE_CACHE=/var/tmp/moldclaw-compile-cache",
1319
- " mkdir -p /var/tmp/moldclaw-compile-cache",
1320
- " export MOLDCLAW_NO_RESPAWN=1",
1321
- isTruthyEnvValue(disableCompileCache) ? " unset NODE_DISABLE_COMPILE_CACHE" : void 0
1322
- ].filter((line) => Boolean(line));
1323
- noteFn([...lines, ...suggestions].join("\n"), "Startup optimization");
1324
- }
1325
- //#endregion
1326
- //#region src/commands/doctor-prompter.ts
1327
- function createDoctorPrompter(params) {
1328
- const yes = params.options.yes === true;
1329
- const requestedNonInteractive = params.options.nonInteractive === true;
1330
- const shouldRepair = params.options.repair === true || yes;
1331
- const shouldForce = params.options.force === true;
1332
- const isTty = Boolean(process.stdin.isTTY);
1333
- const nonInteractive = requestedNonInteractive || !isTty && !yes;
1334
- const canPrompt = isTty && !yes && !nonInteractive;
1335
- const confirmDefault = async (p) => {
1336
- if (nonInteractive) return false;
1337
- if (shouldRepair) return true;
1338
- if (!canPrompt) return Boolean(p.initialValue ?? false);
1339
- return guardCancel(await confirm({
1340
- ...p,
1341
- message: stylePromptMessage(p.message)
1342
- }), params.runtime);
1343
- };
1344
- return {
1345
- confirm: confirmDefault,
1346
- confirmRepair: async (p) => {
1347
- if (nonInteractive) return false;
1348
- return confirmDefault(p);
1349
- },
1350
- confirmAggressive: async (p) => {
1351
- if (nonInteractive) return false;
1352
- if (shouldRepair && shouldForce) return true;
1353
- if (shouldRepair && !shouldForce) return false;
1354
- if (!canPrompt) return Boolean(p.initialValue ?? false);
1355
- return guardCancel(await confirm({
1356
- ...p,
1357
- message: stylePromptMessage(p.message)
1358
- }), params.runtime);
1359
- },
1360
- confirmSkipInNonInteractive: async (p) => {
1361
- if (nonInteractive) return false;
1362
- if (shouldRepair) return true;
1363
- return confirmDefault(p);
1364
- },
1365
- select: async (p, fallback) => {
1366
- if (!canPrompt || shouldRepair) return fallback;
1367
- return guardCancel(await select({
1368
- ...p,
1369
- message: stylePromptMessage(p.message),
1370
- options: p.options.map((opt) => opt.hint === void 0 ? opt : {
1371
- ...opt,
1372
- hint: stylePromptHint(opt.hint)
1373
- })
1374
- }), params.runtime);
1375
- },
1376
- shouldRepair,
1377
- shouldForce
1378
- };
1379
- }
1380
- //#endregion
1381
- //#region src/commands/doctor-sandbox.ts
1382
- function resolveSandboxScript(scriptRel) {
1383
- const candidates = /* @__PURE__ */ new Set();
1384
- candidates.add(process.cwd());
1385
- const argv1 = process.argv[1];
1386
- if (argv1) {
1387
- const normalized = path.resolve(argv1);
1388
- candidates.add(path.resolve(path.dirname(normalized), ".."));
1389
- candidates.add(path.resolve(path.dirname(normalized)));
1390
- }
1391
- for (const root of candidates) {
1392
- const scriptPath = path.join(root, scriptRel);
1393
- if (fs.existsSync(scriptPath)) return {
1394
- scriptPath,
1395
- cwd: root
1396
- };
1397
- }
1398
- return null;
1399
- }
1400
- async function runSandboxScript(scriptRel, runtime) {
1401
- const script = resolveSandboxScript(scriptRel);
1402
- if (!script) {
1403
- note$1(`Unable to locate ${scriptRel}. Run it from the repo root.`, "Sandbox");
1404
- return false;
1405
- }
1406
- runtime.log(`Running ${scriptRel}...`);
1407
- const result = await runCommandWithTimeout(["bash", script.scriptPath], {
1408
- timeoutMs: 1200 * 1e3,
1409
- cwd: script.cwd
1410
- });
1411
- if (result.code !== 0) {
1412
- runtime.error(`Failed running ${scriptRel}: ${result.stderr.trim() || result.stdout.trim() || "unknown error"}`);
1413
- return false;
1414
- }
1415
- runtime.log(`Completed ${scriptRel}.`);
1416
- return true;
1417
- }
1418
- async function isDockerAvailable() {
1419
- try {
1420
- await runExec("docker", [
1421
- "version",
1422
- "--format",
1423
- "{{.Server.Version}}"
1424
- ], { timeoutMs: 5e3 });
1425
- return true;
1426
- } catch {
1427
- return false;
1428
- }
1429
- }
1430
- async function dockerImageExists(image) {
1431
- try {
1432
- await runExec("docker", [
1433
- "image",
1434
- "inspect",
1435
- image
1436
- ], { timeoutMs: 5e3 });
1437
- return true;
1438
- } catch (error) {
1439
- const stderr = error?.stderr || error?.message || "";
1440
- if (String(stderr).includes("No such image")) return false;
1441
- throw error;
1442
- }
1443
- }
1444
- function resolveSandboxDockerImage(cfg) {
1445
- const image = cfg.agents?.defaults?.sandbox?.docker?.image?.trim();
1446
- return image ? image : DEFAULT_SANDBOX_IMAGE;
1447
- }
1448
- function resolveSandboxBackend(cfg) {
1449
- return cfg.agents?.defaults?.sandbox?.backend?.trim() || "docker";
1450
- }
1451
- function resolveSandboxBrowserImage(cfg) {
1452
- const image = cfg.agents?.defaults?.sandbox?.browser?.image?.trim();
1453
- return image ? image : DEFAULT_SANDBOX_BROWSER_IMAGE;
1454
- }
1455
- function updateSandboxDockerImage(cfg, image) {
1456
- return {
1457
- ...cfg,
1458
- agents: {
1459
- ...cfg.agents,
1460
- defaults: {
1461
- ...cfg.agents?.defaults,
1462
- sandbox: {
1463
- ...cfg.agents?.defaults?.sandbox,
1464
- docker: {
1465
- ...cfg.agents?.defaults?.sandbox?.docker,
1466
- image
1467
- }
1468
- }
1469
- }
1470
- }
1471
- };
1472
- }
1473
- function updateSandboxBrowserImage(cfg, image) {
1474
- return {
1475
- ...cfg,
1476
- agents: {
1477
- ...cfg.agents,
1478
- defaults: {
1479
- ...cfg.agents?.defaults,
1480
- sandbox: {
1481
- ...cfg.agents?.defaults?.sandbox,
1482
- browser: {
1483
- ...cfg.agents?.defaults?.sandbox?.browser,
1484
- image
1485
- }
1486
- }
1487
- }
1488
- }
1489
- };
1490
- }
1491
- async function handleMissingSandboxImage(params, runtime, prompter) {
1492
- if (await dockerImageExists(params.image)) return;
1493
- const buildHint = params.buildScript ? `Build it with ${params.buildScript}.` : "Build or pull it first.";
1494
- note$1(`Sandbox ${params.kind} image missing: ${params.image}. ${buildHint}`, "Sandbox");
1495
- let built = false;
1496
- if (params.buildScript) {
1497
- if (await prompter.confirmSkipInNonInteractive({
1498
- message: `Build ${params.kind} sandbox image now?`,
1499
- initialValue: true
1500
- })) built = await runSandboxScript(params.buildScript, runtime);
1501
- }
1502
- if (built) return;
1503
- }
1504
- async function maybeRepairSandboxImages(cfg, runtime, prompter) {
1505
- const sandbox = cfg.agents?.defaults?.sandbox;
1506
- const mode = sandbox?.mode ?? "off";
1507
- if (!sandbox || mode === "off") return cfg;
1508
- const backend = resolveSandboxBackend(cfg);
1509
- if (backend !== "docker") {
1510
- if (sandbox.browser?.enabled) note$1(`Sandbox backend "${backend}" selected. Docker browser health checks are skipped; browser sandbox currently requires the docker backend.`, "Sandbox");
1511
- return cfg;
1512
- }
1513
- if (!await isDockerAvailable()) {
1514
- note$1([
1515
- `Sandbox mode is enabled (mode: "${mode}") but Docker is not available.`,
1516
- "Docker is required for sandbox mode to function.",
1517
- "Isolated sessions (cron jobs, sub-agents) will fail without Docker.",
1518
- "",
1519
- "Options:",
1520
- "- Install Docker and restart the gateway",
1521
- "- Disable sandbox mode: moldclaw config set agents.defaults.sandbox.mode off"
1522
- ].join("\n"), "Sandbox");
1523
- return cfg;
1524
- }
1525
- let next = cfg;
1526
- const changes = [];
1527
- const dockerImage = resolveSandboxDockerImage(cfg);
1528
- await handleMissingSandboxImage({
1529
- kind: "base",
1530
- image: dockerImage,
1531
- buildScript: dockerImage === "moldclaw-sandbox-common:bookworm-slim" ? "scripts/sandbox-common-setup.sh" : dockerImage === "moldclaw-sandbox:bookworm-slim" ? "scripts/sandbox-setup.sh" : void 0,
1532
- updateConfig: (image) => {
1533
- next = updateSandboxDockerImage(next, image);
1534
- changes.push(`Updated agents.defaults.sandbox.docker.image → ${image}`);
1535
- }
1536
- }, runtime, prompter);
1537
- if (sandbox.browser?.enabled) await handleMissingSandboxImage({
1538
- kind: "browser",
1539
- image: resolveSandboxBrowserImage(cfg),
1540
- buildScript: "scripts/sandbox-browser-setup.sh",
1541
- updateConfig: (image) => {
1542
- next = updateSandboxBrowserImage(next, image);
1543
- changes.push(`Updated agents.defaults.sandbox.browser.image → ${image}`);
1544
- }
1545
- }, runtime, prompter);
1546
- if (changes.length > 0) note$1(changes.join("\n"), "Doctor changes");
1547
- return next;
1548
- }
1549
- function noteSandboxScopeWarnings(cfg) {
1550
- const globalSandbox = cfg.agents?.defaults?.sandbox;
1551
- const agents = Array.isArray(cfg.agents?.list) ? cfg.agents.list : [];
1552
- const warnings = [];
1553
- for (const agent of agents) {
1554
- const agentId = agent.id;
1555
- const agentSandbox = agent.sandbox;
1556
- if (!agentSandbox) continue;
1557
- if (resolveSandboxScope({
1558
- scope: agentSandbox.scope ?? globalSandbox?.scope,
1559
- perSession: agentSandbox.perSession ?? globalSandbox?.perSession
1560
- }) !== "shared") continue;
1561
- const overrides = [];
1562
- if (agentSandbox.docker && Object.keys(agentSandbox.docker).length > 0) overrides.push("docker");
1563
- if (agentSandbox.browser && Object.keys(agentSandbox.browser).length > 0) overrides.push("browser");
1564
- if (agentSandbox.prune && Object.keys(agentSandbox.prune).length > 0) overrides.push("prune");
1565
- if (overrides.length === 0) continue;
1566
- warnings.push([`- agents.list (id "${agentId}") sandbox ${overrides.join("/")} overrides ignored.`, ` scope resolves to "shared".`].join("\n"));
1567
- }
1568
- if (warnings.length > 0) note$1(warnings.join("\n"), "Sandbox");
1569
- }
1570
- //#endregion
1571
- //#region src/commands/doctor-security.ts
1572
- function collectImplicitHeartbeatDirectPolicyWarnings(cfg) {
1573
- const warnings = [];
1574
- const maybeWarn = (params) => {
1575
- const heartbeat = params.heartbeat;
1576
- if (!heartbeat || heartbeat.target === void 0 || heartbeat.target === "none") return;
1577
- if (heartbeat.directPolicy !== void 0) return;
1578
- warnings.push(`- ${params.label}: heartbeat delivery is configured while ${params.pathHint} is unset.`, " Heartbeat now allows direct/DM targets by default. Set it explicitly to \"allow\" or \"block\" to pin upgrade behavior.");
1579
- };
1580
- maybeWarn({
1581
- label: "Heartbeat defaults",
1582
- heartbeat: cfg.agents?.defaults?.heartbeat,
1583
- pathHint: "agents.defaults.heartbeat.directPolicy"
1584
- });
1585
- for (const agent of cfg.agents?.list ?? []) maybeWarn({
1586
- label: `Heartbeat agent "${agent.id}"`,
1587
- heartbeat: agent.heartbeat,
1588
- pathHint: `heartbeat.directPolicy for agent "${agent.id}"`
1589
- });
1590
- return warnings;
1591
- }
1592
- async function noteSecurityWarnings(cfg) {
1593
- const warnings = [];
1594
- const auditHint = `- Run: ${formatCliCommand("moldclaw security audit --deep")}`;
1595
- if (cfg.approvals?.exec?.enabled === false) warnings.push("- Note: approvals.exec.enabled=false disables approval forwarding only.", " Host exec gating still comes from ~/.moldclaw/exec-approvals.json.", ` Check local policy with: ${formatCliCommand("moldclaw approvals get --gateway")}`);
1596
- warnings.push(...collectImplicitHeartbeatDirectPolicyWarnings(cfg));
1597
- const gatewayBind = cfg.gateway?.bind ?? "loopback";
1598
- const customBindHost = cfg.gateway?.customBindHost?.trim();
1599
- const bindMode = [
1600
- "auto",
1601
- "lan",
1602
- "loopback",
1603
- "custom",
1604
- "tailnet"
1605
- ].includes(gatewayBind) ? gatewayBind : void 0;
1606
- const resolvedBindHost = bindMode ? await resolveGatewayBindHost(bindMode, customBindHost) : "0.0.0.0";
1607
- const isExposed = !isLoopbackHost(resolvedBindHost);
1608
- const resolvedAuth = resolveGatewayAuth({
1609
- authConfig: cfg.gateway?.auth,
1610
- env: process.env,
1611
- tailscaleMode: cfg.gateway?.tailscale?.mode ?? "off"
1612
- });
1613
- const authToken = resolvedAuth.token?.trim() ?? "";
1614
- const authPassword = resolvedAuth.password?.trim() ?? "";
1615
- const hasToken = authToken.length > 0 || hasConfiguredSecretInput(cfg.gateway?.auth?.token, cfg.secrets?.defaults);
1616
- const hasPassword = authPassword.length > 0 || hasConfiguredSecretInput(cfg.gateway?.auth?.password, cfg.secrets?.defaults);
1617
- const hasSharedSecret = resolvedAuth.mode === "token" && hasToken || resolvedAuth.mode === "password" && hasPassword;
1618
- const bindDescriptor = `"${gatewayBind}" (${resolvedBindHost})`;
1619
- const saferRemoteAccessLines = [
1620
- " Safer remote access: keep bind loopback and use Tailscale Serve/Funnel or an SSH tunnel.",
1621
- " Example tunnel: ssh -N -L 28789:127.0.0.1:28789 user@gateway-host",
1622
- " Docs: https://docs.moldclaw.ai/gateway/remote"
1623
- ];
1624
- if (isExposed) if (!hasSharedSecret) {
1625
- const authFixLines = resolvedAuth.mode === "password" ? [` Fix: ${formatCliCommand("moldclaw configure")} to set a password`, ` Or switch to token: ${formatCliCommand("moldclaw config set gateway.auth.mode token")}`] : [` Fix: ${formatCliCommand("moldclaw doctor --fix")} to generate a token`, ` Or set token directly: ${formatCliCommand("moldclaw config set gateway.auth.mode token")}`];
1626
- warnings.push(`- CRITICAL: Gateway bound to ${bindDescriptor} without authentication.`, ` Anyone on your network (or internet if port-forwarded) can fully control your agent.`, ` Fix: ${formatCliCommand("moldclaw config set gateway.bind loopback")}`, ...saferRemoteAccessLines, ...authFixLines);
1627
- } else warnings.push(`- WARNING: Gateway bound to ${bindDescriptor} (network-accessible).`, ` Ensure your auth credentials are strong and not exposed.`, ...saferRemoteAccessLines);
1628
- const warnDmPolicy = async (params) => {
1629
- const dmPolicy = params.dmPolicy;
1630
- const policyPath = params.policyPath ?? `${params.allowFromPath}policy`;
1631
- const { hasWildcard, allowCount, isMultiUserDm } = await resolveDmAllowState({
1632
- provider: params.provider,
1633
- accountId: params.accountId,
1634
- allowFrom: params.allowFrom,
1635
- normalizeEntry: params.normalizeEntry
1636
- });
1637
- const dmScope = cfg.session?.dmScope ?? "main";
1638
- if (dmPolicy === "open") {
1639
- const allowFromPath = `${params.allowFromPath}allowFrom`;
1640
- warnings.push(`- ${params.label} DMs: OPEN (${policyPath}="open"). Anyone can DM it.`);
1641
- if (!hasWildcard) warnings.push(`- ${params.label} DMs: config invalid — "open" requires ${allowFromPath} to include "*".`);
1642
- }
1643
- if (dmPolicy === "disabled") {
1644
- warnings.push(`- ${params.label} DMs: disabled (${policyPath}="disabled").`);
1645
- return;
1646
- }
1647
- if (dmPolicy !== "open" && allowCount === 0) {
1648
- warnings.push(`- ${params.label} DMs: locked (${policyPath}="${dmPolicy}") with no allowlist; unknown senders will be blocked / get a pairing code.`);
1649
- warnings.push(` ${params.approveHint}`);
1650
- }
1651
- if (dmScope === "main" && isMultiUserDm) warnings.push(`- ${params.label} DMs: multiple senders share the main session; run: ` + formatCliCommand("moldclaw config set session.dmScope \"per-channel-peer\"") + " (or \"per-account-channel-peer\" for multi-account channels) to isolate sessions.");
1652
- };
1653
- for (const plugin of listChannelPlugins()) {
1654
- if (!plugin.security) continue;
1655
- const { defaultAccountId, account, enabled, configured, diagnostics } = await resolveDefaultChannelAccountContext(plugin, cfg, {
1656
- mode: "read_only",
1657
- commandName: "doctor"
1658
- });
1659
- for (const diagnostic of diagnostics) warnings.push(`- [secrets] ${diagnostic}`);
1660
- if (!enabled) continue;
1661
- if (!configured) continue;
1662
- const dmPolicy = plugin.security.resolveDmPolicy?.({
1663
- cfg,
1664
- accountId: defaultAccountId,
1665
- account
1666
- });
1667
- if (dmPolicy) await warnDmPolicy({
1668
- label: plugin.meta.label ?? plugin.id,
1669
- provider: plugin.id,
1670
- accountId: defaultAccountId,
1671
- dmPolicy: dmPolicy.policy,
1672
- allowFrom: dmPolicy.allowFrom,
1673
- policyPath: dmPolicy.policyPath,
1674
- allowFromPath: dmPolicy.allowFromPath,
1675
- approveHint: dmPolicy.approveHint,
1676
- normalizeEntry: dmPolicy.normalizeEntry
1677
- });
1678
- if (plugin.security.collectWarnings) {
1679
- const extra = await plugin.security.collectWarnings({
1680
- cfg,
1681
- accountId: defaultAccountId,
1682
- account
1683
- });
1684
- if (extra?.length) warnings.push(...extra);
1685
- }
1686
- }
1687
- const lines = warnings.length > 0 ? warnings : ["- No channel security warnings detected."];
1688
- lines.push(auditHint);
1689
- note$1(lines.join("\n"), "Security");
1690
- }
1691
- //#endregion
1692
- //#region src/commands/doctor-session-locks.ts
1693
- const DEFAULT_STALE_MS = 1800 * 1e3;
1694
- function formatAge(ageMs) {
1695
- if (ageMs === null) return "unknown";
1696
- const seconds = Math.floor(ageMs / 1e3);
1697
- if (seconds < 60) return `${seconds}s`;
1698
- const minutes = Math.floor(seconds / 60);
1699
- const remainingSeconds = seconds % 60;
1700
- if (minutes < 60) return `${minutes}m${remainingSeconds}s`;
1701
- return `${Math.floor(minutes / 60)}h${minutes % 60}m`;
1702
- }
1703
- function formatLockLine(lock) {
1704
- const pidStatus = lock.pid === null ? "pid=missing" : `pid=${lock.pid} (${lock.pidAlive ? "alive" : "dead"})`;
1705
- const ageStatus = `age=${formatAge(lock.ageMs)}`;
1706
- const staleStatus = lock.stale ? `stale=yes (${lock.staleReasons.join(", ") || "unknown"})` : "stale=no";
1707
- const removedStatus = lock.removed ? " [removed]" : "";
1708
- return `- ${shortenHomePath(lock.lockPath)} ${pidStatus} ${ageStatus} ${staleStatus}${removedStatus}`;
1709
- }
1710
- async function noteSessionLockHealth(params) {
1711
- const shouldRepair = params?.shouldRepair === true;
1712
- const staleMs = params?.staleMs ?? DEFAULT_STALE_MS;
1713
- let sessionDirs = [];
1714
- try {
1715
- sessionDirs = await resolveAgentSessionDirs(resolveStateDir(process.env));
1716
- } catch (err) {
1717
- note$1(`- Failed to inspect session lock files: ${String(err)}`, "Session locks");
1718
- return;
1719
- }
1720
- if (sessionDirs.length === 0) return;
1721
- const allLocks = [];
1722
- for (const sessionsDir of sessionDirs) {
1723
- const result = await cleanStaleLockFiles({
1724
- sessionsDir,
1725
- staleMs,
1726
- removeStale: shouldRepair
1727
- });
1728
- allLocks.push(...result.locks);
1729
- }
1730
- if (allLocks.length === 0) return;
1731
- const staleCount = allLocks.filter((lock) => lock.stale).length;
1732
- const removedCount = allLocks.filter((lock) => lock.removed).length;
1733
- const lines = [`- Found ${allLocks.length} session lock file${allLocks.length === 1 ? "" : "s"}.`, ...allLocks.toSorted((a, b) => a.lockPath.localeCompare(b.lockPath)).map(formatLockLine)];
1734
- if (staleCount > 0 && !shouldRepair) {
1735
- lines.push(`- ${staleCount} lock file${staleCount === 1 ? " is" : "s are"} stale.`);
1736
- lines.push("- Run \"moldclaw doctor --fix\" to remove stale lock files automatically.");
1737
- }
1738
- if (shouldRepair && removedCount > 0) lines.push(`- Removed ${removedCount} stale session lock file${removedCount === 1 ? "" : "s"}.`);
1739
- note$1(lines.join("\n"), "Session locks");
1740
- }
1741
- //#endregion
1742
- //#region src/commands/doctor-state-integrity.ts
1743
- function existsDir(dir) {
1744
- try {
1745
- return fs.existsSync(dir) && fs.statSync(dir).isDirectory();
1746
- } catch {
1747
- return false;
1748
- }
1749
- }
1750
- function existsFile(filePath) {
1751
- try {
1752
- return fs.existsSync(filePath) && fs.statSync(filePath).isFile();
1753
- } catch {
1754
- return false;
1755
- }
1756
- }
1757
- function canWriteDir(dir) {
1758
- try {
1759
- fs.accessSync(dir, fs.constants.W_OK);
1760
- return true;
1761
- } catch {
1762
- return false;
1763
- }
1764
- }
1765
- function ensureDir(dir) {
1766
- try {
1767
- fs.mkdirSync(dir, { recursive: true });
1768
- return { ok: true };
1769
- } catch (err) {
1770
- return {
1771
- ok: false,
1772
- error: String(err)
1773
- };
1774
- }
1775
- }
1776
- function dirPermissionHint(dir) {
1777
- const uid = typeof process.getuid === "function" ? process.getuid() : null;
1778
- const gid = typeof process.getgid === "function" ? process.getgid() : null;
1779
- try {
1780
- const stat = fs.statSync(dir);
1781
- if (uid !== null && stat.uid !== uid) return `Owner mismatch (uid ${stat.uid}). Run: sudo chown -R $USER "${dir}"`;
1782
- if (gid !== null && stat.gid !== gid) return `Group mismatch (gid ${stat.gid}). If access fails, run: sudo chown -R $USER "${dir}"`;
1783
- } catch {
1784
- return null;
1785
- }
1786
- return null;
1787
- }
1788
- function addUserRwx(mode) {
1789
- return mode & 511 | 448;
1790
- }
1791
- function countJsonlLines(filePath) {
1792
- try {
1793
- const raw = fs.readFileSync(filePath, "utf-8");
1794
- if (!raw) return 0;
1795
- let count = 0;
1796
- for (let i = 0; i < raw.length; i += 1) if (raw[i] === "\n") count += 1;
1797
- if (!raw.endsWith("\n")) count += 1;
1798
- return count;
1799
- } catch {
1800
- return 0;
1801
- }
1802
- }
1803
- function findOtherStateDirs(stateDir) {
1804
- const resolvedState = path.resolve(stateDir);
1805
- const roots = process.platform === "darwin" ? ["/Users"] : process.platform === "linux" ? ["/home"] : [];
1806
- const found = [];
1807
- for (const root of roots) {
1808
- let entries = [];
1809
- try {
1810
- entries = fs.readdirSync(root, { withFileTypes: true });
1811
- } catch {
1812
- continue;
1813
- }
1814
- for (const entry of entries) {
1815
- if (!entry.isDirectory()) continue;
1816
- if (entry.name.startsWith(".")) continue;
1817
- const candidates = [".moldclaw"].map((dir) => path.resolve(root, entry.name, dir));
1818
- for (const candidate of candidates) {
1819
- if (candidate === resolvedState) continue;
1820
- if (existsDir(candidate)) found.push(candidate);
1821
- }
1822
- }
1823
- }
1824
- return found;
1825
- }
1826
- function isPathUnderRoot(targetPath, rootPath) {
1827
- const normalizedTarget = path.resolve(targetPath);
1828
- const normalizedRoot = path.resolve(rootPath);
1829
- const rootToken = path.parse(normalizedRoot).root;
1830
- if (normalizedRoot === rootToken) return normalizedTarget.startsWith(rootToken);
1831
- return normalizedTarget === normalizedRoot || normalizedTarget.startsWith(`${normalizedRoot}${path.sep}`);
1832
- }
1833
- function tryResolveRealPath(targetPath) {
1834
- try {
1835
- return fs.realpathSync(targetPath);
1836
- } catch {
1837
- return null;
1838
- }
1839
- }
1840
- function decodeMountInfoPath(value) {
1841
- return value.replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(Number.parseInt(octal, 8)));
1842
- }
1843
- function escapeControlCharsForTerminal(value) {
1844
- let escaped = "";
1845
- for (const char of value) {
1846
- if (char === "\x1B") {
1847
- escaped += "\\x1b";
1848
- continue;
1849
- }
1850
- if (char === "\r") {
1851
- escaped += "\\r";
1852
- continue;
1853
- }
1854
- if (char === "\n") {
1855
- escaped += "\\n";
1856
- continue;
1857
- }
1858
- if (char === " ") {
1859
- escaped += "\\t";
1860
- continue;
1861
- }
1862
- const code = char.charCodeAt(0);
1863
- if (code >= 0 && code <= 8 || code === 11 || code === 12 || code >= 14 && code <= 31) {
1864
- escaped += `\\x${code.toString(16).padStart(2, "0")}`;
1865
- continue;
1866
- }
1867
- if (code === 127) {
1868
- escaped += "\\x7f";
1869
- continue;
1870
- }
1871
- escaped += char;
1872
- }
1873
- return escaped;
1874
- }
1875
- function parseLinuxMountInfo(rawMountInfo) {
1876
- const entries = [];
1877
- for (const line of rawMountInfo.split("\n")) {
1878
- const trimmed = line.trim();
1879
- if (!trimmed) continue;
1880
- const separatorIndex = trimmed.indexOf(" - ");
1881
- if (separatorIndex === -1) continue;
1882
- const left = trimmed.slice(0, separatorIndex);
1883
- const right = trimmed.slice(separatorIndex + 3);
1884
- const leftFields = left.split(" ");
1885
- const rightFields = right.split(" ");
1886
- if (leftFields.length < 5 || rightFields.length < 2) continue;
1887
- entries.push({
1888
- mountPoint: decodeMountInfoPath(leftFields[4]),
1889
- fsType: rightFields[0],
1890
- source: decodeMountInfoPath(rightFields[1])
1891
- });
1892
- }
1893
- return entries;
1894
- }
1895
- function isPathUnderRootWithPathOps(targetPath, rootPath, pathOps) {
1896
- const normalizedTarget = pathOps.resolve(targetPath);
1897
- const normalizedRoot = pathOps.resolve(rootPath);
1898
- const rootToken = pathOps.parse(normalizedRoot).root;
1899
- if (normalizedRoot === rootToken) return normalizedTarget.startsWith(rootToken);
1900
- return normalizedTarget === normalizedRoot || normalizedTarget.startsWith(`${normalizedRoot}${pathOps.sep}`);
1901
- }
1902
- function findLinuxMountInfoEntryForPath(targetPath, entries, pathOps) {
1903
- const normalizedTarget = pathOps.resolve(targetPath);
1904
- let bestMatch = null;
1905
- for (const entry of entries) {
1906
- if (!isPathUnderRootWithPathOps(normalizedTarget, entry.mountPoint, pathOps)) continue;
1907
- if (!bestMatch || pathOps.resolve(entry.mountPoint).length > pathOps.resolve(bestMatch.mountPoint).length) bestMatch = entry;
1908
- }
1909
- return bestMatch;
1910
- }
1911
- function isMmcDevicePath(devicePath, pathOps) {
1912
- const name = pathOps.basename(devicePath);
1913
- return /^mmcblk\d+(?:p\d+)?$/.test(name);
1914
- }
1915
- function tryReadLinuxMountInfo() {
1916
- try {
1917
- return fs.readFileSync("/proc/self/mountinfo", "utf8");
1918
- } catch {
1919
- return null;
1920
- }
1921
- }
1922
- function detectLinuxSdBackedStateDir(stateDir, deps) {
1923
- if ((deps?.platform ?? process.platform) !== "linux") return null;
1924
- const linuxPath = path.posix;
1925
- const resolvedStatePath = (deps?.resolveRealPath ?? tryResolveRealPath)(stateDir) ?? linuxPath.resolve(stateDir);
1926
- const mountInfo = deps?.mountInfo ?? tryReadLinuxMountInfo();
1927
- if (!mountInfo) return null;
1928
- const mountEntry = findLinuxMountInfoEntryForPath(resolvedStatePath, parseLinuxMountInfo(mountInfo), linuxPath);
1929
- if (!mountEntry) return null;
1930
- const sourceCandidates = [mountEntry.source];
1931
- if (mountEntry.source.startsWith("/dev/")) {
1932
- const resolvedDevicePath = (deps?.resolveDeviceRealPath ?? tryResolveRealPath)(mountEntry.source);
1933
- if (resolvedDevicePath) sourceCandidates.push(linuxPath.resolve(resolvedDevicePath));
1934
- }
1935
- if (!sourceCandidates.some((candidate) => isMmcDevicePath(candidate, linuxPath))) return null;
1936
- return {
1937
- path: linuxPath.resolve(resolvedStatePath),
1938
- mountPoint: linuxPath.resolve(mountEntry.mountPoint),
1939
- fsType: mountEntry.fsType,
1940
- source: mountEntry.source
1941
- };
1942
- }
1943
- function formatLinuxSdBackedStateDirWarning(displayStateDir, linuxSdBackedStateDir) {
1944
- const displayMountPoint = linuxSdBackedStateDir.mountPoint === "/" ? "/" : shortenHomePath(linuxSdBackedStateDir.mountPoint);
1945
- return [
1946
- `- State directory appears to be on SD/eMMC storage (${displayStateDir}; device ${escapeControlCharsForTerminal(linuxSdBackedStateDir.source)}, fs ${escapeControlCharsForTerminal(linuxSdBackedStateDir.fsType)}, mount ${escapeControlCharsForTerminal(displayMountPoint)}).`,
1947
- "- SD/eMMC media can be slower for random I/O and wear faster under session/log churn.",
1948
- "- For better startup and state durability, prefer SSD/NVMe (or USB SSD on Raspberry Pi) for MOLDCLAW_STATE_DIR."
1949
- ].join("\n");
1950
- }
1951
- function detectMacCloudSyncedStateDir(stateDir, deps) {
1952
- if ((deps?.platform ?? process.platform) !== "darwin") return null;
1953
- const homedir = deps?.homedir ?? os.homedir();
1954
- const roots = [{
1955
- storage: "iCloud Drive",
1956
- root: path.join(homedir, "Library", "Mobile Documents", "com~apple~CloudDocs")
1957
- }, {
1958
- storage: "CloudStorage provider",
1959
- root: path.join(homedir, "Library", "CloudStorage")
1960
- }];
1961
- const realPath = (deps?.resolveRealPath ?? tryResolveRealPath)(stateDir);
1962
- const candidates = realPath ? [path.resolve(realPath)] : [path.resolve(stateDir)];
1963
- for (const candidate of candidates) for (const { storage, root } of roots) if (isPathUnderRoot(candidate, root)) return {
1964
- path: candidate,
1965
- storage
1966
- };
1967
- return null;
1968
- }
1969
- function isRecord(value) {
1970
- return typeof value === "object" && value !== null;
1971
- }
1972
- function isPairingPolicy(value) {
1973
- return typeof value === "string" && value.trim().toLowerCase() === "pairing";
1974
- }
1975
- function hasPairingPolicy(value) {
1976
- if (!isRecord(value)) return false;
1977
- if (isPairingPolicy(value.dmPolicy)) return true;
1978
- if (isRecord(value.dm) && isPairingPolicy(value.dm.policy)) return true;
1979
- if (!isRecord(value.accounts)) return false;
1980
- for (const accountCfg of Object.values(value.accounts)) if (hasPairingPolicy(accountCfg)) return true;
1981
- return false;
1982
- }
1983
- function isSlashRoutingSessionKey(sessionKey) {
1984
- const raw = sessionKey.trim().toLowerCase();
1985
- if (!raw) return false;
1986
- const scoped = parseAgentSessionKey(raw)?.rest ?? raw;
1987
- return /^[^:]+:slash:[^:]+(?:$|:)/.test(scoped);
1988
- }
1989
- function shouldRequireOAuthDir(cfg, env) {
1990
- if (env.MOLDCLAW_OAUTH_DIR?.trim()) return true;
1991
- const channels = cfg.channels;
1992
- if (!isRecord(channels)) return false;
1993
- if (isRecord(channels.whatsapp)) return true;
1994
- for (const [channelId, channelCfg] of Object.entries(channels)) {
1995
- if (channelId === "defaults" || channelId === "modelByChannel") continue;
1996
- if (hasPairingPolicy(channelCfg)) return true;
1997
- }
1998
- return false;
1999
- }
2000
- async function noteStateIntegrity(cfg, prompter, configPath) {
2001
- const warnings = [];
2002
- const changes = [];
2003
- const env = process.env;
2004
- const homedir = () => resolveRequiredHomeDir(env, os.homedir);
2005
- const stateDir = resolveStateDir(env, homedir);
2006
- const defaultStateDir = path.join(homedir(), ".moldclaw");
2007
- const oauthDir = resolveOAuthDir(env, stateDir);
2008
- const agentId = resolveDefaultAgentId(cfg);
2009
- const sessionsDir = resolveSessionTranscriptsDirForAgent(agentId, env, homedir);
2010
- const storePath = resolveStorePath(cfg.session?.store, { agentId });
2011
- const storeDir = path.dirname(storePath);
2012
- const absoluteStorePath = path.resolve(storePath);
2013
- const displayStateDir = shortenHomePath(stateDir);
2014
- const displayOauthDir = shortenHomePath(oauthDir);
2015
- const displaySessionsDir = shortenHomePath(sessionsDir);
2016
- const displayStoreDir = shortenHomePath(storeDir);
2017
- const displayConfigPath = configPath ? shortenHomePath(configPath) : void 0;
2018
- const requireOAuthDir = shouldRequireOAuthDir(cfg, env);
2019
- const cloudSyncedStateDir = detectMacCloudSyncedStateDir(stateDir);
2020
- const linuxSdBackedStateDir = detectLinuxSdBackedStateDir(stateDir);
2021
- if (cloudSyncedStateDir) warnings.push([
2022
- `- State directory is under macOS cloud-synced storage (${displayStateDir}; ${cloudSyncedStateDir.storage}).`,
2023
- "- This can cause slow I/O and sync/lock races for sessions and credentials.",
2024
- "- Prefer a local non-synced state dir (for example: ~/.moldclaw).",
2025
- ` Set locally: MOLDCLAW_STATE_DIR=~/.moldclaw ${formatCliCommand("moldclaw doctor")}`
2026
- ].join("\n"));
2027
- if (linuxSdBackedStateDir) warnings.push(formatLinuxSdBackedStateDirWarning(displayStateDir, linuxSdBackedStateDir));
2028
- let stateDirExists = existsDir(stateDir);
2029
- if (!stateDirExists) {
2030
- warnings.push(`- CRITICAL: state directory missing (${displayStateDir}). Sessions, credentials, logs, and config are stored there.`);
2031
- if (cfg.gateway?.mode === "remote") warnings.push("- Gateway is in remote mode; run doctor on the remote host where the gateway runs.");
2032
- if (await prompter.confirmSkipInNonInteractive({
2033
- message: `Create ${displayStateDir} now?`,
2034
- initialValue: false
2035
- })) {
2036
- const created = ensureDir(stateDir);
2037
- if (created.ok) {
2038
- changes.push(`- Created ${displayStateDir}`);
2039
- stateDirExists = true;
2040
- } else warnings.push(`- Failed to create ${displayStateDir}: ${created.error}`);
2041
- }
2042
- }
2043
- if (stateDirExists && !canWriteDir(stateDir)) {
2044
- warnings.push(`- State directory not writable (${displayStateDir}).`);
2045
- const hint = dirPermissionHint(stateDir);
2046
- if (hint) warnings.push(` ${hint}`);
2047
- if (await prompter.confirmSkipInNonInteractive({
2048
- message: `Repair permissions on ${displayStateDir}?`,
2049
- initialValue: true
2050
- })) try {
2051
- const target = addUserRwx(fs.statSync(stateDir).mode);
2052
- fs.chmodSync(stateDir, target);
2053
- changes.push(`- Repaired permissions on ${displayStateDir}`);
2054
- } catch (err) {
2055
- warnings.push(`- Failed to repair ${displayStateDir}: ${String(err)}`);
2056
- }
2057
- }
2058
- if (stateDirExists && process.platform !== "win32") try {
2059
- const dirLstat = fs.lstatSync(stateDir);
2060
- const isDirSymlink = dirLstat.isSymbolicLink();
2061
- const stat = isDirSymlink ? fs.statSync(stateDir) : dirLstat;
2062
- if (!(isDirSymlink ? fs.realpathSync(stateDir) : stateDir).startsWith("/nix/store/") && (stat.mode & 63) !== 0) {
2063
- warnings.push(`- State directory permissions are too open (${displayStateDir}). Recommend chmod 700.`);
2064
- if (await prompter.confirmSkipInNonInteractive({
2065
- message: `Tighten permissions on ${displayStateDir} to 700?`,
2066
- initialValue: true
2067
- })) {
2068
- fs.chmodSync(stateDir, 448);
2069
- changes.push(`- Tightened permissions on ${displayStateDir} to 700`);
2070
- }
2071
- }
2072
- } catch (err) {
2073
- warnings.push(`- Failed to read ${displayStateDir} permissions: ${String(err)}`);
2074
- }
2075
- if (configPath && existsFile(configPath) && process.platform !== "win32") try {
2076
- const configLstat = fs.lstatSync(configPath);
2077
- const isSymlink = configLstat.isSymbolicLink();
2078
- const stat = isSymlink ? fs.statSync(configPath) : configLstat;
2079
- if (!(isSymlink ? fs.realpathSync(configPath) : configPath).startsWith("/nix/store/") && (stat.mode & 63) !== 0) {
2080
- warnings.push(`- Config file is group/world readable (${displayConfigPath ?? configPath}). Recommend chmod 600.`);
2081
- if (await prompter.confirmSkipInNonInteractive({
2082
- message: `Tighten permissions on ${displayConfigPath ?? configPath} to 600?`,
2083
- initialValue: true
2084
- })) {
2085
- fs.chmodSync(configPath, 384);
2086
- changes.push(`- Tightened permissions on ${displayConfigPath ?? configPath} to 600`);
2087
- }
2088
- }
2089
- } catch (err) {
2090
- warnings.push(`- Failed to read config permissions (${displayConfigPath ?? configPath}): ${String(err)}`);
2091
- }
2092
- if (stateDirExists) {
2093
- const dirCandidates = /* @__PURE__ */ new Map();
2094
- dirCandidates.set(sessionsDir, "Sessions dir");
2095
- dirCandidates.set(storeDir, "Session store dir");
2096
- if (requireOAuthDir) dirCandidates.set(oauthDir, "OAuth dir");
2097
- else if (!existsDir(oauthDir)) warnings.push(`- OAuth dir not present (${displayOauthDir}). Skipping create because no WhatsApp/pairing channel config is active.`);
2098
- const displayDirFor = (dir) => {
2099
- if (dir === sessionsDir) return displaySessionsDir;
2100
- if (dir === storeDir) return displayStoreDir;
2101
- if (dir === oauthDir) return displayOauthDir;
2102
- return shortenHomePath(dir);
2103
- };
2104
- for (const [dir, label] of dirCandidates) {
2105
- const displayDir = displayDirFor(dir);
2106
- if (!existsDir(dir)) {
2107
- warnings.push(`- CRITICAL: ${label} missing (${displayDir}).`);
2108
- if (await prompter.confirmSkipInNonInteractive({
2109
- message: `Create ${label} at ${displayDir}?`,
2110
- initialValue: true
2111
- })) {
2112
- const created = ensureDir(dir);
2113
- if (created.ok) changes.push(`- Created ${label}: ${displayDir}`);
2114
- else warnings.push(`- Failed to create ${displayDir}: ${created.error}`);
2115
- }
2116
- continue;
2117
- }
2118
- if (!canWriteDir(dir)) {
2119
- warnings.push(`- ${label} not writable (${displayDir}).`);
2120
- const hint = dirPermissionHint(dir);
2121
- if (hint) warnings.push(` ${hint}`);
2122
- if (await prompter.confirmSkipInNonInteractive({
2123
- message: `Repair permissions on ${label}?`,
2124
- initialValue: true
2125
- })) try {
2126
- const target = addUserRwx(fs.statSync(dir).mode);
2127
- fs.chmodSync(dir, target);
2128
- changes.push(`- Repaired permissions on ${label}: ${displayDir}`);
2129
- } catch (err) {
2130
- warnings.push(`- Failed to repair ${displayDir}: ${String(err)}`);
2131
- }
2132
- }
2133
- }
2134
- }
2135
- const extraStateDirs = /* @__PURE__ */ new Set();
2136
- if (path.resolve(stateDir) !== path.resolve(defaultStateDir)) {
2137
- if (existsDir(defaultStateDir)) extraStateDirs.add(defaultStateDir);
2138
- }
2139
- for (const other of findOtherStateDirs(stateDir)) extraStateDirs.add(other);
2140
- if (extraStateDirs.size > 0) warnings.push([
2141
- "- Multiple state directories detected. This can split session history.",
2142
- ...Array.from(extraStateDirs).map((dir) => ` - ${shortenHomePath(dir)}`),
2143
- ` Active state dir: ${displayStateDir}`
2144
- ].join("\n"));
2145
- const store = loadSessionStore(storePath);
2146
- const sessionPathOpts = resolveSessionFilePathOptions({
2147
- agentId,
2148
- storePath
2149
- });
2150
- const entries = Object.entries(store).filter(([, entry]) => entry && typeof entry === "object");
2151
- if (entries.length > 0) {
2152
- const recentTranscriptCandidates = entries.slice().toSorted((a, b) => {
2153
- const aUpdated = typeof a[1].updatedAt === "number" ? a[1].updatedAt : 0;
2154
- return (typeof b[1].updatedAt === "number" ? b[1].updatedAt : 0) - aUpdated;
2155
- }).slice(0, 5).filter(([key]) => !isSlashRoutingSessionKey(key));
2156
- const missing = recentTranscriptCandidates.filter(([, entry]) => {
2157
- const sessionId = entry.sessionId;
2158
- if (!sessionId) return false;
2159
- return !existsFile(resolveSessionFilePath(sessionId, entry, sessionPathOpts));
2160
- });
2161
- if (missing.length > 0) warnings.push([
2162
- `- ${missing.length}/${recentTranscriptCandidates.length} recent sessions are missing transcripts.`,
2163
- ` Verify sessions in store: ${formatCliCommand(`moldclaw sessions --store "${absoluteStorePath}"`)}`,
2164
- ` Preview cleanup impact: ${formatCliCommand(`moldclaw sessions cleanup --store "${absoluteStorePath}" --dry-run`)}`,
2165
- ` Prune missing entries: ${formatCliCommand(`moldclaw sessions cleanup --store "${absoluteStorePath}" --enforce --fix-missing`)}`
2166
- ].join("\n"));
2167
- const mainEntry = store[resolveMainSessionKey(cfg)];
2168
- if (mainEntry?.sessionId) {
2169
- const transcriptPath = resolveSessionFilePath(mainEntry.sessionId, mainEntry, sessionPathOpts);
2170
- if (!existsFile(transcriptPath)) warnings.push(`- Main session transcript missing (${shortenHomePath(transcriptPath)}). History will appear to reset.`);
2171
- else {
2172
- const lineCount = countJsonlLines(transcriptPath);
2173
- if (lineCount <= 1) warnings.push(`- Main session transcript has only ${lineCount} line. Session history may not be appending.`);
2174
- }
2175
- }
2176
- }
2177
- if (existsDir(sessionsDir)) {
2178
- const referencedTranscriptPaths = /* @__PURE__ */ new Set();
2179
- for (const [, entry] of entries) {
2180
- if (!entry?.sessionId) continue;
2181
- try {
2182
- referencedTranscriptPaths.add(path.resolve(resolveSessionFilePath(entry.sessionId, entry, sessionPathOpts)));
2183
- } catch {}
2184
- }
2185
- const orphanTranscriptPaths = fs.readdirSync(sessionsDir, { withFileTypes: true }).filter((entry) => entry.isFile() && isPrimarySessionTranscriptFileName(entry.name)).map((entry) => path.resolve(path.join(sessionsDir, entry.name))).filter((filePath) => !referencedTranscriptPaths.has(filePath));
2186
- if (orphanTranscriptPaths.length > 0) {
2187
- warnings.push(`- Found ${orphanTranscriptPaths.length} orphan transcript file(s) in ${displaySessionsDir}. They are not referenced by sessions.json and can consume disk over time.`);
2188
- if (await prompter.confirmSkipInNonInteractive({
2189
- message: `Archive ${orphanTranscriptPaths.length} orphan transcript file(s) in ${displaySessionsDir}?`,
2190
- initialValue: false
2191
- })) {
2192
- let archived = 0;
2193
- const archivedAt = formatSessionArchiveTimestamp();
2194
- for (const orphanPath of orphanTranscriptPaths) {
2195
- const archivedPath = `${orphanPath}.deleted.${archivedAt}`;
2196
- try {
2197
- fs.renameSync(orphanPath, archivedPath);
2198
- archived += 1;
2199
- } catch (err) {
2200
- warnings.push(`- Failed to archive orphan transcript ${shortenHomePath(orphanPath)}: ${String(err)}`);
2201
- }
2202
- }
2203
- if (archived > 0) changes.push(`- Archived ${archived} orphan transcript file(s) in ${displaySessionsDir}`);
2204
- }
2205
- }
2206
- }
2207
- if (warnings.length > 0) note$1(warnings.join("\n"), "State integrity");
2208
- if (changes.length > 0) note$1(changes.join("\n"), "Doctor changes");
2209
- }
2210
- function noteWorkspaceBackupTip(workspaceDir) {
2211
- if (!existsDir(workspaceDir)) return;
2212
- const gitMarker = path.join(workspaceDir, ".git");
2213
- if (fs.existsSync(gitMarker)) return;
2214
- note$1([
2215
- "- Tip: back up the workspace in a private git repo (GitHub or GitLab).",
2216
- "- Keep ~/.moldclaw out of git; it contains credentials and session history.",
2217
- "- Details: /concepts/agent-workspace#git-backup-recommended"
2218
- ].join("\n"), "Workspace");
2219
- }
2220
- //#endregion
2221
- //#region src/commands/doctor-ui.ts
2222
- async function maybeRepairUiProtocolFreshness(_runtime, prompter) {
2223
- const root = await resolvemoldClawPackageRoot({
2224
- moduleUrl: import.meta.url,
2225
- argv1: process.argv[1],
2226
- cwd: process.cwd()
2227
- });
2228
- if (!root) return;
2229
- const schemaPath = path.join(root, "src/gateway/protocol/schema.ts");
2230
- const uiIndexPath = (await resolveControlUiDistIndexHealth({
2231
- root,
2232
- argv1: process.argv[1]
2233
- })).indexPath ?? resolveControlUiDistIndexPathForRoot(root);
2234
- try {
2235
- const [schemaStats, uiStats] = await Promise.all([fs$1.stat(schemaPath).catch(() => null), fs$1.stat(uiIndexPath).catch(() => null)]);
2236
- if (schemaStats && !uiStats) {
2237
- note$1(["- Control UI assets are missing.", "- Run: pnpm ui:build"].join("\n"), "UI");
2238
- const uiSourcesPath = path.join(root, "ui/package.json");
2239
- if (!await fs$1.stat(uiSourcesPath).catch(() => null)) {
2240
- note$1("Skipping UI build: ui/ sources not present.", "UI");
2241
- return;
2242
- }
2243
- if (await prompter.confirmRepair({
2244
- message: "Build Control UI assets now?",
2245
- initialValue: true
2246
- })) {
2247
- note$1("Building Control UI assets... (this may take a moment)", "UI");
2248
- const uiScriptPath = path.join(root, "scripts/ui.js");
2249
- const buildResult = await runCommandWithTimeout([
2250
- process.execPath,
2251
- uiScriptPath,
2252
- "build"
2253
- ], {
2254
- cwd: root,
2255
- timeoutMs: 12e4,
2256
- env: {
2257
- ...process.env,
2258
- FORCE_COLOR: "1"
2259
- }
2260
- });
2261
- if (buildResult.code === 0) note$1("UI build complete.", "UI");
2262
- else note$1([`UI build failed (exit ${buildResult.code ?? "unknown"}).`, buildResult.stderr.trim() ? buildResult.stderr.trim() : null].filter(Boolean).join("\n"), "UI");
2263
- }
2264
- return;
2265
- }
2266
- if (!schemaStats || !uiStats) return;
2267
- if (schemaStats.mtime > uiStats.mtime) {
2268
- const gitLog = await runCommandWithTimeout([
2269
- "git",
2270
- "-C",
2271
- root,
2272
- "log",
2273
- `--since=${uiStats.mtime.toISOString()}`,
2274
- "--format=%h %s",
2275
- "src/gateway/protocol/schema.ts"
2276
- ], { timeoutMs: 5e3 }).catch(() => null);
2277
- if (gitLog && gitLog.code === 0 && gitLog.stdout.trim()) {
2278
- note$1(`UI assets are older than the protocol schema.\nFunctional changes since last build:\n${gitLog.stdout.trim().split("\n").map((l) => `- ${l}`).join("\n")}`, "UI Freshness");
2279
- if (await prompter.confirmAggressive({
2280
- message: "Rebuild UI now? (Detected protocol mismatch requiring update)",
2281
- initialValue: true
2282
- })) {
2283
- const uiSourcesPath = path.join(root, "ui/package.json");
2284
- if (!await fs$1.stat(uiSourcesPath).catch(() => null)) {
2285
- note$1("Skipping UI rebuild: ui/ sources not present.", "UI");
2286
- return;
2287
- }
2288
- note$1("Rebuilding stale UI assets... (this may take a moment)", "UI");
2289
- const uiScriptPath = path.join(root, "scripts/ui.js");
2290
- const buildResult = await runCommandWithTimeout([
2291
- process.execPath,
2292
- uiScriptPath,
2293
- "build"
2294
- ], {
2295
- cwd: root,
2296
- timeoutMs: 12e4,
2297
- env: {
2298
- ...process.env,
2299
- FORCE_COLOR: "1"
2300
- }
2301
- });
2302
- if (buildResult.code === 0) note$1("UI rebuild complete.", "UI");
2303
- else note$1([`UI rebuild failed (exit ${buildResult.code ?? "unknown"}).`, buildResult.stderr.trim() ? buildResult.stderr.trim() : null].filter(Boolean).join("\n"), "UI");
2304
- }
2305
- }
2306
- }
2307
- } catch {}
2308
- }
2309
- //#endregion
2310
- //#region src/commands/doctor-update.ts
2311
- async function detectmoldClawGitCheckout(root) {
2312
- const res = await runCommandWithTimeout([
2313
- "git",
2314
- "-C",
2315
- root,
2316
- "rev-parse",
2317
- "--show-toplevel"
2318
- ], { timeoutMs: 5e3 }).catch(() => null);
2319
- if (!res) return "unknown";
2320
- if (res.code !== 0) {
2321
- if (res.stderr.toLowerCase().includes("not a git repository")) return "not-git";
2322
- return "unknown";
2323
- }
2324
- return res.stdout.trim() === root ? "git" : "not-git";
2325
- }
2326
- async function maybeOfferUpdateBeforeDoctor(params) {
2327
- if (!(!isTruthyEnvValue$1(process.env.MOLDCLAW_UPDATE_IN_PROGRESS) && params.options.nonInteractive !== true && params.options.yes !== true && params.options.repair !== true && Boolean(process.stdin.isTTY)) || !params.root) return { updated: false };
2328
- const git = await detectmoldClawGitCheckout(params.root);
2329
- if (git === "git") {
2330
- if (!await params.confirm({
2331
- message: "Update moldClaw from git before running doctor?",
2332
- initialValue: true
2333
- })) return { updated: false };
2334
- note$1("Running update (fetch/rebase/build/ui:build/doctor)…", "Update");
2335
- const result = await runGatewayUpdate({
2336
- cwd: params.root,
2337
- argv1: process.argv[1]
2338
- });
2339
- note$1([
2340
- `Status: ${result.status}`,
2341
- `Mode: ${result.mode}`,
2342
- result.root ? `Root: ${result.root}` : null,
2343
- result.reason ? `Reason: ${result.reason}` : null
2344
- ].filter(Boolean).join("\n"), "Update result");
2345
- if (result.status === "ok") {
2346
- params.outro("Update completed (doctor already ran as part of the update).");
2347
- return {
2348
- updated: true,
2349
- handled: true
2350
- };
2351
- }
2352
- return {
2353
- updated: true,
2354
- handled: false
2355
- };
2356
- }
2357
- if (git === "not-git") note$1(["This install is not a git checkout.", `Run \`${formatCliCommand("moldclaw update")}\` to update via your package manager (npm/pnpm), then rerun doctor.`].join("\n"), "Update");
2358
- return { updated: false };
2359
- }
2360
- //#endregion
2361
- //#region src/commands/doctor-workspace.ts
2362
- const MEMORY_SYSTEM_PROMPT = [
2363
- "Memory system not found in workspace.",
2364
- "Paste this into your agent:",
2365
- "",
2366
- "Install the memory system by applying:",
2367
- "https://github.com/moldclaw/moldclaw/commit/9ffea23f31ca1df5183b25668f8f814bee0fb34e",
2368
- "https://github.com/moldclaw/moldclaw/commit/7d1fee70e76f2f634f1b41fca927ee663914183a"
2369
- ].join("\n");
2370
- async function shouldSuggestMemorySystem(workspaceDir) {
2371
- const memoryPaths = [path.join(workspaceDir, "MEMORY.md"), path.join(workspaceDir, "memory.md")];
2372
- for (const memoryPath of memoryPaths) try {
2373
- await fs.promises.access(memoryPath);
2374
- return false;
2375
- } catch {}
2376
- const agentsPath = path.join(workspaceDir, DEFAULT_AGENTS_FILENAME);
2377
- try {
2378
- const content = await fs.promises.readFile(agentsPath, "utf-8");
2379
- if (/memory\.md/i.test(content)) return false;
2380
- } catch {}
2381
- return true;
2382
- }
2383
- function detectLegacyWorkspaceDirs(params) {
2384
- return {
2385
- activeWorkspace: path.resolve(params.workspaceDir),
2386
- legacyDirs: []
2387
- };
2388
- }
2389
- function formatLegacyWorkspaceWarning(detection) {
2390
- return [
2391
- "Extra workspace directories detected (may contain old agent files):",
2392
- ...detection.legacyDirs.map((dir) => `- ${shortenHomePath(dir)}`),
2393
- `Active workspace: ${shortenHomePath(detection.activeWorkspace)}`,
2394
- "If unused, archive or move to Trash."
2395
- ].join("\n");
2396
- }
2397
- //#endregion
2398
- //#region src/commands/doctor-workspace-status.ts
2399
- function noteWorkspaceStatus(cfg) {
2400
- const workspaceDir = resolveAgentWorkspaceDir(cfg, resolveDefaultAgentId(cfg));
2401
- const legacyWorkspace = detectLegacyWorkspaceDirs({ workspaceDir });
2402
- if (legacyWorkspace.legacyDirs.length > 0) note$1(formatLegacyWorkspaceWarning(legacyWorkspace), "Extra workspace");
2403
- const skillsReport = buildWorkspaceSkillStatus(workspaceDir, { config: cfg });
2404
- note$1([
2405
- `Eligible: ${skillsReport.skills.filter((s) => s.eligible).length}`,
2406
- `Missing requirements: ${skillsReport.skills.filter((s) => !s.eligible && !s.disabled && !s.blockedByAllowlist).length}`,
2407
- `Blocked by allowlist: ${skillsReport.skills.filter((s) => s.blockedByAllowlist).length}`
2408
- ].join("\n"), "Skills status");
2409
- const pluginRegistry = loadmoldClawPlugins({
2410
- config: cfg,
2411
- workspaceDir,
2412
- logger: {
2413
- info: () => {},
2414
- warn: () => {},
2415
- error: () => {},
2416
- debug: () => {}
2417
- }
2418
- });
2419
- if (pluginRegistry.plugins.length > 0) {
2420
- const loaded = pluginRegistry.plugins.filter((p) => p.status === "loaded");
2421
- const disabled = pluginRegistry.plugins.filter((p) => p.status === "disabled");
2422
- const errored = pluginRegistry.plugins.filter((p) => p.status === "error");
2423
- note$1([
2424
- `Loaded: ${loaded.length}`,
2425
- `Disabled: ${disabled.length}`,
2426
- `Errors: ${errored.length}`,
2427
- errored.length > 0 ? `- ${errored.slice(0, 10).map((p) => p.id).join("\n- ")}${errored.length > 10 ? "\n- ..." : ""}` : null
2428
- ].filter((line) => Boolean(line)).join("\n"), "Plugins");
2429
- }
2430
- if (pluginRegistry.diagnostics.length > 0) note$1(pluginRegistry.diagnostics.map((diag) => {
2431
- const prefix = diag.level.toUpperCase();
2432
- const plugin = diag.pluginId ? ` ${diag.pluginId}` : "";
2433
- const source = diag.source ? ` (${diag.source})` : "";
2434
- return `- ${prefix}${plugin}: ${diag.message}${source}`;
2435
- }).join("\n"), "Plugin diagnostics");
2436
- return { workspaceDir };
2437
- }
2438
- //#endregion
2439
- //#region src/commands/doctor.ts
2440
- const intro$1 = (message) => intro(stylePromptTitle(message) ?? message);
2441
- const outro$1 = (message) => outro(stylePromptTitle(message) ?? message);
2442
- function resolveMode(cfg) {
2443
- return cfg.gateway?.mode === "remote" ? "remote" : "local";
2444
- }
2445
- async function doctorCommand(runtime = defaultRuntime, options = {}) {
2446
- const prompter = createDoctorPrompter({
2447
- runtime,
2448
- options
2449
- });
2450
- printWizardHeader(runtime);
2451
- intro$1("moldClaw doctor");
2452
- const root = await resolvemoldClawPackageRoot({
2453
- moduleUrl: import.meta.url,
2454
- argv1: process.argv[1],
2455
- cwd: process.cwd()
2456
- });
2457
- if ((await maybeOfferUpdateBeforeDoctor({
2458
- runtime,
2459
- options,
2460
- root,
2461
- confirm: (p) => prompter.confirm(p),
2462
- outro: outro$1
2463
- })).handled) return;
2464
- await maybeRepairUiProtocolFreshness(runtime, prompter);
2465
- noteSourceInstallIssues(root);
2466
- noteDeprecatedLegacyEnvVars();
2467
- noteStartupOptimizationHints();
2468
- const configResult = await loadAndMaybeMigrateDoctorConfig({
2469
- options,
2470
- confirm: (p) => prompter.confirm(p)
2471
- });
2472
- let cfg = configResult.cfg;
2473
- const cfgForPersistence = structuredClone(cfg);
2474
- const sourceConfigValid = configResult.sourceConfigValid ?? true;
2475
- const configPath = configResult.path ?? CONFIG_PATH;
2476
- if (!cfg.gateway?.mode) {
2477
- const lines = [
2478
- "gateway.mode is unset; gateway start will be blocked.",
2479
- `Fix: run ${formatCliCommand("moldclaw configure")} and set Gateway mode (local/remote).`,
2480
- `Or set directly: ${formatCliCommand("moldclaw config set gateway.mode local")}`
2481
- ];
2482
- if (!fs.existsSync(configPath)) lines.push(`Missing config: run ${formatCliCommand("moldclaw setup")} first.`);
2483
- note$1(lines.join("\n"), "Gateway");
2484
- }
2485
- if (resolveMode(cfg) === "local" && hasAmbiguousGatewayAuthModeConfig(cfg)) note$1([
2486
- "gateway.auth.token and gateway.auth.password are both configured while gateway.auth.mode is unset.",
2487
- "Set an explicit mode to avoid ambiguous auth selection and startup/runtime failures.",
2488
- `Set token mode: ${formatCliCommand("moldclaw config set gateway.auth.mode token")}`,
2489
- `Set password mode: ${formatCliCommand("moldclaw config set gateway.auth.mode password")}`
2490
- ].join("\n"), "Gateway auth");
2491
- cfg = await maybeRepairAnthropicOAuthProfileId(cfg, prompter);
2492
- cfg = await maybeRemoveDeprecatedCliAuthProfiles(cfg, prompter);
2493
- await noteAuthProfileHealth({
2494
- cfg,
2495
- prompter,
2496
- allowKeychainPrompt: options.nonInteractive !== true && Boolean(process.stdin.isTTY)
2497
- });
2498
- const gatewayDetails = buildGatewayConnectionDetails({ config: cfg });
2499
- if (gatewayDetails.remoteFallbackNote) note$1(gatewayDetails.remoteFallbackNote, "Gateway");
2500
- if (resolveMode(cfg) === "local" && sourceConfigValid) {
2501
- const gatewayTokenRef = resolveSecretInputRef({
2502
- value: cfg.gateway?.auth?.token,
2503
- defaults: cfg.secrets?.defaults
2504
- }).ref;
2505
- const auth = resolveGatewayAuth({
2506
- authConfig: cfg.gateway?.auth,
2507
- tailscaleMode: cfg.gateway?.tailscale?.mode ?? "off"
2508
- });
2509
- if (auth.mode !== "password" && (auth.mode !== "token" || !auth.token)) if (gatewayTokenRef) note$1([
2510
- "Gateway token is managed via SecretRef and is currently unavailable.",
2511
- "Doctor will not overwrite gateway.auth.token with a plaintext value.",
2512
- "Resolve/rotate the external secret source, then rerun doctor."
2513
- ].join("\n"), "Gateway auth");
2514
- else {
2515
- note$1("Gateway auth is off or missing a token. Token auth is now the recommended default (including loopback).", "Gateway auth");
2516
- if (options.generateGatewayToken === true ? true : options.nonInteractive === true ? false : await prompter.confirmRepair({
2517
- message: "Generate and configure a gateway token now?",
2518
- initialValue: true
2519
- })) {
2520
- const nextToken = randomToken();
2521
- cfg = {
2522
- ...cfg,
2523
- gateway: {
2524
- ...cfg.gateway,
2525
- auth: {
2526
- ...cfg.gateway?.auth,
2527
- mode: "token",
2528
- token: nextToken
2529
- }
2530
- }
2531
- };
2532
- note$1("Gateway token configured.", "Gateway auth");
2533
- }
2534
- }
2535
- }
2536
- const legacyState = await detectLegacyStateMigrations({ cfg });
2537
- if (legacyState.preview.length > 0) {
2538
- note$1(legacyState.preview.join("\n"), "Legacy state detected");
2539
- if (options.nonInteractive === true ? true : await prompter.confirm({
2540
- message: "Migrate legacy state (sessions/agent/WhatsApp auth) now?",
2541
- initialValue: true
2542
- })) {
2543
- const migrated = await runLegacyStateMigrations({ detected: legacyState });
2544
- if (migrated.changes.length > 0) note$1(migrated.changes.join("\n"), "Doctor changes");
2545
- if (migrated.warnings.length > 0) note$1(migrated.warnings.join("\n"), "Doctor warnings");
2546
- }
2547
- }
2548
- await noteStateIntegrity(cfg, prompter, configResult.path ?? CONFIG_PATH);
2549
- await noteSessionLockHealth({ shouldRepair: prompter.shouldRepair });
2550
- await maybeRepairLegacyCronStore({
2551
- cfg,
2552
- options,
2553
- prompter
2554
- });
2555
- cfg = await maybeRepairSandboxImages(cfg, runtime, prompter);
2556
- noteSandboxScopeWarnings(cfg);
2557
- await maybeScanExtraGatewayServices(options, runtime, prompter);
2558
- await maybeRepairGatewayServiceConfig(cfg, resolveMode(cfg), runtime, prompter);
2559
- await noteMacLaunchAgentOverrides();
2560
- await noteMacLaunchctlGatewayEnvOverrides(cfg);
2561
- await noteSecurityWarnings(cfg);
2562
- await noteChromeMcpBrowserReadiness(cfg);
2563
- await noteOpenAIOAuthTlsPrerequisites({
2564
- cfg,
2565
- deep: options.deep === true
2566
- });
2567
- if (cfg.hooks?.gmail?.model?.trim()) {
2568
- const hooksModelRef = resolveHooksGmailModel({
2569
- cfg,
2570
- defaultProvider: DEFAULT_PROVIDER
2571
- });
2572
- if (!hooksModelRef) note$1(`- hooks.gmail.model "${cfg.hooks.gmail.model}" could not be resolved`, "Hooks");
2573
- else {
2574
- const { provider: defaultProvider, model: defaultModel } = resolveConfiguredModelRef({
2575
- cfg,
2576
- defaultProvider: DEFAULT_PROVIDER,
2577
- defaultModel: DEFAULT_MODEL
2578
- });
2579
- const catalog = await loadModelCatalog({ config: cfg });
2580
- const status = getModelRefStatus({
2581
- cfg,
2582
- catalog,
2583
- ref: hooksModelRef,
2584
- defaultProvider,
2585
- defaultModel
2586
- });
2587
- const warnings = [];
2588
- if (!status.allowed) warnings.push(`- hooks.gmail.model "${status.key}" not in agents.defaults.models allowlist (will use primary instead)`);
2589
- if (!status.inCatalog) warnings.push(`- hooks.gmail.model "${status.key}" not in the model catalog (may fail at runtime)`);
2590
- if (warnings.length > 0) note$1(warnings.join("\n"), "Hooks");
2591
- }
2592
- }
2593
- if (options.nonInteractive !== true && process.platform === "linux" && resolveMode(cfg) === "local") {
2594
- const service = resolveGatewayService();
2595
- let loaded = false;
2596
- try {
2597
- loaded = await service.isLoaded({ env: process.env });
2598
- } catch {
2599
- loaded = false;
2600
- }
2601
- if (loaded) await ensureSystemdUserLingerInteractive({
2602
- runtime,
2603
- prompter: {
2604
- confirm: async (p) => prompter.confirm(p),
2605
- note: note$1
2606
- },
2607
- reason: "Gateway runs as a systemd user service. Without lingering, systemd stops the user session on logout/idle and kills the Gateway.",
2608
- requireConfirm: true
2609
- });
2610
- }
2611
- noteWorkspaceStatus(cfg);
2612
- await noteBootstrapFileSize(cfg);
2613
- await doctorShellCompletion(runtime, prompter, { nonInteractive: options.nonInteractive });
2614
- const { healthOk } = await checkGatewayHealth({
2615
- runtime,
2616
- cfg,
2617
- timeoutMs: options.nonInteractive === true ? 3e3 : 1e4
2618
- });
2619
- const gatewayMemoryProbe = healthOk ? await probeGatewayMemoryStatus({
2620
- cfg,
2621
- timeoutMs: options.nonInteractive === true ? 3e3 : 1e4
2622
- }) : {
2623
- checked: false,
2624
- ready: false
2625
- };
2626
- await noteMemorySearchHealth(cfg, { gatewayMemoryProbe });
2627
- await maybeRepairGatewayDaemon({
2628
- cfg,
2629
- runtime,
2630
- prompter,
2631
- options,
2632
- gatewayDetailsMessage: gatewayDetails.message,
2633
- healthOk
2634
- });
2635
- if (configResult.shouldWriteConfig || JSON.stringify(cfg) !== JSON.stringify(cfgForPersistence)) {
2636
- cfg = applyWizardMetadata(cfg, {
2637
- command: "doctor",
2638
- mode: resolveMode(cfg)
2639
- });
2640
- await writeConfigFile(cfg);
2641
- logConfigUpdated(runtime);
2642
- const backupPath = `${CONFIG_PATH}.bak`;
2643
- if (fs.existsSync(backupPath)) runtime.log(`Backup: ${shortenHomePath(backupPath)}`);
2644
- } else if (!prompter.shouldRepair) runtime.log(`Run "${formatCliCommand("moldclaw doctor --fix")}" to apply changes.`);
2645
- if (options.workspaceSuggestions !== false) {
2646
- const workspaceDir = resolveAgentWorkspaceDir(cfg, resolveDefaultAgentId(cfg));
2647
- noteWorkspaceBackupTip(workspaceDir);
2648
- if (await shouldSuggestMemorySystem(workspaceDir)) note$1(MEMORY_SYSTEM_PROMPT, "Workspace");
2649
- }
2650
- const finalSnapshot = await readConfigFileSnapshot();
2651
- if (finalSnapshot.exists && !finalSnapshot.valid) {
2652
- runtime.error("Invalid config:");
2653
- for (const issue of finalSnapshot.issues) {
2654
- const path = issue.path || "<root>";
2655
- runtime.error(`- ${path}: ${issue.message}`);
2656
- }
2657
- }
2658
- outro$1("Doctor complete.");
2659
- }
2660
- //#endregion
2661
- //#region src/terminal/prompt-select-styled.ts
2662
- function selectStyled(params) {
2663
- return select({
2664
- ...params,
2665
- message: stylePromptMessage(params.message),
2666
- options: params.options.map((opt) => opt.hint === void 0 ? opt : {
2667
- ...opt,
2668
- hint: stylePromptHint(opt.hint)
2669
- })
2670
- });
2671
- }
2672
- //#endregion
2673
- export { doctorCommand as n, selectStyled as t };