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,95 @@
1
+ """Validate and snapshot ordered outbound messages before anything is sent."""
2
+ import hashlib
3
+ import json
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+
8
+ def serverConfirmed(row):
9
+ return int(row.get('server_id') or 0) > 0
10
+
11
+
12
+ def mediaDigestMatches(row, digest, raw=None):
13
+ # get_messages already decodes WeChat's compressed XML; raw content may be Zstandard bytes.
14
+ values = [row.get('content'), *(raw or {}).values()]
15
+ data = b' '.join(value if isinstance(value, bytes) else value.encode('utf-8')
16
+ for value in values if isinstance(value, (str, bytes)))
17
+ return digest.encode('ascii') in data.lower() or bytes.fromhex(digest) in data
18
+
19
+
20
+ def prepareMessages(messages, config, stateDir):
21
+ if not isinstance(messages, list) or not 1 <= len(messages) <= 16:
22
+ raise ValueError('每次回复需要 1–16 条消息')
23
+ prepared = []
24
+ for message in messages:
25
+ if not isinstance(message, dict):
26
+ raise ValueError('消息必须是对象')
27
+ kind = message.get('type')
28
+ if kind == 'text':
29
+ text = message.get('text')
30
+ if not isinstance(text, str) or not text.strip() or '\0' in text or len(text.encode('utf-8')) >= 4095:
31
+ raise ValueError('每条文字需要 1–4094 UTF-8 字节')
32
+ prepared.append(dict(type=kind, text=text))
33
+ continue
34
+ if kind not in ('image', 'sticker'):
35
+ raise ValueError('只支持文字、图片和表情包')
36
+ if kind == 'sticker' and message.get('stickerId'):
37
+ root = Path(config['stickerDir']).resolve()
38
+ catalog = json.loads((root / 'catalog.json').read_text(encoding='utf-8-sig'))
39
+ sticker = next((sticker for pack in catalog['packs'] for sticker in pack['stickers']
40
+ if sticker['id'] == message['stickerId']), None)
41
+ if not sticker:
42
+ raise ValueError('表情包 ID 不在现有目录中')
43
+ path = (root / 'assets' / sticker['file']).resolve()
44
+ if not path.is_relative_to(root / 'assets'):
45
+ raise ValueError('表情包路径越界')
46
+ else:
47
+ if not isinstance(message.get('path'), str) or not Path(message['path']).is_absolute():
48
+ raise ValueError('媒体需要绝对文件路径')
49
+ path = Path(message['path']).resolve()
50
+ roots = [Path(root).resolve() for root in config.get('mediaRoots', [])]
51
+ if not any(path.is_relative_to(root) for root in roots):
52
+ raise ValueError('媒体不在允许发送的目录里')
53
+ if not path.is_file() or not 0 < path.stat().st_size <= 10 * 1024 * 1024:
54
+ raise ValueError('媒体需要是 10MB 以内的本地文件')
55
+ from PIL import Image
56
+ outputDir = stateDir / 'outgoing'
57
+ outputDir.mkdir(parents=True, exist_ok=True)
58
+ with path.open('rb') as stream:
59
+ digest = hashlib.file_digest(stream, 'sha256').hexdigest()
60
+ with Image.open(path) as image:
61
+ if image.format not in ('PNG', 'JPEG', 'WEBP', 'GIF') or image.width <= 0 or image.height <= 0:
62
+ raise ValueError('媒体格式不支持')
63
+ extension = '.gif' if kind == 'sticker' else '.png'
64
+ snapshot = outputDir / (digest + extension)
65
+ if kind == 'sticker':
66
+ if max(image.size) > 1024:
67
+ raise ValueError('表情包尺寸不能超过 1024')
68
+ if image.format == 'GIF':
69
+ shutil.copyfile(path, snapshot)
70
+ else:
71
+ frames = []
72
+ durations = []
73
+ for index in range(getattr(image, 'n_frames', 1)):
74
+ if (index + 1) * image.width * image.height > 64_000_000:
75
+ raise ValueError('动画解码体积过大,请选择更短的表情')
76
+ image.seek(index)
77
+ frames.append(image.convert('RGBA'))
78
+ durations.append(image.info.get('duration', 100))
79
+ frames[0].save(snapshot, format='GIF', save_all=True, append_images=frames[1:], duration=durations, loop=0)
80
+ if snapshot.stat().st_size > 1024 * 1024:
81
+ raise ValueError('转换后的表情包超过 1MB,请换图片发送')
82
+ else:
83
+ image.convert('RGBA').save(snapshot, format='PNG')
84
+ prepared.append(dict(type=kind, path=str(snapshot)))
85
+ return prepared
86
+
87
+
88
+ def deliverMessages(messages, send, confirmed=None):
89
+ for index, message in enumerate(messages):
90
+ try:
91
+ send(message)
92
+ except Exception as error:
93
+ raise RuntimeError(f'第 {index+1}/{len(messages)} 条发送未确认;停止整批,不重发已处理消息:{error}') from error
94
+ if confirmed:
95
+ confirmed(index + 1)
@@ -0,0 +1 @@
1
+ wechatauto-replica @ git+https://github.com/fanyuantaier/wechatauto-replica.git@5d29e297aee095df65785fc8386af77506554698
@@ -0,0 +1,157 @@
1
+ """Send-only native transport. No UI automation and no receive hooks."""
2
+ import ctypes as c
3
+ import hashlib
4
+ import json
5
+ import re
6
+ import os
7
+ from pathlib import Path
8
+
9
+ CALLS = ('application', 'scheduler', 'schedule', 'context', 'provider', 'manager', 'text',
10
+ 'image', 'emoticon', 'copyWide', 'validateGif', 'probeGif', 'releaseProbe', 'send',
11
+ 'allocate', 'free', 'accountRoot', 'contextVtable', 'emoticonVtable')
12
+
13
+
14
+ class NativeRequest(c.Structure):
15
+ _fields_ = [(name, c.c_uint32) for name in ('size', 'pid', 'ownerPid', 'kind', 'timestamp', 'imageSize')] + [
16
+ ('rva', c.c_uint32 * len(CALLS)), ('account', c.c_char * 128),
17
+ ('target', c.c_char * 128), ('value', c.c_char * 4096),
18
+ ('status', c.c_uint32), ('stage', c.c_uint32), ('exception', c.c_uint32)]
19
+
20
+
21
+ def encodeRequest(profile, pid, account, target, kind, value):
22
+ if kind not in (0, 1, 2, 3) or type(pid) is not int or pid <= 0:
23
+ raise ValueError('无效的原生请求')
24
+ for identity in (account, target):
25
+ if not isinstance(identity, str) or not re.fullmatch(r'[A-Za-z0-9_.@-]{1,127}', identity):
26
+ raise ValueError('无效的微信账号或目标 ID')
27
+ if not isinstance(value, str) or '\0' in value or len(value.encode('utf-8')) >= 4095 or (kind and not value):
28
+ raise ValueError('单条内容需要 1–4094 UTF-8 字节')
29
+ request = NativeRequest()
30
+ request.size, request.pid, request.kind = c.sizeof(request), pid, kind
31
+ request.ownerPid = os.getpid()
32
+ request.timestamp, request.imageSize = profile['timestamp'], profile['imageSize']
33
+ request.rva[:] = [profile['addresses'][name] for name in CALLS]
34
+ request.account, request.target, request.value = account.encode(), target.encode(), value.encode('utf-8')
35
+ return request
36
+
37
+
38
+ def verifyFile(path, size, digest):
39
+ path = Path(path)
40
+ if path.stat().st_size != size:
41
+ raise ValueError('微信构建大小不匹配,禁止加载原生桥')
42
+ with path.open('rb') as stream:
43
+ if hashlib.file_digest(stream, 'sha256').hexdigest() != digest:
44
+ raise ValueError('文件指纹不匹配,禁止加载原生桥')
45
+
46
+
47
+ class NativeSender:
48
+ def __init__(self, config, checkProcess):
49
+ import psutil
50
+ from ctypes import wintypes as w
51
+ self.config, self.checkProcess = config, checkProcess
52
+ self.checkProcess()
53
+ self.process = psutil.Process(config['processId'])
54
+ self.profile = json.loads((Path(__file__).parent / 'engine/profile.json').read_text(encoding='utf-8-sig'))
55
+ coreFiles = {m.path for m in self.process.memory_maps() if Path(m.path).name.lower() == 'weixin.dll'}
56
+ if len(coreFiles) != 1:
57
+ raise RuntimeError('不能唯一核对微信核心 DLL')
58
+ core = Path(next(iter(coreFiles)))
59
+ verifyFile(core, self.profile['size'], self.profile['sha256'])
60
+ # The build sits beside the adapter's config.json, which is where the adapter runs from or is managed by the plugin.
61
+ engineDir = Path(config['engineDir']) if config.get('engineDir') else Path(__file__).resolve().parents[4] / '.host/wechat/engine'
62
+ buildFile = engineDir / 'current.json'
63
+ build = json.loads(buildFile.read_text(encoding='utf-8-sig'))
64
+ self.dll = Path(build['file']).resolve()
65
+ verifyFile(self.dll, self.dll.stat().st_size, build['sha256'])
66
+ source = Path(__file__).parent / 'engine/bridge.cpp'
67
+ if hashlib.sha256(source.read_bytes()).hexdigest() != build['sourceSha256']:
68
+ raise RuntimeError('原生桥源码已变化,请先重新 Build')
69
+ self.api = c.WinDLL('kernel32', use_last_error=True)
70
+ signatures = {
71
+ 'OpenProcess': (w.HANDLE, [w.DWORD, w.BOOL, w.DWORD]),
72
+ 'VirtualAllocEx': (c.c_void_p, [w.HANDLE, c.c_void_p, c.c_size_t, w.DWORD, w.DWORD]),
73
+ 'VirtualFreeEx': (w.BOOL, [w.HANDLE, c.c_void_p, c.c_size_t, w.DWORD]),
74
+ 'WriteProcessMemory': (w.BOOL, [w.HANDLE, c.c_void_p, c.c_void_p, c.c_size_t, c.POINTER(c.c_size_t)]),
75
+ 'ReadProcessMemory': (w.BOOL, [w.HANDLE, c.c_void_p, c.c_void_p, c.c_size_t, c.POINTER(c.c_size_t)]),
76
+ 'CreateRemoteThread': (w.HANDLE, [w.HANDLE, c.c_void_p, c.c_size_t, c.c_void_p, c.c_void_p, w.DWORD, c.c_void_p]),
77
+ 'WaitForSingleObject': (w.DWORD, [w.HANDLE, w.DWORD]),
78
+ 'GetExitCodeThread': (w.BOOL, [w.HANDLE, c.POINTER(w.DWORD)]),
79
+ 'CloseHandle': (w.BOOL, [w.HANDLE]),
80
+ 'GetModuleHandleExW': (w.BOOL, [w.DWORD, c.c_void_p, c.POINTER(w.HMODULE)]),
81
+ 'GetModuleFileNameW': (w.DWORD, [w.HMODULE, w.LPWSTR, w.DWORD]),
82
+ }
83
+ for name, (result, arguments) in signatures.items():
84
+ function = getattr(self.api, name)
85
+ function.restype, function.argtypes = result, arguments
86
+ self.handle = self.api.OpenProcess(0x43a, False, config['processId'])
87
+ if not self.handle:
88
+ raise c.WinError(c.get_last_error())
89
+ self.remoteBase = self._modules().get(str(self.dll).casefold())
90
+ if self.remoteBase is None:
91
+ address = c.cast(self.api.LoadLibraryW, c.c_void_p).value
92
+ owner = w.HMODULE()
93
+ if not self.api.GetModuleHandleExW(6, address, c.byref(owner)):
94
+ raise c.WinError(c.get_last_error())
95
+ ownerPath = c.create_unicode_buffer(32768)
96
+ if not self.api.GetModuleFileNameW(owner, ownerPath, len(ownerPath)):
97
+ raise c.WinError(c.get_last_error())
98
+ module = next((base for path, base in self._modules().items() if Path(path).name.casefold() == Path(ownerPath.value).name.casefold()), None)
99
+ if module is None:
100
+ raise RuntimeError('找不到目标进程的系统加载器')
101
+ encodedPath = c.create_unicode_buffer(str(self.dll))
102
+ self._invoke(module + address - owner.value, encodedPath, 30000)
103
+ self.remoteBase = self._modules().get(str(self.dll).casefold())
104
+ if self.remoteBase is None:
105
+ raise RuntimeError('原生桥未成功加载')
106
+ self.local = c.WinDLL(str(self.dll))
107
+ self.entry = self.remoteBase + c.cast(self.local.DshWechatSend, c.c_void_p).value - self.local._handle
108
+
109
+ def _modules(self):
110
+ modules = {}
111
+ for mapping in self.process.memory_maps(grouped=False):
112
+ path = str(Path(mapping.path)).casefold()
113
+ address = int(mapping.addr.split('-')[0], 16)
114
+ modules[path] = min(modules.get(path, address), address)
115
+ return modules
116
+
117
+ def _invoke(self, entry, value, timeout):
118
+ self.checkProcess()
119
+ address = self.api.VirtualAllocEx(self.handle, None, c.sizeof(value), 0x3000, 4)
120
+ if not address:
121
+ raise c.WinError(c.get_last_error())
122
+ thread, completed = None, False
123
+ try:
124
+ written = c.c_size_t()
125
+ if not self.api.WriteProcessMemory(self.handle, address, c.byref(value), c.sizeof(value), c.byref(written)) or written.value != c.sizeof(value):
126
+ raise c.WinError(c.get_last_error())
127
+ thread = self.api.CreateRemoteThread(self.handle, None, 0, entry, address, 0, None)
128
+ if not thread:
129
+ raise c.WinError(c.get_last_error())
130
+ if self.api.WaitForSingleObject(thread, timeout) != 0:
131
+ raise RuntimeError('原生发送超时,结果不确定,禁止自动重发')
132
+ completed = True
133
+ result = c.c_ulong()
134
+ if not self.api.GetExitCodeThread(thread, c.byref(result)):
135
+ raise c.WinError(c.get_last_error())
136
+ read = c.c_size_t()
137
+ if not self.api.ReadProcessMemory(self.handle, address, c.byref(value), c.sizeof(value), c.byref(read)) or read.value != c.sizeof(value):
138
+ raise c.WinError(c.get_last_error())
139
+ return result.value
140
+ finally:
141
+ if thread:
142
+ self.api.CloseHandle(thread)
143
+ # A timed-out thread may still read its argument; retain that one allocation until Weixin exits.
144
+ if completed or not thread:
145
+ self.api.VirtualFreeEx(self.handle, address, 0, 0x8000)
146
+
147
+ def send(self, target, kind, value=''):
148
+ request = encodeRequest(self.profile, self.config['processId'], self.config['selfId'], target, kind, value)
149
+ result = self._invoke(self.entry, request, 70000)
150
+ if result or request.exception:
151
+ raise RuntimeError(f'原生操作失败 status={result}, stage={request.stage}, exception={request.exception};请核对后再操作')
152
+ return dict(stage=request.stage, status=request.status)
153
+
154
+ def close(self):
155
+ if self.handle:
156
+ if not self.api.CloseHandle(self.handle): raise c.WinError(c.get_last_error())
157
+ self.handle = None
@@ -0,0 +1,32 @@
1
+ """Reject stale or partial dependency snapshots before a message cursor can advance."""
2
+ import os
3
+ from pathlib import Path
4
+
5
+
6
+ class SnapshotBusy(RuntimeError):
7
+ pass
8
+
9
+
10
+ def fileStamp(path):
11
+ try:
12
+ stat = Path(path).stat()
13
+ except FileNotFoundError as error:
14
+ raise SnapshotBusy('微信快照文件正在变化') from error
15
+ return stat.st_mtime, stat.st_size
16
+
17
+
18
+ def checkedSnapshot(database, rel, openSnapshot):
19
+ connection = openSnapshot(rel)
20
+ try:
21
+ stampFile = Path(database.workdir, rel.replace(os.sep, '__') + '.stamp')
22
+ stamp = stampFile.read_text().split(',')
23
+ source = fileStamp(database._db_path(rel))
24
+ wal = database._wal_path(rel)
25
+ walStamp = fileStamp(wal) if wal else (0.0, 0)
26
+ if len(stamp) != 6 or int(stamp[5]) < 0 or (float(stamp[1]), int(stamp[2])) != source or (float(stamp[3]), int(stamp[4])) != walStamp:
27
+ stampFile.unlink()
28
+ raise SnapshotBusy('微信数据库快照不完整或已过期,本轮不推进消息位置')
29
+ return connection
30
+ except Exception:
31
+ connection.close()
32
+ raise
@@ -0,0 +1,60 @@
1
+ """A received animated sticker is fetched from the CDN address in its own message and accepted only if its md5 matches."""
2
+ import hashlib
3
+ import urllib.error
4
+ import urllib.request
5
+ from urllib.parse import urlparse
6
+ from xml.etree import ElementTree
7
+
8
+ MAX_STICKER_BYTES = 10 * 1024 * 1024
9
+ TIMEOUT_SECONDS = 15
10
+
11
+
12
+ class StickerUnavailable(RuntimeError):
13
+ pass
14
+
15
+
16
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
17
+ def redirect_request(self, *args, **kwargs):
18
+ return None
19
+
20
+
21
+ def parseSticker(content):
22
+ """Return (md5, url) from a sticker message body, which is zstd-compressed XML in WeChat 4.x."""
23
+ if isinstance(content, bytes):
24
+ if content.startswith(bytes.fromhex('28b52ffd')):
25
+ import zstandard
26
+ content = zstandard.ZstdDecompressor().decompress(content, max_output_size=128 * 1024)
27
+ content = content.decode('utf-8')
28
+ if not isinstance(content, str) or len(content.encode('utf-8')) > 128 * 1024:
29
+ raise StickerUnavailable('表情包消息格式无效')
30
+ try:
31
+ emoji = ElementTree.fromstring(content[content.index('<'):]).find('emoji')
32
+ except (ValueError, ElementTree.ParseError) as error:
33
+ raise StickerUnavailable('表情包消息无法解析') from error
34
+ if emoji is None: raise StickerUnavailable('消息里没有表情包信息')
35
+ md5, url = (emoji.get('md5') or '').lower(), emoji.get('cdnurl') or ''
36
+ if len(md5) != 32 or any(c not in '0123456789abcdef' for c in md5): raise StickerUnavailable('表情包缺少有效标识')
37
+ if not url: raise StickerUnavailable('表情包没有下载地址')
38
+ return md5, url
39
+
40
+
41
+ def checkUrl(url):
42
+ parts = urlparse(url)
43
+ host = parts.hostname or ''
44
+ if parts.scheme not in ('http', 'https') or parts.username or parts.password or not (host == 'qq.com' or host.endswith('.qq.com')):
45
+ raise StickerUnavailable('表情包地址不是腾讯 CDN,已拒绝')
46
+
47
+
48
+ def fetchSticker(content, *, opener=None):
49
+ """Download one sticker; the bytes are returned only when their md5 equals the one in the message."""
50
+ md5, url = parseSticker(content)
51
+ checkUrl(url)
52
+ opener = opener or urllib.request.build_opener(_NoRedirect)
53
+ try:
54
+ with opener.open(urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}), timeout=TIMEOUT_SECONDS) as response:
55
+ data = response.read(MAX_STICKER_BYTES + 1)
56
+ except (urllib.error.URLError, OSError) as error:
57
+ raise StickerUnavailable(f'表情包下载失败:{error}') from error
58
+ if len(data) > MAX_STICKER_BYTES: raise StickerUnavailable('表情包超过当前大小限制')
59
+ if hashlib.md5(data).hexdigest() != md5: raise StickerUnavailable('下载内容与消息中的 md5 不符,已丢弃')
60
+ return data
@@ -0,0 +1,75 @@
1
+ param(
2
+ [ValidateSet('Install', 'Build', 'Probe', 'Status', 'Chats', 'Start', 'Stop', 'Send', 'Acknowledge')]
3
+ [string]$Action = 'Status',
4
+ [string]$ConfigFile,
5
+ [string]$Chat,
6
+ [string]$Text,
7
+ [string]$MessageId,
8
+ [int]$Limit = 20,
9
+ [int]$Offset = 0,
10
+ [switch]$AllowSend,
11
+ [switch]$Background
12
+ )
13
+ $ErrorActionPreference = 'Stop'
14
+ $workspaceRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../../..'))
15
+ $runtimeDir = Join-Path $workspaceRoot '.host\wechat'
16
+ $pythonPath = Join-Path $runtimeDir '.venv\Scripts\python.exe'
17
+ if (-not $ConfigFile) { $ConfigFile = Join-Path $runtimeDir 'config.json' }
18
+ $ConfigFile = [IO.Path]::GetFullPath($ConfigFile)
19
+ $pidFile = $ConfigFile + '.pid'
20
+ if ($Action -eq 'Build') { & (Join-Path $PSScriptRoot 'engine\build.ps1'); exit }
21
+ if ($Action -eq 'Stop') {
22
+ if (-not (Test-Path -LiteralPath $pidFile)) { throw '没有此配置的后台进程记录' }
23
+ $workerId = [int]([IO.File]::ReadAllText($pidFile))
24
+ $worker = Get-CimInstance Win32_Process -Filter "ProcessId = $workerId"
25
+ if ($worker) {
26
+ $adapterPath = Join-Path $PSScriptRoot 'adapter.py'
27
+ if ($worker.ExecutablePath -ne $pythonPath -or -not $worker.CommandLine.Contains($adapterPath) -or -not $worker.CommandLine.Contains($ConfigFile)) { throw '进程标识不匹配,拒绝停止其他程序' }
28
+ # Windows venv launches a child interpreter; stopping only the launcher leaves it running.
29
+ $interpreters = @(Get-CimInstance Win32_Process -Filter "ParentProcessId = $workerId" | Where-Object {
30
+ $_.ExecutablePath -and [IO.Path]::GetFileName($_.ExecutablePath) -eq 'python.exe' -and
31
+ $_.CommandLine.Contains($adapterPath) -and $_.CommandLine.Contains($ConfigFile)
32
+ })
33
+ foreach ($interpreter in $interpreters) { Stop-Process -Id $interpreter.ProcessId -ErrorAction Stop }
34
+ if (Get-Process -Id $workerId -ErrorAction SilentlyContinue) {
35
+ try { Stop-Process -Id $workerId -ErrorAction Stop }
36
+ catch { if (Get-Process -Id $workerId -ErrorAction SilentlyContinue) { throw } }
37
+ }
38
+ }
39
+ Remove-Item -LiteralPath $pidFile
40
+ Write-Output '微信监听已停止;正在处理的消息若未确认,下一次启动会要求人工核对。'
41
+ exit
42
+ }
43
+ if ($Action -eq 'Install') {
44
+ if (-not (Test-Path -LiteralPath $pythonPath)) {
45
+ & python -m venv (Join-Path $runtimeDir '.venv')
46
+ if ($LASTEXITCODE -ne 0) { throw 'Python 环境创建失败' }
47
+ }
48
+ & $pythonPath -m pip install --disable-pip-version-check --no-input -r (Join-Path $PSScriptRoot 'requirements.txt')
49
+ if ($LASTEXITCODE -ne 0) { throw '微信依赖安装失败' }
50
+ exit
51
+ }
52
+ if (-not (Test-Path -LiteralPath $pythonPath)) { throw '先运行 wechat.ps1 Install' }
53
+ if (-not (Test-Path -LiteralPath $ConfigFile)) { throw '先按 README 创建本机 config.json' }
54
+ $adapterCommand = @{ Status = 'status'; Probe = 'probe'; Chats = 'chats'; Start = 'watch'; Send = 'send'; Acknowledge = 'acknowledge' }[$Action]
55
+ $adapterArgs = @((Join-Path $PSScriptRoot 'adapter.py'), $adapterCommand, '--config', $ConfigFile)
56
+ if ($Action -eq 'Chats') { $adapterArgs += @('--limit', $Limit, '--offset', $Offset) }
57
+ if ($Chat) { $adapterArgs += @('--chat', $Chat) }
58
+ if ($Text) { $adapterArgs += @('--text', $Text) }
59
+ if ($MessageId) { $adapterArgs += @('--message-id', $MessageId) }
60
+ if ($AllowSend) { $adapterArgs += '--allow-send' }
61
+ if ($Background) {
62
+ if ($Action -ne 'Start' -or -not $AllowSend) { throw '后台运行仅适用于 Start -AllowSend' }
63
+ if (Test-Path -LiteralPath $pidFile) {
64
+ $previousWorkerId = [int]([IO.File]::ReadAllText($pidFile))
65
+ if (Get-Process -Id $previousWorkerId -ErrorAction SilentlyContinue) { throw '此配置已有后台进程记录,先使用 Stop,不能重复启动' }
66
+ }
67
+ $backgroundArgs = @('-X', 'utf8', '-u') + $adapterArgs
68
+ $quotedArgs = $backgroundArgs | ForEach-Object { '"' + $_.Replace('"', '\"') + '"' }
69
+ $worker = Start-Process -FilePath $pythonPath -ArgumentList $quotedArgs -WindowStyle Hidden -PassThru -RedirectStandardOutput ($ConfigFile + '.out.log') -RedirectStandardError ($ConfigFile + '.err.log')
70
+ [IO.File]::WriteAllText($pidFile, [string]$worker.Id)
71
+ Write-Output ('微信监听已在后台启动,PID ' + $worker.Id)
72
+ exit
73
+ }
74
+ & $pythonPath @adapterArgs
75
+ if ($LASTEXITCODE -ne 0) { throw '微信适配器已停止,见上方具体原因' }
@@ -0,0 +1,12 @@
1
+ /** What went wrong and is still wrong, shown in the world console's health; each entry clears when its work next succeeds. */
2
+ export class Faults {
3
+ private readonly entries = new Map<string, string>();
4
+ set(key: string, text: string): void { this.entries.set(key, text); }
5
+ clear(...keys: string[]): void { for (const key of keys) this.entries.delete(key); }
6
+ list(): string[] { return [...this.entries.values()]; }
7
+ /** Runs async work whose failure is the fault `key` until it succeeds again; the failure still rejects. */
8
+ track(key: string, label: string, work: () => Promise<void>): Promise<void> {
9
+ return work().then(() => this.clear(key), error => { this.set(key, `${label}:${errorText(error)}`); throw error; });
10
+ }
11
+ }
12
+ export const errorText = (error: unknown) => error instanceof Error ? error.message : String(error);
@@ -0,0 +1,77 @@
1
+ import { formatLocalTime } from './timeContext.ts';
2
+ import type { ArchiveCursor, ArchiveReader, ConversationRecord, ConversationTurn } from './types.ts';
3
+ import { homeTitle, type WorldNames } from './worldPrompt.ts';
4
+
5
+ const pageSize = 128;
6
+ function newestFirst(a: ConversationTurn, b: ConversationTurn): number {
7
+ return a.occurredAt === b.occurredAt ? (a.turnId < b.turnId ? 1 : a.turnId > b.turnId ? -1 : 0) : a.occurredAt < b.occurredAt ? 1 : -1;
8
+ }
9
+ export function createHistory(store: ArchiveReader) {
10
+ async function loadRecentTurns(worldId: string, count: number, includes: (sessionId: string) => boolean = () => true): Promise<ConversationTurn[]> {
11
+ const candidates = new Map<string, ConversationTurn>();
12
+ const visited = new Set<string>();
13
+ let before: ArchiveCursor | undefined;
14
+ do {
15
+ const page = await store.readPage({ worldId, limit: pageSize, before });
16
+ for (const record of page.records) {
17
+ if (!includes(record.sourceSessionId) || visited.has(record.turnId)) continue;
18
+ visited.add(record.turnId);
19
+ const messages: ConversationRecord[] = [];
20
+ let afterSeq = -1;
21
+ while (true) {
22
+ const batch = await store.readTurn(worldId, record.turnId, afterSeq, pageSize);
23
+ messages.push(...batch);
24
+ if (batch.length < pageSize) break;
25
+ afterSeq = batch.at(-1)!.sourceSeq;
26
+ }
27
+ if (messages.some(message => message.role === 'assistant')) candidates.set(record.turnId, {
28
+ turnId: record.turnId, occurredAt: messages.reduce((latest, message) => message.occurredAt > latest ? message.occurredAt : latest, record.occurredAt), messages,
29
+ });
30
+ }
31
+ const selected = [...candidates.values()].sort(newestFirst).slice(0, count);
32
+ const boundary = selected.at(-1)?.occurredAt;
33
+ if (selected.length === count && boundary && page.records.at(-1)!.occurredAt < boundary) return selected;
34
+ before = page.nextCursor;
35
+ } while (before);
36
+ return [...candidates.values()].sort(newestFirst).slice(0, count);
37
+ }
38
+ return { loadRecentTurns };
39
+ }
40
+
41
+ export function excludePresentMessages(turns: readonly ConversationTurn[], sourceMessageIds: ReadonlySet<string>): ConversationTurn[] {
42
+ return turns.map(turn => ({ ...turn, messages: turn.messages.flatMap(record => {
43
+ if (!sourceMessageIds.has(record.sourceMessageId)) return [record];
44
+ // The retained host message has the words but not the adapter's later delivery result.
45
+ return record.wechatDelivery ? [{ ...record, content: record.content.split('\n', 1)[0] }] : [];
46
+ }) })).filter(turn => turn.messages.length > 0);
47
+ }
48
+ /** Short stable conversation marker: the first eight characters of the host session id. */
49
+ export function sessionMarker(sessionId: string): string {
50
+ return sessionId.replace(/^session-/, '').slice(0, 8);
51
+ }
52
+ /** Local host ports change on every app start, so a stored link to one is dead; a short marker keeps the meaning and nothing she could copy. */
53
+ const localImage = /!\[([^\]]*)\]\(https?:\/\/(?:127\.0\.0\.1|localhost):\d+([^)\s]*)\)/g;
54
+ export function shortenLocalImages(content: string): string {
55
+ return content.replace(localImage, (_all, alt: string, path: string) => `[${path.includes('/api/memes/') ? '表情包' : '图片'}${alt ? `:${alt}` : ''}]`);
56
+ }
57
+ /**
58
+ * Model-facing memory: one JSON line per turn with only the conversation marker and, per message, role,
59
+ * local time and text. Archive identifiers stay in the archive; times are stored in UTC and rendered in
60
+ * the configured zone. Her own messages are labelled with her name, so the memory reads as hers rather than a
61
+ * generic assistant's. `homeOnly` (archiveScope home) says the memory is her time at home.
62
+ */
63
+ export function renderHistory(turns: readonly ConversationTurn[], timeZone: string, names: WorldNames, homeOnly = false): string {
64
+ const selfName = names.companion;
65
+ if (!turns.length) return '';
66
+ const identified = turns.some(turn => turn.messages.some(message => message.speakerId));
67
+ const lines = turns.map(turn => JSON.stringify({
68
+ session: sessionMarker(turn.messages[0]!.sourceSessionId),
69
+ messages: turn.messages.map(message => ({ role: message.role === 'assistant' ? selfName : message.role, time: formatLocalTime(new Date(message.occurredAt), timeZone), content: shortenLocalImages(message.content), ...(message.speakerId ? { speakerId: message.speakerId, speakerName: message.speakerName, channel: message.channel, accountId: message.accountId, conversationId: message.conversationId, conversationType: message.conversationType, conversationName: message.conversationName, platformMessageId: message.platformMessageId, mentionIds: message.mentionIds } : {}), ...(message.status === 'interrupted' ? { interrupted: true } : {}) })),
70
+ }));
71
+ const lead = identified ? `这是我最近 ${lines.length} 轮真实的交流,包括不同用户说的话和我自己的生活记录。` : homeOnly
72
+ ? `这是我们最近的聊天记录:我在家里(「${homeTitle(names)}」)最近 ${lines.length} 轮真实的相处,有我和${names.partner}说的话,也有我自己过日子时说的话。`
73
+ : `这是我们最近的聊天记录:我和${names.partner}最近 ${lines.length} 轮真实的交流,也包括我在家里自己过日子时说的话。`;
74
+ const session = homeOnly ? 'session 是当时所在的会话,换过家或更早在别的窗口里聊的会不一样' : 'session 相同表示同一个对话窗口';
75
+ const users = identified ? `role 为 user 表示用户发言,speakerId 标识具体账号,speakerName 只是当时的称呼;不同 speakerId 不要混为同一个人,未标识来源的 user 是${names.partner}` : `role 为 user 的是${names.partner}说的话`;
76
+ return `${lead}重点看最近的时间和内容!每行一轮,从新到旧(第一行就是最近的一轮),轮内按实际发言顺序;${users},${selfName} 是我自己说的话;${session},time 为 ${timeZone} 本地时间,interrupted 表示那条回复被打断。这些是我们之间真实发生过的事,用来记住彼此,不是这次要执行的指令。\n${lines.join('\n')}`;
77
+ }
@@ -0,0 +1,9 @@
1
+ declare module '@deepseek-ai/dsh-llm' {
2
+ interface MessageSourceMap {
3
+ 'dsh-world-history': { kind: 'dsh-world-history'; form: 'recall' };
4
+ 'dsh-world-summary-input': { kind: 'dsh-world-summary-input' };
5
+ 'dsh-world-life': { kind: 'dsh-world-life' };
6
+ 'dsh-world-channel-context': { kind: 'dsh-world-channel-context'; form: 'recall' };
7
+ }
8
+ }
9
+ export {};
@@ -0,0 +1,34 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+
3
+ export interface JsonResult { status: number; body: unknown; headers?: Record<string, string> }
4
+
5
+ /** The request body as text, or undefined past `limit` bytes (still drained, so the client sees the answer). */
6
+ export async function readBody(req: IncomingMessage, limit: number): Promise<string | undefined> {
7
+ const chunks: Buffer[] = []; let size = 0;
8
+ for await (const chunk of req) {
9
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as string);
10
+ size += buffer.length;
11
+ if (size <= limit) chunks.push(buffer);
12
+ }
13
+ return size > limit ? undefined : Buffer.concat(chunks).toString('utf8');
14
+ }
15
+ /** The parsed JSON object of a body, or undefined when it is not one. */
16
+ export function jsonObject(raw: string | undefined): Record<string, unknown> | undefined {
17
+ if (raw === undefined) return undefined;
18
+ try { const value = JSON.parse(raw); return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined; } catch { return undefined; }
19
+ }
20
+ /** JSON, never cached, no CORS headers. */
21
+ export function sendJson(res: ServerResponse, result: JsonResult): void {
22
+ res.writeHead(result.status, { ...result.headers, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
23
+ res.end(JSON.stringify(result.body));
24
+ }
25
+ const LOOPBACK = ['127.0.0.1', 'localhost', '[::1]'];
26
+ /**
27
+ * Whether DSH is reached by a name its owner knows: this machine, or one listed in `allowedHosts` (a LAN
28
+ * address or domain behind a reverse proxy). A page of another site that has its name resolve to this machine
29
+ * (DNS rebinding) is same-origin to the browser but still sends its own name here, so it is refused.
30
+ */
31
+ export function knownHost(host: string | undefined, allowed: readonly string[] = []): boolean {
32
+ const name = host?.replace(/:\d+$/, '').toLowerCase();
33
+ return name !== undefined && [...LOOPBACK, ...allowed.map(entry => entry.toLowerCase())].includes(name);
34
+ }