dsh-chat-comprehension 0.2.0 → 0.3.0

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 +30 -9
  4. package/lib/engines.mjs +136 -0
  5. package/lib/index.js +37 -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 +3278 -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,48 @@
1
+ import type { Agent } from '@deepseek-ai/dsh-agent';
2
+ import type {} from '@deepseek-ai/dsh-tools';
3
+ import { errorText, type Faults } from '../faults.ts';
4
+ import type { lifeTools } from './tools.ts';
5
+
6
+ type Registration = (() => void)[];
7
+ const ALARM_TOOLS = ['plan_next', 'check_alarm', 'cancel_alarm'];
8
+ const HOME_TOOLS = ['reach_out'];
9
+
10
+ /** Disposes in reverse; a disposer whose agent scope is already gone may throw and is skipped. */
11
+ function undo(list: Registration): void {
12
+ for (const dispose of list.splice(0).reverse()) { try { dispose(); } catch { /* scope already disposed */ } }
13
+ }
14
+
15
+ /**
16
+ * The alarm tools are held by every world session (she can set her alarm anywhere; it rings at home);
17
+ * reach_out only by the current home. A registration that fails (a name clash) is a fault and never breaks
18
+ * agent creation; it registers all of a group or none.
19
+ */
20
+ export function createToolRegistry(deps: { faults: Faults; logger: { error(...args: unknown[]): void }; tools: () => ReturnType<typeof lifeTools>; isHome(agent: Agent): boolean }) {
21
+ const alarm = new Map<Agent, Registration>();
22
+ const home = new Map<Agent, Registration>();
23
+ function register(agent: Agent, tools: ReturnType<typeof lifeTools>, names: string[]): Registration {
24
+ const done: Registration = [];
25
+ try { for (const tool of tools) if (names.includes(tool.name)) done.push(agent.ctx.tools.register(tool)); }
26
+ catch (error) { undo(done); throw error; }
27
+ return done;
28
+ }
29
+ return {
30
+ attach(agent: Agent): void {
31
+ const needsAlarm = !alarm.get(agent)?.length, needsHome = deps.isHome(agent) && !home.get(agent)?.length;
32
+ if (!needsAlarm && !needsHome) return;
33
+ try {
34
+ const tools = deps.tools();
35
+ if (needsAlarm) alarm.set(agent, register(agent, tools, ALARM_TOOLS));
36
+ if (needsHome) home.set(agent, register(agent, tools, HOME_TOOLS));
37
+ deps.faults.clear(`attach:${agent.id}`);
38
+ } catch (error) { deps.faults.set(`attach:${agent.id}`, `工具挂载失败:${errorText(error)}`); deps.logger.error(error); }
39
+ },
40
+ forget(agent: Agent): void { alarm.delete(agent); home.delete(agent); deps.faults.clear(`attach:${agent.id}`); },
41
+ /** A rebuilt home takes reach_out from the old one. */
42
+ releaseOldHomes(): void { for (const [agent, list] of home) if (!deps.isHome(agent)) undo(list); },
43
+ clear(): void {
44
+ for (const list of [...home.values(), ...alarm.values()]) undo(list);
45
+ home.clear(); alarm.clear();
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,61 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools';
2
+ import type { Notifier } from './notify.ts';
3
+ import type { WorldNames } from '../worldPrompt.ts';
4
+ import { exampleTime, fillMessage, readAlarmMessages } from './messages.ts';
5
+ import { pushOf } from '../ecosystem/shared/outlets.ts';
6
+
7
+ export interface AlarmDescriptions { plan: string; check: string; cancel: string }
8
+ export interface LifeToolHost {
9
+ planNext(input: { at?: string; after_minutes?: number }, note: string): string;
10
+ /** With both, check_alarm and cancel_alarm are offered too. */
11
+ checkAlarm?(): string;
12
+ cancelAlarm?(): string;
13
+ notifier: Notifier;
14
+ names?: WorldNames;
15
+ /** The DSH origin, for sticker URLs in her words. */
16
+ origin?(): string | undefined;
17
+ /** From the alarm template; the shipped wording otherwise. */
18
+ descriptions?: AlarmDescriptions;
19
+ }
20
+ export function alarmDescriptions(messages = readAlarmMessages(undefined), values: Record<string, string> = { example: exampleTime('UTC'), fallbackWakeTime: '09:00' }): AlarmDescriptions {
21
+ return { plan: fillMessage(messages, 'plan_next 说明', values), check: fillMessage(messages, 'check_alarm 说明', values), cancel: fillMessage(messages, 'cancel_alarm 说明', values) };
22
+ }
23
+ const text = { schema: { type: 'string' as const }, render: (_args: unknown, value: string) => [{ type: 'text' as const, text: value }] };
24
+
25
+ export function lifeTools(host: LifeToolHost) {
26
+ const { companion, partner } = host.names ?? { companion: 'TA', partner: '伙伴' };
27
+ const descriptions = host.descriptions ?? alarmDescriptions();
28
+ const planNext = defineTool({
29
+ name: 'plan_next',
30
+ description: descriptions.plan,
31
+ parameters: { at: { type: 'string' }, after_minutes: { type: 'number' }, note: { type: 'string', required: true } },
32
+ output: text,
33
+ execute: async ({ at, after_minutes, note }) => host.planNext({ ...(at === undefined ? {} : { at }), ...(after_minutes === undefined ? {} : { after_minutes }) }, note),
34
+ });
35
+ const { toast, outlets } = host.notifier;
36
+ const reaching = outlets.filter(outlet => outlet.kinds.includes('reach'));
37
+ const channelNames = [...(toast ? ['系统通知'] : []), ...reaching.map(outlet => outlet.name)];
38
+ const reachOut = defineTool({
39
+ name: 'reach_out',
40
+ description: `想找${partner}时用:先在家里正常把话说出来,再用它把这句话送到${partner}面前(${channelNames.length ? channelNames.join(' + ') : '现在还没有配置任何通道'})。image 可选,是一个表情的名字,接收的一方认得才会显示。找${partner}时说一两句就好,细节留在家里,${partner}来了自己会看。`,
41
+ parameters: { text: { type: 'string', required: true }, image: { type: 'string' } },
42
+ output: text,
43
+ execute: async ({ text: message, image }) => {
44
+ if (!channelNames.length) throw new Error('现在还没有配置任何通道,话留在家里了。');
45
+ const push = pushOf(message, 'reach', companion, host.origin?.(), image);
46
+ const channels: [string, string, Promise<void>][] = [
47
+ ...(toast ? [['系统通知', '已发出', toast.call(host.notifier, companion, message)] as [string, string, Promise<void>]] : []),
48
+ ...reaching.map(outlet => [outlet.name, '已送到', outlet.send(push)] as [string, string, Promise<void>]),
49
+ ];
50
+ const results = await Promise.allSettled(channels.map(([, , sent]) => sent));
51
+ const summary = `${results.map((result, index) => { const [name, done] = channels[index]!; return result.status === 'fulfilled' ? `${name}${done}` : `${name}没送到:${result.reason instanceof Error ? result.reason.message : String(result.reason)}`; }).join(';')}。`;
52
+ if (results.every(result => result.status === 'rejected')) throw new Error(summary);
53
+ return summary;
54
+ },
55
+ });
56
+ const { checkAlarm, cancelAlarm } = host;
57
+ if (!checkAlarm || !cancelAlarm) return [planNext, reachOut] as const;
58
+ const check = defineTool({ name: 'check_alarm', description: descriptions.check, parameters: {}, output: text, execute: async () => checkAlarm.call(host) });
59
+ const cancel = defineTool({ name: 'cancel_alarm', description: descriptions.cancel, parameters: {}, output: text, execute: async () => cancelAlarm.call(host) });
60
+ return [planNext, reachOut, check, cancel] as const;
61
+ }
@@ -0,0 +1,19 @@
1
+ export type AlarmSource = 'plan' | 'fallback';
2
+ /** `nudged`: she was already asked once, when a home turn stopped well before this alarm, whether she is done. */
3
+ export interface Alarm { at: string; note: string; setAt: string; source: AlarmSource; nudged?: true }
4
+ /** The next look back on a day: when it is due, and the local day it looks back on. */
5
+ export interface Review { at: string; day: string }
6
+ /** A word the plugin owes her home: `arrival` when a new home was built, `return` when her world was started again. */
7
+ export interface Greeting { at: string; kind: 'arrival' | 'return' }
8
+ /** What her home spent on the local `day`, in CNY, and whether she was told she went past her budget. */
9
+ export interface Spend { day: string; yuan: number; reminded?: true }
10
+ export interface LifeState { version: 1; homeSessionId?: string; alarm?: Alarm; greeting?: Greeting; review?: Review; spend?: Spend }
11
+ /** `first` is a new home's first wake, `return` the word when her world starts again, `review` the daily look back. */
12
+ export interface WakeRecord { scheduledAt: string; deliveredAt: string; source: AlarmSource | 'first' | 'return' | 'review'; lateMs: number }
13
+ export interface ActivityRecord { time: string; sessionId: string; callId: string; tool: string; summary: string; outside: boolean; gapBefore?: true; status?: 'ok' | 'error' }
14
+ export interface CompactionRecord { time: string; sessionId: string; ok: boolean; shadowedTokens?: number; error?: string }
15
+ export interface LifeOptions {
16
+ worldDir: string; roomDir: string; diaryDir: string; selfFile: string; fallbackWakeTime: string; timeZone: string;
17
+ /** Her alarm wording; the shipped `templates/alarm.md` when absent or missing. */
18
+ alarmFile?: string;
19
+ }
@@ -0,0 +1,26 @@
1
+ import { existsSync, readFileSync, rmSync } from 'node:fs';
2
+ import { durableWrite } from './life/lifeStore.ts';
3
+ import { parseSections } from './life/messages.ts';
4
+
5
+ /** Her persona in layers, each a `## 名字` section of `<world>/persona.md`, filled in the world console. */
6
+ export const PERSONA_LAYERS = ['名字', '她是谁', '性格', '说话方式', '愿景', '补充'] as const;
7
+ export type PersonaLayer = typeof PERSONA_LAYERS[number];
8
+ export type Persona = Record<PersonaLayer, string>;
9
+
10
+ /** Missing or unreadable means not written yet: every layer empty. */
11
+ export function readPersona(file: string): Persona {
12
+ let sections = new Map<string, string>();
13
+ try { if (existsSync(file)) sections = parseSections(readFileSync(file, 'utf8')); } catch { /* treated as not written */ }
14
+ return Object.fromEntries(PERSONA_LAYERS.map(layer => [layer, sections.get(layer) ?? ''])) as Persona;
15
+ }
16
+ /** Only layers with text are kept; a persona with none removes the file. */
17
+ export function writePersona(file: string, persona: Partial<Persona>): void {
18
+ const kept = PERSONA_LAYERS.flatMap(layer => { const text = persona[layer]?.trim(); return text ? [`## ${layer}\n${text}`] : []; });
19
+ if (kept.length) durableWrite(file, `${kept.join('\n\n')}\n`); else rmSync(file, { force: true });
20
+ }
21
+ /** The persona as she reads it at the top of her system prompt, in her own voice; empty when nothing is written. */
22
+ export function renderPersona(persona: Persona): string {
23
+ const opening = [persona.名字 ? `我是${persona.名字}。` : '', persona.她是谁].filter(Boolean).join('');
24
+ const layers = (['性格', '说话方式', '愿景'] as const).flatMap(layer => persona[layer] ? [`# ${layer}\n${persona[layer]}`] : []);
25
+ return [opening, ...layers, persona.补充].filter(Boolean).join('\n\n');
26
+ }
@@ -0,0 +1,71 @@
1
+ import type { Agent } from '@deepseek-ai/dsh-agent';
2
+ import type { Session } from '@deepseek-ai/dsh-session';
3
+ import type {} from '@deepseek-ai/dsh-system-prompt';
4
+ import { errorText, type Faults } from './faults.ts';
5
+ import { readPersona, renderPersona } from './persona.ts';
6
+ import { renderSelf } from './self.ts';
7
+ import { belongsToWorld } from './sourceArchive.ts';
8
+ import type { WorldConfig } from './types.ts';
9
+ import { readTemplate, renderWorldPrompt, type WorldPrompt } from './worldPrompt.ts';
10
+
11
+ export interface WorldPromptSource { prompt: WorldPrompt; isHome(sessionId: string): boolean; archiveSession?(sessionId: string): boolean }
12
+ interface PromptText { template: string; self?: { file: string; text: string }; persona: string }
13
+ interface Entry { text: PromptText; world: () => void; persona?: () => void }
14
+ /** The host's persona section; a preset may also register it for its own agents. */
15
+ const HOST_PERSONA = 'deployment:persona-prefix';
16
+
17
+ /**
18
+ * Her persona and the world prompt, sections of every world session's system prompt so she sees them on every
19
+ * request. They are read when the session opens and again after each successful compaction (the host assembles
20
+ * the system prompt before pre-step, so the refresh happens on compaction/end), never in between, so the prompt
21
+ * stays in the provider-cached prefix. Whether the session is her home is asked per request.
22
+ *
23
+ * Her persona takes the place of the host's: registered under the host persona's name for her agent, it shadows
24
+ * the deployment default. Where her preset already gave her agent a persona, that name is taken, so hers follows
25
+ * it under its own name and the console says so.
26
+ */
27
+ export function createPromptSections(config: WorldConfig, world: WorldPromptSource, deps: { faults: Faults; logger: { warn(...args: unknown[]): void } }) {
28
+ const entries = new Map<Agent, Entry>();
29
+ const agents = new WeakMap<Session, Agent>();
30
+ function read(): PromptText {
31
+ const template = readTemplate(world.prompt.file);
32
+ if (template.error) deps.logger.warn(`dsh-world: ${template.error}`);
33
+ return {
34
+ template: template.text,
35
+ ...(config.selfFile ? { self: { file: config.selfFile, text: renderSelf(config.selfFile) } } : {}),
36
+ persona: world.prompt.persona ? renderPersona(readPersona(world.prompt.persona)) : '',
37
+ };
38
+ }
39
+ /** Registers her persona when she has one and drops it when she has none. */
40
+ function placePersona(agent: Agent, entry: Entry): void {
41
+ if (!entry.text.persona) { entry.persona?.(); delete entry.persona; return; }
42
+ if (entry.persona) return;
43
+ const prompt = agent.ctx.systemPrompt;
44
+ const order = prompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX') ?? 0;
45
+ const text = () => entry.text.persona;
46
+ try { entry.persona = prompt.section({ name: HOST_PERSONA, order, interpolate: false, text }); deps.faults.clear('persona'); }
47
+ catch (error) {
48
+ entry.persona = prompt.section({ name: 'dsh-world-persona', order: order + 1, interpolate: false, text });
49
+ deps.faults.set('persona', `她的预设自带人设,你写的人设排在它后面(${errorText(error)})`);
50
+ }
51
+ }
52
+ return {
53
+ add(agent: Agent): void {
54
+ if (entries.has(agent) || !belongsToWorld(agent.session, config)) return;
55
+ const text = read();
56
+ const entry: Entry = { text, world: agent.ctx.systemPrompt.section({ name: 'dsh-world', order: 50, interpolate: false, text: () => renderWorldPrompt(world.prompt, entry.text.template, entry.text.self, world.isHome(agent.id)) }) };
57
+ entries.set(agent, entry); agents.set(agent.session, agent);
58
+ placePersona(agent, entry);
59
+ },
60
+ refresh(session: Session): void {
61
+ const agent = agents.get(session); const entry = agent && entries.get(agent);
62
+ if (!agent || !entry) return;
63
+ entry.text = read();
64
+ placePersona(agent, entry);
65
+ },
66
+ clear(): void {
67
+ for (const entry of entries.values()) for (const dispose of [entry.world, entry.persona]) { try { dispose?.(); } catch { /* agent scope already gone */ } }
68
+ entries.clear();
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,51 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+
3
+ /**
4
+ * The sessions this world is allowed to remember and speak into, written by dsh-agent-md when it
5
+ * binds a conversation to the QQ gateway. `scope: 'qq'` makes the memory line follow that binding
6
+ * instead of the host preset or workspace: the current bound conversation reads what the earlier
7
+ * QQ conversations wrote, and no other conversation is injected or archived.
8
+ *
9
+ * The file shape is `{ "version": 1, "sessions": ["session-…", "…"], "updatedAt": "…" }`.
10
+ */
11
+ interface Snapshot { file: string; mtime: number; sessions: ReadonlySet<string>; current: string }
12
+ let cache: Snapshot = { file: '', mtime: -1, sessions: new Set(), current: '' };
13
+
14
+ function snapshot(file: string | undefined): Snapshot {
15
+ if (!file) return { file: '', mtime: -1, sessions: new Set(), current: '' };
16
+ try {
17
+ const info = statSync(file);
18
+ if (cache.file === file && cache.mtime === info.mtimeMs) return cache;
19
+ const raw = JSON.parse(readFileSync(file, 'utf8')) as { sessions?: unknown; current?: unknown };
20
+ const sessions = new Set(Array.isArray(raw?.sessions) ? raw.sessions.filter((id): id is string => typeof id === 'string' && id !== '') : []);
21
+ const current = typeof raw?.current === 'string' ? raw.current : '';
22
+ cache = { file, mtime: info.mtimeMs, sessions, current };
23
+ return cache;
24
+ } catch {
25
+ return { file, mtime: -1, sessions: new Set(), current: '' };
26
+ }
27
+ }
28
+
29
+ /** Every conversation whose messages belong to this world's memory (current + the earlier QQ conversations). */
30
+ export function qqScopeSessions(file: string | undefined): ReadonlySet<string> {
31
+ return snapshot(file).sessions;
32
+ }
33
+
34
+ /**
35
+ * The one conversation the QQ gateway is bound to right now. Only this session receives the memory block;
36
+ * the earlier conversations in `sessions` are archive sources, never injection targets.
37
+ */
38
+ export function qqScopeCurrent(file: string | undefined): string {
39
+ return snapshot(file).current;
40
+ }
41
+
42
+ /** Whether this session is one of the QQ-bound conversations (the current one and its predecessors). */
43
+ export function inQqScope(sessionId: string, file: string | undefined): boolean {
44
+ return qqScopeSessions(file).has(String(sessionId));
45
+ }
46
+
47
+ /** Whether this session is the conversation QQ currently speaks through. */
48
+ export function isQqCurrent(sessionId: string, file: string | undefined): boolean {
49
+ const current = qqScopeCurrent(file);
50
+ return current !== '' && current === String(sessionId);
51
+ }
@@ -0,0 +1,172 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import type { Context } from '@deepseek-ai/cordis';
4
+ import type { Agent } from '@deepseek-ai/dsh-agent';
5
+ import { createUserMessage, isAgentLoopRequest, type StreamChunk, type UserMessage } from '@deepseek-ai/dsh-llm';
6
+ import type { Session, SessionSeq } from '@deepseek-ai/dsh-session';
7
+ import type {} from '@deepseek-ai/dsh-compaction';
8
+ import './hostContract.ts';
9
+ import { Faults } from './faults.ts';
10
+ import { createHistory, excludePresentMessages, renderHistory } from './history.ts';
11
+ import { createPromptSections, type WorldPromptSource } from './promptSection.ts';
12
+ import { belongsToWorld, createSourceArchive } from './sourceArchive.ts';
13
+ import type { ArchiveStore } from './store.ts';
14
+ import type { WorldConfig } from './types.ts';
15
+ import { worldNames } from './worldPrompt.ts';
16
+ import { DEFAULT_MEMORY_TURNS } from './worldSwitch.ts';
17
+
18
+ export type { WorldPromptSource } from './promptSection.ts';
19
+ const memorySource = 'dsh-world-history';
20
+
21
+ /**
22
+ * Per session: whether the memory block must be (re)built at the next step, and where the injected blocks
23
+ * still on the surface sit, so they can be retired.
24
+ */
25
+ interface MemoryState { reload: boolean; injected: Map<string, SessionSeq>; pendingId?: string }
26
+
27
+ /**
28
+ * The memory line: her conversations are archived as they happen, and every world session gets a memory
29
+ * block of the newest turns at its start and after each successful compaction, never in between, so it stays
30
+ * inside the provider-cached prefix. `home` archives the current home; `workspace` uses host membership. The memory block still
31
+ * goes to every world session. With a world prompt source, the world prompt joins every world session.
32
+ * `memoryTurns` is read each time a block is built (default 200).
33
+ */
34
+ export function createWorldRuntime(ctx: Context, config: WorldConfig, store: ArchiveStore, world?: WorldPromptSource, memoryTurns: () => number = () => DEFAULT_MEMORY_TURNS) {
35
+ if (config.archiveScope === 'workspace' && !world?.archiveSession) throw new Error('Workspace archive requires the host workspace selection');
36
+ const archivedByScope = world?.archiveSession ?? ((sessionId: string) => config.archiveScope !== 'home' || !!world?.isHome(sessionId));
37
+ /** False while some session's workspace was unknown (the host's workspace service was not up yet); `retryCatchUp` reads those later. */
38
+ let undecided = false;
39
+ /** Archiving never fails on unknown membership: the session waits, and what it said is read in order later. */
40
+ const archived = (sessionId: string) => { try { return archivedByScope(sessionId); } catch { undecided = true; return false; } };
41
+ const archive = createSourceArchive(ctx, config, store, archived);
42
+ const history = createHistory(store);
43
+ const names = world?.prompt.names ?? worldNames(config);
44
+ const faults = new Faults();
45
+ const prompts = world && createPromptSections(config, world, { faults, logger: ctx.logger });
46
+ const memory = new WeakMap<Session, MemoryState>();
47
+ const attaching = new WeakMap<Session, Promise<void>>();
48
+ const disposers: (() => void)[] = [];
49
+ let stopping: Promise<void> | undefined;
50
+
51
+ /** Locate earlier memory blocks; every runtime start rebuilds from the active scope and real times. */
52
+ async function readMemoryState(session: Session): Promise<MemoryState> {
53
+ const injected = new Map<string, SessionSeq>();
54
+ const surface = new Set(session.surface.nodes);
55
+ const handle = await ctx.sessionPersistence.open(session.id, 'read');
56
+ try {
57
+ for (let offset = 0; ; offset += 128) {
58
+ const { events } = await handle.read(offset, 128);
59
+ if (!events.length) break;
60
+ for (const event of events) {
61
+ const block = event.type === 'user/message' && event.data.source.kind === memorySource;
62
+ if (block && surface.has(event.seq)) injected.set(event.data.id, event.seq);
63
+ }
64
+ }
65
+ } finally { await handle.close(); }
66
+ return { reload: true, injected };
67
+ }
68
+ async function attach(agent: Agent): Promise<void> {
69
+ const { session } = agent;
70
+ if (!belongsToWorld(session, config) || memory.has(session)) return;
71
+ const pending = attaching.get(session);
72
+ if (pending) return pending;
73
+ const job = (async () => {
74
+ if (archived(session.id)) await store.commitRecords([], store.progress(session.id));
75
+ await archive.schedule(session.id);
76
+ memory.set(session, await readMemoryState(session));
77
+ })();
78
+ attaching.set(session, job);
79
+ try { await job; } finally { attaching.delete(session); }
80
+ }
81
+ /** Retires the blocks still on the surface (they must be found, or the session would carry two) and builds a fresh one without the messages already present. */
82
+ async function freshBlock(session: Session, state: MemoryState): Promise<UserMessage | undefined> {
83
+ const messages = session.deriveMessages();
84
+ const turns = await history.loadRecentTurns(config.worldId, memoryTurns(), archivedByScope);
85
+ const present = new Set(messages.filter(message => message.role === 'assistant' || message.source.kind === 'user').map(message => message.id));
86
+ const text = renderHistory(excludePresentMessages(turns, present), config.timeZone, names, config.archiveScope === 'home');
87
+ writeQqMirror(text);
88
+ const oldBlocks = messages.filter(message => message.source.kind === memorySource);
89
+ for (const [index, message] of oldBlocks.entries()) {
90
+ const seq = state.injected.get(message.id);
91
+ if (seq === undefined || !session.surface.nodes.includes(seq)) throw new Error('dsh-world: cannot locate retained injected context in the host surface');
92
+ const replacement = createUserMessage({ content: [{ type: 'text', text: index === 0 ? text : '' }], source: { kind: memorySource, form: 'recall' } });
93
+ session.append('user/message', replacement, { surfaceOp: { op: 'replace', startSeq: seq, endSeq: seq }, sourceEventSeqs: [seq] });
94
+ state.injected.delete(message.id);
95
+ }
96
+ if (oldBlocks.length) return undefined;
97
+ return text ? createUserMessage({ content: [{ type: 'text', text }], source: { kind: memorySource, form: 'recall' } }) : undefined;
98
+ }
99
+
100
+ /**
101
+ * A readable copy of the exact block the QQ conversation receives. Only the QQ-bound session builds a
102
+ * block, so only it writes this file; a failed mirror never disturbs the memory itself.
103
+ */
104
+ function writeQqMirror(text: string): void {
105
+ if (config.scope !== 'qq' || !config.qqMirrorFile || !text) return;
106
+ try {
107
+ mkdirSync(dirname(config.qqMirrorFile), { recursive: true });
108
+ writeFileSync(config.qqMirrorFile, `<!-- dsh-world: QQ 绑定对话的近期记忆 · ${new Date().toISOString()} -->\n\n${text}\n`, 'utf8');
109
+ } catch { /* the mirror is a convenience, never a dependency */ }
110
+ }
111
+
112
+ /** Reads what the first catch-up had to leave, once the host can say which sessions belong to her. */
113
+ async function retryCatchUp(): Promise<void> {
114
+ if (!undecided) return;
115
+ undecided = false;
116
+ await archive.catchUp();
117
+ }
118
+
119
+ /** `fresh`: her world was just started from the console, so what was said while it was stopped is not archived. */
120
+ async function start(options: { fresh?: boolean } = {}): Promise<void> {
121
+ try {
122
+ disposers.push(ctx.on('session/event', (session, event) => {
123
+ if (session.header.origin === 'subagent' || (session.header.delegationDepth ?? 0) > 0 || (!config.archiveScope && !belongsToWorld(session, config))) return;
124
+ const state = memory.get(session);
125
+ const compacted = event.type === 'compaction/end' && event.data.error === undefined;
126
+ if (state && event.type === 'user/message' && event.data.source.kind === memorySource) state.injected.set(event.data.id, event.seq);
127
+ if (state && event.type === 'user/message' && event.data.id === state.pendingId) { state.reload = false; state.pendingId = undefined; }
128
+ if (state && compacted) state.reload = true;
129
+ if (compacted) prompts?.refresh(session);
130
+ if (event.type === 'assistant/message' || event.type === 'turn/end' || event.type === 'turn/start' || event.type === 'compaction/end' || (event.type === 'user/message' && event.data.source.kind === 'user')) void archive.schedule(session.id).catch(() => {});
131
+ }));
132
+ disposers.push(ctx.on('agent/created', async ({ agent }) => { prompts?.add(agent); await attach(agent); return undefined; }));
133
+ // Admitted ahead of the step's new input; the host's own admission order (contexts, time-context last) is kept.
134
+ disposers.push(ctx.on('agent/pre-step', async (payload, next) => {
135
+ const decision = await next();
136
+ const { agent, turn, step, signal } = payload;
137
+ // An empty first step ends the turn; any later step runs anyway, so adding to it is safe.
138
+ if (decision.kind !== 'enter' || (step === 1 && !decision.messages.length) || signal.aborted || !belongsToWorld(agent.session, config)) return decision;
139
+ await attach(agent); await archive.schedule(agent.id); signal.throwIfAborted();
140
+ const state = memory.get(agent.session)!;
141
+ if (!state.reload) return decision;
142
+ const block = await freshBlock(agent.session, state);
143
+ if (!block) { state.reload = false; return decision; }
144
+ state.pendingId = block.id;
145
+ return { ...decision, messages: [block, ...decision.messages] };
146
+ }));
147
+ disposers.push(ctx.on('llm/stream', async function* (request, next) {
148
+ const agent = isAgentLoopRequest(request) && request.sessionId ? ctx.agents.get(request.sessionId) : undefined;
149
+ const owned = agent && belongsToWorld(agent.session, config);
150
+ for await (const chunk of next()) {
151
+ if (owned && chunk.type === 'finish' && chunk.reason.kind === 'error' && chunk.reason.failure.code === 'CONTEXT_WINDOW_EXCEEDED') yield {
152
+ ...chunk, reason: { ...chunk.reason, failure: { ...chunk.reason.failure, message: `dsh-world: 模型总容量不足,完整近期记忆未被裁剪。${chunk.reason.failure.message}` } },
153
+ } satisfies StreamChunk;
154
+ else yield chunk;
155
+ }
156
+ }));
157
+ await archive.catchUp(options.fresh);
158
+ if (options.fresh) for (const agent of ctx.agents.list()) if (belongsToWorld(agent.session, config)) await archive.skip(agent.id);
159
+ for (const agent of ctx.agents.list()) { prompts?.add(agent); await attach(agent); }
160
+ } catch (error) { await stop(); throw error; }
161
+ }
162
+ function stop(): Promise<void> {
163
+ return stopping ??= (async () => {
164
+ prompts?.clear();
165
+ for (const dispose of disposers.splice(0).reverse()) dispose();
166
+ await archive.flush();
167
+ })();
168
+ }
169
+ /** Re-read the selected sessions after the QQ binding changes, so earlier conversations are archived before the next turn. */
170
+ const refreshScope = () => archive.catchUp();
171
+ return { start, retryCatchUp, refreshScope, flush: archive.flush, stop, faults: () => faults.list() };
172
+ }
@@ -0,0 +1,32 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
2
+ import { basename, dirname, extname, join } from 'node:path';
3
+
4
+ /** Characters of her self-description read per session; she is asked to keep it to what matters. */
5
+ export const SELF_CAP = 4000;
6
+
7
+ /**
8
+ * Her 我是谁 file as it goes into `{{self}}`: only what she wrote, tagged so her own headings do not read as
9
+ * sections of the world prompt. What the file is and that she may rewrite it is the template's to say.
10
+ * Empty when she has not written it. Never throws: an unreadable file becomes a short note.
11
+ */
12
+ export function renderSelf(selfFile: string): string {
13
+ let text: string;
14
+ // trim() also drops a leading BOM.
15
+ try { text = existsSync(selfFile) ? readFileSync(selfFile, 'utf8').trim() : ''; }
16
+ catch (error) { return `(这次没能读到我是谁.md:${error instanceof Error ? error.message : String(error)}。它还在,下次会再试。)`; }
17
+ if (!text) return '';
18
+ const chars = Array.from(text);
19
+ const capped = chars.length > SELF_CAP;
20
+ const body = `<我是谁.md>\n${capped ? chars.slice(0, SELF_CAP).join('') : text}\n</我是谁.md>`;
21
+ return capped ? `${body}\n(后面还有 ${chars.length - SELF_CAP} 字没读进来;挑最要紧的留下吧。)` : body;
22
+ }
23
+ /** Keeps her 我是谁 as it is today beside it, in `<name>.history/<day><ext>`, so every change she makes can be seen and undone. Undefined when she has not written one. */
24
+ export function keepSelfCopy(selfFile: string, day: string): string | undefined {
25
+ if (!existsSync(selfFile)) return undefined;
26
+ const ext = extname(selfFile);
27
+ const dir = join(dirname(selfFile), `${basename(selfFile, ext)}.history`);
28
+ mkdirSync(dir, { recursive: true });
29
+ const copy = join(dir, `${day}${ext}`);
30
+ copyFileSync(selfFile, copy);
31
+ return copy;
32
+ }
@@ -0,0 +1,132 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { SessionId, type Session } from '@deepseek-ai/dsh-session';
3
+ import type {} from '@deepseek-ai/dsh-session-persistence';
4
+ import { extractConversationRecords } from './archive.ts';
5
+ import type { ArchiveStore } from './store.ts';
6
+ import type { WorldConfig } from './types.ts';
7
+ import { inQqScope, isQqCurrent } from './qqScope.ts';
8
+ import { wechatDeliveryPatch } from './ecosystem/wechat/archive.ts';
9
+
10
+ const pageSize = 128;
11
+ /**
12
+ * A session log the host itself cannot read (a compaction cut off mid-write, a half-flushed turn). It is not
13
+ * our bug and it never fixes itself, so retrying adds nothing — one broken conversation must not cost her the
14
+ * whole world: flushed and thrown, it fails the plugin's load and every session loses its memory block.
15
+ */
16
+ export function isCorruptSessionLog(error: unknown): boolean {
17
+ const text = error instanceof Error ? `${error.name} ${error.message}` : String(error ?? '');
18
+ return /stored log is corrupt|SessionFormatError|does not match an open turn/i.test(text);
19
+ }
20
+ export function belongsToWorld(session: Pick<Session, 'header'>, config: WorldConfig): boolean {
21
+ const header = session.header;
22
+ if (header.origin === 'subagent' || (header.delegationDepth ?? 0) > 0) return false;
23
+ if (config.scope === 'qq') return isQqCurrent(header.id, config.qqSessionsFile);
24
+ return header.agentPreset === config.agentPreset;
25
+ }
26
+ const isNotFound = (error: unknown) => error instanceof Error && error.name === 'SessionPersistenceNotFoundError';
27
+ const ordinary =(header: Session['header']) => header.origin !== 'subagent' && (header.delegationDepth ?? 0) === 0;
28
+
29
+ /**
30
+ * Copies her conversations from the host's session logs into the archive. Each session is replayed from where
31
+ * the archive left off; replays run one at a time, and a session already queued is not queued twice. Sessions
32
+ * outside `archived` are left alone.
33
+ */
34
+ export function createSourceArchive(ctx: Context, config: WorldConfig, store: ArchiveStore, archived: (sessionId: string) => boolean = () => true) {
35
+ const dirty = new Set<string>();
36
+ const jobs = new Map<string, Promise<void>>();
37
+ const failures = new Map<string, unknown>();
38
+ let tail = Promise.resolve();
39
+
40
+ /** Copies what the archive has not seen yet; `skip` moves past it without keeping it. */
41
+ async function replay(sessionId: string, skip = false): Promise<void> {
42
+ const id = SessionId(sessionId);
43
+ const live = ctx.sessions.get(id);
44
+ if (live) await ctx.sessions.flush(live);
45
+ // A deleted session keeps what it already archived; there is nothing left to replay.
46
+ const handle = await ctx.sessionPersistence.open(id, 'read').catch(error => {
47
+ if (isNotFound(error)) { ctx.logger.warn(`dsh-world: session ${sessionId} is no longer stored; skipping replay`); store.forgetProgress(sessionId); return undefined; }
48
+ throw error;
49
+ });
50
+ if (!handle) return;
51
+ try {
52
+ let { nextSeq, turn } = store.progress(id);
53
+ while (true) {
54
+ const { events } = await handle.read(nextSeq, pageSize);
55
+ if (!events.length) break;
56
+ const records = events.flatMap(event => {
57
+ if (event.type === 'turn/start') turn = event.data.turn;
58
+ return skip ? [] : extractConversationRecords(event, { ...config, header: handle.header, inheritedEventCount: handle.inheritedEventCount, turn }).map(record => {
59
+ const delivery = record.wechatDelivery ? store.delivery(record.recordId) : undefined;
60
+ return delivery ? { ...record, ...wechatDeliveryPatch(record, delivery) } : record;
61
+ });
62
+ });
63
+ nextSeq = events.at(-1)!.seq + 1;
64
+ await store.commitRecords(records, { sessionId: id, nextSeq, turn });
65
+ }
66
+ } finally { await handle.close(); }
67
+ }
68
+ /** Runs after every queued replay. */
69
+ function enqueue(work: () => Promise<void>): Promise<void> {
70
+ const job = tail.then(work);
71
+ tail = job.catch(error => { ctx.logger.error(error); });
72
+ return job;
73
+ }
74
+ function schedule(sessionId: string): Promise<void> {
75
+ // Not archived itself, it still waits for the replays already queued, so its memory block is current.
76
+ if (!archived(sessionId)) return tail;
77
+ dirty.add(sessionId);
78
+ const pending = jobs.get(sessionId);
79
+ if (pending) return pending;
80
+ const job = tail.then(async () => {
81
+ while (dirty.delete(sessionId)) await replay(sessionId);
82
+ failures.delete(sessionId);
83
+ });
84
+ jobs.set(sessionId, job);
85
+ tail = job.catch(error => {
86
+ // Skips and a warning instead of a stored failure — see `isCorruptSessionLog`.
87
+ if (isCorruptSessionLog(error)) { dirty.delete(sessionId); ctx.logger.warn(`dsh-world: 会话 ${sessionId} 的日志读不动,先跳过(这段对话不归档)`); return; }
88
+ failures.set(sessionId, error); ctx.logger.error(error);
89
+ }).finally(() => { jobs.delete(sessionId); });
90
+ return job;
91
+ }
92
+ return {
93
+ schedule,
94
+ /**
95
+ * Every session the archive has seen, replayed again so nothing written while the plugin was not loaded is
96
+ * missed; with `skip`, what was said while her world was stopped is passed over instead.
97
+ */
98
+ async catchUp(skip = false): Promise<void> {
99
+ // One session's failure is kept for flush(); it must not stop the sessions after it.
100
+ const replayOne = (id: string) => (skip ? enqueue(() => replay(id, true)) : schedule(id)).catch(() => {});
101
+ // The host exposes a metadata inventory; every selected message log is still read in pages.
102
+ const snapshots = await ctx.sessionPersistence.list();
103
+ const visited = new Set<string>();
104
+ for (let offset = 0; offset < snapshots.length; offset += pageSize) {
105
+ for (const { header } of snapshots.slice(offset, offset + pageSize)) {
106
+ if (!ordinary(header) || (!config.archiveScope && header.agentPreset !== config.agentPreset) || !archived(header.id)) continue;
107
+ visited.add(header.id);
108
+ await replayOne(header.id);
109
+ }
110
+ }
111
+ let after = '';
112
+ for (let ids = store.sourcePage(after); ids.length; ids = store.sourcePage(after)) {
113
+ for (const id of ids) {
114
+ after = id;
115
+ if (visited.has(id)) continue;
116
+ // A session deleted from the host (not merely archived there) keeps its records but has nothing left to resume.
117
+ if (!await ctx.sessionPersistence.stat(SessionId(id))) { store.forgetProgress(id); continue; }
118
+ if (!archived(id)) continue;
119
+ await replayOne(id);
120
+ }
121
+ }
122
+ },
123
+ /** Moves past everything a session holds now without keeping it (said while her world was stopped). */
124
+ skip: (sessionId: string) => enqueue(() => replay(sessionId, true)),
125
+ /** Waits for every queued replay; rejects while any session still has an unresolved failure. */
126
+ async flush(): Promise<void> {
127
+ let current: Promise<void>;
128
+ do { current = tail; await current; } while (current !== tail);
129
+ if (failures.size) throw new AggregateError([...failures.values()], 'dsh-world: source archive has unresolved failures');
130
+ },
131
+ };
132
+ }