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,286 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import type { Context } from '@deepseek-ai/cordis';
4
+ import z from '@deepseek-ai/schemastery';
5
+ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths';
6
+ import { createBridge, type Bridge } from './ecosystem/bridge/bridge.ts';
7
+ import { bridgeRoute } from './ecosystem/bridge/route.ts';
8
+ import { consoleRoute, type ConsoleActions } from './console/routes.ts';
9
+ import { consoleSources } from './console/snapshot.ts';
10
+ import { errorText, Faults } from './faults.ts';
11
+ import { hostLife } from './life/host.ts';
12
+ import { createLifeStore, durableWrite } from './life/lifeStore.ts';
13
+ import { toastSupported, windowsToast, type Notifier } from './life/notify.ts';
14
+ import { createLifeRuntime, type LifeRuntime } from './life/runtime.ts';
15
+ import type { LifeOptions } from './life/types.ts';
16
+ import { createOutlet } from './ecosystem/shared/outlets.ts';
17
+ import { readPersona, writePersona } from './persona.ts';
18
+ import { createQqBridge, syncBridgeSessionMode, type QqBridge } from './ecosystem/qq/bridge.ts';
19
+ import { createQqSupervisor } from './ecosystem/qq/supervisor.ts';
20
+ import { qqRoute } from './ecosystem/qq/route.ts';
21
+ import { createConsoleDoors } from './ecosystem/qq/panel.ts';
22
+ import { createWorldRuntime } from './runtime.ts';
23
+ import { createArchiveStore } from './store.ts';
24
+ import type { WorldConfig } from './types.ts';
25
+ import { DEFAULT_TEMPLATE_FILE, roomTitle, worldNames } from './worldPrompt.ts';
26
+ import { createWorldSwitch } from './worldSwitch.ts';
27
+ import { createWechatModule, type WechatModule } from './ecosystem/wechat/index.ts';
28
+ import { createWechatRecorder } from './ecosystem/wechat/archive.ts';
29
+ import { createAdapterSupervisor, type AdapterSupervisor } from './ecosystem/wechat/supervisor.ts';
30
+ import { createChannelSessions } from './ecosystem/shared/sessions.ts';
31
+ import { createArchiveSelection } from './archiveSelection.ts';
32
+ import { belongsToWorld } from './sourceArchive.ts';
33
+
34
+ export { createWorldRuntime } from './runtime.ts';
35
+ export type { WorldConfig, ConversationRecord, ConversationTurn, ArchiveCursor } from './types.ts';
36
+ export const name = 'dsh-world';
37
+ export const inject = ['agents', 'sessions', 'sessionPersistence', 'llm'];
38
+ /** What `apply` receives: the schema below fills these defaults. */
39
+ export type Config = WorldConfig & Required<Pick<WorldConfig, 'life' | 'fallbackWakeTime' | 'outlets' | 'bridge' | 'toast' | 'allowedHosts' | 'qqBridgeDir' | 'qqBridgePort' | 'qqBridgeAutoStart' | 'qqBridgeBindHomeSession'>>;
40
+ // One companion per profile is the usual case, so it works as installed: the standard preset, a world named
41
+ // default and the system time zone, with the life line on (it needs the desktop host's services and stays off without them).
42
+ const systemTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
43
+ export const Config = z.object({
44
+ worldId: z.string().default('default'), agentPreset: z.string().default('standard'), timeZone: z.string().default(systemTimeZone),
45
+ // `world` = upstream behavior (host preset); `qq` = only the conversations dsh-agent-md binds to the
46
+ // QQ gateway read and write this world's memory.
47
+ scope: z.union([z.const('world'), z.const('qq')]).default('world'),
48
+ qqSessionsFile: z.string().default(''),
49
+ qqMirrorFile: z.string().default(''),
50
+ companionName: z.string(), partnerName: z.string(),
51
+ archiveScope: z.union([z.const('home').description('仅家会话'), z.const('workspace').description('家所在工作区'), z.transform(z.const('world').hidden(), () => 'workspace' as const).hidden()]).default('workspace').description('记忆归档范围,修改后重启生效'),
52
+ life: z.boolean().default(true), diaryDir: z.string(), fallbackWakeTime: z.string().pattern(/^([01]\d|2[0-3]):[0-5]\d$/).default('09:00'),
53
+ selfFile: z.string(), worldPromptFile: z.string(), alarmTemplateFile: z.string(), personaFile: z.string(),
54
+ // Where her words go outside DSH; no app is known by name (see README for the push body).
55
+ outlets: z.array(z.object({ name: z.string().required(), url: z.string(), urlFile: z.string(), path: z.string(), kinds: z.array(z.union([z.const('reply'), z.const('busy'), z.const('reach')])) })).default([]),
56
+ // A local app may hand her partner's words to her home through POST /dsh-world/bridge/say.
57
+ bridge: z.boolean().default(false),
58
+ wechat: z.boolean().default(false),
59
+ wechatAdapter: z.object({ python: z.string(), config: z.string() }).description('随微信模块启动和停止 Windows 适配器;写上即视为允许它发送消息'),
60
+ toast: z.boolean().default(true),
61
+ // The console and the bridge answer only this machine by name, plus these (a LAN address or domain behind a proxy).
62
+ allowedHosts: z.array(z.string()).default([]),
63
+ // QQ: her home is reachable from outside DSH through a separate `qq-bridge` process. Empty qqBridgeDir leaves
64
+ // this whole module off; the bridge is started by hand from the console unless qqBridgeAutoStart says otherwise.
65
+ qqBridgeDir: z.string().default(''), qqBridgePort: z.number().default(3100), qqBridgeNode: z.string(),
66
+ qqBridgeAutoStart: z.boolean().default(false),
67
+ // 谁和谁共用一个会话。空着就不碰桥的 config.json(尊重人自己填的);'owner' 让每个群各自一份会话、
68
+ // 只有主人私聊用她的家会话——这是装上之后最想要的那个,人在插件配置里说一次就够了。
69
+ qqBridgeBindHomeSession: z.union([z.const('owner').description('群各自独立,主人私聊用她的家会话'), z.const('all').description('所有入口都用她的家会话'), z.const('none').description('谁都不绑,每个入口各建一个'), z.const('')]).default(''),
70
+ });
71
+ interface WebServer { register(route: ReturnType<typeof consoleRoute> | ReturnType<typeof bridgeRoute> | ReturnType<typeof qqRoute>): () => void }
72
+
73
+ /**
74
+ * Her world runs only after her partner presses start in the world console, and stops when they press stop:
75
+ * memory block, persona, world prompt, archive and life line come and go together. The switch is kept in
76
+ * `<world>/world.json`, so it outlasts a restart.
77
+ */
78
+ export async function apply(ctx: Context, config: Config): Promise<void> {
79
+ const dshHome = resolveDshHome();
80
+ const worldDir = join(dshHome, 'worlds', config.worldId);
81
+ const store = createArchiveStore({ ...config, root: dshHome });
82
+ const power = createWorldSwitch(worldDir, config.archiveScope ?? 'workspace');
83
+ const qqSessionsFile = config.qqSessionsFile || join(dshHome, 'agents', 'qq-memory.json');
84
+ const qqMirrorFile = config.qqMirrorFile || join(dshHome, 'agents', 'qq-memory.md');
85
+ const memoryConfig = { ...config, archiveScope: power.archiveScope(), qqSessionsFile, qqMirrorFile };
86
+ const faults = new Faults();
87
+ // Her self-description lives in her room whether or not the life line runs; she writes it with her file tools.
88
+ const selfFile = config.selfFile || join(worldDir, 'room', '我是谁.md');
89
+ const personaFile = config.personaFile || join(worldDir, 'persona.md');
90
+ const worldPromptFile = config.worldPromptFile || join(worldDir, 'world-prompt.md');
91
+ // In QQ scope the persona lives in the 人格 page (dsh-agent-md). The shipped world prompt would add a
92
+ // second, conflicting identity ("digital life with full access"), so a fresh world starts with it empty.
93
+ if (config.scope === 'qq') {
94
+ try {
95
+ mkdirSync(dirname(worldPromptFile), { recursive: true });
96
+ if (!existsSync(worldPromptFile)) writeFileSync(worldPromptFile, '', 'utf8');
97
+ } catch { /* the console can still edit it */ }
98
+ }
99
+ const options: LifeOptions = { worldDir, roomDir: join(worldDir, 'room'), diaryDir: config.diaryDir || join(worldDir, 'diary'), selfFile, fallbackWakeTime: config.fallbackWakeTime, timeZone: config.timeZone, alarmFile: config.alarmTemplateFile || join(worldDir, 'alarm.md') };
100
+ /** The name in her persona comes first, then the configured one. */
101
+ const names = () => worldNames({ ...config, companionName: readPersona(personaFile).名字 || config.companionName });
102
+ const lifeStore = (() => {
103
+ if (!config.life) return undefined;
104
+ try { const current = createLifeStore(worldDir, config.timeZone); current.read(); return current; }
105
+ catch (error) { faults.set('life', `生活线没能启动:${errorText(error)}`); ctx.logger.error(error); return undefined; }
106
+ })();
107
+ const storedHome = () => lifeStore?.read().homeSessionId;
108
+ let isHome: (sessionId: string) => boolean = id => id === storedHome();
109
+ const includesSession = createArchiveSelection(ctx, power.archiveScope(), id => isHome(id), options.roomDir, {
110
+ scope: config.scope,
111
+ sessionsFile: qqSessionsFile,
112
+ });
113
+
114
+ let memory: ReturnType<typeof createWorldRuntime> | undefined;
115
+ let stopLifeLine: (() => Promise<void>) | undefined;
116
+ async function startMemory(fresh: boolean): Promise<void> {
117
+ if (memory) return;
118
+ const prompt = { file: worldPromptFile, persona: personaFile, conversationsDir: join(worldDir, 'conversations'), names: names(), ...(config.life ? { life: options } : {}) };
119
+ memory = createWorldRuntime(ctx, { ...memoryConfig, selfFile }, store, { prompt, isHome: id => isHome(id), archiveSession: includesSession }, power.memoryTurns);
120
+ await memory.start({ fresh });
121
+ }
122
+ async function stopMemory(): Promise<void> {
123
+ const running = memory; memory = undefined;
124
+ await running?.stop();
125
+ }
126
+ ctx.effect(() => async () => {
127
+ if (scopeWatch) clearInterval(scopeWatch);
128
+ try { await stopLifeLine?.(); }
129
+ finally { await stopMemory().finally(() => store.close()); }
130
+ }, 'dsh-world memory line');
131
+ if (power.running()) await startMemory(false);
132
+ // QQ scope follows a file dsh-agent-md writes on every bind. When it changes, replay the newly selected
133
+ // conversations (the current one and its predecessors) so the next turn already sees the earlier history.
134
+ let scopeWatch: ReturnType<typeof setInterval> | undefined;
135
+ if (config.scope === 'qq') {
136
+ let lastMtime = -1;
137
+ const tick = (): void => {
138
+ let mtime = -1;
139
+ try { mtime = statSync(qqSessionsFile).mtimeMs; } catch { /* not bound yet */ }
140
+ if (mtime === lastMtime) return;
141
+ lastMtime = mtime;
142
+ void memory?.refreshScope().catch(error => ctx.logger.warn(error));
143
+ };
144
+ tick();
145
+ scopeWatch = setInterval(tick, 3000);
146
+ scopeWatch.unref?.();
147
+ }
148
+ // The host's workspace service may come up after this plugin; what the first catch-up could not place is read then.
149
+ ctx.inject(['workspaceRegistry'], injected => { void memory?.retryCatchUp().catch(error => injected.logger.error(error)); });
150
+
151
+ // The console and the life line need the desktop host.
152
+ ctx.inject(['sessionController', 'permissionPresets', 'webServer'], async lifeCtx => {
153
+ const webServer = (lifeCtx as unknown as { webServer: WebServer }).webServer;
154
+ const host = hostLife(lifeCtx);
155
+ // QQ: one more door into her home, managed here rather than by a launcher script. The endpoint is aligned
156
+ // on every start whether or not the bridge runs — DSH picks a new port each restart, and a stale baseUrl
157
+ // looks exactly like a dead bridge (a dead event stream, no error, for hours). The console switch starts
158
+ // and stops this management at any time; it does not stop a bridge that is already running.
159
+ let qq: QqBridge | undefined;
160
+ let qqSupervisor: ReturnType<typeof createQqSupervisor> | undefined;
161
+ let unregisterQq: (() => void) | undefined;
162
+ function startQq(): void {
163
+ if (qq || !config.qqBridgeDir || !power.qqEnabled()) return;
164
+ const service = createQqBridge({ dir: config.qqBridgeDir, port: config.qqBridgePort, nodePath: config.qqBridgeNode || process.execPath, origin: () => host.origin(), logger: lifeCtx.logger });
165
+ qq = service;
166
+ // 会话绑定先写:桥是启动时才读 config.json 的,这条必须在 ensureRunning/syncEndpoint 之前。
167
+ syncBridgeSessionMode(config.qqBridgeDir, config.qqBridgeBindHomeSession, lifeCtx.logger);
168
+ // 两个控制台的门:qq-bridge 的令牌是文件,SnowLuma 的会话令牌得用面板密码现换。
169
+ const doors = createConsoleDoors({ worldDir, bridgeDir: config.qqBridgeDir, port: config.qqBridgePort });
170
+ unregisterQq = webServer.register(qqRoute(service, config.allowedHosts, doors));
171
+ void (config.qqBridgeAutoStart ? service.ensureRunning() : service.syncEndpoint()).catch(error => lifeCtx.logger.warn(error));
172
+ // QQ 巡检:桥是独立进程,崩了、被结束、连不上 DSH 都不会有人知道——上一版只有启动时那一次
173
+ // ensureRunning,之后再无人过问。2026-10-26 那条链路死了四个小时,就是这么来的。
174
+ // 这里只负责「什么时候该拉」,怎么拉仍然是 bridge.ts 的事。
175
+ qqSupervisor = createQqSupervisor({ dir: config.qqBridgeDir, port: config.qqBridgePort, bridge: service, logger: lifeCtx.logger });
176
+ qqSupervisor.start();
177
+ }
178
+ function stopQq(): void {
179
+ qqSupervisor?.stop(); qqSupervisor = undefined;
180
+ unregisterQq?.(); unregisterQq = undefined;
181
+ qq = undefined;
182
+ }
183
+ startQq();
184
+ lifeCtx.effect(() => () => stopQq(), 'dsh-world qq');
185
+ let life: LifeRuntime | undefined;
186
+ let bridge: Bridge | undefined;
187
+ let wechat: WechatModule | undefined;
188
+ let adapter: AdapterSupervisor | undefined;
189
+ let channels: ReturnType<typeof createChannelSessions> | undefined;
190
+ let unregisterWechat: (() => void) | undefined;
191
+ let lifeStop: Promise<void> | undefined;
192
+ let wechatClosing: Promise<void> = Promise.resolve();
193
+ /** Starts the WeChat module (its tools, route and, when configured, the adapter) against the running life line. */
194
+ async function startWechat(current: LifeRuntime): Promise<void> {
195
+ if (wechat || !config.wechat) return;
196
+ await wechatClosing;
197
+ const groupSessions = createChannelSessions({ ctx: lifeCtx, host, store, roomDir: options.roomDir, roomTitle: roomTitle(names()), agentPreset: config.agentPreset });
198
+ channels = groupSessions;
199
+ wechat = createWechatModule({ ctx: lifeCtx, worldId: config.worldId, acceptAgent: agent => belongsToWorld(agent.session, config), home: identity => identity.conversationType === 'group' ? groupSessions.open(identity) : current.home(), origin: () => host.origin(), file: join(worldDir, 'wechat.json'), incomingDir: join(worldDir, 'wechat-incoming'), allowedHosts: config.allowedHosts, settings: () => ({ contextMessages: power.wechatContext(), bufferSeconds: power.wechatBufferSeconds() }),
200
+ ...createWechatRecorder(store, config.worldId, includesSession) });
201
+ wechat.start(); unregisterWechat = webServer.register(wechat.route);
202
+ if (config.wechatAdapter?.python && config.wechatAdapter.config) { adapter = createAdapterSupervisor({ python: config.wechatAdapter.python, config: config.wechatAdapter.config, logFile: join(worldDir, 'wechat-adapter.log'), log: message => lifeCtx.logger.warn(message) }); adapter.start(); }
203
+ }
204
+ /** Takes the WeChat tools, route and adapter down; the adapter goes first because it exits when the module's connection file disappears. */
205
+ function stopWechat(): Promise<void> {
206
+ unregisterWechat?.(); unregisterWechat = undefined;
207
+ const closingAdapter = adapter?.stop(); adapter = undefined;
208
+ const closing = Promise.all([closingAdapter, wechat?.stop()]).then(() => {}); wechat = undefined;
209
+ channels?.stop(); channels = undefined;
210
+ return wechatClosing = closing;
211
+ }
212
+ async function startLife(resumed: boolean): Promise<void> {
213
+ if (!lifeStore || life) return;
214
+ try {
215
+ await lifeStop;
216
+ const outlets = config.outlets.map(outlet => createOutlet(outlet, () => host.origin()));
217
+ const notifier: Notifier = { ...(config.toast && toastSupported() ? { toast: windowsToast() } : {}), outlets };
218
+ const current = createLifeRuntime({ ctx: lifeCtx, config: { ...config, companionName: names().companion }, options, store: lifeStore, host, notifier, dailyBudget: power.dailyBudget });
219
+ life = current; isHome = current.isHome;
220
+ if (config.bridge) { bridge = createBridge({ ctx: lifeCtx, home: () => current.home(), outlets, origin: () => host.origin(), file: join(worldDir, 'bridge.json'), name: names().companion }); bridge.start(); }
221
+ if (config.wechat && power.wechatEnabled()) await startWechat(current);
222
+ faults.clear('life');
223
+ await current.start({ resumed });
224
+ } catch (error) {
225
+ // The console still opens and says why, instead of looking as if the life line were simply off.
226
+ await stopLife();
227
+ faults.set('life', `生活线没能启动:${errorText(error)}`); lifeCtx.logger.error(error);
228
+ }
229
+ }
230
+ function stopLife(): Promise<void> {
231
+ isHome = id => id === storedHome();
232
+ bridge?.stop(); life?.stop();
233
+ const closingWechat = stopWechat();
234
+ bridge = undefined; life = undefined;
235
+ return lifeStop = Promise.all([lifeStop, closingWechat]).then(() => {});
236
+ }
237
+ stopLifeLine = stopLife;
238
+ lifeCtx.effect(() => () => stopLife(), 'dsh-world life line');
239
+ // The host matches exact routes before the longest prefix, so this path never reaches the console.
240
+ if (config.bridge) lifeCtx.effect(() => webServer.register(bridgeRoute(() => bridge, config.allowedHosts)), 'dsh-world bridge route');
241
+
242
+ // Her album lives in her room, so the console shows it whether or not the life line is running.
243
+ const sources = consoleSources({ ctx: lifeCtx, config: memoryConfig, archive: store, names, ...(lifeStore ? { lifeStore } : {}), life: () => life, diaryDir: options.diaryDir, running: power.running, dailyBudget: power.dailyBudget, memoryTurns: power.memoryTurns, selectedArchiveScope: power.selectedArchiveScope, wechat: () => wechat ? { ...wechat.status(), adapter: adapter?.status() ?? null } : undefined, includesSession, ...(config.qqBridgeDir ? { qq: async () => qq ? { ...(await qq.status()), ...(qqSupervisor ? { supervisor: qqSupervisor.snapshot() } : {}) } : null } : {}),
244
+ modules: () => ({ wechat: { available: config.wechat, enabled: power.wechatEnabled(), running: wechat !== undefined }, qq: { available: Boolean(config.qqBridgeDir), enabled: power.qqEnabled(), running: qq !== undefined } }), faults: () => [...faults.list(), ...(memory?.faults() ?? []), ...(bridge?.faults() ?? []), ...(qq?.faults() ?? [])] });
245
+ const actions: ConsoleActions = {
246
+ async start() {
247
+ if (power.running()) return;
248
+ power.set(true);
249
+ try { await startMemory(true); await startLife(true); } finally { sources.invalidate(); }
250
+ },
251
+ async stop() {
252
+ if (!power.running()) return;
253
+ power.set(false);
254
+ await stopLife();
255
+ try { await stopMemory(); } finally { sources.invalidate(); }
256
+ },
257
+ prompts: () => ({
258
+ persona: readPersona(personaFile),
259
+ worldPrompt: existsSync(worldPromptFile) ? { text: readFileSync(worldPromptFile, 'utf8'), custom: true } : { text: readFileSync(DEFAULT_TEMPLATE_FILE, 'utf8'), custom: false },
260
+ }),
261
+ savePersona: persona => { writePersona(personaFile, { ...readPersona(personaFile), ...persona }); sources.invalidate(); },
262
+ setDailyBudget: yuan => { power.setDailyBudget(yuan); sources.invalidate(); },
263
+ setMemoryTurns: turns => { power.setMemoryTurns(turns); sources.invalidate(); },
264
+ async setModules(patch) {
265
+ if (patch.wechat !== undefined && !config.wechat) return '没有配置微信模块(配置里 wechat: true)';
266
+ if (patch.qq !== undefined && !config.qqBridgeDir) return '没有配置 QQ 桥目录(配置里 qqBridgeDir)';
267
+ power.setModules(patch);
268
+ try {
269
+ if (patch.wechat === false) await stopWechat();
270
+ if (patch.wechat === true && life) await startWechat(life);
271
+ if (patch.qq === false) stopQq();
272
+ if (patch.qq === true) startQq();
273
+ } catch (error) { faults.set('wechat', `微信模块没能切换:${errorText(error)}`); lifeCtx.logger.error(error); return `切换失败:${errorText(error)}`; }
274
+ finally { sources.invalidate(); }
275
+ faults.clear('wechat');
276
+ return undefined;
277
+ },
278
+ restartWechatAdapter: async () => { if (!adapter) return false; try { await adapter.restart(); } finally { sources.invalidate(); } return true; },
279
+ setWechatSettings: next => { power.setWechat(next); sources.invalidate(); },
280
+ setArchiveScope: scope => { power.setArchiveScope(scope); sources.invalidate(); return power.restartRequired(); },
281
+ saveWorldPrompt: text => { if (text.trim()) durableWrite(worldPromptFile, text); else rmSync(worldPromptFile, { force: true }); },
282
+ };
283
+ lifeCtx.effect(() => webServer.register(consoleRoute(sources, actions, config.allowedHosts)), 'dsh-world console routes');
284
+ if (power.running()) await startLife(false);
285
+ });
286
+ }
@@ -0,0 +1,48 @@
1
+ import { isAbsolute, relative, resolve } from 'node:path';
2
+ import type { ActivityRecord } from './types.ts';
3
+
4
+ const shells = new Set(['pwsh', 'bash', 'powershell', 'shell']);
5
+ const pathKeys = new Set(['path', 'file_path', 'filePath', 'paths', 'cwd', 'directory', 'dir', 'target', 'source', 'destination', 'root', 'folder']);
6
+ const clip = (text: string) => Array.from(text.replace(/\s+/g, ' ').trim()).slice(0, 160).join('');
7
+
8
+ /** Path strings under pathKeys at any depth, so nested operation arrays are covered. */
9
+ function collectPaths(value: unknown, keyed: boolean, out: string[]): string[] {
10
+ if (typeof value === 'string') { if (keyed) out.push(value); }
11
+ else if (Array.isArray(value)) for (const item of value) collectPaths(item, keyed, out);
12
+ else if (value && typeof value === 'object') for (const [key, item] of Object.entries(value)) collectPaths(item, keyed || pathKeys.has(key), out);
13
+ return out;
14
+ }
15
+
16
+ /** Shell commands cannot be reliably scoped, so they always count as outside the room. The path check is lexical: symlinks/junctions, `~` and `%VAR%` are not resolved. */
17
+ export function summarizeCall(tool: string, argumentsJson: string, roomDir: string): { summary: string; outside: boolean } {
18
+ let parsed: unknown;
19
+ try { parsed = JSON.parse(argumentsJson); } catch { parsed = undefined; }
20
+ const args = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {};
21
+ if (shells.has(tool.toLowerCase())) return { summary: clip(typeof args.command === 'string' ? args.command : argumentsJson), outside: true };
22
+ const paths = collectPaths(args, false, []);
23
+ const inside = (path: string) => { const rel = relative(roomDir, resolve(roomDir, path)); return rel === '' || (!/^\.\.(?:[\\/]|$)/.test(rel) && !isAbsolute(rel)); };
24
+ return { summary: clip(paths.length ? paths.join(', ') : argumentsJson), outside: paths.some(path => !inside(path)) };
25
+ }
26
+
27
+ /**
28
+ * What she actually did between `since` and `now`, in one line she can hold against the note she wrote.
29
+ *
30
+ * She asked for this (2026-10-26): an alarm that only repeats her own promise lets her believe she kept
31
+ * it. Counting her calls and naming the last thing she touched turns "歇着" into a claim that can fail.
32
+ * Empty string means "nothing to say" — the caller drops the sentence rather than print an empty one.
33
+ */
34
+ export function summarizeSince(records: readonly ActivityRecord[], sinceIso: string, now: Date): string {
35
+ const from = Date.parse(sinceIso);
36
+ const until = now.getTime();
37
+ if (!Number.isFinite(from)) return '';
38
+ const mine = records.filter(record => {
39
+ const at = Date.parse(record.time);
40
+ return Number.isFinite(at) && at >= from && at <= until;
41
+ });
42
+ if (!mine.length) return '这段时间我没动过手。';
43
+ const tools = [...new Set(mine.map(record => record.tool))];
44
+ const shown = tools.slice(0, 3).join('、') + (tools.length > 3 ? ` 等 ${tools.length} 种` : '');
45
+ const last = mine[mine.length - 1]!;
46
+ const touched = Array.from(last.summary).slice(0, 40).join('').trim();
47
+ return `这段时间我动了 ${mine.length} 次手(${shown})${touched ? `,最后一次是:${touched}` : ''}。`;
48
+ }
@@ -0,0 +1,119 @@
1
+ import { formatLocalTime } from '../timeContext.ts';
2
+ import type { Alarm, Review } from './types.ts';
3
+ import { ALARM_MARK, exampleTime, fillMessage, readAlarmMessages, type AlarmMessages } from './messages.ts';
4
+
5
+ const MIN_ALARM_MS = 60_000;
6
+ const LATE_NOTICE_MS = 2 * 60_000;
7
+ /** Every evening at this local time she looks back on the day. */
8
+ export const REVIEW_TIME = '23:00';
9
+
10
+ export function resolveAlarmTime(input: { at?: string; after_minutes?: number }, now: Date, timeZone = 'UTC'): Date {
11
+ if ((input.at === undefined) === (input.after_minutes === undefined)) throw new Error('请只给 at 或 after_minutes 其中一个');
12
+ let target: Date;
13
+ if (input.at !== undefined) {
14
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/.test(input.at)) throw new Error(`at 需要 ISO 8601 格式并带时区,例如 ${exampleTime(timeZone)}`);
15
+ target = new Date(input.at);
16
+ } else {
17
+ const minutes = input.after_minutes!;
18
+ if (!Number.isFinite(minutes) || minutes <= 0) throw new Error('after_minutes 必须是正数');
19
+ target = new Date(now.getTime() + minutes * 60_000);
20
+ }
21
+ if (!Number.isFinite(target.getTime())) throw new Error(`无法识别的时间:${input.at ?? input.after_minutes}`);
22
+ if (target.getTime() - now.getTime() < MIN_ALARM_MS) throw new Error('闹钟至少要定在 1 分钟之后');
23
+ return target;
24
+ }
25
+ const offsetMs = (at: number, timeZone: string) => {
26
+ const m = /([+-])(\d{2}):(\d{2})$/.exec(formatLocalTime(new Date(at), timeZone))!;
27
+ return (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])) * 60_000;
28
+ };
29
+ /** The first instant strictly after `now` whose local time in `timeZone` is hhmm:00; a time skipped by a DST gap lands on the first instant after the gap. */
30
+ export function nextLocalTime(now: Date, hhmm: string, timeZone: string): Date {
31
+ const [hour, minute] = hhmm.split(':').map(Number) as [number, number];
32
+ const today = formatLocalTime(now, timeZone);
33
+ const [y, mo, d] = [Number(today.slice(0, 4)), Number(today.slice(5, 7)), Number(today.slice(8, 10))];
34
+ for (let k = 0; k < 3; k++) {
35
+ const wall = Date.UTC(y, mo - 1, d + k, hour, minute);
36
+ const date = new Date(wall).toISOString().slice(0, 10);
37
+ const want = `${date}T${hhmm}:00`;
38
+ const around = [offsetMs(wall - 86_400_000, timeZone), offsetMs(wall + 86_400_000, timeZone)];
39
+ const hits = [...new Set(around)].map(offset => wall - offset).filter(at => formatLocalTime(new Date(at), timeZone).slice(0, 19) === want);
40
+ let at = hits.length ? Math.min(...hits.filter(h => h > now.getTime()), Infinity) : NaN;
41
+ if (!hits.length) {
42
+ // Skipped by a gap: the first instant from which the local clock reads at least the wanted time.
43
+ let [lo, hi] = [wall - Math.max(...around), wall - Math.min(...around)].sort((a, b) => a - b) as [number, number];
44
+ while (hi - lo > 1) { const mid = Math.floor((lo + hi) / 2); if (formatLocalTime(new Date(mid), timeZone).slice(0, 19) >= want) hi = mid; else lo = mid; }
45
+ at = hi;
46
+ }
47
+ if (at > now.getTime() && Number.isFinite(at)) return new Date(at);
48
+ }
49
+ throw new Error(`找不到 ${hhmm} 之后的下一个时间`);
50
+ }
51
+ export function formatDuration(ms: number): string {
52
+ const minutes = Math.max(0, Math.round(ms / 60_000));
53
+ const days = Math.floor(minutes / 1440); const hours = Math.floor((minutes % 1440) / 60); const rest = minutes % 60;
54
+ const parts = [days ? `${days} 天` : '', hours ? `${hours} 小时` : '', rest || (!days && !hours) ? `${rest} 分` : ''];
55
+ return parts.filter(Boolean).join(' ');
56
+ }
57
+ /**
58
+ * What she hears when an alarm rings. The wording comes from the alarm template (`extra` carries her
59
+ * names for templates that use them, plus `did` — one line about what she actually did since she set the
60
+ * alarm, so the promise and the record arrive together); the 【我的时间】 mark is always the plugin's own.
61
+ */
62
+ export function wakeText(alarm: Alarm, now: Date, timeZone: string, fallbackWakeTime: string, messages: AlarmMessages = readAlarmMessages(undefined), extra: Record<string, string> = {}): string {
63
+ const base = { ...extra, timeZone, fallbackWakeTime };
64
+ const lateText = lateNotice(now.getTime() - Date.parse(alarm.at), messages, base);
65
+ const body = alarm.source === 'fallback' ? fillMessage(messages, '早上兜底', { ...base, late: lateText })
66
+ : fillMessage(messages, '闹钟响了', { ...base, time: formatLocalTime(new Date(alarm.at), timeZone), note: alarm.note, late: lateText }, { note: Boolean(alarm.note), did: Boolean(extra.did) });
67
+ return withTail(body, messages, base);
68
+ }
69
+ /** What a new home says the moment it is built, or her home when her world starts again. */
70
+ export function greetingText(kind: 'arrival' | 'return', timeZone: string, fallbackWakeTime: string, messages: AlarmMessages = readAlarmMessages(undefined), extra: Record<string, string> = {}): string {
71
+ const base = { ...extra, timeZone, fallbackWakeTime };
72
+ return withTail(fillMessage(messages, kind === 'arrival' ? '第一次到家' : '重新开始', base), messages, base);
73
+ }
74
+ /** The next evening look back after `now`, and the day it looks back on. */
75
+ export function nextReview(now: Date, timeZone: string): Review {
76
+ const at = nextLocalTime(now, REVIEW_TIME, timeZone);
77
+ return { at: at.toISOString(), day: formatLocalTime(at, timeZone).slice(0, 10) };
78
+ }
79
+ /** Where her day is written down; a file that does not exist is left out. */
80
+ export interface ReviewFiles { conversations?: string; activity?: string; diaryDir: string; selfFile: string; snapshot?: string }
81
+ /** The evening look back: the day, where to read it, and her 我是谁 to rewrite if she has changed. */
82
+ export function reviewText(review: Review, now: Date, files: ReviewFiles, timeZone: string, fallbackWakeTime: string, messages: AlarmMessages = readAlarmMessages(undefined), extra: Record<string, string> = {}): string {
83
+ const base = { ...extra, timeZone, fallbackWakeTime };
84
+ const values = { ...base, date: review.day, diaryDir: files.diaryDir, selfFile: files.selfFile, conversations: files.conversations ?? '', activity: files.activity ?? '', snapshot: files.snapshot ?? '', late: lateNotice(now.getTime() - Date.parse(review.at), messages, base) };
85
+ return withTail(fillMessage(messages, '每日回顾', values, { conversations: Boolean(files.conversations), activity: Boolean(files.activity), snapshot: Boolean(files.snapshot) }), messages, base);
86
+ }
87
+ function lateNotice(late: number, messages: AlarmMessages, values: Record<string, string>): string {
88
+ return late >= LATE_NOTICE_MS ? fillMessage(messages, '晚到说明', { ...values, lateBy: formatDuration(late) }) : '';
89
+ }
90
+ function withTail(body: string, messages: AlarmMessages, values: Record<string, string>): string {
91
+ const tail = fillMessage(messages, '结尾提醒', values);
92
+ return `${ALARM_MARK}${body}${tail ? `\n${tail}` : ''}`;
93
+ }
94
+ /** What she hears when a home turn stops well before the time she said she would keep at it. */
95
+ export function earlyStopText(alarm: Alarm, now: Date, timeZone: string, messages: AlarmMessages = readAlarmMessages(undefined), extra: Record<string, string> = {}): string {
96
+ const body = fillMessage(messages, '提前停下', { ...extra, timeZone, time: formatLocalTime(new Date(alarm.at), timeZone), now: formatLocalTime(now, timeZone), note: alarm.note }, { note: Boolean(alarm.note) });
97
+ return `${ALARM_MARK}${body}`;
98
+ }
99
+ const local = (at: string | Date, timeZone: string) => formatLocalTime(new Date(at), timeZone);
100
+ /** plan_next's answer. Replacing her own plan says what it carried, while she can still copy it over; the plugin's own alarms are replaced silently. */
101
+ export function planReply(at: Date, replaced: Alarm | undefined, timeZone: string): string {
102
+ const old = replaced?.source === 'plan' ? `(替换了原来做到 ${local(replaced.at, timeZone)} 的安排${replaced.note ? `:「${replaced.note}」。还想留着里面的事,就写进新的 note` : ''}。)` : '';
103
+ return `记下了,到 ${local(at, timeZone)} 提醒我。${old}`;
104
+ }
105
+ export function checkReply(alarm: Alarm | undefined, now: Date, timeZone: string): string {
106
+ if (!alarm) return '现在没有闹钟。';
107
+ const left = Date.parse(alarm.at) - now.getTime();
108
+ const when = `${local(alarm.at, timeZone)}(${left > 0 ? `还有 ${formatDuration(left)}` : '已经到点,正在叫我'})`;
109
+ if (alarm.source === 'plan') return `我说好${alarm.note ? `做「${alarm.note}」` : ''}做到 ${when}。`;
110
+ return `我现在没有自己定的闹钟。下一次会在 ${when}按平常的时间叫我。`;
111
+ }
112
+ export function cancelReply(cancelled: Alarm | undefined, next: Alarm | undefined, timeZone: string): string {
113
+ if (cancelled?.source !== 'plan') return `现在没有我自己定的闹钟,不用取消。${next ? `下一次会在 ${local(next.at, timeZone)} 按平常的时间叫我。` : ''}`;
114
+ return `取消了做到 ${local(cancelled.at, timeZone)} 的安排${cancelled.note ? `:「${cancelled.note}」` : ''}。不另定的话,我就休息到 ${next ? local(next.at, timeZone) : '明早'}。`;
115
+ }
116
+ /** Told once a day, when her home has spent past the daily budget. */
117
+ export function budgetText(spent: number, budget: number, messages: AlarmMessages = readAlarmMessages(undefined), extra: Record<string, string> = {}): string {
118
+ return `${ALARM_MARK}${fillMessage(messages, '额度用完', { ...extra, spent: spent.toFixed(2), budget: budget.toFixed(2) })}`;
119
+ }
@@ -0,0 +1,45 @@
1
+ export interface LifeTimers { set(fn: () => void, ms: number): unknown; clear(handle: unknown): void }
2
+ export const realTimers: LifeTimers = { set: (fn, ms) => setTimeout(fn, ms), clear: handle => clearTimeout(handle as ReturnType<typeof setTimeout>) };
3
+
4
+ const retryMinutes = [1, 5, 15, 30, 60];
5
+ /** Timers wait at most this long before re-checking the wall clock, so suspend and clock changes cannot strand an alarm. */
6
+ const SEGMENT_MS = 5 * 60_000;
7
+
8
+ /**
9
+ * Waits for the pending alarm and calls `fire` once it is due, never before. A failed delivery backs off
10
+ * (1, 5, 15, 30, 60 minutes); a new alarm or a delivery that worked starts the backoff over.
11
+ */
12
+ export function createAlarmTimer(deps: { clock: () => Date; timers: LifeTimers; dueAlarm: () => string | undefined; fire: () => void }) {
13
+ const { clock, timers } = deps;
14
+ let handle: unknown;
15
+ let retries = 0;
16
+ let retryAt: number | undefined;
17
+ let stopped = false;
18
+ const dueAt = (at: string) => Math.max(Date.parse(at), retryAt ?? 0);
19
+ function cancel(): void {
20
+ if (handle !== undefined) { timers.clear(handle); handle = undefined; }
21
+ }
22
+ function arm(): void {
23
+ cancel();
24
+ const at = deps.dueAlarm();
25
+ if (stopped || at === undefined) return;
26
+ handle = timers.set(() => {
27
+ handle = undefined;
28
+ const current = deps.dueAlarm();
29
+ if (current !== undefined && dueAt(current) > clock().getTime()) arm(); else deps.fire();
30
+ }, Math.min(Math.max(0, dueAt(at) - clock().getTime()), SEGMENT_MS));
31
+ }
32
+ return {
33
+ arm,
34
+ /** Starts the backoff over (a new alarm, or one that was delivered) and re-arms. */
35
+ reset(): void { retries = 0; retryAt = undefined; arm(); },
36
+ /** A delivery failed: the next try waits out the backoff. Returns the wait in minutes. */
37
+ failed(): number {
38
+ const minutes = retryMinutes[Math.min(retries++, retryMinutes.length - 1)]!;
39
+ retryAt = clock().getTime() + minutes * 60_000;
40
+ arm();
41
+ return minutes;
42
+ },
43
+ stop(): void { stopped = true; cancel(); },
44
+ };
45
+ }
@@ -0,0 +1,10 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ const datePattern = /^\d{4}-\d{2}-\d{2}$/;
5
+ export function createDiaryReader(diaryDir: string) {
6
+ const dates = () => existsSync(diaryDir) ? readdirSync(diaryDir).filter(name => /^\d{4}-\d{2}-\d{2}\.md$/.test(name)).map(name => name.slice(0, 10)).sort().reverse() : [];
7
+ /** Only YYYY-MM-DD names are accepted, so a date can never escape the diary directory. */
8
+ const read = (date: string) => { const file = join(diaryDir, `${date}.md`); return datePattern.test(date) && existsSync(file) ? readFileSync(file, 'utf8') : undefined; };
9
+ return { dates, read };
10
+ }
@@ -0,0 +1,27 @@
1
+ import type { Alarm } from './types.ts';
2
+
3
+ /** A home turn that stops more than this before her own alarm stopped early. */
4
+ export const EARLY_STOP_MS = 5 * 60_000;
5
+
6
+ /**
7
+ * Decides when a home turn that ends counts as her stopping early: a completed turn, well before her own
8
+ * alarm, not yet asked about for that alarm. A turn in which her partner spoke is a conversation pausing,
9
+ * and a turn the plugin started itself (the question, a new home's greeting) is never asked about, so nothing loops.
10
+ */
11
+ export function createEarlyStopWatch() {
12
+ let partnerSpoke = false;
13
+ let ownTurn = false;
14
+ return {
15
+ partnerSpoke(): void { partnerSpoke = true; },
16
+ /** Ends the turn's marks; true when this ending should be asked about. */
17
+ turnEnded(completed: boolean, alarm: Alarm | undefined, now: Date): alarm is Alarm & { source: 'plan' } {
18
+ const quiet = completed && !partnerSpoke && !ownTurn;
19
+ partnerSpoke = false; ownTurn = false;
20
+ return quiet && alarm?.source === 'plan' && !alarm.nudged && Date.parse(alarm.at) - now.getTime() > EARLY_STOP_MS;
21
+ },
22
+ /** The plugin is starting a turn of its own; that turn is not asked about. */
23
+ startsOwnTurn(): void { ownTurn = true; },
24
+ /** Its message never arrived, so no turn of its own will follow. */
25
+ ownTurnFailed(): void { ownTurn = false; },
26
+ };
27
+ }
@@ -0,0 +1,85 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import type { Agent } from '@deepseek-ai/dsh-agent';
3
+ import { errorText, type Faults } from '../faults.ts';
4
+ import type { HostWorkspace, LifeHost } from './host.ts';
5
+
6
+ export interface HomeDeps {
7
+ host: LifeHost;
8
+ roomDir: string;
9
+ agentPreset: string;
10
+ title: string;
11
+ /** The title of her room as a workspace. */
12
+ roomTitle: string;
13
+ faults: Faults;
14
+ logger: { error(...args: unknown[]): void };
15
+ /** The recorded home, if any. */
16
+ current(): string | undefined;
17
+ /** Records a newly built home before anything else can fail, so a retry reuses it instead of building another. */
18
+ moveIn(sessionId: string): void;
19
+ /** Called with the home every time it is opened. */
20
+ opened(agent: Agent): void;
21
+ stopped(): boolean;
22
+ }
23
+
24
+ /**
25
+ * Her home session: the recorded one while it exists and is not archived, otherwise a new one. Full access is
26
+ * granted on every open (selecting the preset in effect is a no-op), so no "still needs access" state has to
27
+ * survive a restart. Her room is a workspace of the host, so the home is listed under it rather than as
28
+ * ungrouped, and new sessions can be opened in the room; a host without workspaces just gets the cwd. The title is applied when the home is built and again after its first turn, because the
29
+ * host retitles a session from its first prompt.
30
+ */
31
+ export function createHome(deps: HomeDeps) {
32
+ const { host, faults } = deps;
33
+ let opening: Promise<Agent> | undefined;
34
+ /** A new home whose title is not applied yet; retried on the next open. */
35
+ let untitled: string | undefined;
36
+ /** A new home before its first turn ends. */
37
+ let firstTurn: string | undefined;
38
+
39
+ async function rename(sessionId: string): Promise<boolean> {
40
+ try { await host.rename(sessionId, deps.title); faults.clear('rename'); return true; }
41
+ catch (error) { faults.set('rename', `家改名失败:${errorText(error)}`); deps.logger.error(error); return false; }
42
+ }
43
+ async function ready(agent: Agent): Promise<Agent> {
44
+ host.setFullAccess(agent.session);
45
+ if (untitled === agent.id && await rename(agent.id) && untitled === agent.id) untitled = undefined;
46
+ deps.opened(agent);
47
+ return agent;
48
+ }
49
+ /** Her room as a workspace; a failure is a fault and the home still opens, ungrouped. */
50
+ async function room(): Promise<HostWorkspace | undefined> {
51
+ mkdirSync(deps.roomDir, { recursive: true });
52
+ try { const workspace = await host.workspace(deps.roomDir, deps.roomTitle); faults.clear('room'); return workspace; }
53
+ catch (error) { faults.set('room', `房间没能成为工作区:${errorText(error)}`); deps.logger.error(error); return undefined; }
54
+ }
55
+ async function build(): Promise<Agent> {
56
+ const workspace = await room();
57
+ const current = deps.current();
58
+ if (current && !host.isArchived(current)) {
59
+ const agent = await host.resolveAgent(current);
60
+ if (agent) {
61
+ // A home built before her room was a workspace moves in.
62
+ if (workspace && !workspace.sessionIds.includes(agent.id)) {
63
+ try { await workspace.attachSession(agent.id); } catch (error) { faults.set('room', `家没能挂进房间:${errorText(error)}`); deps.logger.error(error); }
64
+ }
65
+ return ready(agent);
66
+ }
67
+ }
68
+ const sessionId = await host.createSession(deps.roomDir, deps.agentPreset, workspace?.id);
69
+ if (deps.stopped()) throw new Error('生活线已停止');
70
+ untitled = sessionId; firstTurn = sessionId;
71
+ deps.moveIn(sessionId);
72
+ const agent = await host.resolveAgent(sessionId);
73
+ if (!agent) throw new Error(`dsh-world: the new home ${sessionId} cannot be resolved`);
74
+ return ready(agent);
75
+ }
76
+ return {
77
+ /** The current home, resolving or rebuilding it; one attempt at a time. */
78
+ open(): Promise<Agent> { return opening ??= build().finally(() => { opening = undefined; }); },
79
+ turnEnded(sessionId: string): void {
80
+ if (firstTurn !== sessionId || deps.stopped()) return;
81
+ firstTurn = undefined;
82
+ void rename(sessionId).then(ok => { if (!ok && deps.current() === sessionId) untitled = sessionId; });
83
+ },
84
+ };
85
+ }