hyacinth-ai 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (704) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +205 -0
  3. package/commands.json +25 -0
  4. package/dist/agents/builtins.d.ts +8 -0
  5. package/dist/agents/builtins.js +50 -0
  6. package/dist/agents/config-loader.d.ts +15 -0
  7. package/dist/agents/config-loader.js +75 -0
  8. package/dist/agents/delegate-tool.d.ts +109 -0
  9. package/dist/agents/delegate-tool.js +407 -0
  10. package/dist/agents/index.d.ts +5 -0
  11. package/dist/agents/index.js +5 -0
  12. package/dist/agents/registry.d.ts +2 -0
  13. package/dist/agents/registry.js +2 -0
  14. package/dist/bypass/agents/companion/index.d.ts +57 -0
  15. package/dist/bypass/agents/companion/index.js +487 -0
  16. package/dist/bypass/agents/orchestrator/index.d.ts +17 -0
  17. package/dist/bypass/agents/orchestrator/index.js +414 -0
  18. package/dist/bypass/agents/orchestrator.d.ts +16 -0
  19. package/dist/bypass/agents/orchestrator.js +377 -0
  20. package/dist/bypass/agents/world-engine/agent.d.ts +41 -0
  21. package/dist/bypass/agents/world-engine/agent.js +385 -0
  22. package/dist/bypass/agents/world-engine/index.d.ts +52 -0
  23. package/dist/bypass/agents/world-engine/index.js +198 -0
  24. package/dist/bypass/agents/world-engine/sim.d.ts +14 -0
  25. package/dist/bypass/agents/world-engine/sim.js +120 -0
  26. package/dist/bypass/agents/world-engine/store.d.ts +110 -0
  27. package/dist/bypass/agents/world-engine/store.js +519 -0
  28. package/dist/bypass/agents/world-engine/ticker.d.ts +37 -0
  29. package/dist/bypass/agents/world-engine/ticker.js +214 -0
  30. package/dist/bypass/agents/world-engine/tools.d.ts +6 -0
  31. package/dist/bypass/agents/world-engine/tools.js +380 -0
  32. package/dist/bypass/agents/world-engine/types.d.ts +202 -0
  33. package/dist/bypass/agents/world-engine/types.js +56 -0
  34. package/dist/bypass/agents/world-engine.d.ts +20 -0
  35. package/dist/bypass/agents/world-engine.js +63 -0
  36. package/dist/bypass/base.d.ts +48 -0
  37. package/dist/bypass/base.js +126 -0
  38. package/dist/bypass/index.d.ts +5 -0
  39. package/dist/bypass/index.js +6 -0
  40. package/dist/bypass/manager.d.ts +41 -0
  41. package/dist/bypass/manager.js +179 -0
  42. package/dist/bypass/types.d.ts +63 -0
  43. package/dist/bypass/types.js +14 -0
  44. package/dist/channels/auto-detect.d.ts +25 -0
  45. package/dist/channels/auto-detect.js +77 -0
  46. package/dist/channels/builtin/http-webhook.d.ts +25 -0
  47. package/dist/channels/builtin/http-webhook.js +287 -0
  48. package/dist/channels/builtin/tui-channel.d.ts +33 -0
  49. package/dist/channels/builtin/tui-channel.js +61 -0
  50. package/dist/channels/builtin/tui-ws-session.d.ts +16 -0
  51. package/dist/channels/builtin/tui-ws-session.js +90 -0
  52. package/dist/channels/builtin/webui-output-handler.d.ts +30 -0
  53. package/dist/channels/builtin/webui-output-handler.js +93 -0
  54. package/dist/channels/index.d.ts +5 -0
  55. package/dist/channels/index.js +3 -0
  56. package/dist/channels/interface.d.ts +148 -0
  57. package/dist/channels/interface.js +15 -0
  58. package/dist/channels/manager.d.ts +43 -0
  59. package/dist/channels/manager.js +156 -0
  60. package/dist/channels/message-queue.d.ts +36 -0
  61. package/dist/channels/message-queue.js +91 -0
  62. package/dist/channels/plugins/clawbot/clawbot-auth.d.ts +50 -0
  63. package/dist/channels/plugins/clawbot/clawbot-auth.js +235 -0
  64. package/dist/channels/plugins/clawbot/clawbot-channel.d.ts +76 -0
  65. package/dist/channels/plugins/clawbot/clawbot-channel.js +566 -0
  66. package/dist/channels/plugins/clawbot/clawbot-client.d.ts +180 -0
  67. package/dist/channels/plugins/clawbot/clawbot-client.js +312 -0
  68. package/dist/channels/plugins/clawbot/clawbot-config.d.ts +30 -0
  69. package/dist/channels/plugins/clawbot/clawbot-config.js +28 -0
  70. package/dist/channels/plugins/clawbot/clawbot-message-queue.d.ts +27 -0
  71. package/dist/channels/plugins/clawbot/clawbot-message-queue.js +114 -0
  72. package/dist/channels/plugins/clawbot/clawbot-session.d.ts +10 -0
  73. package/dist/channels/plugins/clawbot/clawbot-session.js +26 -0
  74. package/dist/channels/plugins/clawbot/index.d.ts +17 -0
  75. package/dist/channels/plugins/clawbot/index.js +58 -0
  76. package/dist/channels/plugins/feishu/feishu-channel.d.ts +57 -0
  77. package/dist/channels/plugins/feishu/feishu-channel.js +602 -0
  78. package/dist/channels/plugins/feishu/feishu-client.d.ts +23 -0
  79. package/dist/channels/plugins/feishu/feishu-client.js +86 -0
  80. package/dist/channels/plugins/feishu/feishu-config.d.ts +53 -0
  81. package/dist/channels/plugins/feishu/feishu-config.js +35 -0
  82. package/dist/channels/plugins/feishu/feishu-event.d.ts +102 -0
  83. package/dist/channels/plugins/feishu/feishu-event.js +257 -0
  84. package/dist/channels/plugins/feishu/feishu-log-suppressor.d.ts +7 -0
  85. package/dist/channels/plugins/feishu/feishu-log-suppressor.js +34 -0
  86. package/dist/channels/plugins/feishu/feishu-message-queue.d.ts +27 -0
  87. package/dist/channels/plugins/feishu/feishu-message-queue.js +112 -0
  88. package/dist/channels/plugins/feishu/feishu-send.d.ts +44 -0
  89. package/dist/channels/plugins/feishu/feishu-send.js +232 -0
  90. package/dist/channels/plugins/feishu/feishu-session.d.ts +44 -0
  91. package/dist/channels/plugins/feishu/feishu-session.js +84 -0
  92. package/dist/channels/plugins/feishu/feishu-streaming.d.ts +49 -0
  93. package/dist/channels/plugins/feishu/feishu-streaming.js +185 -0
  94. package/dist/channels/plugins/feishu/feishu-transport.d.ts +29 -0
  95. package/dist/channels/plugins/feishu/feishu-transport.js +99 -0
  96. package/dist/channels/plugins/feishu/index.d.ts +22 -0
  97. package/dist/channels/plugins/feishu/index.js +68 -0
  98. package/dist/cli/doctor.d.ts +20 -0
  99. package/dist/cli/doctor.js +317 -0
  100. package/dist/context/cache-strategy.d.ts +76 -0
  101. package/dist/context/cache-strategy.js +123 -0
  102. package/dist/context/composer.d.ts +77 -0
  103. package/dist/context/composer.js +318 -0
  104. package/dist/context/compressor.d.ts +218 -0
  105. package/dist/context/compressor.js +909 -0
  106. package/dist/context/index.d.ts +14 -0
  107. package/dist/context/index.js +8 -0
  108. package/dist/context/interface.d.ts +33 -0
  109. package/dist/context/interface.js +2 -0
  110. package/dist/context/manifest-defaults.d.ts +51 -0
  111. package/dist/context/manifest-defaults.js +133 -0
  112. package/dist/context/manifest-loader.d.ts +16 -0
  113. package/dist/context/manifest-loader.js +103 -0
  114. package/dist/context/manifest-types.d.ts +26 -0
  115. package/dist/context/manifest-types.js +2 -0
  116. package/dist/context/precision/analyzer.d.ts +31 -0
  117. package/dist/context/precision/analyzer.js +131 -0
  118. package/dist/context/precision/companion.d.ts +27 -0
  119. package/dist/context/precision/companion.js +144 -0
  120. package/dist/context/precision/default.d.ts +14 -0
  121. package/dist/context/precision/default.js +17 -0
  122. package/dist/context/precision/index.d.ts +9 -0
  123. package/dist/context/precision/index.js +7 -0
  124. package/dist/context/precision/keyword-pool.d.ts +27 -0
  125. package/dist/context/precision/keyword-pool.js +66 -0
  126. package/dist/context/precision/strategy.d.ts +18 -0
  127. package/dist/context/precision/strategy.js +51 -0
  128. package/dist/context/precision/summary-store.d.ts +18 -0
  129. package/dist/context/precision/summary-store.js +67 -0
  130. package/dist/context/precision/types.d.ts +23 -0
  131. package/dist/context/precision/types.js +2 -0
  132. package/dist/context/profiles.d.ts +45 -0
  133. package/dist/context/profiles.js +92 -0
  134. package/dist/context/prompt-builder.d.ts +76 -0
  135. package/dist/context/prompt-builder.js +133 -0
  136. package/dist/context/retriever.d.ts +44 -0
  137. package/dist/context/retriever.js +203 -0
  138. package/dist/context/router.d.ts +122 -0
  139. package/dist/context/router.js +291 -0
  140. package/dist/context/section-resolver.d.ts +38 -0
  141. package/dist/context/section-resolver.js +398 -0
  142. package/dist/context/tokenizer.d.ts +23 -0
  143. package/dist/context/tokenizer.js +78 -0
  144. package/dist/dependency/analyzer.d.ts +33 -0
  145. package/dist/dependency/analyzer.js +242 -0
  146. package/dist/dependency/data-flow-tracker.d.ts +12 -0
  147. package/dist/dependency/data-flow-tracker.js +97 -0
  148. package/dist/dependency/function-parser.d.ts +34 -0
  149. package/dist/dependency/function-parser.js +295 -0
  150. package/dist/dependency/index.d.ts +14 -0
  151. package/dist/dependency/index.js +20 -0
  152. package/dist/dependency/parser.d.ts +10 -0
  153. package/dist/dependency/parser.js +93 -0
  154. package/dist/dependency/types.d.ts +57 -0
  155. package/dist/dependency/types.js +2 -0
  156. package/dist/env/env-collector.d.ts +45 -0
  157. package/dist/env/env-collector.js +221 -0
  158. package/dist/env/index.d.ts +3 -0
  159. package/dist/env/index.js +2 -0
  160. package/dist/event-store.d.ts +27 -0
  161. package/dist/event-store.js +71 -0
  162. package/dist/evolution/git-manager.d.ts +46 -0
  163. package/dist/evolution/git-manager.js +276 -0
  164. package/dist/evolution/index.d.ts +3 -0
  165. package/dist/evolution/index.js +2 -0
  166. package/dist/flow/bootstrap-flow.d.ts +19 -0
  167. package/dist/flow/bootstrap-flow.js +72 -0
  168. package/dist/flow/flow-registry.d.ts +12 -0
  169. package/dist/flow/flow-registry.js +74 -0
  170. package/dist/flow/flow-tools.d.ts +8 -0
  171. package/dist/flow/flow-tools.js +106 -0
  172. package/dist/flow/index.d.ts +6 -0
  173. package/dist/flow/index.js +8 -0
  174. package/dist/flow/todo-flow.d.ts +25 -0
  175. package/dist/flow/todo-flow.js +107 -0
  176. package/dist/flow/types.d.ts +78 -0
  177. package/dist/flow/types.js +12 -0
  178. package/dist/flows/bootstrap.d.ts +18 -0
  179. package/dist/flows/bootstrap.js +119 -0
  180. package/dist/flows/index.d.ts +6 -0
  181. package/dist/flows/index.js +11 -0
  182. package/dist/flows/todo.d.ts +26 -0
  183. package/dist/flows/todo.js +174 -0
  184. package/dist/flows/tools.d.ts +8 -0
  185. package/dist/flows/tools.js +119 -0
  186. package/dist/flows/types.d.ts +27 -0
  187. package/dist/flows/types.js +10 -0
  188. package/dist/gateway/cli.d.ts +5 -0
  189. package/dist/gateway/cli.js +1027 -0
  190. package/dist/gateway/factory.d.ts +80 -0
  191. package/dist/gateway/factory.js +832 -0
  192. package/dist/gateway/guardian.d.ts +8 -0
  193. package/dist/gateway/guardian.js +30 -0
  194. package/dist/gateway/index.d.ts +3 -0
  195. package/dist/gateway/index.js +3 -0
  196. package/dist/gateway/server.d.ts +17 -0
  197. package/dist/gateway/server.js +96 -0
  198. package/dist/gateway/tui.d.ts +16 -0
  199. package/dist/gateway/tui.js +3273 -0
  200. package/dist/hot-reload/agent-watcher.d.ts +24 -0
  201. package/dist/hot-reload/agent-watcher.js +175 -0
  202. package/dist/hot-reload/bundle-watcher.d.ts +12 -0
  203. package/dist/hot-reload/bundle-watcher.js +35 -0
  204. package/dist/hot-reload/channel-watcher.d.ts +19 -0
  205. package/dist/hot-reload/channel-watcher.js +54 -0
  206. package/dist/hot-reload/command-watcher.d.ts +14 -0
  207. package/dist/hot-reload/command-watcher.js +54 -0
  208. package/dist/hot-reload/config-watcher.d.ts +20 -0
  209. package/dist/hot-reload/config-watcher.js +58 -0
  210. package/dist/hot-reload/index.d.ts +12 -0
  211. package/dist/hot-reload/index.js +12 -0
  212. package/dist/hot-reload/manager.d.ts +58 -0
  213. package/dist/hot-reload/manager.js +243 -0
  214. package/dist/hot-reload/manifest-watcher.d.ts +9 -0
  215. package/dist/hot-reload/manifest-watcher.js +42 -0
  216. package/dist/hot-reload/mcp-watcher.d.ts +18 -0
  217. package/dist/hot-reload/mcp-watcher.js +64 -0
  218. package/dist/hot-reload/model-catalog-watcher.d.ts +18 -0
  219. package/dist/hot-reload/model-catalog-watcher.js +62 -0
  220. package/dist/hot-reload/plugin-watcher.d.ts +20 -0
  221. package/dist/hot-reload/plugin-watcher.js +56 -0
  222. package/dist/hot-reload/prompt-watcher.d.ts +6 -0
  223. package/dist/hot-reload/prompt-watcher.js +38 -0
  224. package/dist/hot-reload/provider-watcher.d.ts +16 -0
  225. package/dist/hot-reload/provider-watcher.js +45 -0
  226. package/dist/hot-reload/skill-watcher.d.ts +19 -0
  227. package/dist/hot-reload/skill-watcher.js +82 -0
  228. package/dist/hot-reload/tool-watcher.d.ts +16 -0
  229. package/dist/hot-reload/tool-watcher.js +168 -0
  230. package/dist/hot-reload/workflow-watcher.d.ts +19 -0
  231. package/dist/hot-reload/workflow-watcher.js +84 -0
  232. package/dist/index.d.ts +3 -0
  233. package/dist/index.js +6 -0
  234. package/dist/knowledge/fts5-retriever.d.ts +30 -0
  235. package/dist/knowledge/fts5-retriever.js +223 -0
  236. package/dist/knowledge/index.d.ts +11 -0
  237. package/dist/knowledge/index.js +14 -0
  238. package/dist/knowledge/indexer.d.ts +41 -0
  239. package/dist/knowledge/indexer.js +186 -0
  240. package/dist/knowledge/query-preprocessor.d.ts +13 -0
  241. package/dist/knowledge/query-preprocessor.js +63 -0
  242. package/dist/knowledge/retriever.d.ts +45 -0
  243. package/dist/knowledge/retriever.js +9 -0
  244. package/dist/knowledge/store.d.ts +27 -0
  245. package/dist/knowledge/store.js +61 -0
  246. package/dist/knowledge/structured-store.d.ts +78 -0
  247. package/dist/knowledge/structured-store.js +280 -0
  248. package/dist/knowledge/structured-tools.d.ts +12 -0
  249. package/dist/knowledge/structured-tools.js +151 -0
  250. package/dist/knowledge/tools.d.ts +20 -0
  251. package/dist/knowledge/tools.js +238 -0
  252. package/dist/knowledge/watcher.d.ts +28 -0
  253. package/dist/knowledge/watcher.js +113 -0
  254. package/dist/lifecycle/index.d.ts +12 -0
  255. package/dist/lifecycle/index.js +14 -0
  256. package/dist/lifecycle/interface.d.ts +94 -0
  257. package/dist/lifecycle/interface.js +2 -0
  258. package/dist/lifecycle/local-model.d.ts +62 -0
  259. package/dist/lifecycle/local-model.js +331 -0
  260. package/dist/lifecycle/manager.d.ts +70 -0
  261. package/dist/lifecycle/manager.js +374 -0
  262. package/dist/lifecycle/supervisor.d.ts +89 -0
  263. package/dist/lifecycle/supervisor.js +277 -0
  264. package/dist/lifecycle-integration-test.d.ts +2 -0
  265. package/dist/lifecycle-integration-test.js +72 -0
  266. package/dist/local-model/download-manager.d.ts +59 -0
  267. package/dist/local-model/download-manager.js +517 -0
  268. package/dist/local-model/index.d.ts +109 -0
  269. package/dist/local-model/index.js +233 -0
  270. package/dist/local-model/llamacpp-provider.d.ts +95 -0
  271. package/dist/local-model/llamacpp-provider.js +379 -0
  272. package/dist/local-model/model-bridge.d.ts +48 -0
  273. package/dist/local-model/model-bridge.js +256 -0
  274. package/dist/local-model/model-registry.d.ts +47 -0
  275. package/dist/local-model/model-registry.js +188 -0
  276. package/dist/local-model/types.d.ts +49 -0
  277. package/dist/local-model/types.js +2 -0
  278. package/dist/logging/index.d.ts +3 -0
  279. package/dist/logging/index.js +3 -0
  280. package/dist/logging/logger.d.ts +56 -0
  281. package/dist/logging/logger.js +94 -0
  282. package/dist/machine/flows/bootstrap.d.ts +18 -0
  283. package/dist/machine/flows/bootstrap.js +119 -0
  284. package/dist/machine/flows/index.d.ts +6 -0
  285. package/dist/machine/flows/index.js +11 -0
  286. package/dist/machine/flows/spec.d.ts +17 -0
  287. package/dist/machine/flows/spec.js +176 -0
  288. package/dist/machine/flows/todo.d.ts +26 -0
  289. package/dist/machine/flows/todo.js +175 -0
  290. package/dist/machine/flows/tools.d.ts +8 -0
  291. package/dist/machine/flows/tools.js +119 -0
  292. package/dist/machine/flows/types.d.ts +33 -0
  293. package/dist/machine/flows/types.js +10 -0
  294. package/dist/machine/index.d.ts +8 -0
  295. package/dist/machine/index.js +9 -0
  296. package/dist/machine/registry.d.ts +34 -0
  297. package/dist/machine/registry.js +98 -0
  298. package/dist/machine/runner.d.ts +41 -0
  299. package/dist/machine/runner.js +177 -0
  300. package/dist/machine/types.d.ts +121 -0
  301. package/dist/machine/types.js +9 -0
  302. package/dist/mcp/bridge.d.ts +33 -0
  303. package/dist/mcp/bridge.js +99 -0
  304. package/dist/mcp/client.d.ts +37 -0
  305. package/dist/mcp/client.js +161 -0
  306. package/dist/mcp/config.d.ts +15 -0
  307. package/dist/mcp/config.js +85 -0
  308. package/dist/mcp/index.d.ts +7 -0
  309. package/dist/mcp/index.js +7 -0
  310. package/dist/mcp/install-manager.d.ts +31 -0
  311. package/dist/mcp/install-manager.js +158 -0
  312. package/dist/mcp/lifecycle.d.ts +41 -0
  313. package/dist/mcp/lifecycle.js +175 -0
  314. package/dist/mcp/process-transport.d.ts +21 -0
  315. package/dist/mcp/process-transport.js +59 -0
  316. package/dist/mcp/side-effect.d.ts +5 -0
  317. package/dist/mcp/side-effect.js +21 -0
  318. package/dist/mcp/system.d.ts +95 -0
  319. package/dist/mcp/system.js +279 -0
  320. package/dist/memory/companion-session.d.ts +22 -0
  321. package/dist/memory/companion-session.js +77 -0
  322. package/dist/memory/compression-boundary.d.ts +20 -0
  323. package/dist/memory/compression-boundary.js +40 -0
  324. package/dist/memory/conversation.d.ts +34 -0
  325. package/dist/memory/conversation.js +107 -0
  326. package/dist/memory/events.d.ts +42 -0
  327. package/dist/memory/events.js +56 -0
  328. package/dist/memory/index.d.ts +7 -0
  329. package/dist/memory/index.js +6 -0
  330. package/dist/memory/memory-store.d.ts +11 -0
  331. package/dist/memory/memory-store.js +51 -0
  332. package/dist/memory/session-allowlist.d.ts +11 -0
  333. package/dist/memory/session-allowlist.js +50 -0
  334. package/dist/memory/session.d.ts +48 -0
  335. package/dist/memory/session.js +275 -0
  336. package/dist/memory/stats.d.ts +23 -0
  337. package/dist/memory/stats.js +59 -0
  338. package/dist/memory/summary.d.ts +7 -0
  339. package/dist/memory/summary.js +23 -0
  340. package/dist/multimodal/index.d.ts +66 -0
  341. package/dist/multimodal/index.js +210 -0
  342. package/dist/orchestrator/index.d.ts +5 -0
  343. package/dist/orchestrator/index.js +4 -0
  344. package/dist/orchestrator/loop.d.ts +331 -0
  345. package/dist/orchestrator/loop.js +2443 -0
  346. package/dist/orchestrator/plan-store.d.ts +81 -0
  347. package/dist/orchestrator/plan-store.js +167 -0
  348. package/dist/orchestrator/planner.d.ts +20 -0
  349. package/dist/orchestrator/planner.js +34 -0
  350. package/dist/parser/index.d.ts +2 -0
  351. package/dist/parser/index.js +2 -0
  352. package/dist/parser/router.d.ts +30 -0
  353. package/dist/parser/router.js +61 -0
  354. package/dist/plugins/api.d.ts +39 -0
  355. package/dist/plugins/api.js +85 -0
  356. package/dist/plugins/define.d.ts +27 -0
  357. package/dist/plugins/define.js +32 -0
  358. package/dist/plugins/index.d.ts +9 -0
  359. package/dist/plugins/index.js +5 -0
  360. package/dist/plugins/loader.d.ts +39 -0
  361. package/dist/plugins/loader.js +128 -0
  362. package/dist/plugins/manager.d.ts +61 -0
  363. package/dist/plugins/manager.js +257 -0
  364. package/dist/plugins/types.d.ts +82 -0
  365. package/dist/plugins/types.js +2 -0
  366. package/dist/prompts/agents/code-reviewer.md +16 -0
  367. package/dist/prompts/agents/security-auditor.md +17 -0
  368. package/dist/prompts/agents/test-writer.md +15 -0
  369. package/dist/prompts/attention/attention.md +12 -0
  370. package/dist/prompts/environment/environment.md +18 -0
  371. package/dist/prompts/environment/feishu.md +107 -0
  372. package/dist/prompts/flows/bootstrap-confirm.md +14 -0
  373. package/dist/prompts/flows/bootstrap-identity.md +11 -0
  374. package/dist/prompts/flows/bootstrap-soul.md +19 -0
  375. package/dist/prompts/flows/bootstrap-user.md +11 -0
  376. package/dist/prompts/flows/spec-checklist.md +27 -0
  377. package/dist/prompts/flows/spec-define.md +64 -0
  378. package/dist/prompts/flows/spec-executing-checklist.md +15 -0
  379. package/dist/prompts/flows/spec-executing-tasks.md +15 -0
  380. package/dist/prompts/flows/spec-spec.md +51 -0
  381. package/dist/prompts/flows/spec-tasks.md +32 -0
  382. package/dist/prompts/flows/todo-execution.md +7 -0
  383. package/dist/prompts/flows/todo-planning.md +18 -0
  384. package/dist/prompts/framework/architecture.md +131 -0
  385. package/dist/prompts/identity/identity.md +2 -0
  386. package/dist/prompts/loader.d.ts +24 -0
  387. package/dist/prompts/loader.js +102 -0
  388. package/dist/prompts/loader.ts +119 -0
  389. package/dist/prompts/orchestration/summary.md +14 -0
  390. package/dist/prompts/persona/BOOTSTRAP.md +5 -0
  391. package/dist/prompts/persona/IDENTITY.md +16 -0
  392. package/dist/prompts/persona/PartnerMemory.md +5 -0
  393. package/dist/prompts/persona/PartnerSoul.md +7 -0
  394. package/dist/prompts/persona/SOUL.md +30 -0
  395. package/dist/prompts/persona/USER.md +16 -0
  396. package/dist/prompts/precise/analyze.md +23 -0
  397. package/dist/prompts/precise/persona.md +18 -0
  398. package/dist/prompts/safety/coding-standards.md +5 -0
  399. package/dist/prompts/safety/safety.md +4 -0
  400. package/dist/prompts/skills/code-review.md +4 -0
  401. package/dist/prompts/skills/debug.md +7 -0
  402. package/dist/prompts/skills/framework-reference.md +131 -0
  403. package/dist/prompts/skills/refactor.md +6 -0
  404. package/dist/prompts/summary.md +22 -0
  405. package/dist/prompts/tools/framework-capabilities.md +241 -0
  406. package/dist/prompts/tools/tool-rules.md +15 -0
  407. package/dist/provider/anthropic.d.ts +62 -0
  408. package/dist/provider/anthropic.js +361 -0
  409. package/dist/provider/catalog.d.ts +58 -0
  410. package/dist/provider/catalog.js +97 -0
  411. package/dist/provider/compatible.d.ts +89 -0
  412. package/dist/provider/compatible.js +328 -0
  413. package/dist/provider/config.d.ts +23 -0
  414. package/dist/provider/config.js +158 -0
  415. package/dist/provider/deepseek.d.ts +25 -0
  416. package/dist/provider/deepseek.js +37 -0
  417. package/dist/provider/fallback.d.ts +51 -0
  418. package/dist/provider/fallback.js +113 -0
  419. package/dist/provider/gemini.d.ts +27 -0
  420. package/dist/provider/gemini.js +170 -0
  421. package/dist/provider/index.d.ts +36 -0
  422. package/dist/provider/index.js +42 -0
  423. package/dist/provider/interface.d.ts +62 -0
  424. package/dist/provider/interface.js +2 -0
  425. package/dist/provider/local-config.d.ts +37 -0
  426. package/dist/provider/local-config.js +146 -0
  427. package/dist/provider/local.d.ts +45 -0
  428. package/dist/provider/local.js +248 -0
  429. package/dist/provider/manager.d.ts +67 -0
  430. package/dist/provider/manager.js +355 -0
  431. package/dist/provider/mimo.d.ts +19 -0
  432. package/dist/provider/mimo.js +30 -0
  433. package/dist/provider/minimax.d.ts +22 -0
  434. package/dist/provider/minimax.js +33 -0
  435. package/dist/provider/model-catalog-loader.d.ts +42 -0
  436. package/dist/provider/model-catalog-loader.js +89 -0
  437. package/dist/provider/model-channel-registry.d.ts +130 -0
  438. package/dist/provider/model-channel-registry.js +488 -0
  439. package/dist/provider/model-router.d.ts +60 -0
  440. package/dist/provider/model-router.js +87 -0
  441. package/dist/provider/openai.d.ts +54 -0
  442. package/dist/provider/openai.js +274 -0
  443. package/dist/provider/qwen.d.ts +19 -0
  444. package/dist/provider/qwen.js +30 -0
  445. package/dist/provider/resilient.d.ts +46 -0
  446. package/dist/provider/resilient.js +181 -0
  447. package/dist/provider/retry.d.ts +16 -0
  448. package/dist/provider/retry.js +78 -0
  449. package/dist/provider/router.d.ts +68 -0
  450. package/dist/provider/router.js +145 -0
  451. package/dist/provider/tool-args-recovery.d.ts +36 -0
  452. package/dist/provider/tool-args-recovery.js +91 -0
  453. package/dist/provider/user-id.d.ts +13 -0
  454. package/dist/provider/user-id.js +53 -0
  455. package/dist/provider/zhipu.d.ts +19 -0
  456. package/dist/provider/zhipu.js +32 -0
  457. package/dist/registry/agent.registry.d.ts +57 -0
  458. package/dist/registry/agent.registry.js +224 -0
  459. package/dist/registry/base.d.ts +54 -0
  460. package/dist/registry/base.js +99 -0
  461. package/dist/registry/channel.registry.d.ts +53 -0
  462. package/dist/registry/channel.registry.js +87 -0
  463. package/dist/registry/index.d.ts +9 -0
  464. package/dist/registry/index.js +10 -0
  465. package/dist/registry/mcp.registry.d.ts +2 -0
  466. package/dist/registry/mcp.registry.js +2 -0
  467. package/dist/registry/plugin.registry.d.ts +33 -0
  468. package/dist/registry/plugin.registry.js +66 -0
  469. package/dist/registry/provider.registry.d.ts +51 -0
  470. package/dist/registry/provider.registry.js +104 -0
  471. package/dist/registry/skill.registry.d.ts +33 -0
  472. package/dist/registry/skill.registry.js +95 -0
  473. package/dist/registry/tool.registry.d.ts +68 -0
  474. package/dist/registry/tool.registry.js +185 -0
  475. package/dist/repair/loop-guard.d.ts +98 -0
  476. package/dist/repair/loop-guard.js +217 -0
  477. package/dist/repair/scavenge.d.ts +19 -0
  478. package/dist/repair/scavenge.js +81 -0
  479. package/dist/repair/storm.d.ts +7 -0
  480. package/dist/repair/storm.js +7 -0
  481. package/dist/rollback/index.d.ts +5 -0
  482. package/dist/rollback/index.js +4 -0
  483. package/dist/rollback/rollback-tool.d.ts +13 -0
  484. package/dist/rollback/rollback-tool.js +167 -0
  485. package/dist/rollback/turn-recorder.d.ts +37 -0
  486. package/dist/rollback/turn-recorder.js +183 -0
  487. package/dist/rollback/turn-store.d.ts +29 -0
  488. package/dist/rollback/turn-store.js +114 -0
  489. package/dist/rollback/types.d.ts +51 -0
  490. package/dist/rollback/types.js +9 -0
  491. package/dist/runtime/config-center.d.ts +92 -0
  492. package/dist/runtime/config-center.js +467 -0
  493. package/dist/runtime/config-schema.d.ts +201 -0
  494. package/dist/runtime/config-schema.js +2 -0
  495. package/dist/runtime/defaults.d.ts +3 -0
  496. package/dist/runtime/defaults.js +146 -0
  497. package/dist/schedule/cron.d.ts +24 -0
  498. package/dist/schedule/cron.js +145 -0
  499. package/dist/schedule/index.d.ts +6 -0
  500. package/dist/schedule/index.js +4 -0
  501. package/dist/schedule/persistence.d.ts +33 -0
  502. package/dist/schedule/persistence.js +106 -0
  503. package/dist/schedule/scheduler.d.ts +85 -0
  504. package/dist/schedule/scheduler.js +630 -0
  505. package/dist/schedule/types.d.ts +185 -0
  506. package/dist/schedule/types.js +2 -0
  507. package/dist/setup/config.d.ts +189 -0
  508. package/dist/setup/config.js +253 -0
  509. package/dist/setup/index.d.ts +3 -0
  510. package/dist/setup/index.js +3 -0
  511. package/dist/setup/model-defaults.d.ts +13 -0
  512. package/dist/setup/model-defaults.js +87 -0
  513. package/dist/setup/persona-bootstrap.d.ts +42 -0
  514. package/dist/setup/persona-bootstrap.js +379 -0
  515. package/dist/setup/wizard.d.ts +32 -0
  516. package/dist/setup/wizard.js +384 -0
  517. package/dist/skills/index.d.ts +4 -0
  518. package/dist/skills/index.js +4 -0
  519. package/dist/skills/loader.d.ts +12 -0
  520. package/dist/skills/loader.js +83 -0
  521. package/dist/skills/registry.d.ts +2 -0
  522. package/dist/skills/registry.js +2 -0
  523. package/dist/skills/skill-tool.d.ts +20 -0
  524. package/dist/skills/skill-tool.js +49 -0
  525. package/dist/tools/archive.d.ts +17 -0
  526. package/dist/tools/archive.js +131 -0
  527. package/dist/tools/ask-user.d.ts +9 -0
  528. package/dist/tools/ask-user.js +62 -0
  529. package/dist/tools/background-registry.d.ts +45 -0
  530. package/dist/tools/background-registry.js +164 -0
  531. package/dist/tools/bash.d.ts +56 -0
  532. package/dist/tools/bash.js +391 -0
  533. package/dist/tools/bundle-registry.d.ts +42 -0
  534. package/dist/tools/bundle-registry.js +239 -0
  535. package/dist/tools/bundle-tools.d.ts +11 -0
  536. package/dist/tools/bundle-tools.js +168 -0
  537. package/dist/tools/channel-info.d.ts +5 -0
  538. package/dist/tools/channel-info.js +38 -0
  539. package/dist/tools/compression.d.ts +7 -0
  540. package/dist/tools/compression.js +21 -0
  541. package/dist/tools/config.d.ts +23 -0
  542. package/dist/tools/config.js +255 -0
  543. package/dist/tools/db-query.d.ts +12 -0
  544. package/dist/tools/db-query.js +107 -0
  545. package/dist/tools/diagnostics.d.ts +30 -0
  546. package/dist/tools/diagnostics.js +111 -0
  547. package/dist/tools/diff-channel.d.ts +9 -0
  548. package/dist/tools/diff-channel.js +17 -0
  549. package/dist/tools/diff-files.d.ts +17 -0
  550. package/dist/tools/diff-files.js +88 -0
  551. package/dist/tools/disk-usage.d.ts +34 -0
  552. package/dist/tools/disk-usage.js +258 -0
  553. package/dist/tools/edit.d.ts +30 -0
  554. package/dist/tools/edit.js +235 -0
  555. package/dist/tools/executor.d.ts +32 -0
  556. package/dist/tools/executor.js +66 -0
  557. package/dist/tools/file-tracker.d.ts +20 -0
  558. package/dist/tools/file-tracker.js +44 -0
  559. package/dist/tools/filtered-registry.d.ts +29 -0
  560. package/dist/tools/filtered-registry.js +50 -0
  561. package/dist/tools/flow.d.ts +10 -0
  562. package/dist/tools/flow.js +180 -0
  563. package/dist/tools/git-tool.d.ts +24 -0
  564. package/dist/tools/git-tool.js +113 -0
  565. package/dist/tools/glob.d.ts +29 -0
  566. package/dist/tools/glob.js +152 -0
  567. package/dist/tools/grep.d.ts +14 -0
  568. package/dist/tools/grep.js +325 -0
  569. package/dist/tools/http-request.d.ts +14 -0
  570. package/dist/tools/http-request.js +126 -0
  571. package/dist/tools/index.d.ts +43 -0
  572. package/dist/tools/index.js +76 -0
  573. package/dist/tools/injection-filter.d.ts +6 -0
  574. package/dist/tools/injection-filter.js +71 -0
  575. package/dist/tools/insert.d.ts +13 -0
  576. package/dist/tools/insert.js +61 -0
  577. package/dist/tools/interface.d.ts +30 -0
  578. package/dist/tools/interface.js +2 -0
  579. package/dist/tools/json-edit.d.ts +15 -0
  580. package/dist/tools/json-edit.js +122 -0
  581. package/dist/tools/multi-edit.d.ts +9 -0
  582. package/dist/tools/multi-edit.js +146 -0
  583. package/dist/tools/path-sandbox.d.ts +14 -0
  584. package/dist/tools/path-sandbox.js +60 -0
  585. package/dist/tools/process-tools.d.ts +15 -0
  586. package/dist/tools/process-tools.js +95 -0
  587. package/dist/tools/python-bridge/bridge.d.ts +24 -0
  588. package/dist/tools/python-bridge/bridge.js +39 -0
  589. package/dist/tools/python-bridge/executor.d.ts +6 -0
  590. package/dist/tools/python-bridge/executor.js +69 -0
  591. package/dist/tools/python-bridge/index.d.ts +5 -0
  592. package/dist/tools/python-bridge/index.js +4 -0
  593. package/dist/tools/python-bridge/parser.d.ts +21 -0
  594. package/dist/tools/python-bridge/parser.js +258 -0
  595. package/dist/tools/read.d.ts +16 -0
  596. package/dist/tools/read.js +276 -0
  597. package/dist/tools/registry.d.ts +2 -0
  598. package/dist/tools/registry.js +2 -0
  599. package/dist/tools/restart.d.ts +10 -0
  600. package/dist/tools/restart.js +46 -0
  601. package/dist/tools/result-buffer.d.ts +66 -0
  602. package/dist/tools/result-buffer.js +146 -0
  603. package/dist/tools/runtime-control.d.ts +163 -0
  604. package/dist/tools/runtime-control.js +1780 -0
  605. package/dist/tools/symbol-references.d.ts +5 -0
  606. package/dist/tools/symbol-references.js +331 -0
  607. package/dist/tools/system-info.d.ts +3 -0
  608. package/dist/tools/system-info.js +55 -0
  609. package/dist/tools/write.d.ts +18 -0
  610. package/dist/tools/write.js +118 -0
  611. package/dist/tools/xref/index.d.ts +25 -0
  612. package/dist/tools/xref/index.js +25 -0
  613. package/dist/tools/xref/manager.d.ts +85 -0
  614. package/dist/tools/xref/manager.js +948 -0
  615. package/dist/tools/xref/parser.d.ts +34 -0
  616. package/dist/tools/xref/parser.js +64 -0
  617. package/dist/tools/xref/regex-parser.d.ts +26 -0
  618. package/dist/tools/xref/regex-parser.js +446 -0
  619. package/dist/tools/xref/schema.d.ts +104 -0
  620. package/dist/tools/xref/schema.js +68 -0
  621. package/dist/tools/xref/ts-parser.d.ts +20 -0
  622. package/dist/tools/xref/ts-parser.js +403 -0
  623. package/dist/tools/xref/xref-build.d.ts +20 -0
  624. package/dist/tools/xref/xref-build.js +128 -0
  625. package/dist/tools/xref/xref-graph.d.ts +24 -0
  626. package/dist/tools/xref/xref-graph.js +88 -0
  627. package/dist/tools/xref/xref-query.d.ts +30 -0
  628. package/dist/tools/xref/xref-query.js +123 -0
  629. package/dist/types.d.ts +217 -0
  630. package/dist/types.js +2 -0
  631. package/dist/ui/assistant-message.d.ts +7 -0
  632. package/dist/ui/assistant-message.js +18 -0
  633. package/dist/ui/chat-log.d.ts +52 -0
  634. package/dist/ui/chat-log.js +246 -0
  635. package/dist/ui/command-registry.d.ts +73 -0
  636. package/dist/ui/command-registry.js +838 -0
  637. package/dist/ui/diff-component.d.ts +14 -0
  638. package/dist/ui/diff-component.js +42 -0
  639. package/dist/ui/hyperlink-markdown.d.ts +10 -0
  640. package/dist/ui/hyperlink-markdown.js +21 -0
  641. package/dist/ui/markdown-message.d.ts +10 -0
  642. package/dist/ui/markdown-message.js +16 -0
  643. package/dist/ui/osc8-hyperlinks.d.ts +4 -0
  644. package/dist/ui/osc8-hyperlinks.js +142 -0
  645. package/dist/ui/pi-tui-editor.d.ts +35 -0
  646. package/dist/ui/pi-tui-editor.js +79 -0
  647. package/dist/ui/slash-commands.d.ts +16 -0
  648. package/dist/ui/slash-commands.js +29 -0
  649. package/dist/ui/slash-panel.d.ts +54 -0
  650. package/dist/ui/slash-panel.js +199 -0
  651. package/dist/ui/theme.d.ts +120 -0
  652. package/dist/ui/theme.js +154 -0
  653. package/dist/ui/tool-display.d.ts +13 -0
  654. package/dist/ui/tool-display.js +85 -0
  655. package/dist/ui/tool-execution.d.ts +22 -0
  656. package/dist/ui/tool-execution.js +87 -0
  657. package/dist/ui/tui-formatters.d.ts +2 -0
  658. package/dist/ui/tui-formatters.js +145 -0
  659. package/dist/ui/user-message.d.ts +5 -0
  660. package/dist/ui/user-message.js +11 -0
  661. package/dist/update/check.d.ts +8 -0
  662. package/dist/update/check.js +28 -0
  663. package/dist/update/config.d.ts +6 -0
  664. package/dist/update/config.js +18 -0
  665. package/dist/update/download.d.ts +3 -0
  666. package/dist/update/download.js +27 -0
  667. package/dist/update/index.d.ts +6 -0
  668. package/dist/update/index.js +5 -0
  669. package/dist/update/install.d.ts +3 -0
  670. package/dist/update/install.js +33 -0
  671. package/dist/update/types.d.ts +16 -0
  672. package/dist/update/types.js +2 -0
  673. package/dist/utils/diff.d.ts +9 -0
  674. package/dist/utils/diff.js +45 -0
  675. package/dist/utils/misc.d.ts +12 -0
  676. package/dist/utils/misc.js +34 -0
  677. package/dist/world-engine/agent.d.ts +41 -0
  678. package/dist/world-engine/agent.js +385 -0
  679. package/dist/world-engine/index.d.ts +45 -0
  680. package/dist/world-engine/index.js +160 -0
  681. package/dist/world-engine/sim.d.ts +14 -0
  682. package/dist/world-engine/sim.js +120 -0
  683. package/dist/world-engine/store.d.ts +110 -0
  684. package/dist/world-engine/store.js +519 -0
  685. package/dist/world-engine/ticker.d.ts +37 -0
  686. package/dist/world-engine/ticker.js +214 -0
  687. package/dist/world-engine/tools.d.ts +6 -0
  688. package/dist/world-engine/tools.js +380 -0
  689. package/dist/world-engine/types.d.ts +202 -0
  690. package/dist/world-engine/types.js +56 -0
  691. package/docs/api.md +180 -0
  692. package/docs/architecture.md +206 -0
  693. package/docs/diagnostics/2026-06-08-config-prompt-guidance.md +67 -0
  694. package/docs/superpowers/plans/2026-06-08-global-bootstrap-mode.md +89 -0
  695. package/docs/superpowers/specs/2026-06-08-global-bootstrap-mode-design.md +174 -0
  696. package/docs/user-guide.md +226 -0
  697. package/package.json +63 -0
  698. package/plugins/example-greeter/index.js +55 -0
  699. package/plugins/example-greeter/plugin.json +8 -0
  700. package/pnpm-workspace.yaml +5 -0
  701. package/provider_arch.md +179 -0
  702. package/start-webui.sh +27 -0
  703. package/tsconfig.tsbuildinfo +1 -0
  704. package/webui-channel-design.md +789 -0
@@ -0,0 +1,566 @@
1
+ // ============================================================
2
+ // ClawbotChannel — 微信 ClawBot 渠道处理器
3
+ // ============================================================
4
+ //
5
+ // 实现 ChannelHandler 接口,通过 HTTP 长轮询收发微信 ClawBot 消息。
6
+ //
7
+ // 与飞书渠道的关键差异:
8
+ // - HTTP 长轮询(非 WebSocket)
9
+ // - 无 SDK,裸 HTTP JSON 调用
10
+ // - 单会话(无群聊/多用户/多 session)
11
+ // - context_token 机制(回复消息必须携带对上一条消息的 context_token)
12
+ // - get_updates_buf opaque blob 管理
13
+ // - 消息分片(2000 字符阈值)
14
+ // - 二维码授权(非 appId/appSecret)
15
+ //
16
+ // 生命周期:
17
+ // 1. register → 注册到 ChannelManager
18
+ // 2. start() → 授权 → 启动长轮询监听
19
+ // 3. 收到消息 → 过滤 state ≠ FINISH → 入队 → 构造 ChannelMessageEvent
20
+ // 4. handleMessage() → 创建/复用 loop → run → 收集回复 → 分片发送
21
+ // 5. stop() → 停止长轮询 → 清理资源
22
+ // ============================================================
23
+ import { resolveClawbotConfig, } from './clawbot-config.js';
24
+ import { ClawbotClient, ClawbotAPIError } from './clawbot-client.js';
25
+ import { ClawbotAuthManager } from './clawbot-auth.js';
26
+ import { ClawbotMessageQueue } from './clawbot-message-queue.js';
27
+ import { createCollectHandler } from './clawbot-session.js';
28
+ import { generateSessionId } from '../../../memory/session.js';
29
+ import fs from 'node:fs/promises';
30
+ import path from 'node:path';
31
+ function defaultLogger() {
32
+ return {
33
+ info: (msg) => process.stderr.write(`[clawbot] ${msg}\n`),
34
+ error: (msg) => process.stderr.write(`[clawbot] ${msg}\n`),
35
+ };
36
+ }
37
+ // ── ClawbotChannel ────────────────────────────────────────────
38
+ export class ClawbotChannel {
39
+ id = 'clawbot';
40
+ name = '微信 ClawBot';
41
+ description = '微信官方 AI 助手连接插件,支持 HTTP 长轮询收发消息';
42
+ pluginId = undefined;
43
+ status = 'registered';
44
+ config;
45
+ logger = defaultLogger();
46
+ // ── 核心依赖 ──────────────────────────────────────────────────
47
+ client = null;
48
+ auth = null;
49
+ messageQueue = new ClawbotMessageQueue();
50
+ agentFactory = null;
51
+ // ── 长轮询状态 ────────────────────────────────────────────────
52
+ polling = false;
53
+ pollAbortController = null;
54
+ /** getUpdates 的 opaque blob,首次空字符串,后续回传上次返回值 */
55
+ getUpdatesBuf = '';
56
+ // ── 会话状态 ──────────────────────────────────────────────────
57
+ /** 单会话信息(ClawBot 只有一个会话) */
58
+ sessionInfo = null;
59
+ /** sessionId → SessionInfo 映射(兼容多 session 接口) */
60
+ sessionMap = new Map();
61
+ // ── AgentLoop 引用 ───────────────────────────────────────────
62
+ loop = null;
63
+ collectHandler = null;
64
+ sessionId = null;
65
+ // ── typing 状态 ──────────────────────────────────────────────
66
+ typingTicket = '';
67
+ typingConfigFetched = false;
68
+ // ── TUI 同步 ─────────────────────────────────────────────────
69
+ onUserMessage = null;
70
+ onAgentReply = null;
71
+ // ── Session 持久化 ───────────────────────────────────────────
72
+ persistSessionFile = path.join(process.cwd(), '.agent', 'clawbot_session.json');
73
+ // ── 定时器 ───────────────────────────────────────────────────
74
+ /** 每日 token 过期检查定时器 */
75
+ dailyCheckTimer = null;
76
+ // ═══════════════════════════════════════════════════════════
77
+ // ChannelHandler 接口实现
78
+ // ═══════════════════════════════════════════════════════════
79
+ async start(config) {
80
+ this.status = 'starting';
81
+ this.config = resolveClawbotConfig(config);
82
+ // TUI 同步回调
83
+ this.onUserMessage = config.onUserMessage ?? null;
84
+ this.onAgentReply = config.onAgentReply ?? null;
85
+ const baseUrl = this.config.baseUrl;
86
+ // ── 授权回调(将二维码和中转状态输出到 TUI / 控制台) ──
87
+ const authCallbacks = {
88
+ onQRCode: (qrUrl, _qrcode) => {
89
+ this.logger.info(`QR Code URL: ${qrUrl}`);
90
+ if (this.onUserMessage) {
91
+ this.onUserMessage('ClawBot', `🔐 请扫描二维码授权登录微信 ClawBot:\n${qrUrl}`);
92
+ }
93
+ },
94
+ onStatusChange: (status) => {
95
+ this.logger.info(`Auth: ${status}`);
96
+ },
97
+ };
98
+ this.auth = new ClawbotAuthManager(baseUrl, this.config.httpTimeoutMs, authCallbacks);
99
+ // 尝试从缓存恢复 token
100
+ const restored = await this.auth.restoreFromCache();
101
+ if (restored) {
102
+ // 已有有效 token → 直接激活
103
+ await this.activateClient();
104
+ }
105
+ else if (this.config.botToken) {
106
+ // 配置中直接提供了 botToken
107
+ this.auth.setTokenDirect(this.config.botToken, this.config.botId, this.config.userId);
108
+ this.logger.info('Using botToken from config');
109
+ await this.activateClient();
110
+ }
111
+ else {
112
+ // 无 token → 不自动弹二维码,等待用户通过 /clawbot login 触发
113
+ this.logger.info('No botToken available — use /clawbot login to authorize');
114
+ this.status = 'active'; // 渠道已启动但未连接
115
+ }
116
+ }
117
+ /** 初始化/更新 HTTP 客户端并启动长轮询 */
118
+ async activateClient() {
119
+ if (!this.auth?.token)
120
+ return;
121
+ const baseUrl = this.config.baseUrl;
122
+ this.client = new ClawbotClient(baseUrl, this.auth.token, this.config.httpTimeoutMs);
123
+ this.config.botId = this.auth.botIdentifier;
124
+ this.config.userId = this.auth.userIdentifier;
125
+ // ── 注册到 channelLoop 注册表(供定时任务路由) ──
126
+ const registry = globalThis.__channelLoopRegistry;
127
+ if (registry) {
128
+ registry.set('clawbot', {
129
+ notifyTaskFired: async (name, sessionId) => {
130
+ await this.handleTaskNotification(name, sessionId);
131
+ },
132
+ sendProactiveMessage: async (sessionId, text) => {
133
+ await this.sendProactiveMessage(sessionId, text);
134
+ },
135
+ });
136
+ this.logger.info('registered in channelLoop registry for scheduled task routing');
137
+ }
138
+ // ── 预取 typing ticket ──
139
+ this.fetchTypingConfig().catch(() => { });
140
+ // ── 恢复持久化的 session 映射 ──
141
+ await this.restoreSession();
142
+ // ── 启动长轮询 ──
143
+ this.polling = true;
144
+ this.startPollingLoop();
145
+ // ── 每日 token 检查 ──
146
+ if (!this.dailyCheckTimer) {
147
+ this.dailyCheckTimer = setInterval(() => {
148
+ this.auth?.checkAndWarn();
149
+ }, 24 * 60 * 60 * 1000);
150
+ }
151
+ this.status = 'active';
152
+ this.logger.info(`ClawBot channel active (bot: ${this.auth.botIdentifier}, user: ${this.auth.userIdentifier})`);
153
+ }
154
+ /** 手动触发扫码授权流程(供 /clawbot login 命令调用) */
155
+ async triggerAuth() {
156
+ if (!this.auth) {
157
+ this.logger.error('triggerAuth: auth manager not initialized');
158
+ return false;
159
+ }
160
+ if (this.auth.hasValidToken && this.polling) {
161
+ this.logger.info('Already authorized and polling');
162
+ return true;
163
+ }
164
+ this.logger.info('Starting manual QR code authorization...');
165
+ const ok = await this.auth.startAuthorization();
166
+ if (ok) {
167
+ await this.activateClient();
168
+ }
169
+ else {
170
+ this.logger.error('Authorization failed or cancelled');
171
+ }
172
+ return ok;
173
+ }
174
+ /** 返回当前授权状态(供 /clawbot status 命令调用) */
175
+ getAuthStatus() {
176
+ return {
177
+ authorized: this.auth?.hasValidToken ?? false,
178
+ polling: this.polling,
179
+ remainingDays: this.auth?.remainingDays ?? 0,
180
+ botId: this.auth?.botIdentifier ?? this.config.botId ?? '',
181
+ userId: this.auth?.userIdentifier ?? this.config.userId ?? '',
182
+ };
183
+ }
184
+ // ── Session 持久化 ─────────────────────────────────────────────
185
+ async persistSession() {
186
+ try {
187
+ const data = {};
188
+ for (const [sid, info] of this.sessionMap) {
189
+ data[info.userId] = sid;
190
+ }
191
+ await fs.mkdir(path.dirname(this.persistSessionFile), { recursive: true });
192
+ await fs.writeFile(this.persistSessionFile, JSON.stringify(data), 'utf-8');
193
+ }
194
+ catch { /* 写入失败不阻塞 */ }
195
+ }
196
+ async restoreSession() {
197
+ try {
198
+ const raw = await fs.readFile(this.persistSessionFile, 'utf-8');
199
+ const data = JSON.parse(raw);
200
+ for (const [userId, sid] of Object.entries(data)) {
201
+ if (typeof sid === 'string') {
202
+ this.sessionMap.set(sid, { userId, contextToken: '' });
203
+ this.sessionId = sid;
204
+ }
205
+ }
206
+ if (this.sessionId) {
207
+ this.logger.info(`restored session: ${this.sessionId}`);
208
+ }
209
+ }
210
+ catch { /* 首次启动无文件,正常 */ }
211
+ }
212
+ /** ChannelHandler: 处理 TUI 子命令(/clawbot/login, /clawbot/status) */
213
+ async handleTuiCommand(cmdPath, _args) {
214
+ if (cmdPath === 'clawbot/login') {
215
+ const ok = await this.triggerAuth();
216
+ return ok ? '✅ ClawBot 授权成功,已开始监听消息'
217
+ : '❌ ClawBot 授权失败或已取消';
218
+ }
219
+ if (cmdPath === 'clawbot/status') {
220
+ const s = this.getAuthStatus();
221
+ return [
222
+ '── ClawBot ──',
223
+ `授权: ${s.authorized ? '✅ 已授权' : '⚠️ 未授权'}`,
224
+ `监听: ${s.polling ? '✅ 运行中' : '⏸ 已暂停'}`,
225
+ `Bot: ${s.botId || '-'} 用户: ${s.userId || '-'}`,
226
+ `Token: ${s.authorized ? s.remainingDays.toFixed(1) + ' 天' : '-'}`,
227
+ ].join('\n');
228
+ }
229
+ return null;
230
+ }
231
+ async stop() {
232
+ this.logger.info('stopping channel...');
233
+ this.polling = false;
234
+ this.pollAbortController?.abort();
235
+ this.pollAbortController = null;
236
+ if (this.dailyCheckTimer) {
237
+ clearInterval(this.dailyCheckTimer);
238
+ this.dailyCheckTimer = null;
239
+ }
240
+ this.messageQueue.clear();
241
+ this.sessionMap.clear();
242
+ this.loop = null;
243
+ this.collectHandler = null;
244
+ this.sessionId = null;
245
+ this.status = 'stopped';
246
+ this.logger.info('channel stopped');
247
+ }
248
+ onEvent(handler) {
249
+ // 初始化消息队列:processFn 调用 eventHandler(ChannelManager.onEvent 回调)
250
+ this.messageQueue.setProcessFn(async (event) => {
251
+ await handler(event);
252
+ });
253
+ }
254
+ async reply(sessionId, reply) {
255
+ if (!this.client) {
256
+ this.logger.error('reply failed: client not initialized');
257
+ return;
258
+ }
259
+ const session = this.sessionMap.get(sessionId);
260
+ if (!session) {
261
+ this.logger.error(`reply failed: session ${sessionId} not found`);
262
+ return;
263
+ }
264
+ const text = reply.content;
265
+ if (!text)
266
+ return;
267
+ try {
268
+ // 分片发送(微信 ClawBot 保守 2000 字符上限)
269
+ await this.client.sendMessageChunked(session.userId, session.contextToken, text, this.config.textChunkLimit ?? 2000);
270
+ }
271
+ catch (err) {
272
+ this.logger.error(`reply failed: ${err instanceof Error ? err.message : String(err)}`);
273
+ // 检测 token 过期
274
+ if (err instanceof ClawbotAPIError && err.isSessionTimeout) {
275
+ this.logger.info('bot_token expired during reply, triggering re-authorization...');
276
+ await this.handleTokenExpiry();
277
+ }
278
+ }
279
+ }
280
+ getStatus() {
281
+ return this.status;
282
+ }
283
+ // ── handleMessage ──────────────────────────────────────────────
284
+ async handleMessage(event, replyFn, agentFactory) {
285
+ this.agentFactory = agentFactory;
286
+ const userId = event.metadata?.userId ?? event.userId;
287
+ // TUI 同步
288
+ if (this.config.tuiSync && this.onUserMessage) {
289
+ const label = '微信';
290
+ this.onUserMessage(label, event.content);
291
+ }
292
+ try {
293
+ // 获取或创建 AgentLoop
294
+ if (!this.loop || !this.collectHandler) {
295
+ this.collectHandler = createCollectHandler();
296
+ this.sessionId = event.sessionId;
297
+ const { loop } = await agentFactory.createAgent({
298
+ outputHandler: this.collectHandler,
299
+ sessionId: event.sessionId,
300
+ channel: 'clawbot',
301
+ });
302
+ this.loop = loop;
303
+ }
304
+ this.collectHandler.reset();
305
+ if (event.images?.length)
306
+ this.loop.channelImages = event.images;
307
+ await this.loop.run(event.content);
308
+ const response = this.collectHandler.getResponse();
309
+ if (response) {
310
+ await replyFn({ content: response });
311
+ }
312
+ if (this.config.tuiSync && this.onAgentReply && response) {
313
+ this.onAgentReply(response);
314
+ }
315
+ }
316
+ catch (err) {
317
+ this.logger.error(`handleMessage error: ${String(err instanceof Error ? err.message : err)}`);
318
+ try {
319
+ await replyFn({ content: `处理出错: ${err instanceof Error ? err.message : String(err)}` });
320
+ }
321
+ catch { /* ignore */ }
322
+ }
323
+ }
324
+ // ── 长轮询 ────────────────────────────────────────────────────
325
+ /** 启动长轮询循环(while loop,非递归) */
326
+ startPollingLoop() {
327
+ // 异步启动,不阻塞 start()
328
+ this.runPollLoop().catch(err => {
329
+ this.logger.error(`poll loop fatal: ${err instanceof Error ? err.message : String(err)}`);
330
+ });
331
+ }
332
+ async runPollLoop() {
333
+ while (this.polling) {
334
+ if (!this.client) {
335
+ await this.sleep(1000);
336
+ continue;
337
+ }
338
+ try {
339
+ const result = await this.client.getUpdates(this.getUpdatesBuf);
340
+ // 保存 opaque blob
341
+ if (result.get_updates_buf) {
342
+ this.getUpdatesBuf = result.get_updates_buf;
343
+ }
344
+ // 处理消息
345
+ const msgs = result.msgs;
346
+ if (msgs && msgs.length > 0) {
347
+ for (const msg of msgs) {
348
+ await this.handleIncomingMessage(msg);
349
+ }
350
+ }
351
+ // 无消息时(超时返回空),立即发起下一次长轮询
352
+ }
353
+ catch (err) {
354
+ if (err instanceof ClawbotAPIError && err.isSessionTimeout) {
355
+ // token 过期 → 重新授权
356
+ this.logger.info('bot_token expired, re-authorizing...');
357
+ await this.handleTokenExpiry();
358
+ // 重授权成功后继续轮询
359
+ continue;
360
+ }
361
+ // 其他错误 → 等待后重试
362
+ this.logger.error(`poll error: ${err instanceof Error ? err.message : String(err)}`);
363
+ await this.sleep(this.config.pollRetryIntervalMs ?? 3000);
364
+ }
365
+ }
366
+ }
367
+ /** 处理长轮询收到的入站消息 */
368
+ async handleIncomingMessage(msg) {
369
+ // ── 过滤非 FINISH 状态的消息 ──
370
+ // GENERATING (1) = 模型还在生成,内容不完整;FINALIZED 由后续 FINISH 消息覆盖
371
+ // NEW (0) = 消息刚刚到达
372
+ if (msg.message_state !== 2) {
373
+ this.logger.info(`skipping message_state=${msg.message_state}`);
374
+ return;
375
+ }
376
+ // ── 过滤 BOT 自身的消息(message_type=2) ──
377
+ if (msg.message_type !== 1) {
378
+ return;
379
+ }
380
+ // ── 提取文本和图片 ──
381
+ let content = '';
382
+ const images = [];
383
+ for (const item of msg.item_list) {
384
+ switch (item.type) {
385
+ case 1: // TEXT
386
+ content += item.text_item?.text ?? '';
387
+ break;
388
+ case 2: // IMAGE
389
+ // 微信图片消息:尝试从 URL 下载(如果提供了 URL)
390
+ if (item.image_item?.url) {
391
+ try {
392
+ const imgResp = await fetch(item.image_item.url);
393
+ if (imgResp.ok) {
394
+ const buf = Buffer.from(await imgResp.arrayBuffer());
395
+ const contentType = imgResp.headers.get('content-type') || 'image/png';
396
+ images.push({ data: buf.toString('base64'), media_type: contentType });
397
+ }
398
+ }
399
+ catch {
400
+ this.logger.error('failed to download image from ClawBot message');
401
+ }
402
+ }
403
+ break;
404
+ // 语音/文件/视频暂不处理(后续可扩展)
405
+ default:
406
+ break;
407
+ }
408
+ }
409
+ if (!content && images.length === 0)
410
+ return;
411
+ // ── 更新会话信息 ──
412
+ const userId = msg.from_user_id;
413
+ const contextToken = msg.context_token;
414
+ this.sessionInfo = { userId, contextToken };
415
+ // 生成或复用 sessionId
416
+ let sessionId;
417
+ for (const [sid, info] of this.sessionMap) {
418
+ if (info.userId === userId) {
419
+ sessionId = sid;
420
+ // 更新 contextToken(始终使用最新一条的 token)
421
+ info.contextToken = contextToken;
422
+ break;
423
+ }
424
+ }
425
+ if (!sessionId) {
426
+ sessionId = generateSessionId('clawbot');
427
+ this.sessionMap.set(sessionId, { userId, contextToken });
428
+ this.persistSession().catch(() => { }); // 持久化新 session,重启后复用
429
+ }
430
+ this.sessionId = sessionId;
431
+ // ── 构造 ChannelMessageEvent ──
432
+ const channelEvent = {
433
+ type: 'message',
434
+ sessionId,
435
+ userId,
436
+ content,
437
+ channel: this.id,
438
+ images: images.length > 0 ? images : undefined,
439
+ metadata: {
440
+ userId,
441
+ // 使用 context_token 的前 12 位作为消息去重键
442
+ messageId: contextToken.slice(0, 24),
443
+ },
444
+ };
445
+ // 入队(立即返回,不阻塞轮询循环)
446
+ this.messageQueue.enqueue(sessionId, channelEvent);
447
+ }
448
+ // ── Token 过期处理 ────────────────────────────────────────────
449
+ async handleTokenExpiry() {
450
+ this.polling = false; // 暂停轮询
451
+ if (this.auth) {
452
+ const ok = await this.auth.refreshToken();
453
+ if (ok && this.auth.token) {
454
+ // 更新客户端的 token
455
+ this.client?.setBotToken(this.auth.token);
456
+ this.logger.info('re-authorization successful, resuming polling');
457
+ this.polling = true;
458
+ this.getUpdatesBuf = ''; // 重置 opaque blob(新 session)
459
+ this.startPollingLoop();
460
+ }
461
+ else {
462
+ this.status = 'error';
463
+ this.logger.error('re-authorization failed, channel stopped');
464
+ }
465
+ }
466
+ }
467
+ // ── 主动推送 ──────────────────────────────────────────────────
468
+ /**
469
+ * 主动推送消息(非回复模式)。
470
+ * ClawBot 是单会话,直接向最近活跃的用户发送。
471
+ */
472
+ async sendProactiveMessage(sessionId, text) {
473
+ if (!this.client) {
474
+ this.logger.error('sendProactiveMessage: client not initialized');
475
+ return;
476
+ }
477
+ const session = this.sessionMap.get(sessionId) ?? this.sessionInfo;
478
+ if (!session) {
479
+ this.logger.error('sendProactiveMessage: no session available');
480
+ return;
481
+ }
482
+ try {
483
+ await this.client.sendMessageChunked(session.userId, session.contextToken, text, this.config.textChunkLimit ?? 2000);
484
+ this.logger.info(`proactive message sent to ${sessionId.slice(0, 16)}...`);
485
+ }
486
+ catch (err) {
487
+ this.logger.error(`sendProactiveMessage failed: ${err instanceof Error ? err.message : String(err)}`);
488
+ }
489
+ }
490
+ /**
491
+ * 处理定时任务通知。
492
+ * 运行 Agent 并将结果主动推送到 ClawBot 会话。
493
+ */
494
+ async handleTaskNotification(taskName, sessionId) {
495
+ const effectiveSessionId = sessionId ?? this.sessionId;
496
+ if (!effectiveSessionId) {
497
+ this.logger.error('handleTaskNotification: no session available');
498
+ return;
499
+ }
500
+ const loop = this.loop;
501
+ if (!loop) {
502
+ this.logger.error('handleTaskNotification: no loop available — no message has been processed yet');
503
+ return;
504
+ }
505
+ const queued = await this.hasQueuedMessage(effectiveSessionId);
506
+ if (queued) {
507
+ this.logger.info(`handleTaskNotification: session ${effectiveSessionId.slice(0, 16)}... has queued messages, skipping task`);
508
+ return;
509
+ }
510
+ const prompt = `[Scheduled Task Triggered]\nYour scheduled task "${taskName}" has just been triggered via WeChat ClawBot. Execute it now and respond naturally. If this was a one-shot task, it has completed — no need to reschedule.`;
511
+ const texts = [];
512
+ const taskHandler = {
513
+ onTurnStart: () => { texts.length = 0; },
514
+ onText: (text) => { texts.push(text); },
515
+ onStatus: (msg, level) => { this.logger.info(`[clawbot-task] ${level}: ${msg}`); },
516
+ };
517
+ loop.setOutputHandler(taskHandler);
518
+ try {
519
+ await loop.run(prompt);
520
+ const response = texts.join('').trim();
521
+ if (response) {
522
+ await this.sendProactiveMessage(effectiveSessionId, response);
523
+ }
524
+ else {
525
+ this.logger.info(`handleTaskNotification: task "${taskName}" produced no text output`);
526
+ }
527
+ }
528
+ catch (err) {
529
+ this.logger.error(`handleTaskNotification error: ${String(err instanceof Error ? err.message : err)}`);
530
+ }
531
+ finally {
532
+ // 恢复原 handler
533
+ if (this.collectHandler) {
534
+ loop.setOutputHandler(this.collectHandler);
535
+ }
536
+ }
537
+ }
538
+ // ── typing 提示 ───────────────────────────────────────────────
539
+ /** 获取 typing_ticket(预取一次,缓存使用) */
540
+ async fetchTypingConfig() {
541
+ if (!this.client || this.typingConfigFetched)
542
+ return;
543
+ try {
544
+ const cfg = await this.client.getConfig();
545
+ if (cfg.typing_ticket) {
546
+ this.typingTicket = cfg.typing_ticket;
547
+ this.typingConfigFetched = true;
548
+ }
549
+ }
550
+ catch {
551
+ // 非关键,失败不影响功能
552
+ }
553
+ }
554
+ // ── 工具 ──────────────────────────────────────────────────────
555
+ async hasQueuedMessage(sessionId) {
556
+ return this.messageQueue.getQueueSize(sessionId) > 0;
557
+ }
558
+ sleep(ms) {
559
+ return new Promise(resolve => setTimeout(resolve, ms));
560
+ }
561
+ }
562
+ // ── 工厂函数 ─────────────────────────────────────────────────
563
+ export function createClawbotChannel() {
564
+ return new ClawbotChannel();
565
+ }
566
+ //# sourceMappingURL=clawbot-channel.js.map