dsh-chat-comprehension 0.2.0 → 0.3.1

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 (364) hide show
  1. package/NOTICE.md +20 -0
  2. package/README.md +20 -9
  3. package/client.js +41 -9
  4. package/lib/engines.mjs +136 -0
  5. package/lib/index.js +54 -4
  6. package/lib/qqbot-0.5.3-patches.json +75 -70
  7. package/lib/qqbot-patch.mjs +12 -7
  8. package/lib/video.mjs +11 -2
  9. package/package.json +7 -23
  10. package/vendor/dsh-agent-md/LICENSE +21 -0
  11. package/vendor/dsh-agent-md/cordis.patch.yml +8 -0
  12. package/vendor/dsh-agent-md/lib/index.js +775 -0
  13. package/vendor/dsh-agent-md/lib/persona.js +634 -0
  14. package/vendor/dsh-agent-md/lib/qq.js +527 -0
  15. package/vendor/dsh-agent-md/package.json +50 -0
  16. package/vendor/dsh-bili-scroll/LICENSE +21 -0
  17. package/vendor/dsh-bili-scroll/NOTICE.md +18 -0
  18. package/vendor/dsh-bili-scroll/cordis.patch.yml +20 -0
  19. package/vendor/dsh-bili-scroll/index.js +3293 -0
  20. package/vendor/dsh-bili-scroll/lib/asr.py +141 -0
  21. package/vendor/dsh-bili-scroll/lib/diagnose.mjs +95 -0
  22. package/vendor/dsh-bili-scroll/lib/dm.mjs +110 -0
  23. package/vendor/dsh-bili-scroll/lib/favops.py +90 -0
  24. package/vendor/dsh-bili-scroll/lib/hostdeps.mjs +148 -0
  25. package/vendor/dsh-bili-scroll/lib/login.mjs +141 -0
  26. package/vendor/dsh-bili-scroll/lib/mcp.mjs +144 -0
  27. package/vendor/dsh-bili-scroll/lib/state.mjs +236 -0
  28. package/vendor/dsh-bili-scroll/lib/uid.mjs +61 -0
  29. package/vendor/dsh-bili-scroll/lib/uvfetch.mjs +217 -0
  30. package/vendor/dsh-bili-scroll/lib/verify.mjs +184 -0
  31. package/vendor/dsh-bili-scroll/package.json +84 -0
  32. package/vendor/dsh-bili-scroll/profile-template/bili-duty/cordis.patch.yml +116 -0
  33. package/vendor/dsh-bili-scroll/profile-template/bili-duty/cordis.yml +4 -0
  34. package/vendor/dsh-bili-scroll/profile-template/bili-duty/package.json +13 -0
  35. package/vendor/dsh-bili-scroll/prompts/duty.md +296 -0
  36. package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/LICENSE +21 -0
  37. package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/README.md +176 -0
  38. package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/mcp_server.py +2015 -0
  39. package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/requirements.txt +10 -0
  40. package/vendor/dsh-meme/.dsh/skills/dsh-meme-maintenance/SKILL.md +50 -0
  41. package/vendor/dsh-meme/LICENSE +21 -0
  42. package/vendor/dsh-meme/anim.js +588 -0
  43. package/vendor/dsh-meme/cordis.patch.yml +13 -0
  44. package/vendor/dsh-meme/icon.jpg +0 -0
  45. package/vendor/dsh-meme/index.js +2616 -0
  46. package/vendor/dsh-meme/locale/en.json +6 -0
  47. package/vendor/dsh-meme/locale/zh.json +6 -0
  48. package/vendor/dsh-meme/memes/dafeiyu-001/index.db +0 -0
  49. package/vendor/dsh-meme/memes/dafeiyu-001/manifest.json +13 -0
  50. package/vendor/dsh-meme/memes/dafeiyu-001/memes/angry/shengqi.jpg +0 -0
  51. package/vendor/dsh-meme/memes/dafeiyu-001/memes/baka/xianqi.jpg +0 -0
  52. package/vendor/dsh-meme/memes/dafeiyu-001/memes/color/huachi.jpg +0 -0
  53. package/vendor/dsh-meme/memes/dafeiyu-001/memes/confused/jiazai.jpg +0 -0
  54. package/vendor/dsh-meme/memes/dafeiyu-001/memes/confused/wenhao.jpg +0 -0
  55. package/vendor/dsh-meme/memes/dafeiyu-001/memes/cpu/jiaban.jpg +0 -0
  56. package/vendor/dsh-meme/memes/dafeiyu-001/memes/daily/ganfan.jpg +0 -0
  57. package/vendor/dsh-meme/memes/dafeiyu-001/memes/fool/buyao.jpg +0 -0
  58. package/vendor/dsh-meme/memes/dafeiyu-001/memes/givemoney/yaoqian.jpg +0 -0
  59. package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/deyi.jpg +0 -0
  60. package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/ok.jpg +0 -0
  61. package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/piaole.jpg +0 -0
  62. package/vendor/dsh-meme/memes/dafeiyu-001/memes/like/bixin.jpg +0 -0
  63. package/vendor/dsh-meme/memes/dafeiyu-001/memes/meow/maozhua.jpg +0 -0
  64. package/vendor/dsh-meme/memes/dafeiyu-001/memes/morning/zaoshanghao.jpg +0 -0
  65. package/vendor/dsh-meme/memes/dafeiyu-001/memes/sad/qiurao.jpg +0 -0
  66. package/vendor/dsh-meme/memes/dafeiyu-001/memes/sad/yun.jpg +0 -0
  67. package/vendor/dsh-meme/memes/dafeiyu-001/memes/see/zhenjing.jpg +0 -0
  68. package/vendor/dsh-meme/memes/dafeiyu-001/memes/shy/haixiu.jpg +0 -0
  69. package/vendor/dsh-meme/memes/dafeiyu-001/memes/shy/toukan.jpg +0 -0
  70. package/vendor/dsh-meme/memes/dafeiyu-001/memes/sigh/wuyu.jpg +0 -0
  71. package/vendor/dsh-meme/memes/dafeiyu-001/memes/sleep/shuijiao.jpg +0 -0
  72. package/vendor/dsh-meme/memes/dafeiyu-001/memes/surprised/xia.jpg +0 -0
  73. package/vendor/dsh-meme/memes/dafeiyu-001/memes/work/tangping.jpg +0 -0
  74. package/vendor/dsh-meme/memes.js +998 -0
  75. package/vendor/dsh-meme/package.json +67 -0
  76. package/vendor/dsh-meme/panel.html +210 -0
  77. package/vendor/dsh-video-storyboard/LICENSE +21 -0
  78. package/vendor/dsh-video-storyboard/NOTICE +12 -0
  79. package/vendor/dsh-video-storyboard/bin/_args.mjs +16 -0
  80. package/vendor/dsh-video-storyboard/bin/asr-check.mjs +85 -0
  81. package/vendor/dsh-video-storyboard/bin/scan-stats.mjs +43 -0
  82. package/vendor/dsh-video-storyboard/bin/scan-video.mjs +38 -0
  83. package/vendor/dsh-video-storyboard/bin/storyboard.mjs +195 -0
  84. package/vendor/dsh-video-storyboard/cordis.patch.yml +3 -0
  85. package/vendor/dsh-video-storyboard/dsh.plugin.json +12 -0
  86. package/vendor/dsh-video-storyboard/package.json +88 -0
  87. package/vendor/dsh-video-storyboard/scripts/check-syntax.mjs +56 -0
  88. package/vendor/dsh-video-storyboard/scripts/install-dev.mjs +104 -0
  89. package/vendor/dsh-video-storyboard/src/flicker.js +104 -0
  90. package/vendor/dsh-video-storyboard/src/index.js +82 -0
  91. package/vendor/dsh-video-storyboard/src/ocr_bridge.py +103 -0
  92. package/vendor/dsh-video-storyboard/src/storyboard/asr-lifecycle.js +262 -0
  93. package/vendor/dsh-video-storyboard/src/storyboard/asr.js +488 -0
  94. package/vendor/dsh-video-storyboard/src/storyboard/audio.js +168 -0
  95. package/vendor/dsh-video-storyboard/src/storyboard/binaries.js +69 -0
  96. package/vendor/dsh-video-storyboard/src/storyboard/board.js +121 -0
  97. package/vendor/dsh-video-storyboard/src/storyboard/browser-time.js +504 -0
  98. package/vendor/dsh-video-storyboard/src/storyboard/cache.js +143 -0
  99. package/vendor/dsh-video-storyboard/src/storyboard/cells.js +70 -0
  100. package/vendor/dsh-video-storyboard/src/storyboard/density.js +545 -0
  101. package/vendor/dsh-video-storyboard/src/storyboard/direct-url.js +130 -0
  102. package/vendor/dsh-video-storyboard/src/storyboard/fetch.js +373 -0
  103. package/vendor/dsh-video-storyboard/src/storyboard/flash.js +180 -0
  104. package/vendor/dsh-video-storyboard/src/storyboard/format.js +573 -0
  105. package/vendor/dsh-video-storyboard/src/storyboard/frames.js +212 -0
  106. package/vendor/dsh-video-storyboard/src/storyboard/index.js +32 -0
  107. package/vendor/dsh-video-storyboard/src/storyboard/injection.js +76 -0
  108. package/vendor/dsh-video-storyboard/src/storyboard/layout-order.js +176 -0
  109. package/vendor/dsh-video-storyboard/src/storyboard/locate.js +113 -0
  110. package/vendor/dsh-video-storyboard/src/storyboard/media-store.js +106 -0
  111. package/vendor/dsh-video-storyboard/src/storyboard/memory.js +94 -0
  112. package/vendor/dsh-video-storyboard/src/storyboard/ocr-subs.js +107 -0
  113. package/vendor/dsh-video-storyboard/src/storyboard/ocr.js +167 -0
  114. package/vendor/dsh-video-storyboard/src/storyboard/pipeline.js +853 -0
  115. package/vendor/dsh-video-storyboard/src/storyboard/plan.js +400 -0
  116. package/vendor/dsh-video-storyboard/src/storyboard/probe.js +132 -0
  117. package/vendor/dsh-video-storyboard/src/storyboard/provenance.js +44 -0
  118. package/vendor/dsh-video-storyboard/src/storyboard/python.js +84 -0
  119. package/vendor/dsh-video-storyboard/src/storyboard/register.js +32 -0
  120. package/vendor/dsh-video-storyboard/src/storyboard/scan.js +486 -0
  121. package/vendor/dsh-video-storyboard/src/storyboard/segments.js +117 -0
  122. package/vendor/dsh-video-storyboard/src/storyboard/sheet.js +507 -0
  123. package/vendor/dsh-video-storyboard/src/storyboard/storage.js +93 -0
  124. package/vendor/dsh-video-storyboard/src/storyboard/subtitles.js +181 -0
  125. package/vendor/dsh-video-storyboard/src/storyboard/tool-spec.js +544 -0
  126. package/vendor/dsh-video-storyboard/src/storyboard/transcript-file.js +146 -0
  127. package/vendor/dsh-video-storyboard/src/storyboard/url.js +69 -0
  128. package/vendor/dsh-video-storyboard/src/storyboard/ytdlp.js +289 -0
  129. package/vendor/dsh-video-storyboard/src/tool-spec.js +17 -0
  130. package/vendor/dsh-video-storyboard/src/tools/locate.js +39 -0
  131. package/vendor/dsh-video-storyboard/src/tools/probe.js +23 -0
  132. package/vendor/dsh-video-storyboard/src/tools/shared.js +39 -0
  133. package/vendor/dsh-video-storyboard/src/tools/storyboard.js +20 -0
  134. package/vendor/dsh-video-storyboard/src/tools/zoom.js +56 -0
  135. package/vendor/dsh-world/LICENSE +21 -0
  136. package/vendor/dsh-world/assets/qq-card.png +0 -0
  137. package/vendor/dsh-world/cordis.patch.yml +6 -0
  138. package/vendor/dsh-world/lib/archive.d.ts +6 -0
  139. package/vendor/dsh-world/lib/archive.js +49 -0
  140. package/vendor/dsh-world/lib/archiveSelection.d.ts +8 -0
  141. package/vendor/dsh-world/lib/archiveSelection.js +20 -0
  142. package/vendor/dsh-world/lib/compaction.d.ts +124 -0
  143. package/vendor/dsh-world/lib/compaction.js +273 -0
  144. package/vendor/dsh-world/lib/compactionRegion.d.ts +42 -0
  145. package/vendor/dsh-world/lib/compactionRegion.js +210 -0
  146. package/vendor/dsh-world/lib/console/routes.d.ts +57 -0
  147. package/vendor/dsh-world/lib/console/routes.js +129 -0
  148. package/vendor/dsh-world/lib/console/snapshot.d.ts +39 -0
  149. package/vendor/dsh-world/lib/console/snapshot.js +51 -0
  150. package/vendor/dsh-world/lib/ecosystem/bridge/bridge.d.ts +36 -0
  151. package/vendor/dsh-world/lib/ecosystem/bridge/bridge.js +140 -0
  152. package/vendor/dsh-world/lib/ecosystem/bridge/route.d.ts +9 -0
  153. package/vendor/dsh-world/lib/ecosystem/bridge/route.js +46 -0
  154. package/vendor/dsh-world/lib/ecosystem/qq/bridge.d.ts +123 -0
  155. package/vendor/dsh-world/lib/ecosystem/qq/bridge.js +380 -0
  156. package/vendor/dsh-world/lib/ecosystem/qq/panel.d.ts +75 -0
  157. package/vendor/dsh-world/lib/ecosystem/qq/panel.js +187 -0
  158. package/vendor/dsh-world/lib/ecosystem/qq/route.d.ts +32 -0
  159. package/vendor/dsh-world/lib/ecosystem/qq/route.js +134 -0
  160. package/vendor/dsh-world/lib/ecosystem/qq/supervisor.d.ts +57 -0
  161. package/vendor/dsh-world/lib/ecosystem/qq/supervisor.js +188 -0
  162. package/vendor/dsh-world/lib/ecosystem/shared/context.d.ts +14 -0
  163. package/vendor/dsh-world/lib/ecosystem/shared/context.js +42 -0
  164. package/vendor/dsh-world/lib/ecosystem/shared/identity.d.ts +15 -0
  165. package/vendor/dsh-world/lib/ecosystem/shared/identity.js +36 -0
  166. package/vendor/dsh-world/lib/ecosystem/shared/outlets.d.ts +43 -0
  167. package/vendor/dsh-world/lib/ecosystem/shared/outlets.js +70 -0
  168. package/vendor/dsh-world/lib/ecosystem/shared/sessions.d.ts +16 -0
  169. package/vendor/dsh-world/lib/ecosystem/shared/sessions.js +52 -0
  170. package/vendor/dsh-world/lib/ecosystem/wechat/archive.d.ts +24 -0
  171. package/vendor/dsh-world/lib/ecosystem/wechat/archive.js +62 -0
  172. package/vendor/dsh-world/lib/ecosystem/wechat/home.d.ts +21 -0
  173. package/vendor/dsh-world/lib/ecosystem/wechat/home.js +111 -0
  174. package/vendor/dsh-world/lib/ecosystem/wechat/images.d.ts +5 -0
  175. package/vendor/dsh-world/lib/ecosystem/wechat/images.js +43 -0
  176. package/vendor/dsh-world/lib/ecosystem/wechat/index.d.ts +41 -0
  177. package/vendor/dsh-world/lib/ecosystem/wechat/index.js +166 -0
  178. package/vendor/dsh-world/lib/ecosystem/wechat/messages.d.ts +24 -0
  179. package/vendor/dsh-world/lib/ecosystem/wechat/messages.js +35 -0
  180. package/vendor/dsh-world/lib/ecosystem/wechat/sending.d.ts +30 -0
  181. package/vendor/dsh-world/lib/ecosystem/wechat/sending.js +216 -0
  182. package/vendor/dsh-world/lib/ecosystem/wechat/supervisor.d.ts +39 -0
  183. package/vendor/dsh-world/lib/ecosystem/wechat/supervisor.js +138 -0
  184. package/vendor/dsh-world/lib/faults.d.ts +10 -0
  185. package/vendor/dsh-world/lib/faults.js +13 -0
  186. package/vendor/dsh-world/lib/history.d.ts +16 -0
  187. package/vendor/dsh-world/lib/history.js +80 -0
  188. package/vendor/dsh-world/lib/hostContract.d.ts +19 -0
  189. package/vendor/dsh-world/lib/hostContract.js +1 -0
  190. package/vendor/dsh-world/lib/http.d.ts +18 -0
  191. package/vendor/dsh-world/lib/http.js +39 -0
  192. package/vendor/dsh-world/lib/index.d.ts +108 -0
  193. package/vendor/dsh-world/lib/index.js +356 -0
  194. package/vendor/dsh-world/lib/life/activity.d.ts +14 -0
  195. package/vendor/dsh-world/lib/life/activity.js +58 -0
  196. package/vendor/dsh-world/lib/life/alarm.d.ts +39 -0
  197. package/vendor/dsh-world/lib/life/alarm.js +132 -0
  198. package/vendor/dsh-world/lib/life/alarmTimer.d.ts +22 -0
  199. package/vendor/dsh-world/lib/life/alarmTimer.js +49 -0
  200. package/vendor/dsh-world/lib/life/diary.d.ts +4 -0
  201. package/vendor/dsh-world/lib/life/diary.js +9 -0
  202. package/vendor/dsh-world/lib/life/earlyStop.d.ts +19 -0
  203. package/vendor/dsh-world/lib/life/earlyStop.js +25 -0
  204. package/vendor/dsh-world/lib/life/home.d.ts +34 -0
  205. package/vendor/dsh-world/lib/life/home.js +91 -0
  206. package/vendor/dsh-world/lib/life/host.d.ts +22 -0
  207. package/vendor/dsh-world/lib/life/host.js +24 -0
  208. package/vendor/dsh-world/lib/life/journal.d.ts +20 -0
  209. package/vendor/dsh-world/lib/life/journal.js +59 -0
  210. package/vendor/dsh-world/lib/life/lifeStore.d.ts +16 -0
  211. package/vendor/dsh-world/lib/life/lifeStore.js +105 -0
  212. package/vendor/dsh-world/lib/life/messages.d.ts +17 -0
  213. package/vendor/dsh-world/lib/life/messages.js +53 -0
  214. package/vendor/dsh-world/lib/life/notify.d.ts +15 -0
  215. package/vendor/dsh-world/lib/life/notify.js +40 -0
  216. package/vendor/dsh-world/lib/life/pricing.d.ts +4 -0
  217. package/vendor/dsh-world/lib/life/pricing.js +30 -0
  218. package/vendor/dsh-world/lib/life/runtime.d.ts +52 -0
  219. package/vendor/dsh-world/lib/life/runtime.js +376 -0
  220. package/vendor/dsh-world/lib/life/toolRegistry.d.ts +22 -0
  221. package/vendor/dsh-world/lib/life/toolRegistry.js +64 -0
  222. package/vendor/dsh-world/lib/life/tools.d.ts +24 -0
  223. package/vendor/dsh-world/lib/life/tools.js +47 -0
  224. package/vendor/dsh-world/lib/life/types.d.ts +67 -0
  225. package/vendor/dsh-world/lib/life/types.js +1 -0
  226. package/vendor/dsh-world/lib/persona.d.ts +10 -0
  227. package/vendor/dsh-world/lib/persona.js +29 -0
  228. package/vendor/dsh-world/lib/promptSection.d.ts +30 -0
  229. package/vendor/dsh-world/lib/promptSection.js +81 -0
  230. package/vendor/dsh-world/lib/qqScope.d.ts +11 -0
  231. package/vendor/dsh-world/lib/qqScope.js +39 -0
  232. package/vendor/dsh-world/lib/runtime.d.ts +23 -0
  233. package/vendor/dsh-world/lib/runtime.js +206 -0
  234. package/vendor/dsh-world/lib/self.d.ts +10 -0
  235. package/vendor/dsh-world/lib/self.js +36 -0
  236. package/vendor/dsh-world/lib/sourceArchive.d.ts +28 -0
  237. package/vendor/dsh-world/lib/sourceArchive.js +156 -0
  238. package/vendor/dsh-world/lib/store.d.ts +30 -0
  239. package/vendor/dsh-world/lib/store.js +191 -0
  240. package/vendor/dsh-world/lib/timeContext.d.ts +3 -0
  241. package/vendor/dsh-world/lib/timeContext.js +13 -0
  242. package/vendor/dsh-world/lib/types.d.ts +118 -0
  243. package/vendor/dsh-world/lib/types.js +1 -0
  244. package/vendor/dsh-world/lib/worldPrompt.d.ts +47 -0
  245. package/vendor/dsh-world/lib/worldPrompt.js +49 -0
  246. package/vendor/dsh-world/lib/worldSwitch.d.ts +44 -0
  247. package/vendor/dsh-world/lib/worldSwitch.js +78 -0
  248. package/vendor/dsh-world/package-lock.json +1088 -0
  249. package/vendor/dsh-world/package.json +88 -0
  250. package/vendor/dsh-world/scripts/enable-tool-free-compaction.ps1 +33 -0
  251. package/vendor/dsh-world/src/archive.ts +45 -0
  252. package/vendor/dsh-world/src/archiveSelection.ts +27 -0
  253. package/vendor/dsh-world/src/compaction.ts +260 -0
  254. package/vendor/dsh-world/src/compactionRegion.ts +172 -0
  255. package/vendor/dsh-world/src/console/routes.ts +125 -0
  256. package/vendor/dsh-world/src/console/snapshot.ts +84 -0
  257. package/vendor/dsh-world/src/ecosystem/README.md +14 -0
  258. package/vendor/dsh-world/src/ecosystem/bridge/bridge.ts +121 -0
  259. package/vendor/dsh-world/src/ecosystem/bridge/route.ts +35 -0
  260. package/vendor/dsh-world/src/ecosystem/qq/bridge.ts +456 -0
  261. package/vendor/dsh-world/src/ecosystem/qq/panel.ts +178 -0
  262. package/vendor/dsh-world/src/ecosystem/qq/route.ts +130 -0
  263. package/vendor/dsh-world/src/ecosystem/qq/supervisor.ts +262 -0
  264. package/vendor/dsh-world/src/ecosystem/shared/context.ts +38 -0
  265. package/vendor/dsh-world/src/ecosystem/shared/identity.ts +42 -0
  266. package/vendor/dsh-world/src/ecosystem/shared/outlets.ts +75 -0
  267. package/vendor/dsh-world/src/ecosystem/shared/sessions.ts +47 -0
  268. package/vendor/dsh-world/src/ecosystem/wechat/archive.ts +66 -0
  269. package/vendor/dsh-world/src/ecosystem/wechat/home.ts +94 -0
  270. package/vendor/dsh-world/src/ecosystem/wechat/images.ts +38 -0
  271. package/vendor/dsh-world/src/ecosystem/wechat/index.ts +101 -0
  272. package/vendor/dsh-world/src/ecosystem/wechat/messages.ts +43 -0
  273. package/vendor/dsh-world/src/ecosystem/wechat/sending.ts +177 -0
  274. package/vendor/dsh-world/src/ecosystem/wechat/supervisor.ts +116 -0
  275. package/vendor/dsh-world/src/ecosystem/wechat/windows/README.md +117 -0
  276. package/vendor/dsh-world/src/ecosystem/wechat/windows/adapter.py +572 -0
  277. package/vendor/dsh-world/src/ecosystem/wechat/windows/binding.py +52 -0
  278. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/LICENSE +43 -0
  279. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/NOTICE.md +10 -0
  280. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/bridge.cpp +229 -0
  281. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/build.ps1 +19 -0
  282. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/profile.json +28 -0
  283. package/vendor/dsh-world/src/ecosystem/wechat/windows/groups.py +42 -0
  284. package/vendor/dsh-world/src/ecosystem/wechat/windows/incoming.py +157 -0
  285. package/vendor/dsh-world/src/ecosystem/wechat/windows/native.py +168 -0
  286. package/vendor/dsh-world/src/ecosystem/wechat/windows/outgoing.py +95 -0
  287. package/vendor/dsh-world/src/ecosystem/wechat/windows/requirements.txt +1 -0
  288. package/vendor/dsh-world/src/ecosystem/wechat/windows/sender.py +157 -0
  289. package/vendor/dsh-world/src/ecosystem/wechat/windows/snapshot.py +32 -0
  290. package/vendor/dsh-world/src/ecosystem/wechat/windows/stickers.py +60 -0
  291. package/vendor/dsh-world/src/ecosystem/wechat/windows/wechat.ps1 +75 -0
  292. package/vendor/dsh-world/src/faults.ts +12 -0
  293. package/vendor/dsh-world/src/history.ts +77 -0
  294. package/vendor/dsh-world/src/hostContract.ts +9 -0
  295. package/vendor/dsh-world/src/http.ts +34 -0
  296. package/vendor/dsh-world/src/index.ts +286 -0
  297. package/vendor/dsh-world/src/life/activity.ts +48 -0
  298. package/vendor/dsh-world/src/life/alarm.ts +119 -0
  299. package/vendor/dsh-world/src/life/alarmTimer.ts +45 -0
  300. package/vendor/dsh-world/src/life/diary.ts +10 -0
  301. package/vendor/dsh-world/src/life/earlyStop.ts +27 -0
  302. package/vendor/dsh-world/src/life/home.ts +85 -0
  303. package/vendor/dsh-world/src/life/host.ts +50 -0
  304. package/vendor/dsh-world/src/life/journal.ts +44 -0
  305. package/vendor/dsh-world/src/life/lifeStore.ts +70 -0
  306. package/vendor/dsh-world/src/life/messages.ts +44 -0
  307. package/vendor/dsh-world/src/life/notify.ts +47 -0
  308. package/vendor/dsh-world/src/life/pricing.ts +37 -0
  309. package/vendor/dsh-world/src/life/runtime.ts +318 -0
  310. package/vendor/dsh-world/src/life/toolRegistry.ts +48 -0
  311. package/vendor/dsh-world/src/life/tools.ts +61 -0
  312. package/vendor/dsh-world/src/life/types.ts +19 -0
  313. package/vendor/dsh-world/src/persona.ts +26 -0
  314. package/vendor/dsh-world/src/promptSection.ts +71 -0
  315. package/vendor/dsh-world/src/qqScope.ts +51 -0
  316. package/vendor/dsh-world/src/runtime.ts +172 -0
  317. package/vendor/dsh-world/src/self.ts +32 -0
  318. package/vendor/dsh-world/src/sourceArchive.ts +132 -0
  319. package/vendor/dsh-world/src/store.ts +170 -0
  320. package/vendor/dsh-world/src/timeContext.ts +13 -0
  321. package/vendor/dsh-world/src/types.ts +112 -0
  322. package/vendor/dsh-world/src/worldPrompt.ts +64 -0
  323. package/vendor/dsh-world/src/worldSwitch.ts +82 -0
  324. package/vendor/dsh-world/templates/alarm.md +49 -0
  325. package/vendor/dsh-world/templates/world-prompt.md +7 -0
  326. package/vendor/dsh-world/tests/archive.test.ts +57 -0
  327. package/vendor/dsh-world/tests/archiveScope.test.ts +86 -0
  328. package/vendor/dsh-world/tests/bridge.test.ts +211 -0
  329. package/vendor/dsh-world/tests/channelSessions.test.ts +79 -0
  330. package/vendor/dsh-world/tests/clientHooks.test.ts +103 -0
  331. package/vendor/dsh-world/tests/compaction.test.ts +141 -0
  332. package/vendor/dsh-world/tests/console.test.ts +202 -0
  333. package/vendor/dsh-world/tests/consoleClient.test.ts +101 -0
  334. package/vendor/dsh-world/tests/enableCompaction.test.ts +19 -0
  335. package/vendor/dsh-world/tests/fixtures.ts +6 -0
  336. package/vendor/dsh-world/tests/history.test.ts +100 -0
  337. package/vendor/dsh-world/tests/hostFixture.ts +46 -0
  338. package/vendor/dsh-world/tests/lifeActivity.test.ts +70 -0
  339. package/vendor/dsh-world/tests/lifeAlarm.test.ts +87 -0
  340. package/vendor/dsh-world/tests/lifeDiary.test.ts +33 -0
  341. package/vendor/dsh-world/tests/lifeMessages.test.ts +61 -0
  342. package/vendor/dsh-world/tests/lifeNotify.test.ts +46 -0
  343. package/vendor/dsh-world/tests/lifeParts.test.ts +45 -0
  344. package/vendor/dsh-world/tests/lifeRuntime.test.ts +660 -0
  345. package/vendor/dsh-world/tests/lifeStore.test.ts +90 -0
  346. package/vendor/dsh-world/tests/lifeTools.test.ts +53 -0
  347. package/vendor/dsh-world/tests/outlets.test.ts +85 -0
  348. package/vendor/dsh-world/tests/panel.test.ts +85 -0
  349. package/vendor/dsh-world/tests/plugin.test.ts +614 -0
  350. package/vendor/dsh-world/tests/pricing.test.ts +21 -0
  351. package/vendor/dsh-world/tests/qq.test.ts +121 -0
  352. package/vendor/dsh-world/tests/qqSessionMode.test.ts +97 -0
  353. package/vendor/dsh-world/tests/qqSupervisor.test.ts +149 -0
  354. package/vendor/dsh-world/tests/sourceArchive.test.ts +58 -0
  355. package/vendor/dsh-world/tests/store.test.ts +82 -0
  356. package/vendor/dsh-world/tests/storeWriter.ts +5 -0
  357. package/vendor/dsh-world/tests/timeContext.test.ts +15 -0
  358. package/vendor/dsh-world/tests/wechat.test.ts +254 -0
  359. package/vendor/dsh-world/tests/wechatImages.test.ts +130 -0
  360. package/vendor/dsh-world/tests/wechatSending.test.ts +142 -0
  361. package/vendor/dsh-world/tests/wechatSupervisor.test.ts +91 -0
  362. package/vendor/dsh-world/tests/worldPrompt.test.ts +201 -0
  363. package/vendor/dsh-world/tsconfig.build.json +5 -0
  364. package/vendor/dsh-world/tsconfig.json +8 -0
@@ -0,0 +1,572 @@
1
+ """Windows adapter for the independent dsh-world WeChat module."""
2
+ import argparse
3
+ from contextlib import contextmanager
4
+ import json
5
+ import sqlite3
6
+ import sys
7
+ import time
8
+ from concurrent.futures import Future
9
+ from threading import Thread
10
+ from datetime import datetime, timezone
11
+ from pathlib import Path
12
+ from urllib.parse import urlparse
13
+ from urllib.request import Request, urlopen
14
+ from outgoing import deliverMessages, prepareMessages
15
+ from snapshot import SnapshotBusy
16
+ from groups import MAX_CONTEXT_MESSAGES, mentionedIds, recentContext
17
+ from incoming import ImageUnavailable
18
+ from binding import WechatOffline
19
+
20
+ IMAGE_BUFFER_SECONDS = 3
21
+ # Exit code for "a person must check WeChat and run acknowledge"; the plugin stops restarting the adapter on it.
22
+ EXIT_NEEDS_HUMAN = 2
23
+
24
+
25
+ class NeedsHuman(RuntimeError):
26
+ pass
27
+ IMAGE_BUFFER_POLL_SECONDS = 0.1
28
+ MAX_PRIVATE_IMAGES = 2
29
+
30
+
31
+ @contextmanager
32
+ def exclusiveRun(directory):
33
+ import msvcrt
34
+ stream = (directory / 'runtime.lock').open('a+b')
35
+ try:
36
+ if stream.tell() == 0:
37
+ stream.write(b'0')
38
+ stream.flush()
39
+ stream.seek(0)
40
+ try:
41
+ msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
42
+ except OSError as error:
43
+ raise RuntimeError('此账号已有微信适配器在运行,不能同时操作') from error
44
+ try:
45
+ yield
46
+ finally:
47
+ stream.seek(0)
48
+ msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
49
+ finally:
50
+ stream.close()
51
+
52
+
53
+ def validateConfig(config, requireChats=True):
54
+ for name in ('account', 'selfId', 'dbDir', 'moduleFile'):
55
+ if not isinstance(config.get(name), str) or not config[name].strip():
56
+ raise ValueError(f'请先配置 {name}')
57
+ if any(c in config['account'] for c in '/\\:') or config['account'] in ('.', '..'):
58
+ raise ValueError('account 必须是明确的账号目录名')
59
+ if 'processId' in config and (type(config['processId']) is not int or config['processId'] <= 0):
60
+ raise ValueError('旧 processId 配置必须为正整数;可删除此字段,由绑定账号自动识别进程')
61
+ chats = config.get('chats')
62
+ if not isinstance(chats, list) or (requireChats and not chats):
63
+ raise ValueError('请显式选择至少一个聊天')
64
+ if any(not isinstance(chat, dict) or not chat.get('id') or not chat.get('name') for chat in chats):
65
+ raise ValueError('聊天需要稳定 id 和明确 name')
66
+ if len({chat['id'] for chat in chats}) != len(chats):
67
+ raise ValueError('聊天 id 不能重复')
68
+ if any(chat['id'].endswith('@chatroom') and chat.get('trigger') != 'mention' for chat in chats):
69
+ raise ValueError('群聊需要显式配置 trigger: mention')
70
+ if not 1 <= config.get('pageSize', 50) <= 100:
71
+ raise ValueError('pageSize 应在 1–100 之间')
72
+ if not 0.5 <= config.get('pollSeconds', 2) <= 60:
73
+ raise ValueError('pollSeconds 应在 0.5–60 之间')
74
+ if 'stickerDir' in config and (not isinstance(config['stickerDir'], str) or not Path(config['stickerDir']).is_absolute()):
75
+ raise ValueError('stickerDir 需要绝对目录')
76
+ if 'mediaRoots' in config and (not isinstance(config['mediaRoots'], list) or any(not isinstance(root, str) or not Path(root).is_absolute() for root in config['mediaRoots'])):
77
+ raise ValueError('mediaRoots 需要绝对目录数组')
78
+ return config
79
+
80
+
81
+ def messageKey(row):
82
+ if not row.get('shard'):
83
+ raise ValueError('消息分片标识为空,停止而不猜测消息 ID')
84
+ return f"{row['shard']}:{row['local_id']}"
85
+
86
+
87
+ def newMessages(database, chatId, sinceSeq, pageSize):
88
+ found = {}
89
+ offset = 0
90
+ while True:
91
+ page = database.get_messages(chatId, limit=pageSize, offset=offset)
92
+ for row in page:
93
+ if int(row['sort_seq']) >= sinceSeq:
94
+ found[messageKey(row)] = row
95
+ if len(page) < pageSize or any(int(row['sort_seq']) < sinceSeq for row in page):
96
+ break
97
+ offset += len(page)
98
+ return sorted(found.values(), key=lambda row: (int(row['sort_seq']), row['shard'], int(row['local_id'])))
99
+
100
+
101
+ def bufferImageMessages(config, database, store, chat, first, *, clock=time.monotonic, sleep=time.sleep):
102
+ deadline = clock() + config.get('bufferSeconds', IMAGE_BUFFER_SECONDS)
103
+ order = lambda row: (int(row['sort_seq']), row['shard'], int(row['local_id']))
104
+ batch = [first]
105
+ while True:
106
+ if clock() >= deadline: return batch
107
+ candidates = newMessages(database, chat['id'], int(first['sort_seq']), config.get('pageSize', 50))
108
+ if clock() > deadline: return batch
109
+ batch = [first]
110
+ images = 1
111
+ for row in candidates:
112
+ if order(row) <= order(first) or store.seen(chat['id'], messageKey(row)):
113
+ continue
114
+ if row.get('sender_username') != first.get('sender_username') or row['type'] not in ('文本', '图片'):
115
+ return batch
116
+ if row['type'] == '图片':
117
+ if images == MAX_PRIVATE_IMAGES: return batch
118
+ images += 1
119
+ batch.append(row)
120
+ else:
121
+ if str(row['content']).strip() and len(str(row['content'])) <= 2000: batch.append(row)
122
+ return batch
123
+ remaining = deadline - clock()
124
+ if remaining <= 0: return batch
125
+ sleep(min(IMAGE_BUFFER_POLL_SECONDS, remaining))
126
+
127
+
128
+ def normalizeMessage(row, chatId, selfId, people=None, *, includeSelf=False, conversationName=None):
129
+ if row['type'] != '文本':
130
+ return None
131
+ sender = row.get('sender_username')
132
+ if not sender:
133
+ raise ValueError(f'消息 {messageKey(row)} 的发送者未解析,停止处理而不猜测身份')
134
+ if sender == selfId and not includeSelf:
135
+ return None
136
+ text = str(row['content'])
137
+ if chatId.endswith('@chatroom') and text.startswith(sender + ':\n'):
138
+ text = text[len(sender) + 2:]
139
+ if not text.strip():
140
+ return None
141
+ if len(text) > 2000:
142
+ raise ValueError('消息超过当前模块 2000 字限制,请分开发送')
143
+ identity = dict(channel='wechat', accountId=selfId, conversationType='group' if chatId.endswith('@chatroom') else 'private', conversationId=chatId, speakerId='wechat:' + sender)
144
+ identity['platformMessageId'] = messageKey(row)
145
+ if conversationName:
146
+ identity['conversationName'] = conversationName
147
+ if (people or {}).get(sender):
148
+ identity['speakerName'] = people[sender]
149
+ return dict(text=text, identity=identity)
150
+
151
+
152
+ def incomingMessage(database, chat, row, config):
153
+ if not chat['id'].endswith('@chatroom'):
154
+ if row['type'] == '图片':
155
+ message = normalizeMessage({**row, 'type': '文本', 'content': '【微信图片】'}, chat['id'], config['selfId'], config.get('people'), conversationName=chat.get('name'))
156
+ if message is None: return None
157
+ entry = dict(**message, id=messageKey(row), occurredAt=datetime.fromtimestamp(int(row['create_time']), timezone.utc).isoformat())
158
+ try: entry['image'] = database.readImage(chat['id'], row)
159
+ except ImageUnavailable as error: entry['text'] = f'【图片未读取:{error}】'
160
+ return dict(text='', identity=message['identity'], media=[entry])
161
+ if row['type'] == '动画表情' and row.get('sender_username') != config['selfId']:
162
+ message = normalizeMessage({**row, 'type': '文本', 'content': '【微信表情包】'}, chat['id'], config['selfId'], config.get('people'), conversationName=chat.get('name'))
163
+ if message is None: return None
164
+ entry = dict(**message, id=messageKey(row), occurredAt=datetime.fromtimestamp(int(row['create_time']), timezone.utc).isoformat())
165
+ try: entry['image'] = database.readSticker(chat['id'], row)
166
+ except ImageUnavailable as error: entry['text'] = f'【微信表情包,未读取:{error}】'
167
+ return dict(text='', identity=message['identity'], media=[entry])
168
+ return normalizeMessage(row, chat['id'], config['selfId'], config.get('people'), conversationName=chat.get('name'))
169
+ if row['type'] != '文本' or row.get('sender_username') == config['selfId']:
170
+ return None
171
+ raw = database.get_message_row(chat['id'], row['local_id'], shard=row['shard'])
172
+ if raw is None:
173
+ raise RuntimeError('群消息原始来源无法读取,停止且不推进位置')
174
+ mentions = mentionedIds(raw['source'])
175
+ if config['selfId'] not in mentions:
176
+ return None
177
+ people = {**config.get('people', {})}
178
+ def normalize(row, includeSelf=False):
179
+ sender = row.get('sender_username')
180
+ if sender and sender not in people:
181
+ people[sender] = database.get_nickname(sender)
182
+ return normalizeMessage(row, chat['id'], config['selfId'], people, includeSelf=includeSelf, conversationName=chat['name'])
183
+ message = normalize(row)
184
+ if not message:
185
+ return None
186
+ message['identity']['mentionIds'] = ['wechat:' + wxid for wxid in mentions]
187
+ def contextMessage(previous):
188
+ if previous['type'] not in ('文本', '图片') or (previous['type'] == '文本' and len(str(previous['content'])) > 2000):
189
+ return None
190
+ normalized = normalize({**previous, 'type': '文本', 'content': '【群图片】'} if previous['type'] == '图片' else previous, includeSelf=True)
191
+ if not normalized: return None
192
+ entry = dict(**normalized, id=messageKey(previous), occurredAt=datetime.fromtimestamp(int(previous['create_time']), timezone.utc).isoformat())
193
+ if previous['type'] == '图片':
194
+ entry['imageRow'] = {key: previous[key] for key in ('local_id','shard','sort_seq','create_time','type','sender_username')}
195
+ return entry
196
+ message['context'] = recentContext(database, chat['id'], row, contextMessage, config.get('pageSize', 50), config.get('contextMessages', MAX_CONTEXT_MESSAGES))
197
+ imageCount = 0
198
+ for entry in reversed(message['context']):
199
+ picture = entry.pop('imageRow', None)
200
+ if picture is None: continue
201
+ imageCount += 1
202
+ if imageCount > 2:
203
+ entry['text'] = '【较早图片,本轮只附最近两张】'
204
+ continue
205
+ try:
206
+ entry['image'] = database.readImage(chat['id'], picture)
207
+ except ImageUnavailable as error:
208
+ entry['text'] = f'【图片未读取:{error}】'
209
+ return message
210
+
211
+
212
+ class MessageStore:
213
+ def __init__(self, path):
214
+ self.db = sqlite3.connect(path)
215
+ self.db.executescript('''
216
+ CREATE TABLE IF NOT EXISTS cursors(chatId TEXT PRIMARY KEY, seq INTEGER NOT NULL);
217
+ CREATE TABLE IF NOT EXISTS messages(chatId TEXT, messageId TEXT, seq INTEGER NOT NULL,
218
+ status TEXT NOT NULL, PRIMARY KEY(chatId,messageId));
219
+ CREATE TABLE IF NOT EXISTS receipts(replyId TEXT PRIMARY KEY, total INTEGER NOT NULL,
220
+ confirmed INTEGER NOT NULL, status TEXT NOT NULL, posted INTEGER NOT NULL);
221
+ ''')
222
+
223
+ def cursor(self, chatId):
224
+ row = self.db.execute('SELECT seq FROM cursors WHERE chatId=?', (chatId,)).fetchone()
225
+ return row[0] if row else None
226
+
227
+ def baseline(self, chatId, seq, rows=()):
228
+ with self.db:
229
+ self.db.execute('INSERT OR IGNORE INTO cursors VALUES (?,?)', (chatId, seq))
230
+ self.db.executemany('INSERT OR IGNORE INTO messages VALUES (?,?,?,?)',
231
+ [(chatId, messageKey(row), seq, 'done') for row in rows])
232
+
233
+ def seen(self, chatId, key):
234
+ return self.db.execute('SELECT 1 FROM messages WHERE chatId=? AND messageId=? LIMIT 1', (chatId, key)).fetchone() is not None
235
+
236
+ def begin(self, chatId, key, seq):
237
+ with self.db:
238
+ self.db.execute('INSERT INTO messages VALUES (?,?,?,?)', (chatId, key, seq, 'pending'))
239
+
240
+ def finish(self, chatId, key, seq):
241
+ with self.db:
242
+ self.db.execute('UPDATE messages SET status=? WHERE chatId=? AND messageId=?', ('done', chatId, key))
243
+ self.db.execute('UPDATE cursors SET seq=MAX(seq,?) WHERE chatId=?', (seq, chatId))
244
+
245
+ def beginBatch(self, chatId, rows):
246
+ with self.db:
247
+ self.db.executemany("INSERT INTO messages VALUES (?,?,?,'pending')", [(chatId, messageKey(row), int(row['sort_seq'])) for row in rows])
248
+
249
+ def finishBatch(self, chatId, rows):
250
+ with self.db:
251
+ result = self.db.executemany("UPDATE messages SET status='done' WHERE chatId=? AND messageId=? AND status='pending'", [(chatId, messageKey(row)) for row in rows])
252
+ if result.rowcount != len(rows): raise RuntimeError('接收批次状态不一致,停止且不推进位置')
253
+ self.db.execute('UPDATE cursors SET seq=MAX(seq,?) WHERE chatId=?', (max(int(row['sort_seq']) for row in rows), chatId))
254
+
255
+ def checkPending(self, activeIncoming=None):
256
+ excluded, parameters = '', ()
257
+ if activeIncoming:
258
+ chatId, keys = activeIncoming
259
+ keys = [keys] if isinstance(keys, str) else keys
260
+ if not keys: raise ValueError('活动接收批次不能为空')
261
+ excluded = ' AND NOT(chatId=? AND messageId IN (' + ','.join('?' for _ in keys) + '))'
262
+ parameters = (chatId, *keys)
263
+ row = self.db.execute("SELECT chatId,messageId FROM messages WHERE status='pending'" + excluded + ' ORDER BY rowid LIMIT 1', parameters).fetchone()
264
+ if row:
265
+ raise NeedsHuman(f'上次消息结果尚未确认:{row[0]} / {row[1]}。核对家和微信后使用 acknowledge,不自动重发。')
266
+
267
+ def acknowledge(self, chatId, key):
268
+ row = self.db.execute("SELECT seq FROM messages WHERE chatId=? AND messageId=? AND status='pending' LIMIT 1", (chatId, key)).fetchone()
269
+ if not row:
270
+ raise ValueError('没有这条待核对消息')
271
+ self.finish(chatId, key, row[0])
272
+
273
+ def close(self):
274
+ self.db.close()
275
+
276
+ def beginReply(self, replyId, total, chatId=None, seq=None):
277
+ if not isinstance(replyId, str) or len(replyId) != 64 or any(c not in '0123456789abcdef' for c in replyId) or not 1 <= total <= 16:
278
+ raise ValueError('回复缺少有效归档 ID 或消息数量,停止发送')
279
+ with self.db:
280
+ if chatId is not None:
281
+ self.db.execute('INSERT INTO messages VALUES (?,?,?,?)', (chatId, 'outgoing:' + replyId, seq, 'pending'))
282
+ self.db.execute('INSERT INTO receipts VALUES (?,?,0,?,0)', (replyId, total, 'uncertain'))
283
+
284
+ def reply(self, replyId):
285
+ row = self.db.execute('SELECT confirmed,status FROM receipts WHERE replyId=? LIMIT 1', (replyId,)).fetchone()
286
+ return dict(id=replyId, confirmed=row[0], status=row[1]) if row else None
287
+
288
+ def confirmReply(self, replyId, confirmed):
289
+ with self.db:
290
+ result = self.db.execute('UPDATE receipts SET confirmed=?, status=CASE WHEN total=? THEN ? ELSE ? END, posted=0 '
291
+ 'WHERE replyId=? AND confirmed<? AND total>=?',
292
+ (confirmed, confirmed, 'sent', 'uncertain', replyId, confirmed, confirmed))
293
+ if result.rowcount != 1:
294
+ raise ValueError('回执进度无效')
295
+
296
+ def failReply(self, replyId):
297
+ with self.db:
298
+ self.db.execute("UPDATE receipts SET status='failed', posted=0 WHERE replyId=? AND confirmed=0", (replyId,))
299
+
300
+ def pendingReceipts(self, afterId='', limit=50):
301
+ return [dict(id=row[0], confirmed=row[1], status=row[2]) for row in self.db.execute(
302
+ 'SELECT replyId,confirmed,status FROM receipts WHERE posted=0 AND replyId>? ORDER BY replyId LIMIT ?', (afterId, limit))]
303
+
304
+ def receiptPosted(self, receipt):
305
+ with self.db:
306
+ self.db.execute('UPDATE receipts SET posted=1 WHERE replyId=? AND confirmed=? AND status=?',
307
+ (receipt['id'], receipt['confirmed'], receipt['status']))
308
+
309
+
310
+ def postHome(moduleFile, message):
311
+ connection = json.loads(Path(moduleFile).read_text(encoding='utf-8-sig'))
312
+ if message.get('media') and connection.get('protocol', 0) < 3:
313
+ raise RuntimeError('私聊图片需要新版宿主协议,请更新并重载 DSH 的 dsh-world 插件')
314
+ origin = urlparse(connection['origin'])
315
+ if origin.scheme != 'http' or origin.hostname not in ('127.0.0.1', 'localhost', '::1') or connection.get('path') != '/dsh-world/wechat/ask':
316
+ raise ValueError('微信模块地址必须是本机 DSH 的独立接口')
317
+ request = Request(connection['origin'].rstrip('/') + connection['path'],
318
+ data=json.dumps(message, ensure_ascii=False).encode(),
319
+ headers={'Content-Type': 'application/json', 'x-dsh-world-token': connection['token']}, method='POST')
320
+ with urlopen(request, timeout=190) as response:
321
+ result = json.load(response)
322
+ if result.get('accepted') is not True:
323
+ raise RuntimeError('DSH 没有确认请求')
324
+ return result
325
+
326
+
327
+ def askHome(moduleFile, message):
328
+ result = postHome(moduleFile, message)
329
+ if not isinstance(result.get('text'), str):
330
+ raise RuntimeError('DSH 没有返回明确的微信回复')
331
+ return result
332
+
333
+
334
+ def reportReceipt(moduleFile, receipt):
335
+ postHome(moduleFile, dict(receipt=receipt))
336
+
337
+
338
+ def flushReceipts(moduleFile, store, report=reportReceipt):
339
+ afterId = ''
340
+ while True:
341
+ receipts = store.pendingReceipts(afterId)
342
+ if not receipts:
343
+ return
344
+ for receipt in receipts:
345
+ report(moduleFile, receipt)
346
+ store.receiptPosted(receipt)
347
+ afterId = receipt['id']
348
+
349
+
350
+ def pollOutgoing(config):
351
+ result = postHome(config['moduleFile'], dict(outbox=dict(accountId=config['selfId'], chats=[dict(id=chat['id'], name=chat['name']) for chat in config['chats']])))
352
+ syncSettings(config, result.get('settings'))
353
+ return result.get('job')
354
+
355
+
356
+ def reportStatus(config, state):
357
+ # Best effort: the console shows this, and a missing module file must not take the adapter down while it waits.
358
+ try: postHome(config['moduleFile'], dict(status=dict(wechat=state)))
359
+ except Exception: pass
360
+
361
+
362
+ def syncSettings(config, settings):
363
+ # The console owns these two numbers; a missing or odd value keeps what the adapter already runs with.
364
+ if not isinstance(settings, dict): return
365
+ context, buffer = settings.get('contextMessages'), settings.get('bufferSeconds')
366
+ if isinstance(context, int) and not isinstance(context, bool) and 1 <= context <= 20: config['contextMessages'] = context
367
+ if isinstance(buffer, (int, float)) and not isinstance(buffer, bool) and 0 <= buffer <= 30: config['bufferSeconds'] = buffer
368
+
369
+
370
+ def flushOutgoing(config, database, store, send, *, poll=pollOutgoing, report=reportReceipt, activeIncoming=None):
371
+ for _ in range(config.get('pageSize', 50)):
372
+ store.checkPending(activeIncoming)
373
+ job = poll(config)
374
+ if job is None:
375
+ return
376
+ if not isinstance(job, dict) or job.get('accountId') != config['selfId']:
377
+ raise ValueError('发送任务不属于绑定的微信账号')
378
+ chat = next((chat for chat in config['chats'] if chat['id'] == job.get('chatId')), None)
379
+ if chat is None:
380
+ raise ValueError('发送目标不在已配置聊天中')
381
+ replyId, items = job.get('id'), job.get('messages')
382
+ if not isinstance(replyId, str) or len(replyId) != 64 or any(c not in '0123456789abcdef' for c in replyId) or not isinstance(items, list) or not 1 <= len(items) <= 16:
383
+ raise ValueError('无效的发送任务')
384
+ previous = store.reply(replyId)
385
+ if previous:
386
+ report(config['moduleFile'], previous)
387
+ store.receiptPosted(previous)
388
+ if previous['status'] == 'uncertain':
389
+ raise NeedsHuman('此前发送结果不明,只补报回执,不能重复发送')
390
+ continue
391
+ baselineChat(database, store, chat['id'], config.get('pageSize', 50))
392
+ seq, key = store.cursor(chat['id']), 'outgoing:' + replyId
393
+ store.beginReply(replyId, len(items), chat['id'], seq)
394
+ try:
395
+ prepared = prepareMessages(items, config, Path(config['moduleFile']).parent / 'wechat-outgoing')
396
+ except Exception:
397
+ store.failReply(replyId)
398
+ store.finish(chat['id'], key, seq)
399
+ flushReceipts(config['moduleFile'], store, report)
400
+ raise
401
+ try:
402
+ deliverMessages(prepared, lambda item: send(chat, item), lambda count: store.confirmReply(replyId, count))
403
+ store.finish(chat['id'], key, seq)
404
+ finally:
405
+ flushReceipts(config['moduleFile'], store, report)
406
+
407
+
408
+ def baselineChat(database, store, chatId, pageSize):
409
+ if store.cursor(chatId) is not None:
410
+ return
411
+ latest = database.get_messages(chatId, limit=1)
412
+ seq = int(latest[0]['sort_seq']) if latest else 0
413
+ rows = [row for row in newMessages(database, chatId, seq, pageSize) if int(row['sort_seq']) == seq]
414
+ store.baseline(chatId, seq, rows)
415
+
416
+
417
+ def askWhileSending(config, message, database, store, send, ask, report, poll, activeIncoming):
418
+ result = Future()
419
+ def request():
420
+ try: result.set_result(ask(config['moduleFile'], message))
421
+ except BaseException as error: result.set_exception(error)
422
+ # Only HTTP waits on this thread; all database/native operations stay on the one sender thread.
423
+ Thread(target=request, daemon=True).start()
424
+ while True:
425
+ try:
426
+ flushOutgoing(config, database, store, send, poll=poll, report=report, activeIncoming=activeIncoming)
427
+ except SnapshotBusy:
428
+ pass
429
+ if result.done():
430
+ return result.result()
431
+ time.sleep(config.get('pollSeconds', 2))
432
+
433
+
434
+ def watch(config, database, store, send, ask=askHome, report=reportReceipt, poll=pollOutgoing):
435
+ pageSize = config.get('pageSize', 50)
436
+ while True:
437
+ flushReceipts(config['moduleFile'], store, report)
438
+ store.checkPending()
439
+ try:
440
+ flushOutgoing(config, database, store, send, poll=poll, report=report)
441
+ for chat in config['chats']:
442
+ baselineChat(database, store, chat['id'], pageSize)
443
+ for row in newMessages(database, chat['id'], store.cursor(chat['id']), pageSize):
444
+ if store.seen(chat['id'], messageKey(row)):
445
+ continue
446
+ rows = bufferImageMessages(config, database, store, chat, row) if not chat['id'].endswith('@chatroom') and row['type'] == '图片' and row.get('sender_username') != config['selfId'] else [row]
447
+ message = incomingMessage(database, chat, row, config)
448
+ for following in rows[1:]:
449
+ extra = incomingMessage(database, chat, following, config)
450
+ if extra is None: raise RuntimeError('接收批次包含无法识别的消息')
451
+ if extra['text']:
452
+ message['text'] = extra['text']
453
+ message['identity'] = extra['identity']
454
+ if extra.get('media'): message.setdefault('media', []).extend(extra['media'])
455
+ store.beginBatch(chat['id'], rows)
456
+ if message:
457
+ askWhileSending(config, message, database, store, send, ask, report, poll, (chat['id'], [messageKey(member) for member in rows]))
458
+ store.finishBatch(chat['id'], rows)
459
+ flushOutgoing(config, database, store, send, poll=poll, report=report)
460
+ except SnapshotBusy:
461
+ # Re-read an unstable snapshot next poll; no message is re-sent here.
462
+ pass
463
+ time.sleep(config.get('pollSeconds', 2))
464
+
465
+
466
+ def watchConnected(config, stateDir, store, connect, *, ask=askHome, report=reportReceipt, poll=pollOutgoing, sleep=time.sleep, status=reportStatus):
467
+ waiting = False
468
+ while True:
469
+ store.checkPending()
470
+ try:
471
+ database, send = connect(config, stateDir)
472
+ try:
473
+ print(f"微信{'已重新连接' if waiting else '账号已绑定'},PID {send.processId};继续原聊天游标。", flush=True)
474
+ waiting = False
475
+ return watch(config, database, store, send, ask, report, poll)
476
+ finally:
477
+ send.close()
478
+ except WechatOffline:
479
+ store.checkPending()
480
+ status(config, 'offline')
481
+ if not waiting:
482
+ print('指定微信账号已离线,暂停收发,等待原账号重新登录;无需重启 DSH。', flush=True)
483
+ waiting = True
484
+ sleep(config.get('pollSeconds', 2))
485
+
486
+
487
+ def run(args, config, stateDir):
488
+ store = MessageStore(stateDir / 'state.sqlite')
489
+ send = None
490
+ try:
491
+ if args.command == 'acknowledge':
492
+ store.acknowledge(args.chat, args.message_id)
493
+ print('已记录核对结果;这条消息不会再次发送。')
494
+ return
495
+ if args.command in ('watch', 'send') and not args.allow_send:
496
+ raise ValueError('发送需要显式提供 --allow-send;先使用 status/chats 核对账号')
497
+ if args.command == 'watch' and not Path(config['moduleFile']).is_file():
498
+ raise ValueError('微信模块尚未启动,请先在 DSH 开启世界及 wechat 配置')
499
+ from native import connect
500
+ if args.command == 'watch':
501
+ print('开始监听所选聊天;Ctrl+C 停止。', flush=True)
502
+ watchConnected(config, stateDir, store, connect)
503
+ return
504
+ database, send = connect(config, stateDir)
505
+ if args.command == 'probe':
506
+ print(json.dumps(dict(nativeReady=True, processId=send.processId, **send.probe())))
507
+ elif args.command == 'chats':
508
+ if not 1 <= args.limit <= 100 or args.offset < 0:
509
+ raise ValueError('分页参数无效')
510
+ rows = database.get_sessions(limit=args.offset + args.limit + 1)
511
+ chats = []
512
+ for row in rows[args.offset:args.offset+args.limit]:
513
+ contact = next((item for item in database.search_contact(row['username']) if item['username'] == row['username']), {})
514
+ chats.append(dict(id=row['username'], name=contact.get('remark') or contact.get('nick_name') or row['username']))
515
+ print(json.dumps(dict(chats=chats, hasMore=len(rows) > args.offset+args.limit), ensure_ascii=False))
516
+ elif args.command == 'send':
517
+ chat = next((chat for chat in config['chats'] if chat['id'] == args.chat), None)
518
+ if not chat or not args.text or len(args.text) > 2000:
519
+ raise ValueError('请选择已配置的聊天,并提供 1–2000 字正文')
520
+ store.checkPending()
521
+ key = 'manual:' + str(time.time_ns())
522
+ baselineChat(database, store, chat['id'], config.get('pageSize', 50))
523
+ seq = store.cursor(chat['id'])
524
+ store.begin(chat['id'], key, seq)
525
+ send(chat, args.text)
526
+ store.finish(chat['id'], key, seq)
527
+ print('发送已核对')
528
+ finally:
529
+ try:
530
+ if send is not None: send.close()
531
+ finally:
532
+ store.close()
533
+
534
+
535
+ def main():
536
+ parser = argparse.ArgumentParser(description='dsh-world 独立微信模块的 Windows 适配器')
537
+ parser.add_argument('command', choices=['status', 'probe', 'chats', 'watch', 'send', 'acknowledge'])
538
+ parser.add_argument('--config', required=True)
539
+ parser.add_argument('--chat')
540
+ parser.add_argument('--text')
541
+ parser.add_argument('--message-id')
542
+ parser.add_argument('--limit', type=int, default=20)
543
+ parser.add_argument('--offset', type=int, default=0)
544
+ parser.add_argument('--allow-send', action='store_true', help='显式允许微信原生发消息')
545
+ args = parser.parse_args()
546
+ configPath = Path(args.config).resolve()
547
+ config = json.loads(configPath.read_text(encoding='utf-8-sig'))
548
+ if args.command == 'status':
549
+ from importlib.metadata import version
550
+ configured = all(config.get(k) for k in ('account', 'selfId', 'dbDir', 'chats'))
551
+ print(json.dumps(dict(dependency=version('wechatauto-replica'), configured=configured,
552
+ moduleReady=Path(config.get('moduleFile', '')).is_file()), ensure_ascii=False))
553
+ return
554
+ validateConfig(config, requireChats=args.command != 'chats')
555
+ stateDir = configPath.parent / config['account']
556
+ stateDir.mkdir(parents=True, exist_ok=True)
557
+ config['engineDir'] = str(configPath.parent / 'engine')
558
+ with exclusiveRun(stateDir):
559
+ run(args, config, stateDir)
560
+
561
+
562
+ if __name__ == '__main__':
563
+ try:
564
+ main()
565
+ except KeyboardInterrupt:
566
+ print('已停止微信适配器。')
567
+ except NeedsHuman as error:
568
+ print(f'微信适配器停止:{error}', file=sys.stderr)
569
+ sys.exit(EXIT_NEEDS_HUMAN)
570
+ except Exception as error:
571
+ print(f'微信适配器停止:{error}', file=sys.stderr)
572
+ sys.exit(1)
@@ -0,0 +1,52 @@
1
+ """Rediscover only the configured account; every live binding pins its process lifetime."""
2
+ from pathlib import Path
3
+ import psutil
4
+
5
+
6
+ class WechatOffline(RuntimeError):
7
+ pass
8
+
9
+
10
+ def processAccounts(process, config):
11
+ root = Path(config['dbDir']).resolve()
12
+ accounts = set()
13
+ for item in process.open_files():
14
+ try:
15
+ parts = Path(item.path).resolve().relative_to(root).parts
16
+ except ValueError:
17
+ continue
18
+ if len(parts) >= 3 and parts[1].lower() == 'db_storage':
19
+ accounts.add(parts[0])
20
+ return accounts
21
+
22
+
23
+ def checkAccountProcess(process, config, started):
24
+ try:
25
+ if process.create_time() != started or process.name().lower() != 'weixin.exe':
26
+ raise WechatOffline('原微信进程已退出或变化')
27
+ if processAccounts(process, config) != {config['account']}:
28
+ raise WechatOffline('原进程已不再独占绑定的微信账号')
29
+ except (psutil.NoSuchProcess, psutil.ZombieProcess) as error:
30
+ raise WechatOffline('原微信进程已退出') from error
31
+
32
+
33
+ def findAccountProcess(config, processes=None):
34
+ provided = processes is not None
35
+ if processes is None:
36
+ processes = (process for process in psutil.process_iter(['name']) if (process.info['name'] or '').lower() == 'weixin.exe')
37
+ matches = []
38
+ for candidate in processes:
39
+ try:
40
+ # A fresh Process avoids carrying cached creation times across PID reuse.
41
+ process = candidate if provided else psutil.Process(candidate.pid)
42
+ if process.name().lower() != 'weixin.exe': continue
43
+ accounts = processAccounts(process, config)
44
+ if config['account'] not in accounts: continue
45
+ if accounts != {config['account']}:
46
+ raise RuntimeError('同一微信进程持有多个账号,禁止自动绑定')
47
+ matches.append(process)
48
+ except (psutil.NoSuchProcess, psutil.ZombieProcess):
49
+ continue
50
+ if len(matches) > 1: raise RuntimeError('绑定账号对应多个微信进程,禁止猜测')
51
+ if not matches: raise WechatOffline('尚未发现已登录的指定微信账号')
52
+ return matches[0]
@@ -0,0 +1,43 @@
1
+ helper 非商业使用许可协议
2
+ 版本:1.0
3
+ 适用版本:附带本协议的项目版本
4
+ SPDX-License-Identifier: LicenseRef-helper-noncommercial-1.0
5
+
6
+ 一、适用范围
7
+
8
+ 本协议适用于 helper 项目中著作权人有权按本协议授权的原创代码、文档及其他材料,以下合称“本项目”。各文件已有的著作权声明应予保留。
9
+
10
+ 第三方组件、依赖及其他另有授权声明的材料,继续适用其各自的许可证。本协议不替代、修改或缩减这些第三方许可证已经授予的权利,也不授予著作权人无权授予的权利。相关声明见 THIRD_PARTY_NOTICES.md 及各组件的原始许可证。
11
+
12
+ 二、允许的非商业使用
13
+
14
+ 在遵守本协议的前提下,允许为个人学习、研究、测试、娱乐及非商业自用,免费使用、复制和修改本项目。
15
+
16
+ 允许以非商业目的免费分享、分发本项目原版或修改版,但必须同时提供本协议,保留原始著作权及第三方授权声明,并在修改版中明确说明已经作出修改。不得通过分发或修改,向他人授予本协议未授予的商业使用权。
17
+
18
+ 三、禁止商业使用
19
+
20
+ 本协议不授予任何商业使用权。未经相应著作权人另行书面授权,不得将本项目全部或部分用于直接或间接获取商业利益的活动,包括但不限于:
21
+
22
+ 1. 销售本项目的源码、可执行程序、打包版本,或包含本项目的修改版、派生产品。
23
+ 2. 基于本项目提供收费机器人、付费群服务、会员服务、订阅服务、接口服务、软件即服务(SaaS)或商业托管服务。
24
+ 3. 将本项目用于广告营销、商业引流、带货、商业客户服务或其他企业营利业务。
25
+ 4. 将本项目集成、交付或部署到面向商业用途的产品或服务中。
26
+
27
+ 免费向最终用户提供服务、未直接收费或经过二次开发,不自动使商业用途成为非商业用途。仅供个人业余学习、自用且不用于商业业务的行为,按本协议第二条处理。
28
+
29
+ 四、权利保留
30
+
31
+ 本协议不转让本项目的著作权、商标权或其他知识产权。未明确授予的权利由各自权利人保留。本协议不限制法律明确允许且无需取得许可的行为,也不追溯变更此前版本另已有效授予的许可。
32
+
33
+ 五、许可终止
34
+
35
+ 违反本协议时,本协议授予的许可立即终止;使用者应停止超出授权范围的使用及分发。本条不影响权利人依法主张其他权利。
36
+
37
+ 六、无担保与责任限制
38
+
39
+ 本项目按“现状”提供,不作任何明示或默示担保,包括适销性、特定用途适用性及不侵权担保。在适用法律允许的最大范围内,著作权人及贡献者不对因使用、修改、分发或无法使用本项目所产生的损失承担责任。
40
+
41
+ 七、协议文本
42
+
43
+ 本文件为本项目非商业使用许可的完整文本。README、网站或其他位置的使用说明是便于阅读的摘要;如有不一致,以本文件及相关第三方组件的适用许可证为准。