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,2616 @@
1
+ /**
2
+ * dsh-meme — selfloom 表情包层作为 DeepSeek Harness 的插件。
3
+ * npm 包名 dsh-meme;插件 id 仍为 dsh-expression(兼容已有安装)。
4
+ *
5
+ * 图库:随插件分发 memes/dafeiyu-001(official-001 已改为市场安装);
6
+ * 设置页扫描用户目录(~/.dsh/meme-packs)下拉切换。SQLite 索引 + memes/<tag>/。
7
+ *
8
+ * 发送(双通道):
9
+ * 1. QQ 通道:消费 dsh-companion 提供的 `companionQq` 服务(sendImage/isOnline);
10
+ * 2. Web 通道:注册 webServer 前缀路由 `/dsh-memes`,以 HTTP 提供图库图片,
11
+ * 模型把 [表情: 描述] 写进回复,前端按描述配图。
12
+ * 两者皆无时不注册 send_meme,避免挂空工具。
13
+ *
14
+ * 管理操作(上传/删除/改元数据)不移植——那是控制台的活,模型只需"选图发送"。
15
+ */
16
+ import { defineTool } from '@deepseek-ai/dsh-tools'
17
+ import { readFileSync, writeFileSync, unlinkSync, mkdirSync, existsSync, rmSync, readdirSync, renameSync, statSync } from 'node:fs'
18
+ import { join, dirname, resolve, sep, basename } from 'node:path'
19
+ import { fileURLToPath } from 'node:url'
20
+ import { createHash } from 'node:crypto'
21
+ import { inflateRawSync } from 'node:zlib'
22
+ import { tmpdir } from 'node:os'
23
+ import { DatabaseSync } from 'node:sqlite'
24
+ import {
25
+ MemesStore, defaultPacksDir, scanPacks, readPackMeta, isPackDir, bundledPacksDir,
26
+ resolveActiveRoot, liveStore, registerSendMemeTool, dshHome, enabledPackIds, packDeleteDir,
27
+ searchRows, prunePackKeywords, imChannelOfSession, IM_CHANNEL_LABELS,
28
+ SEND_MODES, normalizeSendMode, LAYOUT_MODES, normalizeLayoutMode, openIndexWriter,
29
+ scanRowFor, walkPackImages, ensurePackAt, movePackEntries, isInsidePluginPackage, SCAN_IMAGE_EXTS,
30
+ } from './memes.js'
31
+ import { ANIM_DEFAULT_FRAMES, detectAnimation, buildAnimationFilmstrip, animationModelNote } from './anim.js'
32
+
33
+ // ---- 极简 ZIP(store 无压缩)读写:零依赖导出/导入图库包 ----
34
+ const CRC_TABLE = (() => {
35
+ const t = new Int32Array(256)
36
+ for (let n = 0; n < 256; n++) {
37
+ let c = n
38
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)
39
+ t[n] = c
40
+ }
41
+ return t
42
+ })()
43
+ function crc32(buf) {
44
+ let c = -1
45
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xFF] ^ (c >>> 8)
46
+ return (c ^ -1) >>> 0
47
+ }
48
+
49
+ // ---- 来源校验:HTTP 路由只接受本机回环地址来的请求 ----
50
+ // 原来的判据是 `new URL(origin).host === req.headers.host`,自己跟自己比:
51
+ // 攻击者的页面只要先用自己的域名解析、再把它切到 127.0.0.1(DNS rebinding),
52
+ // 浏览器发出的 Origin 与 Host 就同是那个域名,判据成立、请求被放行;
53
+ // 而且 GET 分支在那道校验之前就 return 了,读操作一次都没校验过。
54
+ // 这里不看 Origin(由页面自己填、可以伪造成任何值),只看 Host:
55
+ // 这个头由浏览器按**实际连接目标**写,rebinding 时它就是攻击者的域名,直接落选。
56
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
57
+
58
+ /** 私有网段 IPv4(10/8、172.16/12、192.168/16、169.254/16) */
59
+ const isPrivateV4 = (ip) => {
60
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip)
61
+ if (!m) return false
62
+ const [a, b] = [Number(m[1]), Number(m[2])]
63
+ if (m.some((_, i) => i > 0 && Number(m[i]) > 255)) return false
64
+ return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || a === 127
65
+ }
66
+
67
+ /**
68
+ * 请求是不是从本机回环地址来的。
69
+ * 没有 Host 头时返回 true:HTTP/1.0 与本机 socket 直连都可能不带这个头,那种请求
70
+ * 不是浏览器页面发的、构不成 rebinding;而浏览器**一定**会带上 Host。
71
+ */
72
+ export function hostIsLoopback(req) {
73
+ const raw = String((req && req.headers && req.headers.host) || '')
74
+ if (!raw) return true
75
+ const name = raw.startsWith('[') ? raw.slice(0, raw.indexOf(']') + 1) : raw.split(':')[0]
76
+ return LOOPBACK_HOSTS.has(name.toLowerCase())
77
+ }
78
+
79
+ /**
80
+ * 请求的 Host 是不是本机/局域网 IP 字面量(issue #54:手机通过局域网 IP 访问 DSH Web)。
81
+ * 只认 IP 字面量 + localhost,**不认域名**——DNS rebinding 时 Host 是攻击者的域名,
82
+ * 这条判据照样落选。允许 range:回环、RFC1918 私有网段、链路本地、IPv6 的 ::1/fe80/fc00。
83
+ */
84
+ export function hostIsLocalLan(req) {
85
+ const raw = String((req && req.headers && req.headers.host) || '')
86
+ if (!raw) return true
87
+ const name = (raw.startsWith('[') ? raw.slice(0, raw.indexOf(']') + 1) : raw.split(':')[0]).toLowerCase()
88
+ if (LOOPBACK_HOSTS.has(name)) return true
89
+ if (name.startsWith('[')) {
90
+ // [::1] / [fe80::x%eth0] / [fd..] / [fc..]
91
+ const v6 = name.slice(1, -1)
92
+ return v6 === '::1' || /^fe[89ab]/i.test(v6) || /^f[cd]/i.test(v6)
93
+ }
94
+ return isPrivateV4(name)
95
+ }
96
+
97
+ /**
98
+ * 不是允许的来源就自己回 403 并返回 true,调用方直接 return。
99
+ * allowLan = 设置页「允许局域网访问图库」开关(默认关):打开后本机/局域网 IP
100
+ * 字面量的 Host 也放行,手机、平板才能看到表情包(issue #54);关闭时行为与旧版一致。
101
+ * 域名形式的 Host 在两种情况下都拒绝(DNS rebinding 防线)。
102
+ */
103
+ export function denyNonLoopback(req, res, allowLan = false) {
104
+ if (hostIsLoopback(req)) return false
105
+ if (allowLan && hostIsLocalLan(req)) return false
106
+ const body = JSON.stringify({ ok: false, error: '拒绝: 只接受本机(回环地址)请求。手机/局域网访问请在设置页打开「允许局域网访问图库」' })
107
+ res.writeHead(403, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
108
+ res.end(body)
109
+ return true
110
+ }
111
+
112
+ /** 打包文件列表为 ZIP(store 无压缩):[{name, data}] → Buffer */
113
+ /**
114
+ * 从 GitHub releases 里按图库 id 汇总下载量。tag 形如 <id>-v1.2.0,
115
+ * 同一图库的多个版本相加(用户装过 1.2.0 再装 1.3.0 都算一次下载)。
116
+ * 抽成纯函数是为了能直接喂假数据测。
117
+ */
118
+ export function parseDownloadCounts(releases) {
119
+ const out = {}
120
+ for (const r of (Array.isArray(releases) ? releases : [])) {
121
+ const tag = String((r && r.tag_name) || '')
122
+ const id = tag.replace(/-v[\d.]+$/i, '').trim()
123
+ if (!id || id === tag) continue
124
+ let sum = 0
125
+ for (const a of (Array.isArray(r && r.assets) ? r.assets : [])) sum += Number(a && a.download_count) || 0
126
+ out[id] = (out[id] || 0) + sum
127
+ }
128
+ return out
129
+ }
130
+
131
+ export function zipStore(files) {
132
+ const parts = []
133
+ const central = []
134
+ let offset = 0
135
+ for (const f of files) {
136
+ const nameBuf = Buffer.from(f.name, 'utf8')
137
+ const crc = crc32(f.data)
138
+ const lh = Buffer.alloc(30)
139
+ lh.writeUInt32LE(0x04034b50, 0)
140
+ lh.writeUInt16LE(20, 4)
141
+ lh.writeUInt16LE(0x0800, 6) // UTF-8 文件名
142
+ lh.writeUInt16LE(0, 8) // store
143
+ lh.writeUInt32LE(0, 10)
144
+ lh.writeUInt32LE(crc, 14)
145
+ lh.writeUInt32LE(f.data.length, 18)
146
+ lh.writeUInt32LE(f.data.length, 22)
147
+ lh.writeUInt16LE(nameBuf.length, 26)
148
+ lh.writeUInt16LE(0, 28)
149
+ parts.push(lh, nameBuf, f.data)
150
+ const ch = Buffer.alloc(46)
151
+ ch.writeUInt32LE(0x02014b50, 0)
152
+ ch.writeUInt16LE(20, 4)
153
+ ch.writeUInt16LE(20, 6)
154
+ ch.writeUInt16LE(0x0800, 8)
155
+ ch.writeUInt16LE(0, 10)
156
+ ch.writeUInt32LE(0, 12)
157
+ ch.writeUInt32LE(crc, 16)
158
+ ch.writeUInt32LE(f.data.length, 20)
159
+ ch.writeUInt32LE(f.data.length, 24)
160
+ ch.writeUInt16LE(nameBuf.length, 28)
161
+ ch.writeUInt16LE(0, 30)
162
+ ch.writeUInt16LE(0, 32)
163
+ ch.writeUInt16LE(0, 34)
164
+ ch.writeUInt16LE(0, 36)
165
+ ch.writeUInt32LE(0, 38)
166
+ ch.writeUInt32LE(offset, 42)
167
+ central.push(ch, nameBuf)
168
+ offset += lh.length + nameBuf.length + f.data.length
169
+ }
170
+ const cdSize = central.reduce((s, b) => s + b.length, 0)
171
+ const eocd = Buffer.alloc(22)
172
+ eocd.writeUInt32LE(0x06054b50, 0)
173
+ eocd.writeUInt16LE(0, 4)
174
+ eocd.writeUInt16LE(0, 6)
175
+ eocd.writeUInt16LE(files.length, 8)
176
+ eocd.writeUInt16LE(files.length, 10)
177
+ eocd.writeUInt32LE(cdSize, 12)
178
+ eocd.writeUInt32LE(offset, 16)
179
+ eocd.writeUInt16LE(0, 20)
180
+ return Buffer.concat([...parts, ...central, eocd])
181
+ }
182
+
183
+ /** 解析 ZIP(仅 store/无压缩条目):Buffer → Map<name, Buffer> */
184
+ export function unzipStore(buf) {
185
+ const out = new Map()
186
+ // EOCD:从尾部找签名
187
+ let eocd = -1
188
+ for (let i = buf.length - 22; i >= 0; i--) {
189
+ if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break }
190
+ }
191
+ if (eocd < 0) throw new Error('不是有效的 ZIP 文件')
192
+ const count = buf.readUInt16LE(eocd + 10)
193
+ let pos = buf.readUInt32LE(eocd + 16)
194
+ for (let n = 0; n < count; n++) {
195
+ if (buf.readUInt32LE(pos) !== 0x02014b50) throw new Error('ZIP 中央目录损坏')
196
+ const flags = buf.readUInt16LE(pos + 8)
197
+ const method = buf.readUInt16LE(pos + 10)
198
+ const compSize = buf.readUInt32LE(pos + 20)
199
+ const nameLen = buf.readUInt16LE(pos + 28)
200
+ const extraLen = buf.readUInt16LE(pos + 30)
201
+ const commentLen = buf.readUInt16LE(pos + 32)
202
+ const localOffset = buf.readUInt32LE(pos + 42)
203
+ const name = buf.toString('utf8', pos + 46, pos + 46 + nameLen)
204
+ if (flags & 1) throw new Error('ZIP 含加密条目,不支持: ' + name)
205
+ // local header
206
+ const lNameLen = buf.readUInt16LE(localOffset + 26)
207
+ const lExtraLen = buf.readUInt16LE(localOffset + 28)
208
+ const dataStart = localOffset + 30 + lNameLen + lExtraLen
209
+ // 常规打包工具(WinRAR/7-Zip/系统右键压缩)默认 DEFLATE,此前只认 STORE,
210
+ // 正常压缩包一进来就抛「ZIP 含压缩条目」,用户只能一张张传(用户反馈)。
211
+ const data = method === 0
212
+ ? Buffer.from(buf.subarray(dataStart, dataStart + compSize))
213
+ : method === 8
214
+ ? inflateRawSync(buf.subarray(dataStart, dataStart + compSize))
215
+ : null
216
+ if (data === null) throw new Error('ZIP 使用了不支持的压缩方式(method ' + method + '): ' + name)
217
+ out.set(name, data)
218
+ pos += 46 + nameLen + extraLen + commentLen
219
+ }
220
+ return out
221
+ }
222
+
223
+ export const name = 'dsh-expression'
224
+ export const inject = ['tools', 'webServer', 'agentDefaultModel', 'attachments']
225
+
226
+ const MIME = {
227
+ jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp',
228
+ }
229
+ /** 元数据/响应头里 image/<key> 的 key → MIME */
230
+ const IMAGE_KEY_MIME = { jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp' }
231
+ /** MIME → 落盘扩展名(jpeg 统一 .jpg,与 MIME 表反向对应) */
232
+ const EXT_BY_MIME = { 'image/jpeg': '.jpg', 'image/png': '.png', 'image/gif': '.gif', 'image/webp': '.webp' }
233
+
234
+ /**
235
+ * 按魔数嗅探图片真实格式,识别不了返回 ''(调用方回退到元数据)。
236
+ * 附件元数据(mediaType/文件名)可能与实际字节不符,而图片路由按落盘扩展名查 MIME 表,
237
+ * 扩展名错了就会以错误的 Content-Type 返回 —— 所以落盘格式要以字节为准(issue #36)。
238
+ */
239
+ export function sniffImageMime(buf) {
240
+ if (!buf || buf.length < 3) return ''
241
+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg'
242
+ if (buf.length >= 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 &&
243
+ buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) return 'image/png'
244
+ if (buf.length >= 6 && buf.toString('latin1', 0, 6).startsWith('GIF8')) return 'image/gif'
245
+ if (buf.length >= 12 && buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') return 'image/webp'
246
+ return ''
247
+ }
248
+
249
+ /** 由 MIME 反推扩展名;不在支持列表(或嗅探失败)时返回 ''。 */
250
+ function extByMime(mime) {
251
+ return EXT_BY_MIME[String(mime || '').toLowerCase()] || ''
252
+ }
253
+
254
+ const ROUTE = '/dsh-memes'
255
+
256
+ /**
257
+ * 内置图库目录源,按顺序试第一个能用的。
258
+ * raw 放前面:jsDelivr 对 @main 是「按仓库缓存 12h」,push 之后它会继续吐旧内容
259
+ * (实测带 ?t= 时间戳也绕不过它的 shield 缓存),市场改了 catalog 客户端半天看不到。
260
+ * jsDelivr 留作 raw 被墙时的兜底,加了新 catalog 记得 purge:
261
+ * `curl https://purge.jsdelivr.net/gh/yyh-001/dsh-meme-packs@main/catalog.json`
262
+ */
263
+ export const DEFAULT_REMOTE_DIR_URLS = [
264
+ 'https://raw.githubusercontent.com/yyh-001/dsh-meme-packs/main/catalog.json',
265
+ 'https://cdn.jsdelivr.net/gh/yyh-001/dsh-meme-packs@main/catalog.json',
266
+ 'https://raw.githubusercontent.com/yyh-001/dsh-meme/main/docs/remote-packs.json',
267
+ 'https://cdn.jsdelivr.net/gh/yyh-001/dsh-meme@main/docs/remote-packs.json',
268
+ ]
269
+
270
+ /**
271
+ * 图库目录源预设(设置页下拉框):settings.remoteDirUrl 支持
272
+ * ''(或 'auto') = 自动,内置多镜像竞速(默认,推荐);
273
+ * 'official' = 只直连官方 GitHub raw(海外或直连正常时用);
274
+ * 'mirror' = 只走国内加速镜像(国内直连被墙时用);
275
+ * 仍兼容自定义 http(s) URL;patch 配置里也可以写 URL 数组。
276
+ */
277
+ export const REMOTE_DIR_PRESETS = ['official', 'mirror']
278
+ const REMOTE_DIR_PRESET_LABELS = {
279
+ auto: '自动(内置多镜像)',
280
+ official: '官方源(GitHub 直连)',
281
+ mirror: '镜像源(国内加速)',
282
+ }
283
+
284
+ /**
285
+ * GitHub 加速镜像前缀:原样转发 raw / release 资源,内容实时(国内直连 GitHub 常被墙)。
286
+ * 顺序是实测可用性排序;加新镜像时同步更新 remoteMirrors() 与 docs/remote-pack-spec.md。
287
+ */
288
+ export const GITHUB_MIRROR_PREFIXES = [
289
+ 'https://ghfast.top/',
290
+ 'https://gh-proxy.com/',
291
+ 'https://ghproxy.net/',
292
+ ]
293
+
294
+ /** jsDelivr 家族 CDN 主机(国内可用的 jsDelivr 节点),对 @main 有 12h 仓库级缓存。 */
295
+ const JSDELIVR_CDN_HOSTS = ['cdn.jsdelivr.net', 'fastly.jsdelivr.net', 'testingcf.jsdelivr.net', 'gcore.jsdelivr.net']
296
+ const RAW_GH_RE = /^https:\/\/raw\.githubusercontent\.com\/([^/]+)\/([^/]+)\/([^/]+)\/(.+)$/
297
+ const RELEASE_GH_RE = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/releases\/download\/(.+)$/
298
+
299
+ /** jsDelivr 家族 URL → 去掉主机后的路径(如 `gh/o/r@main/p`);不是 jsDelivr 时返回 ''。 */
300
+ function jsdelivrPath(url) {
301
+ try {
302
+ const u = new URL(String(url || ''))
303
+ if (!JSDELIVR_CDN_HOSTS.includes(u.host) && u.host !== 'cdn.jsdmirror.com') return ''
304
+ const path = u.pathname.replace(/^\/+/, '')
305
+ return path ? path + u.search : ''
306
+ } catch { return '' }
307
+ }
308
+
309
+ /**
310
+ * 给远端资源 URL 生成镜像候选(国内可达性优先,去重):
311
+ * GitHub raw → jsdmirror / gh 加速前缀 / 原始直链 / jsDelivr 家族;
312
+ * GitHub release → gh 加速前缀 / 原始直链;
313
+ * 其它 URL 原样返回。ZIP 仍以 sha256 校验,镜像给旧文件会被拒绝,不会装错。
314
+ * @returns {string[]} 依次尝试的地址;空/非 http(s) 返回 []
315
+ */
316
+ export function remoteMirrors(url) {
317
+ const raw = String(url || '').trim()
318
+ if (!/^https?:\/\//i.test(raw)) return []
319
+ const out = []
320
+ const push = (u) => { if (u && !out.includes(u)) out.push(u) }
321
+ const rawGh = RAW_GH_RE.exec(raw)
322
+ const relGh = RELEASE_GH_RE.exec(raw)
323
+ const jsd = jsdelivrPath(raw)
324
+ if (rawGh) {
325
+ const [, owner, repo, ref, path] = rawGh
326
+ // jsdmirror 是国内 Docker/CDN 常用的 jsDelivr 节点:最快,但可能滞留 12h 内的旧文件;
327
+ // 预览图/清单这种「同一 URL 内容基本不变」的资源用它最划算。
328
+ push('https://cdn.jsdmirror.com/gh/' + owner + '/' + repo + '@' + ref + '/' + path)
329
+ for (const prefix of GITHUB_MIRROR_PREFIXES) push(prefix + raw)
330
+ push(raw)
331
+ for (const host of JSDELIVR_CDN_HOSTS) push('https://' + host + '/gh/' + owner + '/' + repo + '@' + ref + '/' + path)
332
+ } else if (relGh) {
333
+ for (const prefix of GITHUB_MIRROR_PREFIXES) push(prefix + raw)
334
+ push(raw)
335
+ } else if (jsd) {
336
+ push('https://cdn.jsdmirror.com/' + jsd)
337
+ push(raw)
338
+ } else {
339
+ push(raw)
340
+ }
341
+ return out
342
+ }
343
+
344
+ /** 从实际请求成功的 URL 反推镜像提供方前缀(资产下载优先走同一条已验证可用的链路)。 */
345
+ function mirrorProviderPrefix(url) {
346
+ const u = String(url || '')
347
+ for (const prefix of GITHUB_MIRROR_PREFIXES) if (u.startsWith(prefix)) return prefix
348
+ if (u.startsWith('https://cdn.jsdmirror.com/')) return 'https://cdn.jsdmirror.com/'
349
+ for (const host of JSDELIVR_CDN_HOSTS) if (u.startsWith('https://' + host + '/')) return 'https://' + host + '/'
350
+ if (u.startsWith('https://raw.githubusercontent.com/')) return 'https://raw.githubusercontent.com/'
351
+ return ''
352
+ }
353
+
354
+ /**
355
+ * 目录源的两层候选:tier0 = 原始直链 + gh 加速前缀(内容实时);tier1 = jsDelivr 家族
356
+ * (可能滞留旧 catalog,只在 tier0 全挂时兜底)。
357
+ */
358
+ function directoryTiers(url) {
359
+ const raw = String(url || '').trim()
360
+ const tier0 = []
361
+ const tier1 = []
362
+ const push = (arr, u) => { if (u && !tier0.includes(u) && !tier1.includes(u)) arr.push(u) }
363
+ const rawGh = RAW_GH_RE.exec(raw)
364
+ const relGh = RELEASE_GH_RE.exec(raw)
365
+ const jsd = jsdelivrPath(raw)
366
+ if (rawGh) {
367
+ const [, owner, repo, ref, path] = rawGh
368
+ push(tier0, raw)
369
+ for (const prefix of GITHUB_MIRROR_PREFIXES) push(tier0, prefix + raw)
370
+ for (const host of JSDELIVR_CDN_HOSTS) push(tier1, 'https://' + host + '/gh/' + owner + '/' + repo + '@' + ref + '/' + path)
371
+ push(tier1, 'https://cdn.jsdmirror.com/gh/' + owner + '/' + repo + '@' + ref + '/' + path)
372
+ } else if (relGh) {
373
+ push(tier0, raw)
374
+ for (const prefix of GITHUB_MIRROR_PREFIXES) push(tier0, prefix + raw)
375
+ } else if (jsd) {
376
+ push(tier0, 'https://cdn.jsdmirror.com/' + jsd)
377
+ push(tier0, raw)
378
+ } else {
379
+ push(tier0, raw)
380
+ }
381
+ return { tier0, tier1 }
382
+ }
383
+
384
+ /** 给定 GitHub raw URL 的 jsDelivr 家族候选(兜底层,对 @main 有 12h 缓存)。 */
385
+ function jsdelivrFamily(rawUrl) {
386
+ const rawGh = RAW_GH_RE.exec(String(rawUrl || '').trim())
387
+ if (!rawGh) return []
388
+ const [, owner, repo, ref, path] = rawGh
389
+ const out = JSDELIVR_CDN_HOSTS.map((host) => 'https://' + host + '/gh/' + owner + '/' + repo + '@' + ref + '/' + path)
390
+ out.push('https://cdn.jsdmirror.com/gh/' + owner + '/' + repo + '@' + ref + '/' + path)
391
+ return out
392
+ }
393
+
394
+ /**
395
+ * 目录源设置 → 候选分组(纯函数,便于单测)。每组 {key, tier0, tier1}:
396
+ * key = 归属标识(预设名或源 URL),磁盘缓存用它判断「还属不属于当前源」;
397
+ * tier0 = 内容实时的一层(直链 + gh 加速),先竞速;
398
+ * tier1 = jsDelivr 家族兜底(可能滞留 12h 的旧目录,只在 tier0 全挂时用)。
399
+ * @param {string} setting 设置值:''/'auto'/'official'/'mirror'/自定义 http(s) URL
400
+ * @param {string[]|string} fallbackUrls 未设置时用的源列表(patch 配置或内置默认)
401
+ * @returns {{key:string,tier0:string[],tier1:string[]}[]}
402
+ */
403
+ export function directoryGroupsFor(setting, fallbackUrls = DEFAULT_REMOTE_DIR_URLS) {
404
+ const raw = String(setting == null ? '' : setting).trim()
405
+ const lower = raw.toLowerCase()
406
+ const catalog = DEFAULT_REMOTE_DIR_URLS[0]
407
+ if (!raw || lower === 'auto') {
408
+ return [].concat(fallbackUrls || [])
409
+ .map((u) => String(u || '').trim())
410
+ .filter((u) => /^https?:\/\//i.test(u))
411
+ .map((u) => { const { tier0, tier1 } = directoryTiers(u); return { key: u, tier0, tier1 } })
412
+ }
413
+ // 预设的目录地址固定用 dsh-meme-packs 仓库的 catalog.json,语义明确:
414
+ if (lower === 'official') return [{ key: 'official', tier0: [catalog], tier1: [] }]
415
+ if (lower === 'mirror') {
416
+ return [{
417
+ key: 'mirror',
418
+ // 只用国内加速:镜像原样转发 raw,内容实时
419
+ tier0: GITHUB_MIRROR_PREFIXES.map((p) => p + catalog),
420
+ // 镜像全挂时再用 jsDelivr 家族兜底(旧目录也比完全没有强)
421
+ tier1: jsdelivrFamily(catalog),
422
+ }]
423
+ }
424
+ if (/^https?:\/\//i.test(raw)) {
425
+ const { tier0, tier1 } = directoryTiers(raw)
426
+ return [{ key: raw, tier0, tier1 }]
427
+ }
428
+ // 非法值(手改配置文件写错):按自动处理,别让面板直接炸
429
+ return directoryGroupsFor('', fallbackUrls)
430
+ }
431
+
432
+ /**
433
+ * 工具注册时机兜底(issue #51)。
434
+ *
435
+ * dsh 0.2.1-rc.x 冷启动时,apply 同步路径里 ctx.tools 可能还没对 agent 平面生效:
436
+ * register() 不抛错、但工具不进表(learn_meme 当时连 try/catch 都没有),市场里
437
+ * 照样显示 live,API/面板/图片路由全都正常——直到热重挂(服务已 ACTIVE)工具才出现。
438
+ *
439
+ * 注册策略:
440
+ * * 宿主有 ctx.inject:整体挪进 inject(['tools']) 回调,tools 服务 ACTIVE 后再注册,
441
+ * 恰好一次(这是 dsh-live-reload README 记录的 0.2.x 官方姿势:apply 阶段只 ctx.get()
442
+ * 会静默失败,必须 inject 等依赖就绪);
443
+ * * 老宿主没有 inject:保持同步注册,抛错则指数退避重试;duplicate 视为已注册
444
+ * (第一次其实写进去了,重试撞名说明不用再挂)。
445
+ *
446
+ * 任何失败都补一份 ctx.logger.error:桌面端把宿主子进程的 stdout 收走,
447
+ * console.error 用户侧一点痕迹都没有,没日志就没法报障。
448
+ *
449
+ * @param {object} ctx 插件上下文
450
+ * @param {string} label 工具名(日志用)
451
+ * @param {() => void} register 真正执行注册的 thunk(ctx.tools.register 自带生命周期挂接)
452
+ * @param {{retryBaseMs?: number, retryMax?: number}} [options] 测试注入退避参数
453
+ */
454
+ export function registerToolWhenReady(ctx, label, register, options = {}) {
455
+ const retryBaseMs = typeof options.retryBaseMs === 'number' ? options.retryBaseMs : 1000
456
+ const retryMax = typeof options.retryMax === 'number' ? options.retryMax : 5
457
+ const report = (error, attempt) => {
458
+ const detail = error instanceof Error ? error.message : String(error)
459
+ const text = `[dsh-expression] ${label} 注册失败(不影响 API/面板${attempt ? `,第 ${attempt} 次重试` : ''}): ${detail}`
460
+ console.error(text)
461
+ try {
462
+ if (ctx.logger && typeof ctx.logger.error === 'function') ctx.logger.error(text)
463
+ } catch { /* logger 缺席不连坐 */ }
464
+ }
465
+ const safeRegister = (attempt) => {
466
+ try {
467
+ register()
468
+ return true
469
+ } catch (error) {
470
+ if (/duplicate/i.test(String((error && error.message) || error))) return true
471
+ report(error, attempt)
472
+ return false
473
+ }
474
+ }
475
+ if (typeof ctx.inject === 'function') {
476
+ try {
477
+ ctx.inject(['tools'], () => { safeRegister(null) })
478
+ return
479
+ } catch (error) { report(error, null) /* inject 挂不上:退回同步+重试 */ }
480
+ }
481
+ if (safeRegister(null)) return
482
+ // 同步注册失败:指数退避重试(1s、2s、4s…),总共 retryMax 次;每次失败都上报。
483
+ const timers = new Set()
484
+ if (typeof ctx.effect === 'function') {
485
+ try { ctx.effect(() => () => { for (const t of timers) clearTimeout(t); timers.clear() }, `dsh-expression: ${label} retry timers`) } catch { /* effect 缺席不连坐 */ }
486
+ }
487
+ let attempts = 0
488
+ const scheduleRetry = () => {
489
+ attempts++
490
+ const delay = retryBaseMs * Math.pow(2, attempts - 1)
491
+ const timer = setTimeout(() => {
492
+ timers.delete(timer)
493
+ if (safeRegister(attempts)) return
494
+ if (attempts < retryMax) scheduleRetry()
495
+ }, delay)
496
+ timers.add(timer)
497
+ }
498
+ scheduleRetry()
499
+ }
500
+
501
+ export function apply(ctx, config) {
502
+ // 图库目录设置存 ~/.dsh(稳定,不受包升级/图库变化影响):
503
+ // 优先级 用户设置(settings) > patch 配置(config.memeRoot) > 包内默认
504
+ // 插件版本:反馈表单预填要用(从包内 package.json 读,不写死在代码里)
505
+ const pluginVersion = (() => {
506
+ try {
507
+ const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf8'))
508
+ return String(pkg.version || '').trim()
509
+ } catch { return '' }
510
+ })()
511
+ const settingsFile = join(dshHome(), '.dsh', 'dsh-expression.json')
512
+ const readSettings = () => {
513
+ try { return JSON.parse(readFileSync(settingsFile, 'utf8')) } catch (e) { return {} }
514
+ }
515
+ const writeSettings = (patch) => {
516
+ try {
517
+ mkdirSync(join(dshHome(), '.dsh'), { recursive: true })
518
+ writeFileSync(settingsFile, JSON.stringify({ ...readSettings(), ...patch }, null, 2))
519
+ } catch (e) {}
520
+ }
521
+ // 陪伴模式提示词:模型主动斗图。设置页可编辑覆盖(settings.companionPrompt)。
522
+ const DEFAULT_COMPANION_PROMPT = '斗图规则:主动斗图,不要等用户开口:\n' +
523
+ '- 聊天气氛合适就主动用 send_meme 发一张贴题的表情包,不用等用户要求,发图优先于纯文字;\n' +
524
+ '- 发图先 search 拿候选,[表情: 描述] 里的描述必须抄候选原文,自己编的描述前端配不上图;\n' +
525
+ '- 情绪到点、接梗、吐槽、卖萌时都主动甩图,别冷场;对方说正事/干活时克制;\n' +
526
+ '- 发完保持简短,让图自己说话,不啰嗦不复述。'
527
+ /**
528
+ * dsh-im 的 IM 渠道里没有 dsh-meme 的前端配图器:[表情: 描述] 只会被当成一行
529
+ * 方括号文字发出。所以 IM 会话要换一条投递路径——send_meme 在 IM 模式会返回
530
+ * 候选的绝对路径,模型把它交给 dsh-im 的 dsh_im_return_file,由渠道作为原生
531
+ * 图片消息发出。
532
+ *
533
+ * 这里必须显式写「主动发」:dsh-im 自己注入的说明是「用户要求收文件/图片时才
534
+ * 调用 dsh_im_return_file」,只靠原来的主动斗图提示词,模型会以为 IM 里发不了
535
+ * 图、或者要先等用户开口授权——这正是「先说明可以在 QQ/微信发表情才会主动发」
536
+ * 的根因。
537
+ *
538
+ * 另外必须显式禁止「正文里再放一份图」:模型很爱在回复里补 markdown 图片
539
+ * `![描述](C:\...\x.jpg)` 或 `[描述]` 来「确保能看到」,而 IM 客户端只会显示
540
+ * 方括号里的描述文字、把本地路径原样暴露出来,图片本身还是靠原生消息送达。
541
+ */
542
+ const imNoInlineImageRule = (label) => '- 回复正文只写普通聊天的文字:不要写 [表情: …] 或 [任何描述] 这类方括号标记,不要写 markdown 图片(![]()),更不要把本地文件路径贴进回复——' + label + ' 里这些只会显示成难看的文字,图片会由 dsh_im_return_file 作为原生消息发出;\n'
543
+ const imCompanionPrompt = (channel) => {
544
+ const label = IM_CHANNEL_LABELS[channel] || 'IM'
545
+ return '斗图规则:主动斗图,不要等用户开口:\n' +
546
+ '- 聊天气氛合适就主动用 send_meme 拿候选,再把挑中的候选 path(绝对路径)交给 dsh_im_return_file,让它作为 ' + label + ' 原生图片消息发出,发图优先于纯文字;\n' +
547
+ imNoInlineImageRule(label) +
548
+ '- 也不用在正文里解释图片投递过程(不必说「图已排队/等发出」),发完保持简短,让图自己说话,不啰嗦不复述;\n' +
549
+ '- 不用等用户先授权、先说明「可以发表情」,直接发;情绪到点、接梗、吐槽、卖萌时都主动甩图,别冷场,对方说正事/干活时克制。'
550
+ }
551
+ /** 用户自定义过提示词时不动原文,只在末尾补 IM 的投递方式 */
552
+ const imCompanionRules = (channel) => {
553
+ const label = IM_CHANNEL_LABELS[channel] || 'IM'
554
+ return '当前对话来自 ' + label + '(IM 聊天):\n' +
555
+ '- 发图方式是先调用 send_meme 拿候选,再把挑中的候选 path(工具结果里的绝对路径)传给 dsh_im_return_file,让它作为 ' + label + ' 原生图片消息发出;\n' +
556
+ imNoInlineImageRule(label) +
557
+ '- 不用等用户先授权:气氛合适就直接 send_meme → dsh_im_return_file 主动发;对方说正事/干活时克制。'
558
+ }
559
+ /** dsh-im 是否在进程内(它提供 dsh_im_return_file,是 IM 发图的唯一通道) */
560
+ const hasImDelivery = () => {
561
+ try {
562
+ const service = ctx.get && ctx.get('dshIm')
563
+ return service !== undefined && service !== null
564
+ } catch { return false }
565
+ }
566
+ /**
567
+ * 发送方式设置(settings.sendMode):只影响 AI 怎么发,不改前端把 [表情: 描述]
568
+ * 渲染成图片的逻辑。auto = 按渠道自动(默认);text = 纯文字不发图;image = 总是发图。
569
+ */
570
+ const sendModeOf = () => normalizeSendMode(readSettings().sendMode)
571
+ /** 设置页「允许局域网访问图库」(issue #54):默认关,打开后局域网 IP 字面量的 Host 也放行 */
572
+ const allowLanAccess = () => readSettings().allowLanAccess === true
573
+ /** 纯文字模式:默认提示词里教模型写 [表情:] 标记的规则要压掉,否则前端仍会配图 */
574
+ const TEXT_MODE_RULE = '发送方式设置为「纯文字」:不要发图片。不要写 [表情: …] 或 [任何描述] 这类方括号标记,不要调用 dsh_im_return_file,也不要把图片路径贴进回复;想斗图就用文字接梗、吐槽、卖萌。可以用 send_meme 查候选拿描述,但不要真的把图发出去。'
575
+ /** 图片模式:在自动行为上强调「必须真发图」,不允许只描述 */
576
+ const IMAGE_MODE_RULE = '发送方式设置为「图片」:每次用 send_meme 挑好图后都必须把图片真的发出去——Web 聊天把 [表情: 描述] 原样写进回复;IM 聊天把候选 path 交给 dsh_im_return_file。不能只写文字描述、不发图。'
577
+ const memeRoot = resolveActiveRoot(readSettings(), config?.memeRoot)
578
+ let memes = null
579
+ try {
580
+ memes = liveStore(new MemesStore(memeRoot))
581
+ } catch (error) {
582
+ console.error('[dsh-expression] meme store unavailable:', error && error.message)
583
+ return
584
+ }
585
+
586
+ // ---- 陪伴模式:系统提示注入,模型根据对话情绪主动斗图 ----
587
+ // 设置页可整段关掉这项注入(settings.promptEnabled === false),关掉后模型不再主动斗图。
588
+ // IM 会话(dsh-im)追加投递规则:候选路径交给 dsh_im_return_file,不要写标记。
589
+ ctx.on('system-prompt/assemble', async (_assembly, context, next) => {
590
+ const assembled = await next()
591
+ const settingsNow = readSettings()
592
+ if (settingsNow.promptEnabled === false) return assembled
593
+ const sendMode = normalizeSendMode(settingsNow.sendMode)
594
+ const channel = hasImDelivery() ? imChannelOfSession(context?.agent?.session) : null
595
+ const custom = settingsNow.companionPrompt
596
+ let text = custom || DEFAULT_COMPANION_PROMPT
597
+ if (sendMode === 'text') {
598
+ // 纯文字:默认提示词里的发图指令全部压掉(仍保留斗图语气),也不追加 IM 投递规则
599
+ text = text + '\n\n' + TEXT_MODE_RULE
600
+ } else if (channel) {
601
+ // IM 会话:默认提示词整段换成 IM 版([表情:] 那条在 IM 里是错的);
602
+ // 用户自定义提示词则保留原文,只在末尾补投递规则。
603
+ text = custom ? custom + '\n\n' + imCompanionRules(channel) : imCompanionPrompt(channel)
604
+ }
605
+ if (sendMode === 'image') text = text + '\n\n' + IMAGE_MODE_RULE
606
+ assembled.sections.push({ name: 'dsh-expression:companion', text })
607
+ return assembled
608
+ })
609
+
610
+ // ---- Web 通道:图片 HTTP 路由(白名单,只放行索引内路径) ----
611
+ // 容错:同一进程内路由可能已被动态版插件注册(全局共享),冲突则复用。
612
+ // urlPrefix 用**相对路径**:前端按 window.location.origin 补全(issue #54)。
613
+ // 以前拼成 http://127.0.0.1:<port>,桌面端没问题,手机/平板通过局域网 IP
614
+ // 访问时 127.0.0.1 指向手机自己,图片全空白。工具侧只把它当「有 Web 通道」的
615
+ // 标志,不消费具体值。
616
+ let urlPrefix = null
617
+ const webServer = ctx.webServer ?? ctx.get('webServer')
618
+ if (webServer) {
619
+ try {
620
+ // 路由注册挂到 ctx.effect:插件被关开关/热重载时由宿主跑 disposer 摘掉路由,
621
+ // 否则同一进程里再次 apply 会撞 duplicate route(issue #20)。
622
+ ctx.effect(() => webServer.register({
623
+ kind: 'prefix',
624
+ path: ROUTE,
625
+ handler(req, res) {
626
+ if (denyNonLoopback(req, res, allowLanAccess())) return
627
+ const rawUrl = String(req.url || '').split('?')[0]
628
+ // 浏览器对路径里的非 ASCII 一律百分号编码,而下面的白名单来自 index.db 里的
629
+ // 原始路径(中文目录/文件名是未编码的),不先解码的话含非 ASCII 路径的图库
630
+ // 所有图都 404(issue #28)。解码要兜住手打的畸形转义(%E5%A 这类),失败按
631
+ // 404 处理而不是抛 500;先行 split('?') 保证 %3F 不会被当成查询串切走。
632
+ let pathname
633
+ try {
634
+ pathname = decodeURIComponent(rawUrl)
635
+ } catch {
636
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
637
+ res.end('not found')
638
+ return
639
+ }
640
+ const raw = pathname.startsWith(ROUTE + '/') ? pathname.slice(ROUTE.length + 1) : null
641
+ // 带包前缀格式:/dsh-memes/<packId>/<rel>(跨包发图/配图);无前缀按当前激活包
642
+ // (旧格式兼容:那条的 rel 固定以 memes/ 开头,所以首段是 memes 时不当包 id)。
643
+ let root = memes.root
644
+ let stored = raw
645
+ if (raw) {
646
+ const slash = raw.indexOf('/')
647
+ const first = slash > 0 ? raw.slice(0, slash) : ''
648
+ if (first && first !== 'memes') {
649
+ // 认出来是包前缀就必须找到那个包。以前找不到会静默按「当前图库 + 整条 raw」拼路径,
650
+ // 磁盘上碰巧存在同名嵌套目录时会发出另一个包的图/明明是 404 却看着像配错了图,
651
+ // 描述和图对不上还很难查(issue #23)。宁可显式 404。
652
+ let hit = null
653
+ try { hit = listAllPacks().find((p) => p.id === first) } catch { /* 扫描失败 → 当找不到 */ }
654
+ if (!hit) {
655
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' })
656
+ res.end('not found: 未知图库 ' + first)
657
+ return
658
+ }
659
+ root = hit.path
660
+ stored = raw.slice(slash + 1)
661
+ }
662
+ }
663
+ // 每次请求动态构建白名单:静态快照会漏掉新上传的图(历史教训:上传后 404 图片不显示)
664
+ let allowed = null
665
+ let routeStore = null
666
+ try {
667
+ routeStore = new MemesStore(root)
668
+ allowed = new Set(routeStore.list().memes.map((m) => m.path))
669
+ } catch {
670
+ allowed = null
671
+ } finally {
672
+ if (routeStore) routeStore.close()
673
+ }
674
+ if (!stored || !allowed || !allowed.has(stored)) {
675
+ res.writeHead(404, { 'Content-Type': 'text/plain' })
676
+ res.end('not found')
677
+ return
678
+ }
679
+ try {
680
+ const file = join(root, stored)
681
+ const bytes = readFileSync(file)
682
+ const ext = stored.includes('.') ? stored.split('.').pop().toLowerCase() : ''
683
+ res.writeHead(200, {
684
+ 'Content-Type': MIME[ext] || 'application/octet-stream',
685
+ 'Content-Length': String(bytes.byteLength),
686
+ 'Cache-Control': 'public, max-age=3600',
687
+ })
688
+ res.end(bytes)
689
+ } catch {
690
+ res.writeHead(404, { 'Content-Type': 'text/plain' })
691
+ res.end('not found')
692
+ }
693
+ },
694
+ }), 'dsh-expression: /dsh-memes 图片路由')
695
+ } catch (error) {
696
+ console.log('[dsh-expression] 路由已存在,复用:', error && error.message)
697
+ }
698
+ urlPrefix = ROUTE
699
+ }
700
+
701
+ // ---- 模型可用的图库:设置页每张卡片一个开关,可以同时开多个 ----
702
+ // 管理相关的 memes.* 仍只作用于「当前图库」(上传/改/删/学图),
703
+ // send_meme 抽候选则跨所有打开的图库——这里包一层 sampler 给工具用。
704
+ const packRows = () => {
705
+ try { return listAllPacks() } catch { return [] }
706
+ }
707
+ const activePackId = () => {
708
+ const s = readSettings()
709
+ const packs = packRows()
710
+ return s.packId || (packs.find((p) => resolve(p.path) === resolve(memes.root)) || {}).id || ''
711
+ }
712
+ const enabledIds = () => enabledPackIds(readSettings(), packRows(), activePackId())
713
+ // 给单库快路径的行补上图库标注(跨库合并路径在下面就地标):候选带 library,
714
+ // 模型答得出「这图哪个库的」(issue #53)。不改 path,只加字段。
715
+ const annotatePack = (rows, pack) => rows.map((row) => ({ ...row, packId: pack.id, packName: pack.name }))
716
+ // 临时打开某图库跑一句查询,完事即关(包内图库不能常驻连接,issue #43);失败返回 null
717
+ const withStore = (path, fn) => {
718
+ let store = null
719
+ try {
720
+ store = new MemesStore(path)
721
+ return fn(store)
722
+ } catch { return null } finally { if (store) store.close() }
723
+ }
724
+ const sampler = {
725
+ get root() { return memes.root },
726
+ list: (...a) => memes.list(...a),
727
+ replace: (...a) => memes.replace(...a),
728
+ sampleMood(tag, query, n) {
729
+ const ids = enabledIds()
730
+ if (ids.length === 0) {
731
+ const { memes: rows, tags } = memes.list()
732
+ return { mood: resolveMoodName(tag, query, tags), memes: [], tags, reason: '当前没有打开任何图库,去设置页把要用的图库开关打开' }
733
+ }
734
+ const packs = packRows()
735
+ if (ids.length === 1) {
736
+ const hit = packs.find((p) => p.id === ids[0]) || null
737
+ const r = hit
738
+ ? (hit.id === activePackId()
739
+ ? memes.sampleMood(tag, query, n)
740
+ : withStore(hit.path, (store) => store.sampleMood(tag, query, n)))
741
+ : null
742
+ if (r) return { ...r, memes: annotatePack(r.memes, hit) }
743
+ return memes.sampleMood(tag, query, n)
744
+ }
745
+ const per = Math.max(1, Math.ceil(n / ids.length))
746
+ const merged = []
747
+ let mood = ''
748
+ let tags = []
749
+ for (const id of ids) {
750
+ const hit = packs.find((p) => p.id === id)
751
+ if (!hit) continue
752
+ let store = null
753
+ try {
754
+ store = new MemesStore(hit.path)
755
+ const one = store.sampleMood(tag, query, per)
756
+ mood = mood || one.mood
757
+ tags = one.tags.length ? one.tags : tags
758
+ for (const row of one.memes) {
759
+ // 非当前图库的路径带上包前缀,QQ 通道发图时按前缀找对图库;
760
+ // 所有行都带上图库标注(候选出处信息,issue #53)
761
+ merged.push(id === activePackId()
762
+ ? { ...row, packId: hit.id, packName: hit.name }
763
+ : { ...row, path: id + '/' + row.path, packId: hit.id, packName: hit.name })
764
+ }
765
+ } catch { /* 坏包跳过,不影响其他图库 */ } finally { if (store) store.close() }
766
+ }
767
+ if (!mood) return { mood: null, memes: [], tags }
768
+ return { mood, memes: pickShuffled(merged, n), tags }
769
+ },
770
+ // 关键词搜图:和 sampleMood 一样跨所有打开的图库。先把各包的行合并(路径带包前缀),
771
+ // 再统一排序——「所有关键词都命中」只有在合并后比才准,否则每包各自取最优,
772
+ // 只命中一个词的弱结果会和全中的强结果混在一起。
773
+ search(query, n, tag) {
774
+ const ids = enabledIds()
775
+ if (ids.length === 0) {
776
+ const { tags } = memes.list()
777
+ return { query: String(query || '').trim().toLowerCase(), memes: [], tags, reason: '当前没有打开任何图库,去设置页把要用的图库开关打开' }
778
+ }
779
+ const packs = packRows()
780
+ const active = activePackId()
781
+ if (ids.length === 1) {
782
+ const hit = packs.find((p) => p.id === ids[0]) || null
783
+ if (hit) {
784
+ const base = hit.id === active
785
+ ? memes.search(query, n, tag)
786
+ : withStore(hit.path, (store) => {
787
+ const all = store.list(tag)
788
+ return { ...searchRows(annotatePack(all.memes, hit), query, n), tags: all.tags }
789
+ })
790
+ if (base) return base
791
+ }
792
+ return memes.search(query, n, tag)
793
+ }
794
+ const merged = []
795
+ let tags = []
796
+ for (const id of ids) {
797
+ const hit = packs.find((p) => p.id === id)
798
+ if (!hit) continue
799
+ let store = null
800
+ try {
801
+ store = new MemesStore(hit.path)
802
+ const one = store.list(tag)
803
+ tags = one.tags.length ? one.tags : tags
804
+ for (const row of one.memes) {
805
+ // 非当前图库的路径带上包前缀,QQ 通道发图时按前缀找对图库
806
+ merged.push(id === active
807
+ ? { ...row, packId: hit.id, packName: hit.name }
808
+ : { ...row, path: id + '/' + row.path, packId: hit.id, packName: hit.name })
809
+ }
810
+ } catch { /* 坏包跳过,不影响其他图库 */ } finally { if (store) store.close() }
811
+ }
812
+ return { ...searchRows(merged, query, n), tags }
813
+ },
814
+ // 跨启用图库的分类统计(张数降序):send_meme 没命中时给模型真实的换词建议(issue #53)
815
+ tagStats() {
816
+ const out = new Map()
817
+ for (const p of packRows()) {
818
+ if (!enabledIds().includes(p.id)) continue
819
+ let store = null
820
+ try {
821
+ store = new MemesStore(p.path)
822
+ for (const m of store.list().memes) out.set(m.tag, (out.get(m.tag) || 0) + 1)
823
+ } catch { /* 坏包跳过 */ } finally { if (store) store.close() }
824
+ }
825
+ return [...out.entries()].map(([tag, count]) => ({ tag, count })).sort((a, b) => b.count - a.count)
826
+ },
827
+ resolveStored(stored) {
828
+ const raw = String(stored || '')
829
+ const slash = raw.indexOf('/')
830
+ const first = slash > 0 ? raw.slice(0, slash) : ''
831
+ if (first) {
832
+ const hit = packRows().find((p) => p.id === first)
833
+ if (hit) return resolve(join(hit.path, raw.slice(slash + 1)))
834
+ }
835
+ return memes.resolveStored(raw)
836
+ },
837
+ }
838
+ const pickShuffled = (rows, n) => {
839
+ const copy = rows.slice()
840
+ for (let i = copy.length - 1; i > 0; i--) {
841
+ const j = Math.floor(Math.random() * (i + 1))
842
+ const tmp = copy[i]; copy[i] = copy[j]; copy[j] = tmp
843
+ }
844
+ return copy.slice(0, n)
845
+ }
846
+ const resolveMoodName = (tag, query, tags) => {
847
+ // 没有可用图库时也要回一个合法情绪名(否则工具只会说「先选情绪」)
848
+ try { return memes.sampleMood(tag, query, 1).mood } catch { return null }
849
+ }
850
+
851
+ // ---- 发送通道:QQ 优先,Web 兜底;Web 里再按会话来源分流到 IM 原生图片 ----
852
+ // dsh-im 只在进程内时提供 dsh_im_return_file;这里传的是「运行时判断」而不是
853
+ // apply 时的快照——插件装载顺序不定,dsh-im 可能比 dsh-meme 晚就绪。
854
+ const imToolOptions = () => ({
855
+ imChannelOf: (session) => (hasImDelivery() ? imChannelOfSession(session) : null),
856
+ imReady: hasImDelivery(),
857
+ sendMode: sendModeOf,
858
+ // 跨启用图库的真实分类统计:send_meme 没命中时给模型有用的换词建议(issue #53)
859
+ tagStats: () => sampler.tagStats(),
860
+ })
861
+ const qq = ctx.get('companionQq')
862
+ const sendImage = qq !== undefined && typeof qq.sendImage === 'function'
863
+ ? (path, caption) => qq.sendImage(path, caption)
864
+ : null
865
+ if (sendImage || urlPrefix) {
866
+ registerToolWhenReady(ctx, 'send_meme', () => {
867
+ registerSendMemeTool(ctx, sampler, sendImage, urlPrefix, imToolOptions())
868
+ console.log(`[dsh-expression] send_meme 已注册(${sendImage ? 'QQ' : 'Web'}通道${!sendImage && hasImDelivery() ? '+IM' : ''},${urlPrefix || '无路由'})`)
869
+ })
870
+ } else {
871
+ console.log('[dsh-expression] 无可用发送通道(需要 dsh-companion 的 QQ 或 webServer),未注册 send_meme')
872
+ }
873
+
874
+ // companionQq 迟到时补挂(静态插件与 companion 装载顺序不定)。
875
+ const register = () => {
876
+ if (sendImage || urlPrefix) return
877
+ const qqNow = ctx.get('companionQq')
878
+ if (qqNow !== undefined && typeof qqNow.sendImage === 'function') {
879
+ registerToolWhenReady(ctx, 'send_meme', () => {
880
+ registerSendMemeTool(ctx, sampler, (path, caption) => qqNow.sendImage(path, caption), urlPrefix, imToolOptions())
881
+ })
882
+ }
883
+ }
884
+ ctx.on('companionQq/available', register)
885
+
886
+ // ---- 管理 API + 自包含管理面板(HTTP,重启不丢,任何会话可访问) ----
887
+ // 运行时切换图库目录:校验 → 持久化设置 → 原子替换 memes/adminDb。
888
+ // 工具/路由/API 闭包引用变量,替换后立即指向新图库,无需重启。
889
+ // packsDirNow/listAllPacks 定义在 apply 直接作用域:图片路由(注册于
890
+ // if(webServer) 之外)也要按包取图,块内看不到它们(历史教训)。
891
+ const packsDirNow = () => readSettings().packsDir || defaultPacksDir()
892
+ const listAllPacks = () => {
893
+ const packs = scanPacks(packsDirNow())
894
+ const root = resolve(memes.root)
895
+ if (!packs.some((p) => resolve(p.path) === root)) {
896
+ const meta = readPackMeta(memes.root, readSettings().packId || '_custom', 'custom')
897
+ packs.unshift(meta)
898
+ }
899
+ return packs
900
+ }
901
+ // ---- 用户收藏的稳定落点(修复:插件升级清空收藏) ----
902
+ // 内置图库随插件包分发,包目录在 npm/pnpm 更新时会被整个替换——写进内置库的收藏
903
+ // (上传/AI 学图/手动拷贝)一起消失。收藏一律落 packsDir 下的「我的收藏」图库
904
+ // (默认在 ~/.dsh 下,包外,升级不动),并自动启用:send_meme 跨启用图库取图,
905
+ // 不切换当前图库也能发。内置库从此只读。
906
+ const USER_PACK_ID = 'dsh-meme-user'
907
+ const USER_PACK_NAME = '我的收藏(升级不丢)'
908
+ const userPackPath = () => join(packsDirNow(), USER_PACK_ID)
909
+ const isVolatileRoot = (root) => isInsidePluginPackage(root)
910
+ const ensureUserPack = () => {
911
+ const dir = userPackPath()
912
+ ensurePackAt(dir, { id: USER_PACK_ID, name: USER_PACK_NAME, description: '上传与 AI 学图的默认落点;内置图库随插件升级会被清空,收藏统一存这里' })
913
+ try {
914
+ const packs = listAllPacks()
915
+ const enabled = enabledPackIds(readSettings(), packs, activePackId())
916
+ if (packs.some((p) => p.id === USER_PACK_ID) && !enabled.includes(USER_PACK_ID)) {
917
+ writeSettings({ enabledPacks: [...enabled, USER_PACK_ID] })
918
+ }
919
+ } catch (e) { /* 自动启用失败不阻塞写入 */ }
920
+ return dir
921
+ }
922
+ /** 收藏写入目标:当前图库在插件包内(升级会被清空)时改写「我的收藏」,否则原样 */
923
+ const writeTarget = () => (isVolatileRoot(memes.root) ? ensureUserPack() : memes.root)
924
+ const packPaths = (path) => {
925
+ let store = null
926
+ try {
927
+ store = new MemesStore(path)
928
+ return store.list().memes.map((m) => m.path)
929
+ } catch { return [] }
930
+ finally { if (store) store.close() }
931
+ }
932
+ // 启动迁移:内置库里「不在出厂基线里」的文件 = 用户后来加的,搬去「我的收藏」。
933
+ // 基线按插件版本记在稳定设置(bundledBaseline):版本没变就按旧基线比对搬运;
934
+ // 版本变了说明插件刚更新过、包目录已是出厂态(旧基线比对搬不出东西),重记基线;
935
+ // 首次运行(没有基线)只记基线不搬——那时目录里只剩出厂文件。搬完留在原地也行,
936
+ // 但下次更新就没了,所以搬到包外才安心。
937
+ try {
938
+ const bundledRoot = join(bundledPacksDir(), 'dafeiyu-001')
939
+ if (existsSync(join(bundledRoot, 'index.db'))) {
940
+ const baseline = readSettings().bundledBaseline
941
+ let current = null
942
+ if (baseline && Array.isArray(baseline.paths)) {
943
+ current = packPaths(bundledRoot)
944
+ const added = current.filter((p) => !baseline.paths.includes(p))
945
+ if (added.length) {
946
+ const r = movePackEntries(bundledRoot, ensureUserPack(), added)
947
+ if (r.moved.length) console.log(`[dsh-expression] 内置图库里有 ${r.moved.length} 张后加的收藏,已搬到「${USER_PACK_NAME}」(插件目录升级会被清空)`)
948
+ }
949
+ }
950
+ if (!baseline || baseline.version !== pluginVersion) {
951
+ writeSettings({ bundledBaseline: { version: pluginVersion, paths: current || packPaths(bundledRoot) } })
952
+ }
953
+ }
954
+ } catch (error) {
955
+ console.log('[dsh-expression] 内置图库收藏迁移失败(不影响其它功能):', error instanceof Error ? error.message : String(error))
956
+ }
957
+ if (webServer) {
958
+ // 可写连接。插件包内的图库(默认内置包)不常驻:每次写临时开、写完就关,
959
+ // 否则 Windows 上包目录被占住,pnpm 更新 rename 会 EPERM(issue #43)。
960
+ let adminDb = openIndexWriter(memes.root)
961
+ const packPayload = () => {
962
+ const s = readSettings()
963
+ const packs = listAllPacks()
964
+ const packId = s.packId || (packs.find((p) => resolve(p.path) === resolve(memes.root)) || {}).id || ''
965
+ const enabled = enabledPackIds(s, packs, packId)
966
+ return {
967
+ memeRoot: memes.root,
968
+ packId,
969
+ packs: packs.map((p) => ({
970
+ ...p,
971
+ // 本地图库的封面走插件自己的图片路由:图已经装到本地了,不该再去拉远程预览图
972
+ cover: p.cover ? ROUTE + '/' + p.id + '/' + String(p.cover).split('/').map(encodeURIComponent).join('/') : '',
973
+ enabled: enabled.includes(p.id),
974
+ })),
975
+ enabledPacks: enabled,
976
+ packsDir: packsDirNow(),
977
+ companionPrompt: readSettings().companionPrompt || '',
978
+ defaultCompanionPrompt: DEFAULT_COMPANION_PROMPT,
979
+ promptEnabled: readSettings().promptEnabled !== false,
980
+ // AI 发送方式设置:auto(默认)/ text(纯文字)/ image(总是发图)
981
+ sendMode: normalizeSendMode(s.sendMode),
982
+ // 表情排布设置:inline = 图文并排(默认)/ stacked = 图独占一行(issue #50)
983
+ layoutMode: normalizeLayoutMode(s.layoutMode),
984
+ // 局域网访问图库(issue #54):默认关;打开后手机/平板经局域网 IP 才能看到表情包
985
+ allowLanAccess: s.allowLanAccess === true,
986
+ pluginVersion,
987
+ remoteSubs: remoteSubs(),
988
+ remoteDirUrl: remoteDirUrlList(),
989
+ // 用户设置里的原始自定义源(空 = 自动/内置多镜像);设置页输入框用它回显
990
+ remoteDirUrlSetting: typeof s.remoteDirUrl === 'string' ? s.remoteDirUrl : '',
991
+ configured: !!(s.memeRoot || s.packId),
992
+ }
993
+ }
994
+ const reloadMemeStore = (dir, packId) => {
995
+ // 目录不存在则创建;没有 index.db 则初始化空图库(用户可传图/学图逐步填充)
996
+ mkdirSync(dir, { recursive: true })
997
+ const indexPath = join(dir, 'index.db')
998
+ if (!existsSync(indexPath)) {
999
+ const initDb = new DatabaseSync(indexPath)
1000
+ initDb.exec('CREATE TABLE IF NOT EXISTS memes (path TEXT PRIMARY KEY, tag TEXT, file_name TEXT, caption TEXT, keywords TEXT, mtime REAL, captioned_at REAL)')
1001
+ initDb.close()
1002
+ }
1003
+ const next = new MemesStore(dir)
1004
+ const nextDb = openIndexWriter(dir)
1005
+ const abs = resolve(dir)
1006
+ const hit = scanPacks(packsDirNow()).find((p) => resolve(p.path) === abs)
1007
+ writeSettings({
1008
+ memeRoot: abs,
1009
+ packId: packId || (hit ? hit.id : '_custom'),
1010
+ })
1011
+ try { adminDb.close() } catch { /* 已关闭 */ }
1012
+ memes.replace(next)
1013
+ adminDb = nextDb
1014
+ }
1015
+
1016
+ const validTagRe = /^[a-z0-9_-]+$/
1017
+ const IMAGE_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp']
1018
+
1019
+ const takeImageRefs = (content, out) => {
1020
+ if (!Array.isArray(content)) return
1021
+ for (const b of content) {
1022
+ if (b && b.type === 'image' && b.attachment) out.push(b.attachment)
1023
+ if (b && b.type === 'tool-result') takeImageRefs(b.content, out)
1024
+ }
1025
+ }
1026
+ /** 会话里用户发过的图片附件。模型 prompt 里没有 attachmentId(图在 UI 里,发给模型的是像素或转写文字),学图时默认取最近一张。 */
1027
+ const userImageRefs = (exec) => {
1028
+ const out = []
1029
+ const agent = exec && exec.agent
1030
+ const inbox = agent && agent.inbox
1031
+ if (inbox) {
1032
+ for (const msg of [...(inbox.nextTurn || []), ...(inbox.nextStep || [])]) takeImageRefs(msg.content, out)
1033
+ }
1034
+ const session = agent && agent.session
1035
+ if (session && typeof session.deriveMessages === 'function') {
1036
+ for (const msg of session.deriveMessages()) {
1037
+ if (msg && msg.role === 'user') takeImageRefs(msg.content, out)
1038
+ }
1039
+ }
1040
+ return out
1041
+ }
1042
+
1043
+ // ---- AI 自动学表情包:用户附件或 URL,下载收录进图库 ----
1044
+ // 与 send_meme 一样走 registerToolWhenReady:冷启动时 ctx.tools 未就绪,
1045
+ // 同步 register 静默无效,learn_meme 会跟着一起缺席(issue #51)。
1046
+ registerToolWhenReady(ctx, 'learn_meme', () => ctx.tools.register(defineTool({
1047
+ name: 'learn_meme',
1048
+ description: '把一张图片收录进表情包图库(自动学图)。' +
1049
+ '仅当用户明确要求收藏/收录/保存这张图时使用(如「收藏这个表情」「收进图库」)。' +
1050
+ '用户发表情/发图是斗图,不是收藏请求——不要自动收录,正常回应即可。' +
1051
+ '插件会自动识别图片内容(分类/描述/关键词)后存入图库;tag/caption/keywords 可选,手动指定优先。' +
1052
+ '用户刚发的图片附件:直接调用即可,不必传 attachmentId(id 不会出现在 prompt 里,默认收录最近一张用户图)。也可用 attachmentId 或 http(s) imageUrl。',
1053
+ parameters: {
1054
+ attachmentId: { type: 'string', description: '可选。对话附件 id;不传则收录最近一张用户图片' },
1055
+ imageUrl: { type: 'string', description: '可选。图片 http(s) URL,与附件二选一' },
1056
+ tag: { type: 'string', description: '手动指定分类,如 angry/happy(可选,默认自动识别)' },
1057
+ caption: { type: 'string', description: '手动指定描述(可选,默认自动识别)' },
1058
+ keywords: { type: 'string', description: '手动指定搜索关键词,空格分隔(可选,默认自动识别)' },
1059
+ },
1060
+ output: {
1061
+ schema: { type: 'json' },
1062
+ render: (_args, value) => [{ type: 'text', text: value.message }],
1063
+ },
1064
+ async execute(args, exec) {
1065
+ const imageUrl = typeof args.imageUrl === 'string' ? args.imageUrl.trim() : ''
1066
+ const attachmentId = typeof args.attachmentId === 'string' ? args.attachmentId.trim() : ''
1067
+ let tag = typeof args.tag === 'string' ? args.tag.trim().toLowerCase() : ''
1068
+ let caption = String(args.caption || '').trim().slice(0, 200)
1069
+ let keywords = String(args.keywords || '').trim().slice(0, 200)
1070
+ try {
1071
+ let buf
1072
+ let mime
1073
+ let fileName
1074
+ let ext
1075
+ let refName = '' // 附件原始文件名:附件是 .gif 而字节不是 GIF = 聊天通道压平了动图
1076
+ if (!imageUrl) {
1077
+ const refs = userImageRefs(exec)
1078
+ const ref = attachmentId
1079
+ ? refs.find((r) => String(r.attachmentId) === attachmentId)
1080
+ : refs[refs.length - 1]
1081
+ if (!ref) {
1082
+ return { ok: false, message: attachmentId
1083
+ ? '找不到附件 ' + attachmentId + '(必须是本次对话上传的图片)'
1084
+ : '对话里没有用户图片附件' }
1085
+ }
1086
+ const stored = await ctx.get('attachments').readImage(ref)
1087
+ buf = stored.data
1088
+ // MIME/扩展名以字节嗅探为准,附件元数据只作兜底:元数据与真实字节不符时
1089
+ // (如 JPEG 标成 image/gif)照元数据落盘会让图片路由返回错误的 Content-Type(issue #36)。
1090
+ mime = sniffImageMime(buf) || String(stored.ref.mediaType || '')
1091
+ ext = extByMime(mime)
1092
+ if (!ext) {
1093
+ const named = stored.ref.name && stored.ref.name.includes('.') ? '.' + stored.ref.name.split('.').pop().toLowerCase() : ''
1094
+ ext = IMAGE_EXTS.includes(named) ? named : '.jpg'
1095
+ }
1096
+ fileName = stored.ref.name || 'meme' + ext
1097
+ refName = String(stored.ref.name || '')
1098
+ } else {
1099
+ if (!/^https?:\/\//i.test(imageUrl)) return { ok: false, message: 'imageUrl 必须是 http(s) 链接' }
1100
+ const res = await fetch(imageUrl, { signal: AbortSignal.timeout(15000), redirect: 'follow' })
1101
+ if (!res.ok) return { ok: false, message: '下载失败: HTTP ' + res.status }
1102
+ const ctype = String(res.headers.get('content-type') || '')
1103
+ const m = /image\/(jpeg|png|gif|webp)/.exec(ctype)
1104
+ const declared = m ? IMAGE_KEY_MIME[m[1]] : ''
1105
+ if (!declared) return { ok: false, message: '该 URL 不是图片(jpg/png/gif/webp)' }
1106
+ buf = Buffer.from(await res.arrayBuffer())
1107
+ if (buf.byteLength === 0 || buf.byteLength > 8 * 1024 * 1024) return { ok: false, message: '图片大小超限(≤8MB)' }
1108
+ // 响应头 Content-Type 同样只是声明:字节能嗅出来就以字节为准(issue #36,与附件分支同一处理)
1109
+ mime = sniffImageMime(buf) || declared
1110
+ ext = extByMime(mime) || '.jpg'
1111
+ fileName = imageUrl.split('/').pop() || 'meme' + ext
1112
+ }
1113
+ if (buf.byteLength === 0 || buf.byteLength > 8 * 1024 * 1024) return { ok: false, message: '图片大小超限(≤8MB)' }
1114
+ // 未指定分类时自动识图(学图即识图)
1115
+ let auto = false
1116
+ let animInfo = null
1117
+ if (!tag) {
1118
+ const sel = ctx.agentDefaultModel && typeof ctx.agentDefaultModel.currentSelection === 'function'
1119
+ ? ctx.agentDefaultModel.currentSelection() : null
1120
+ const r = await recognizeImageBytes(ctx.get('llm'), sel, buf, mime, fileName)
1121
+ auto = true
1122
+ animInfo = r.animation
1123
+ if (!tag) tag = r.tag
1124
+ if (!caption) caption = r.caption
1125
+ if (!keywords) keywords = r.keywords
1126
+ }
1127
+ if (!tag || !validTagRe.test(tag)) return { ok: false, message: '分类无效(tag 只能小写字母/数字/-/_),请手动指定 tag' }
1128
+ // 落点:当前图库在插件包内(升级会被清空)时改写「我的收藏」。附件是 GIF
1129
+ // 但字节已不是 GIF → 宿主聊天通道把它压成了单帧,结果里要给用户保真路径。
1130
+ const targetRoot = writeTarget()
1131
+ const redirected = resolve(targetRoot) !== resolve(memes.root)
1132
+ const gifFlattened = !imageUrl && /\.gif$/i.test(refName) && mime !== 'image/gif'
1133
+ const name = Date.now() + '_' + Math.floor(Math.random() * 1000) + ext
1134
+ const rel = 'memes/' + tag + '/' + name
1135
+ mkdirSync(join(targetRoot, 'memes', tag), { recursive: true })
1136
+ writeFileSync(join(targetRoot, rel), buf)
1137
+ if (redirected) {
1138
+ const w = openIndexWriter(targetRoot)
1139
+ try {
1140
+ w.prepare('INSERT INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
1141
+ .run(rel, tag, name, caption, keywords, Date.now(), Date.now())
1142
+ } finally { try { w.close() } catch { /* 已关闭 */ } }
1143
+ } else {
1144
+ adminDb.prepare('INSERT INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
1145
+ .run(rel, tag, name, caption, keywords, Date.now(), Date.now())
1146
+ }
1147
+ memes.refresh()
1148
+ return { ok: true, path: rel, tag, url: ROUTE + '/' + (redirected ? USER_PACK_ID + '/' : '') + rel, message: '已收录: [' + tag + '] ' + (caption || name) + (auto ? ' (AI 自动识别' + (animInfo ? ',动图 ' + animInfo.frameCount + ' 帧' + (animInfo.filmstrip ? ',已抽帧给模型' : '') : '') + ')' : '') + ' → ' + rel
1149
+ + (redirected ? ';已存入「我的收藏」(内置图库随插件升级会被清空)' : '')
1150
+ + (gifFlattened ? ';注意:这张 GIF 在聊天上传时已被压成单帧,想保留动画请用设置面板上传,或把 GIF 文件放进图库目录后点「扫描新增」' : '') }
1151
+ } catch (error) {
1152
+ return { ok: false, message: '收录失败: ' + (error instanceof Error ? error.message : String(error)) }
1153
+ }
1154
+ },
1155
+ })))
1156
+
1157
+ // ---- 图库维护工具(issue #53):agent 侧此前只有「加」(learn_meme),没有看/改 ----
1158
+ // meme_list 只读清单(找重复、核对分类);meme_update 改元数据(分类/描述/关键词),
1159
+ // 文件不动只改索引。删除不给 agent——误删成本高,留在管理面板。
1160
+ // 把 meme_list/send_meme 候选里的 path(可能带包前缀、可能是当前库相对路径、
1161
+ // 也可能是 IM 模式给的绝对路径)定位到 { pack, rel }。
1162
+ const locateMemePath = (input) => {
1163
+ const raw = String(input || '').trim()
1164
+ if (!raw) return null
1165
+ const packs = packRows()
1166
+ const abs = resolve(raw)
1167
+ for (const p of packs) {
1168
+ const root = resolve(p.path)
1169
+ if (abs === root || abs.startsWith(root + sep)) {
1170
+ return { pack: p, rel: abs.slice(root.length + 1).replace(/\\/g, '/') }
1171
+ }
1172
+ }
1173
+ const slash = raw.indexOf('/')
1174
+ const first = slash > 0 ? raw.slice(0, slash) : ''
1175
+ if (first) {
1176
+ const hit = packs.find((p) => p.id === first)
1177
+ if (hit) return { pack: hit, rel: raw.slice(slash + 1) }
1178
+ }
1179
+ const active = packs.find((p) => p.id === activePackId())
1180
+ return active ? { pack: active, rel: raw } : null
1181
+ }
1182
+ registerToolWhenReady(ctx, 'meme_list', () => ctx.tools.register(defineTool({
1183
+ name: 'meme_list',
1184
+ description: '列出图库里的表情包清单(只读,维护用):按关键词/分类/图库筛选,每张带 所属图库、分类、描述、关键词、path。找重复图、核对错分类、整理描述时用;发给用户看图请用 send_meme。改元数据用 meme_update。',
1185
+ parameters: {
1186
+ q: { type: 'string', description: '关键词(可选,空格分隔多个全命中):按 描述/关键词/文件名 子串筛' },
1187
+ tag: { type: 'string', description: '分类(可选,如 happy)' },
1188
+ packId: { type: 'string', description: '只看某个图库(可选,图库 id;不填 = 所有启用中的图库)' },
1189
+ limit: { type: 'number', description: '最多返回几张(默认 20,最大 100;清单长就分批看)' },
1190
+ },
1191
+ output: {
1192
+ schema: { type: 'json' },
1193
+ render: (_args, value) => [{ type: 'text', text: value.message }],
1194
+ },
1195
+ execute(args) {
1196
+ const q = typeof args.q === 'string' ? args.q.trim().toLowerCase() : ''
1197
+ const tag = typeof args.tag === 'string' ? args.tag.trim().toLowerCase() : ''
1198
+ const packId = typeof args.packId === 'string' ? args.packId.trim() : ''
1199
+ const limit = Math.max(1, Math.min(100, Math.floor(Number(args.limit) || 20)))
1200
+ const packs = packRows().filter((p) => (packId ? p.id === packId : enabledIds().includes(p.id)))
1201
+ if (packId && packs.length === 0) return { ok: false, message: '图库不存在: ' + packId }
1202
+ const active = activePackId()
1203
+ const matched = []
1204
+ let total = 0
1205
+ for (const p of packs) {
1206
+ const listed = withStore(p.path, (store) => store.list(tag || undefined))
1207
+ if (!listed) continue
1208
+ for (const m of listed.memes) {
1209
+ total++
1210
+ if (!q) { matched.push({ pack: p, m }); continue }
1211
+ const hay = ((m.caption || '') + ' ' + (m.keywords || '') + ' ' + (m.file_name || '')).toLowerCase()
1212
+ if (q.split(/\s+/).filter(Boolean).every((t) => hay.includes(t))) matched.push({ pack: p, m })
1213
+ }
1214
+ }
1215
+ const rows = matched.slice(0, limit).map(({ pack: p, m }) => ({
1216
+ library: p.name + '(' + p.id + ')',
1217
+ tag: m.tag,
1218
+ caption: m.caption || m.file_name,
1219
+ keywords: m.keywords || '',
1220
+ // 与 send_meme 候选同款约定:当前激活库不带前缀,其它库带包前缀
1221
+ path: (p.id === active ? '' : p.id + '/') + m.path,
1222
+ }))
1223
+ const lines = rows.map((r, i) => (i + 1) + '. [' + r.tag + '] ' + r.caption + ' | 库=' + r.library + ' | path=' + r.path)
1224
+ return {
1225
+ ok: true,
1226
+ total,
1227
+ shown: rows.length,
1228
+ rows,
1229
+ message: (packId ? '图库 ' + packId : '启用中的图库') + ' 共 ' + total + ' 张' +
1230
+ (q || tag ? ',筛中 ' + matched.length : '') +
1231
+ (matched.length > rows.length ? ',本次列出前 ' + rows.length + ' 张(要全量就加 limit 或换更细的筛)' : '') +
1232
+ '。改描述/分类用 meme_update。\n' + (lines.length ? lines.join('\n') : '(没有匹配的图)'),
1233
+ }
1234
+ },
1235
+ })))
1236
+ registerToolWhenReady(ctx, 'meme_update', () => ctx.tools.register(defineTool({
1237
+ name: 'meme_update',
1238
+ description: '修改图库里一张表情包的元数据:分类/描述/关键词任选,至少给一项。只改索引不改图片文件。path 用 meme_list 或 send_meme 候选里的原样。',
1239
+ parameters: {
1240
+ path: { type: 'string', description: '要改的那张图的 path(meme_list/send_meme 候选里的原样)' },
1241
+ tag: { type: 'string', description: '新分类(可选,小写字母/数字/-/_)' },
1242
+ caption: { type: 'string', description: '新描述(可选,一句话中文)' },
1243
+ keywords: { type: 'string', description: '新关键词(可选,空格分隔)' },
1244
+ },
1245
+ output: {
1246
+ schema: { type: 'json' },
1247
+ render: (_args, value) => [{ type: 'text', text: value.message }],
1248
+ },
1249
+ execute(args) {
1250
+ const path = String(args.path || '').trim()
1251
+ const tag = args.tag != null ? String(args.tag).trim().toLowerCase() : null
1252
+ const caption = args.caption != null ? String(args.caption).trim().slice(0, 200) : null
1253
+ const keywords = args.keywords != null ? String(args.keywords).trim().slice(0, 200) : null
1254
+ if (!path) return { ok: false, message: '缺少 path——先用 meme_list 找到那张图' }
1255
+ if (tag == null && caption == null && keywords == null) {
1256
+ return { ok: false, message: '至少给一项要改的字段(tag/caption/keywords)' }
1257
+ }
1258
+ if (tag != null && !validTagRe.test(tag)) return { ok: false, message: 'tag 只能是小写字母/数字/-/_' }
1259
+ const located = locateMemePath(path)
1260
+ if (!located) return { ok: false, message: '找不到这张图: ' + path + '(path 用 meme_list/send_meme 候选里的原样)' }
1261
+ const row = withStore(located.pack.path, (store) => store.list().memes.find((m) => m.path === located.rel))
1262
+ if (!row) return { ok: false, message: '索引里没有这张图: ' + path }
1263
+ const nextTag = tag ?? row.tag
1264
+ const nextCaption = caption ?? (row.caption || '')
1265
+ const nextKeywords = keywords ?? (row.keywords || '')
1266
+ const w = openIndexWriter(located.pack.path)
1267
+ try {
1268
+ w.prepare('UPDATE memes SET tag = ?, caption = ?, keywords = ? WHERE path = ?')
1269
+ .run(nextTag, nextCaption, nextKeywords, located.rel)
1270
+ } finally { try { w.close() } catch { /* 已关闭 */ } }
1271
+ if (resolve(located.pack.path) === resolve(memes.root)) memes.refresh()
1272
+ return { ok: true, path, tag: nextTag, caption: nextCaption, keywords: nextKeywords, message: '已更新: [' + nextTag + '] ' + nextCaption + (nextKeywords ? '(关键词: ' + nextKeywords + ')' : '') }
1273
+ },
1274
+ })))
1275
+
1276
+ // ---- AI 识图核心:当前默认模型识别图片 → 分类/描述/关键词 ----
1277
+ async function recognizeImageBytes(llm, sel, buf, mime, fileName) {
1278
+ const provider = sel && sel.provider
1279
+ const model = sel && sel.model
1280
+ if (!llm || !provider || !model) throw new Error('未配置模型,无法识图')
1281
+ const info = await llm.resolveModelInfo(provider, model)
1282
+ const modalities = info && info.inputModalities
1283
+ if (!Array.isArray(modalities) || !modalities.includes('image')) {
1284
+ throw new Error('当前模型「' + model + '」不支持图片输入,无法识图')
1285
+ }
1286
+ // 先 materialize 默认配置(reasoningEffort 等),否则 stream 时配置比对不一致报错
1287
+ // (历史教训: prepared LLM call config changed before adapter dispatch)
1288
+ const base = await llm.resolveCallConfig({ provider, model, maxTokens: 4096 })
1289
+ const prepared = await llm.prepareCall(base)
1290
+ const prompt = '你是表情包分类助手。识别这张表情包图片,只输出 JSON(不要任何其他文字):\n' +
1291
+ '{"tag":"分类(小写英文,参考: angry生气 happy开心 sad难过 shy害羞 confused困惑 surprised惊讶 sleep睡觉 work上班 like喜欢 see看看 meow喵喵 speechless无语),选最贴切的一个","caption":"一句话中文描述这张图表达的情绪/梗","keywords":"3-5个中文搜索词,空格分隔"}\n'
1292
+ const anim = detectAnimation(buf)
1293
+ const strip = anim && anim.format === 'gif' ? buildAnimationFilmstrip(buf, { maxFrames: ANIM_DEFAULT_FRAMES }) : null
1294
+ const animNote = anim ? animationModelNote(anim, strip) : ''
1295
+ const textPart = { type: 'text', text: animNote ? prompt + '\n\n' + animNote : prompt }
1296
+ let imagePart
1297
+ if (strip) {
1298
+ const rawName = fileName || 'meme'
1299
+ const dot = rawName.lastIndexOf('.')
1300
+ const baseName = dot > 0 ? rawName.slice(0, dot) : 'meme'
1301
+ imagePart = { type: 'image', attachment: await ctx.get('attachments').saveImage({ data: strip.png, mediaType: 'image/png', name: baseName + '-frames.png' }) }
1302
+ } else {
1303
+ imagePart = { type: 'image', attachment: await ctx.get('attachments').saveImage({ data: buf, mediaType: mime, name: fileName }) }
1304
+ }
1305
+ let out = ''
1306
+ let reason = ''
1307
+ for await (const chunk of prepared.stream({ ...base, messages: [{ role: 'user', content: [textPart, imagePart] }] })) {
1308
+ if (chunk.type === 'text-delta') out += chunk.text
1309
+ else if (chunk.type === 'reasoning-delta') reason += chunk.text
1310
+ else if (chunk.type === 'finish' && chunk.reason && chunk.reason.kind === 'error') {
1311
+ throw new Error('模型调用失败: ' + (chunk.reason.failure && chunk.reason.failure.message || JSON.stringify(chunk.reason.failure)))
1312
+ }
1313
+ }
1314
+ // 思考型模型可能把 JSON 写在 reasoning 里,正文为空时兜底解析
1315
+ const m = /\{[\s\S]*\}/.exec(out) || /\{[\s\S]*\}/.exec(reason)
1316
+ if (!m) throw new Error('模型未返回有效 JSON')
1317
+ const parsed = JSON.parse(m[0])
1318
+ const tag = String(parsed.tag || '').trim().toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 20)
1319
+ const caption = String(parsed.caption || '').trim().slice(0, 200)
1320
+ const keywords = String(parsed.keywords || '').trim().slice(0, 200)
1321
+ if (!tag) throw new Error('模型未给出分类')
1322
+ return {
1323
+ tag, caption, keywords,
1324
+ animation: anim ? { format: anim.format, frameCount: anim.frameCount, totalMs: anim.totalMs, filmstrip: !!strip } : null,
1325
+ }
1326
+ }
1327
+
1328
+ // ---- 远程图库订阅:清单 JSON → 按需下载成本地包(格式见 docs/remote-pack-spec.md) ----
1329
+ // 订阅 = 服务端拉清单 + 并发下载图片 + 建索引,写入扫描目录;进度经 remoteJobStatus 轮询。
1330
+ // 已下载的包再次提交同一清单 URL 自动转为增量更新(按 .dsh-remote.json 侧车文件识别)。
1331
+ const remoteJobs = new Map() // jobId → job(内存态,重启即清;残留 .tmp 目录在插件启动时清理)
1332
+ let remoteJobSeq = 0
1333
+ const REMOTE_MANIFEST_MAX = 2 * 1024 * 1024
1334
+ const REMOTE_IMAGE_MAX = 8 * 1024 * 1024
1335
+ const REMOTE_ARCHIVE_MAX = 100 * 1024 * 1024
1336
+ const REMOTE_CONCURRENCY = 4
1337
+ const REMOTE_MAX_ITEMS = 500
1338
+ const PREVIEW_MAX = 60 // 预览弹窗最多列这么多张(清单包里可能上百张)
1339
+ const SIDECAR_NAME = '.dsh-remote.json'
1340
+ // 图库目录源:settings.remoteDirUrl > patch config.remoteDirUrl > 内置默认。
1341
+ // 每次请求现读 settings:改配置文件即刻生效,不用重启。
1342
+ // 设置值:''/'auto' = 自动多镜像;'official'/'mirror' = 预设;自定义 http(s) URL。
1343
+ const remoteDirSetting = () => {
1344
+ const value = readSettings().remoteDirUrl
1345
+ return typeof value === 'string' ? value.trim() : ''
1346
+ }
1347
+ // 原始设置 → 归一值:老配置的 'auto' 统一成 '',预设转小写;自定义 URL 原样返回
1348
+ const normalizedDirSetting = () => {
1349
+ const raw = remoteDirSetting()
1350
+ if (!raw || raw.toLowerCase() === 'auto') return ''
1351
+ const key = raw.toLowerCase()
1352
+ return REMOTE_DIR_PRESETS.includes(key) ? key : raw
1353
+ }
1354
+ const dirSourceLabel = (setting) => {
1355
+ const key = String(setting || '').trim().toLowerCase()
1356
+ if (!key || key === 'auto') return REMOTE_DIR_PRESET_LABELS.auto
1357
+ if (REMOTE_DIR_PRESETS.includes(key)) return REMOTE_DIR_PRESET_LABELS[key]
1358
+ return '自定义源:' + String(setting)
1359
+ }
1360
+ // patch 配置兜底源:可以是数组(源列表)也可以是字符串(单源)
1361
+ const fallbackDirUrls = () => {
1362
+ const value = config?.remoteDirUrl
1363
+ if (Array.isArray(value) || typeof value === 'string') return [].concat(value)
1364
+ return DEFAULT_REMOTE_DIR_URLS
1365
+ }
1366
+ // 目录候选分组:预设/自动/自定义都归一成「源 + 实时层 + 兜底层」,拉取和缓存判断共用
1367
+ const directoryGroups = () => directoryGroupsFor(normalizedDirSetting(), fallbackDirUrls())
1368
+ // 给前端/排错统一返回实际会尝试的目录 URL 数组(展开镜像链,去重)
1369
+ const remoteDirUrlList = () => {
1370
+ const out = []
1371
+ for (const group of directoryGroups()) {
1372
+ for (const u of [...group.tier0, ...group.tier1]) if (!out.includes(u)) out.push(u)
1373
+ }
1374
+ return out
1375
+ }
1376
+ const remoteSubs = () => {
1377
+ const subs = readSettings().remoteSubs
1378
+ return Array.isArray(subs) ? subs : []
1379
+ }
1380
+ let remoteDirCache = null // {at, data},60s 内复用,面板每次挂载拉一次也不怕
1381
+ let downloadCache = { at: 0, data: {}, key: '' }
1382
+ // 图库目录拉取结果元信息(给 UI:当前源 / 是否本地缓存 / 最后错误),跨请求保留
1383
+ let remoteDirMeta = { source: '', cached: false, error: '' }
1384
+ // 目录最近一次从哪条镜像链路拉到 → 后续清单/图片/ZIP 下载优先走它(别逐次重试被墙直链)
1385
+ let preferredMirrorPrefix = ''
1386
+ const REMOTE_DIR_ATTEMPT_TIMEOUT = 6000
1387
+ // 上次成功拉到的目录落盘:所有镜像都挂时至少还能看到目录、安装旧版本图库(UI 会带「本地缓存」提示)
1388
+ const catalogCacheFile = join(dshHome(), '.dsh', 'dsh-meme-catalog-cache.json')
1389
+ const withCacheBust = (u) => u + (u.includes('?') ? '&' : '?') + 't=' + Date.now()
1390
+ const shortFetchError = (error) => {
1391
+ const cause = error && error.cause
1392
+ const text = cause ? (cause.code || cause.message) : (error instanceof Error ? error.message : String(error))
1393
+ return String(text || '未知错误').slice(0, 120)
1394
+ }
1395
+ const readCatalogCache = () => {
1396
+ try {
1397
+ const raw = readFileSync(catalogCacheFile, 'utf8')
1398
+ if (raw.length > 4 * 1024 * 1024) return null
1399
+ const parsed = JSON.parse(raw)
1400
+ if (!parsed || !Array.isArray(parsed.entries) || parsed.entries.length === 0 || !parsed.url) return null
1401
+ return parsed
1402
+ } catch { return null }
1403
+ }
1404
+ const writeCatalogCache = (source, entries, sourceUrl) => {
1405
+ try {
1406
+ mkdirSync(dirname(catalogCacheFile), { recursive: true })
1407
+ // source = 实际拉通的镜像 URL(展示用);sourceUrl = 用户配置里的那条源(下次判断缓存还属不属于当前源)
1408
+ writeFileSync(catalogCacheFile, JSON.stringify({ at: Date.now(), url: source, sourceUrl, entries }))
1409
+ } catch { /* 缓存写不进去不影响功能 */ }
1410
+ }
1411
+ /** 解析目录 JSON:支持裸数组与 { packs: [] },过滤掉没有下载地址的脏条目。 */
1412
+ const readDirectoryPayload = async (res) => {
1413
+ const raw = await res.json()
1414
+ const list = Array.isArray(raw) ? raw : (Array.isArray(raw && raw.packs) ? raw.packs : null)
1415
+ if (!list) throw new Error('目录不是数组或 { packs: [] }')
1416
+ return list.filter((e) => e && (e.manifestUrl || e.archiveUrl))
1417
+ }
1418
+ /** 同一层候选并发竞速:谁先返回合法目录用谁,其余请求中止(被墙直链不会拖住整个面板)。 */
1419
+ const raceDirectoryUrls = async (cands, perAttemptTimeout = REMOTE_DIR_ATTEMPT_TIMEOUT) => {
1420
+ const errors = []
1421
+ if (!Array.isArray(cands) || cands.length === 0) return { ok: false, errors }
1422
+ const ctrl = new AbortController()
1423
+ const result = await Promise.any(cands.map(async (u) => {
1424
+ try {
1425
+ const res = await fetch(withCacheBust(u), {
1426
+ // 单次 6s 上限(可被总预算压低):国内直连 raw 往往一直挂着,不能等 8s 才换下一个
1427
+ signal: AbortSignal.any([ctrl.signal, AbortSignal.timeout(Math.max(1000, perAttemptTimeout))]),
1428
+ redirect: 'follow',
1429
+ })
1430
+ if (!res.ok) throw new Error('HTTP ' + res.status)
1431
+ return { ok: true, entries: await readDirectoryPayload(res), source: u }
1432
+ } catch (error) {
1433
+ errors.push(u + ' → ' + shortFetchError(error))
1434
+ throw error
1435
+ }
1436
+ })).catch(() => null)
1437
+ ctrl.abort()
1438
+ return result || { ok: false, errors }
1439
+ }
1440
+ /**
1441
+ * 资产下载(清单/图片/ZIP)的候选顺序:目录拉取成功的镜像链路排第一,其余按 remoteMirrors 顺序。
1442
+ * 国内网络下目录多半是某条加速前缀拉到的,把那条链路复用到图片下载,省掉每张图先等直链超时。
1443
+ */
1444
+ const assetMirrors = (url) => {
1445
+ const list = remoteMirrors(url)
1446
+ if (!preferredMirrorPrefix || list.length < 2) return list
1447
+ const hit = list.find((u) => u.startsWith(preferredMirrorPrefix))
1448
+ if (!hit) return list
1449
+ return [hit, ...list.filter((u) => u !== hit)]
1450
+ }
1451
+ /**
1452
+ * 下载量是活数据,不进 catalog.json:服务端代拉 GitHub releases(一个请求拿全),
1453
+ * 缓存 30 分钟。只认 archiveUrl 指向 github.com 的条目,清单热链的包没有 release
1454
+ * 可数,就不显示。失败一律当「没有数据」,不影响目录本身。
1455
+ */
1456
+ const fetchDownloadCounts = async (entries) => {
1457
+ const repos = new Set()
1458
+ for (const e of (entries || [])) {
1459
+ const m = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/releases\/download\//.exec(String((e && e.archiveUrl) || ''))
1460
+ if (m) repos.add(m[1] + '/' + m[2])
1461
+ }
1462
+ const key = [...repos].sort().join(',')
1463
+ if (!key) return {}
1464
+ // 匿名 API 额度是 60 次/小时/IP:缓存 30 分钟,一次打开发现页最多触发一次
1465
+ if (downloadCache.key === key && Date.now() - downloadCache.at < 1800000) return downloadCache.data
1466
+ const merged = {}
1467
+ for (const repo of repos) {
1468
+ try {
1469
+ const res = await fetch('https://api.github.com/repos/' + repo + '/releases?per_page=100', {
1470
+ headers: { Accept: 'application/vnd.github+json', 'User-Agent': 'dsh-meme' },
1471
+ signal: AbortSignal.timeout(8000),
1472
+ })
1473
+ if (!res.ok) continue
1474
+ Object.assign(merged, parseDownloadCounts(await res.json()))
1475
+ } catch { /* 拉不到就少显示一个数字 */ }
1476
+ }
1477
+ downloadCache = { at: Date.now(), data: merged, key }
1478
+ return merged
1479
+ }
1480
+
1481
+ const fetchRemoteDirectory = async () => {
1482
+ if (remoteDirCache && Date.now() - remoteDirCache.at < 60000) {
1483
+ remoteDirMeta = { source: remoteDirCache.source, cached: false, error: '' }
1484
+ return remoteDirCache.data
1485
+ }
1486
+ const groups = directoryGroups()
1487
+ const errors = []
1488
+ // 总预算:源多(默认 4 条)且都被墙时,不能一条条等满 6s×2 层,12s 后直接走磁盘缓存/报错
1489
+ const startedAt = Date.now()
1490
+ const DIR_TOTAL_BUDGET = 12000
1491
+ for (const group of groups) {
1492
+ if (Date.now() - startedAt > DIR_TOTAL_BUDGET) break
1493
+ // 先竞速「内容实时」的一层(直链 + gh 加速);全挂再试 jsDelivr(可能滞留 12h 的旧目录)
1494
+ for (const tier of [group.tier0, group.tier1]) {
1495
+ const remaining = DIR_TOTAL_BUDGET - (Date.now() - startedAt)
1496
+ if (remaining <= 0) break
1497
+ const r = await raceDirectoryUrls(tier, Math.min(REMOTE_DIR_ATTEMPT_TIMEOUT, remaining))
1498
+ if (r.ok) {
1499
+ const data = { entries: r.entries, source: r.source, cached: false }
1500
+ remoteDirCache = { at: Date.now(), data, source: r.source }
1501
+ preferredMirrorPrefix = mirrorProviderPrefix(r.source) || preferredMirrorPrefix
1502
+ writeCatalogCache(r.source, r.entries, group.key)
1503
+ remoteDirMeta = { source: r.source, cached: false, error: '' }
1504
+ return data
1505
+ }
1506
+ errors.push(...r.errors)
1507
+ }
1508
+ }
1509
+ // 全部镜像失败:回退上次成功拉到的磁盘缓存(至少让用户看到目录,能装旧版本)
1510
+ const cached = readCatalogCache()
1511
+ // 缓存归属按「源分组 key」判断(自动=源 URL、预设=official/mirror);
1512
+ // 老缓存没有 sourceUrl,只能拿实际拉通的镜像 URL 比对
1513
+ if (cached && groups.some((g) => g.key === (cached.sourceUrl || cached.url))) {
1514
+ remoteDirMeta = { source: cached.url, cached: true, error: errors[0] || '' }
1515
+ return { entries: cached.entries, source: cached.url, cached: true }
1516
+ }
1517
+ remoteDirMeta = { source: '', cached: false, error: errors[0] || '目录源全部不可用' }
1518
+ return null
1519
+ }
1520
+ const jobSnapshot = (job) => ({
1521
+ id: job.id, packId: job.packId, name: job.name, mode: job.mode,
1522
+ total: job.total, done: job.done, failed: job.failed,
1523
+ added: job.added, updated: job.updated,
1524
+ state: job.state, message: job.message,
1525
+ errors: job.errors.slice(0, 5), warnings: job.warnings.slice(0, 10),
1526
+ })
1527
+ const fetchRemoteJson = async (url) => {
1528
+ if (!/^https?:\/\//i.test(String(url || ''))) throw new Error('清单地址必须是 http(s) 链接')
1529
+ let lastError = ''
1530
+ // 清单也走镜像:国内直连 raw 拉清单同样会失败(清单下载是订阅/预览的第一步)
1531
+ for (const u of assetMirrors(url)) {
1532
+ let res
1533
+ try {
1534
+ res = await fetch(u, { signal: AbortSignal.timeout(15000), redirect: 'follow' })
1535
+ } catch (error) {
1536
+ lastError = shortFetchError(error)
1537
+ continue
1538
+ }
1539
+ if (!res.ok) {
1540
+ lastError = 'HTTP ' + res.status
1541
+ continue
1542
+ }
1543
+ let text
1544
+ try {
1545
+ text = await res.text()
1546
+ } catch (error) {
1547
+ lastError = shortFetchError(error)
1548
+ continue
1549
+ }
1550
+ // 内容层面的错误不换镜像:JSON 坏了换哪个镜像都一样
1551
+ if (text.length > REMOTE_MANIFEST_MAX) throw new Error('清单超过 2MB,拒绝处理')
1552
+ try {
1553
+ return JSON.parse(text)
1554
+ } catch {
1555
+ throw new Error('清单不是合法 JSON')
1556
+ }
1557
+ }
1558
+ throw new Error('清单下载失败: ' + (lastError || '未知错误'))
1559
+ }
1560
+ const fmtBytes = (n) => (n >= 1048576 ? (n / 1048576).toFixed(1) + 'MB' : Math.max(1, Math.round(n / 1024)) + 'KB')
1561
+ /**
1562
+ * 下载 ZIP 并校验。逐块读,顺便通过 onProgress(已下载字节, content-length) 汇报进度
1563
+ * —— 客户端靠它画进度条(以前用 arrayBuffer 一把梭,安装期间界面上只有一句文字)。
1564
+ */
1565
+ const fetchRemoteArchive = async (url, expectedSha256, onProgress) => {
1566
+ if (!/^https?:\/\//i.test(String(url || ''))) throw new Error('ZIP 地址必须是 http(s) 链接')
1567
+ const expected = String(expectedSha256 || '').trim().toLowerCase()
1568
+ if (expected && !/^[0-9a-f]{64}$/.test(expected)) throw new Error('SHA-256 格式无效')
1569
+ let lastError = ''
1570
+ let lastWasShaMismatch = false
1571
+ // 镜像可能给旧文件/坏文件:sha256 不匹配就换下一个候选,全都不匹配才报损坏
1572
+ for (const u of assetMirrors(url)) {
1573
+ let res
1574
+ try {
1575
+ // 大包给足 3 分钟(上限 100MB,慢链路也够)
1576
+ res = await fetch(u, { signal: AbortSignal.timeout(180000), redirect: 'follow' })
1577
+ } catch (error) {
1578
+ lastError = shortFetchError(error)
1579
+ lastWasShaMismatch = false
1580
+ continue
1581
+ }
1582
+ if (!res.ok) {
1583
+ lastError = 'HTTP ' + res.status
1584
+ lastWasShaMismatch = false
1585
+ continue
1586
+ }
1587
+ const declared = Number(res.headers.get('content-length') || 0)
1588
+ if (declared > REMOTE_ARCHIVE_MAX) throw new Error('ZIP 超过 100MB,拒绝处理')
1589
+ const chunks = []
1590
+ let size = 0
1591
+ try {
1592
+ if (res.body && typeof res.body[Symbol.asyncIterator] === 'function') {
1593
+ for await (const chunk of res.body) {
1594
+ size += chunk.length
1595
+ if (size > REMOTE_ARCHIVE_MAX) throw new Error('ZIP 大小超限(≤100MB)')
1596
+ chunks.push(Buffer.from(chunk))
1597
+ if (onProgress) onProgress(size, declared)
1598
+ }
1599
+ } else {
1600
+ const one = Buffer.from(await res.arrayBuffer())
1601
+ size = one.byteLength
1602
+ chunks.push(one)
1603
+ }
1604
+ } catch (error) {
1605
+ // 大小超限是硬错误,换镜像也一样;网络中断才可以换
1606
+ if (error instanceof Error && /大小超限/.test(error.message)) throw error
1607
+ lastError = shortFetchError(error)
1608
+ lastWasShaMismatch = false
1609
+ continue
1610
+ }
1611
+ const buf = Buffer.concat(chunks)
1612
+ if (buf.byteLength === 0 || buf.byteLength > REMOTE_ARCHIVE_MAX) throw new Error('ZIP 大小超限(≤100MB)')
1613
+ const actual = createHash('sha256').update(buf).digest('hex')
1614
+ if (expected && actual !== expected) {
1615
+ lastError = 'SHA-256 不一致'
1616
+ lastWasShaMismatch = true
1617
+ continue
1618
+ }
1619
+ return { buf, sha256: actual }
1620
+ }
1621
+ if (lastWasShaMismatch) throw new Error('ZIP SHA-256 校验失败,文件可能损坏或已被替换')
1622
+ throw new Error('ZIP 下载失败: ' + (lastError || '未知错误'))
1623
+ }
1624
+ /** 单张远端图片下载:按镜像候选重试。图库动辄几十上百张图,直链被墙时不能每张都等超时。 */
1625
+ const fetchRemoteImage = async (url) => {
1626
+ let lastError = ''
1627
+ for (const u of assetMirrors(url)) {
1628
+ try {
1629
+ const res = await fetch(u, { signal: AbortSignal.timeout(20000), redirect: 'follow' })
1630
+ if (!res.ok) {
1631
+ lastError = 'HTTP ' + res.status
1632
+ continue
1633
+ }
1634
+ const buf = Buffer.from(await res.arrayBuffer())
1635
+ if (buf.byteLength === 0 || buf.byteLength > REMOTE_IMAGE_MAX) throw new Error('图片大小超限(≤8MB)')
1636
+ return buf
1637
+ } catch (error) {
1638
+ if (error instanceof Error && /大小超限/.test(error.message)) throw error
1639
+ lastError = shortFetchError(error)
1640
+ }
1641
+ }
1642
+ throw new Error('下载失败: ' + (lastError || '未知错误'))
1643
+ }
1644
+
1645
+ /** 下载完之后的校验+解包+安装(任务与旧同步路径共用)。 */
1646
+ const installArchiveBuffer = (buf, sha256, opts) => {
1647
+ const entries = unzipStore(buf)
1648
+ let manifest = {}
1649
+ try { manifest = JSON.parse(String(entries.get('manifest.json') || '{}')) } catch { throw new Error('manifest.json 不是合法 JSON') }
1650
+ const requestedId = packSlug(opts.requestedId)
1651
+ const manifestId = packSlug(manifest.id)
1652
+ const id = requestedId || manifestId
1653
+ if (!id) throw new Error('ZIP manifest.json 缺少有效 id')
1654
+ if (requestedId && manifestId && requestedId !== manifestId) {
1655
+ throw new Error('目录 id 与 ZIP manifest id 不一致,已拒绝安装')
1656
+ }
1657
+ const displayName = String(manifest.name || opts.name || id).trim().slice(0, 60) || id
1658
+ const version = String(manifest.version || opts.version || '').trim().slice(0, 40)
1659
+ const sidecar = {
1660
+ sourceType: 'archive', archiveUrl: opts.archiveUrl, sha256,
1661
+ id, name: displayName, version, lastSync: Date.now(),
1662
+ }
1663
+ installZipEntries(entries, id, sidecar)
1664
+ const total = memes.list().memes.length
1665
+ const subs = remoteSubs().filter((s) => s && s.id !== id)
1666
+ subs.unshift({ id, archiveUrl: opts.archiveUrl, sha256, name: displayName, version, total, lastSync: Date.now() })
1667
+ writeSettings({ remoteSubs: subs })
1668
+ return { id, displayName, total, files: entries.size }
1669
+ }
1670
+
1671
+ /** ZIP 安装走任务制:客户端轮询 remoteJobStatus 就能画下载进度条。 */
1672
+ const startArchiveJob = ({ archiveUrl, sha256, requestedId, name, version }) => {
1673
+ const jobId = 'ra-' + Date.now().toString(36) + '-' + (++remoteJobSeq)
1674
+ const job = {
1675
+ id: jobId, packId: packSlug(requestedId) || '', name: name || '', mode: 'archive',
1676
+ total: 0, done: 0, failed: 0, added: 0, updated: 0, warnings: [], errors: [],
1677
+ state: 'running', message: '开始下载…', startedAt: Date.now(),
1678
+ }
1679
+ remoteJobs.set(jobId, job)
1680
+ while (remoteJobs.size > 10) remoteJobs.delete(remoteJobs.keys().next().value)
1681
+ ;(async () => {
1682
+ try {
1683
+ const { buf, sha256: actual } = await fetchRemoteArchive(archiveUrl, sha256, (got, declared) => {
1684
+ job.done = got
1685
+ job.total = declared // 0 = 上游没给 content-length,客户端画不确定进度条
1686
+ job.message = '下载中 ' + fmtBytes(got) + (declared ? ' / ' + fmtBytes(declared) : '')
1687
+ })
1688
+ job.total = buf.byteLength
1689
+ job.done = buf.byteLength
1690
+ job.message = '校验通过,正在解包安装…'
1691
+ const done = installArchiveBuffer(buf, actual, { archiveUrl, requestedId, name, version })
1692
+ job.packId = done.id
1693
+ job.name = done.displayName
1694
+ job.added = done.total
1695
+ job.state = 'done'
1696
+ job.message = '安装完成,已切换到「' + done.displayName + '」'
1697
+ } catch (error) {
1698
+ job.state = 'error'
1699
+ job.message = error instanceof Error ? error.message : String(error)
1700
+ job.errors.push(String(job.message))
1701
+ }
1702
+ })()
1703
+ return job
1704
+ }
1705
+ const packSlug = (s) => String(s || '').trim().toLowerCase().replace(/[^a-z0-9_-]/g, '').replace(/^-+|-+$/g, '').slice(0, 40)
1706
+ const installZipEntries = (entries, packId, sidecar) => {
1707
+ const id = packSlug(packId)
1708
+ if (!id) throw new Error('图库 id 无效')
1709
+ if (!entries.get('index.db')) throw new Error('ZIP 里没有 index.db,不是有效的表情包包')
1710
+ // 装/导入完默认就能用:切换过去 + 打开开关(其它图库的开关保持不动)。
1711
+ // 开关状态要在切包之前取,否则「没设置过」的隐含默认会跟着变成新图库。
1712
+ const enabledBefore = enabledPackIds(readSettings(), listAllPacks(), activePackId())
1713
+ const root = resolve(packsDirNow())
1714
+ const targetAbs = resolve(join(root, id))
1715
+ if (!targetAbs.startsWith(root + sep)) throw new Error('图库目录越界')
1716
+ const nonce = Math.random().toString(16).slice(2, 10)
1717
+ const stageAbs = resolve(join(root, id + '.tmp-' + nonce))
1718
+ const backupAbs = resolve(join(root, id + '.bak-' + nonce))
1719
+ if (!stageAbs.startsWith(root + sep) || !backupAbs.startsWith(root + sep)) throw new Error('临时目录越界')
1720
+
1721
+ const files = new Map(entries)
1722
+ if (sidecar) files.set(SIDECAR_NAME, Buffer.from(JSON.stringify(sidecar, null, 2)))
1723
+ for (const [rel] of files) {
1724
+ if (!rel || /[\\\/]$/.test(rel)) continue
1725
+ const full = resolve(stageAbs, rel)
1726
+ if (full === stageAbs || !full.startsWith(stageAbs + sep)) {
1727
+ throw new Error('ZIP 条目路径越界,已拒绝导入: ' + rel)
1728
+ }
1729
+ }
1730
+
1731
+ mkdirSync(root, { recursive: true })
1732
+ rmSync(stageAbs, { recursive: true, force: true })
1733
+ rmSync(backupAbs, { recursive: true, force: true })
1734
+ try {
1735
+ mkdirSync(stageAbs, { recursive: true })
1736
+ for (const [rel, bytes] of files) {
1737
+ if (!rel || /[\\\/]$/.test(rel)) continue
1738
+ const full = resolve(stageAbs, rel)
1739
+ mkdirSync(dirname(full), { recursive: true })
1740
+ writeFileSync(full, bytes)
1741
+ }
1742
+ const verifyDb = new DatabaseSync(join(stageAbs, 'index.db'), { readOnly: true })
1743
+ try { verifyDb.prepare('SELECT COUNT(*) AS n FROM memes').get() } finally { verifyDb.close() }
1744
+ // 导入的图库常带站点级大标签(出现在几乎每条 keywords 里),对检索零信息量,
1745
+ // 还会让搜那些词命中全库(issue #30 附带的建议)。纯增强,失败不影响导入。
1746
+ try {
1747
+ const pruned = prunePackKeywords(join(stageAbs, 'index.db'))
1748
+ if (pruned.drop.length) {
1749
+ console.log('[dsh-expression] 图库 ' + id + ':剔除 ' + pruned.drop.length + ' 个高频关键词(改动 ' + pruned.changed + ' 条)- ' + pruned.drop.join(' '))
1750
+ }
1751
+ } catch (error) {
1752
+ console.warn('[dsh-expression] 高频关键词清洗跳过:', error instanceof Error ? error.message : String(error))
1753
+ }
1754
+
1755
+ const replacingActive = resolve(memes.root) === targetAbs
1756
+ if (replacingActive) {
1757
+ try { adminDb.close() } catch { /* 已关闭 */ }
1758
+ }
1759
+ let backedUp = false
1760
+ try {
1761
+ if (existsSync(targetAbs)) {
1762
+ renameSync(targetAbs, backupAbs)
1763
+ backedUp = true
1764
+ }
1765
+ renameSync(stageAbs, targetAbs)
1766
+ } catch (error) {
1767
+ if (backedUp && !existsSync(targetAbs) && existsSync(backupAbs)) renameSync(backupAbs, targetAbs)
1768
+ if (replacingActive && existsSync(targetAbs)) reloadMemeStore(targetAbs, id)
1769
+ throw error
1770
+ }
1771
+ rmSync(backupAbs, { recursive: true, force: true })
1772
+ reloadMemeStore(targetAbs, id)
1773
+ writeSettings({ enabledPacks: [...new Set([...enabledBefore, id])] })
1774
+ return targetAbs
1775
+ } finally {
1776
+ rmSync(stageAbs, { recursive: true, force: true })
1777
+ }
1778
+ }
1779
+ // 清单 → 规范化条目;单条非法只跳过并记 warning,不整体失败
1780
+ const normalizeRemoteManifest = (raw, fallbackId, sourceUrl) => {
1781
+ const items = Array.isArray(raw && raw.memes) ? raw.memes : []
1782
+ if (items.length === 0) throw new Error('清单缺少 memes 数组或为空')
1783
+ if (items.length > REMOTE_MAX_ITEMS) throw new Error('清单超过 ' + REMOTE_MAX_ITEMS + ' 条,请拆分成多个包')
1784
+ const slug = (s) => String(s || '').trim().toLowerCase().replace(/[^a-z0-9_-]/g, '').replace(/^-+|-+$/g, '').slice(0, 40)
1785
+ const id = slug(raw.id) || slug(fallbackId)
1786
+ || ('remote-' + createHash('sha1').update(String(sourceUrl || '')).digest('hex').slice(0, 8))
1787
+ const warnings = []
1788
+ const seen = new Set()
1789
+ const out = []
1790
+ for (const it of items) {
1791
+ const url = String((it && it.url) || '').trim()
1792
+ if (!/^https?:\/\//i.test(url)) { warnings.push('跳过非 http(s) 链接: ' + url.slice(0, 60)); continue }
1793
+ const tag = slug(it.tag)
1794
+ if (!tag) { warnings.push('跳过无效分类: ' + url.slice(0, 60)); continue }
1795
+ let fileName = String(it.file || '').trim().split(/[\\/]/).pop().trim()
1796
+ let ext = fileName.includes('.') ? ('.' + fileName.split('.').pop().toLowerCase()) : ''
1797
+ if (!IMAGE_EXTS.includes(ext)) {
1798
+ const m = /\.(jpe?g|png|gif|webp)(?:\?|#|$)/i.exec(url)
1799
+ ext = m ? '.' + (m[1].toLowerCase() === 'jpeg' ? 'jpg' : m[1].toLowerCase()) : '.webp'
1800
+ fileName = fileName ? fileName.replace(/\.[^.]*$/, '') + ext : ''
1801
+ }
1802
+ if (!fileName) fileName = createHash('sha1').update(url).digest('hex').slice(0, 12) + ext
1803
+ if (seen.has(tag + '/' + fileName)) fileName = createHash('sha1').update(url).digest('hex').slice(0, 8) + '-' + fileName
1804
+ seen.add(tag + '/' + fileName)
1805
+ out.push({
1806
+ url, tag, fileName,
1807
+ rel: 'memes/' + tag + '/' + fileName,
1808
+ caption: String((it && it.caption) || '').trim().slice(0, 200),
1809
+ keywords: String((it && it.keywords) || '').trim().slice(0, 200),
1810
+ })
1811
+ }
1812
+ if (out.length === 0) throw new Error('清单没有有效条目(检查 url/tag 字段)')
1813
+ return {
1814
+ id,
1815
+ name: String(raw.name || id).trim().slice(0, 60) || id,
1816
+ description: String(raw.description || '').trim().slice(0, 200),
1817
+ version: String(raw.version || '').trim().slice(0, 40),
1818
+ items: out,
1819
+ warnings,
1820
+ }
1821
+ }
1822
+ const startRemoteJob = (manifest, sourceUrl, mode) => {
1823
+ const jobId = 'rj-' + Date.now().toString(36) + '-' + (++remoteJobSeq)
1824
+ const job = {
1825
+ id: jobId, packId: manifest.id, name: manifest.name, mode,
1826
+ total: manifest.items.length, done: 0, failed: 0, added: 0, updated: 0,
1827
+ warnings: manifest.warnings.slice(0, 20), errors: [],
1828
+ state: 'running', message: '准备中…', startedAt: Date.now(),
1829
+ }
1830
+ remoteJobs.set(jobId, job)
1831
+ while (remoteJobs.size > 10) remoteJobs.delete(remoteJobs.keys().next().value)
1832
+ ;(async () => {
1833
+ const packsDir = resolve(packsDirNow())
1834
+ // id 必须先合法化:join(packsDir, '') 会得到扫描目录本身,后面 fresh 分支的
1835
+ // rmSync(finalDir) 会把整个 meme-packs 目录删掉(清单缺 id 时踩过)
1836
+ const safeId = packSlug(manifest.id)
1837
+ if (!safeId) {
1838
+ job.state = 'error'
1839
+ job.message = '远程清单缺少有效的 id,已中止(不会动本地图库)'
1840
+ return
1841
+ }
1842
+ manifest.id = safeId
1843
+ job.packId = safeId
1844
+ const finalDir = resolve(join(packsDir, safeId))
1845
+ if (!finalDir.startsWith(packsDir + sep)) {
1846
+ job.state = 'error'
1847
+ job.message = '图库目录越界,已中止'
1848
+ return
1849
+ }
1850
+ let workDir = finalDir
1851
+ let effectiveMode = mode
1852
+ if (existsSync(finalDir)) {
1853
+ let sidecar = null
1854
+ try { sidecar = JSON.parse(readFileSync(join(finalDir, SIDECAR_NAME), 'utf8')) } catch { }
1855
+ if (sidecar && sidecar.manifestUrl === sourceUrl) {
1856
+ effectiveMode = 'update'
1857
+ job.mode = 'update'
1858
+ } else {
1859
+ job.state = 'error'
1860
+ job.message = '扫描目录下已存在同名图库「' + manifest.id + '」且不是本清单下载的,请先删除或换个 id'
1861
+ return
1862
+ }
1863
+ }
1864
+ const prev = {} // url → {path}(更新模式用于跳过已下载/刷新元数据)
1865
+ if (effectiveMode === 'update') {
1866
+ try {
1867
+ const sc = JSON.parse(readFileSync(join(finalDir, SIDECAR_NAME), 'utf8'))
1868
+ if (sc && sc.manifestUrl === sourceUrl) for (const it of sc.items || []) prev[it.url] = it
1869
+ } catch { }
1870
+ } else {
1871
+ workDir = resolve(join(packsDir, manifest.id + '.tmp-' + Math.random().toString(16).slice(2, 8)))
1872
+ rmSync(workDir, { recursive: true, force: true })
1873
+ mkdirSync(workDir, { recursive: true })
1874
+ }
1875
+ job.message = (effectiveMode === 'update' ? '更新中 ' : '下载中 ') + '0/' + job.total
1876
+ const db = new DatabaseSync(join(workDir, 'index.db'))
1877
+ db.exec('CREATE TABLE IF NOT EXISTS memes (path TEXT PRIMARY KEY, tag TEXT, file_name TEXT, caption TEXT, keywords TEXT, mtime REAL, captioned_at REAL)')
1878
+ try {
1879
+ const queue = manifest.items.slice()
1880
+ let active = 0
1881
+ await new Promise((allDone) => {
1882
+ const pump = () => {
1883
+ while (active < REMOTE_CONCURRENCY && queue.length) {
1884
+ const item = queue.shift()
1885
+ active++
1886
+ ; (async () => {
1887
+ const known = prev[item.url]
1888
+ if (known && known.path === item.rel && existsSync(join(workDir, item.rel))) {
1889
+ db.prepare('UPDATE memes SET tag = ?, caption = ?, keywords = ?, mtime = ? WHERE path = ?')
1890
+ .run(item.tag, item.caption, item.keywords, Date.now(), item.rel)
1891
+ job.updated++
1892
+ } else {
1893
+ // 逐图下载走镜像候选(国内直连 raw 会失败,图库安装/更新主要卡在这里)
1894
+ const buf = await fetchRemoteImage(item.url)
1895
+ mkdirSync(join(workDir, 'memes', item.tag), { recursive: true })
1896
+ writeFileSync(join(workDir, item.rel), buf)
1897
+ if (known && known.path !== item.rel) {
1898
+ try { unlinkSync(join(workDir, known.path)) } catch { /* 已不在 */ }
1899
+ db.prepare('DELETE FROM memes WHERE path = ?').run(known.path)
1900
+ }
1901
+ db.prepare('INSERT INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
1902
+ .run(item.rel, item.tag, item.fileName, item.caption, item.keywords, Date.now(), Date.now())
1903
+ job.added++
1904
+ }
1905
+ job.done++
1906
+ prev[item.url] = { url: item.url, path: item.rel }
1907
+ })().catch((error) => {
1908
+ job.failed++
1909
+ if (job.errors.length < 20) job.errors.push(item.url.slice(0, 80) + ' — ' + (error instanceof Error ? error.message : String(error)))
1910
+ }).finally(() => {
1911
+ active--
1912
+ job.message = (effectiveMode === 'update' ? '更新中 ' : '下载中 ') + (job.done + job.failed) + '/' + job.total
1913
+ pump()
1914
+ })
1915
+ }
1916
+ if (active === 0) allDone()
1917
+ }
1918
+ pump()
1919
+ })
1920
+ } finally {
1921
+ db.close()
1922
+ }
1923
+ // 清单下载的图库同样清洗一遍高频关键词(与 ZIP 安装路径一致,见 prunePackKeywords)
1924
+ try {
1925
+ const pruned = prunePackKeywords(join(workDir, 'index.db'))
1926
+ if (pruned.drop.length) {
1927
+ console.log('[dsh-expression] 图库 ' + manifest.id + ':剔除 ' + pruned.drop.length + ' 个高频关键词(改动 ' + pruned.changed + ' 条)- ' + pruned.drop.join(' '))
1928
+ }
1929
+ } catch (error) {
1930
+ console.warn('[dsh-expression] 高频关键词清洗跳过:', error instanceof Error ? error.message : String(error))
1931
+ }
1932
+ writeFileSync(join(workDir, SIDECAR_NAME), JSON.stringify({
1933
+ manifestUrl: sourceUrl, id: manifest.id, name: manifest.name, version: manifest.version, lastSync: Date.now(),
1934
+ items: Object.values(prev),
1935
+ }))
1936
+ if (effectiveMode === 'fresh') {
1937
+ writeFileSync(join(workDir, 'manifest.json'), JSON.stringify({ name: manifest.name, description: manifest.description, source: sourceUrl }, null, 2))
1938
+ rmSync(finalDir, { recursive: true, force: true })
1939
+ renameSync(workDir, finalDir)
1940
+ }
1941
+ const subs = remoteSubs().filter((s) => s && s.id !== manifest.id)
1942
+ subs.unshift({ id: manifest.id, url: sourceUrl, name: manifest.name, version: manifest.version, total: job.total, lastSync: Date.now() })
1943
+ writeSettings({ remoteSubs: subs })
1944
+ if (effectiveMode === 'fresh') {
1945
+ // 初次订阅下载完也默认直接可用:切过去 + 打开开关
1946
+ const enabledBefore = enabledPackIds(readSettings(), listAllPacks(), activePackId())
1947
+ reloadMemeStore(finalDir, manifest.id)
1948
+ writeSettings({ enabledPacks: [...new Set([...enabledBefore, manifest.id])] })
1949
+ job.message = '完成:下载 ' + job.added + '/' + job.total + ' 张并已切换到「' + manifest.name + '」'
1950
+ + (job.failed ? '(失败 ' + job.failed + ' 张,可稍后再点一次更新补齐)' : '')
1951
+ } else {
1952
+ job.message = '完成:新增 ' + job.added + ' 张,刷新元数据 ' + job.updated + ' 张' + (job.failed ? ',失败 ' + job.failed + ' 张' : '')
1953
+ }
1954
+ job.state = job.failed ? 'done-with-errors' : 'done'
1955
+ })().catch((error) => {
1956
+ job.state = 'error'
1957
+ job.message = '失败: ' + (error instanceof Error ? error.message : String(error))
1958
+ })
1959
+
1960
+ return job
1961
+ }
1962
+ // 清理上次运行残留的临时下载目录(没有 index.db,扫描不会看到,但会占磁盘)
1963
+ try {
1964
+ const dir = packsDirNow()
1965
+ if (existsSync(dir)) {
1966
+ for (const name of readdirSync(dir)) {
1967
+ if (!/\.tmp-[0-9a-f]+$/.test(name)) continue
1968
+ const p = join(dir, name)
1969
+ try { if (statSync(p).isDirectory()) rmSync(p, { recursive: true, force: true }) } catch { }
1970
+ }
1971
+ }
1972
+ } catch { }
1973
+
1974
+ const readBody = (req, maxBytes = 32 * 1024 * 1024) => new Promise((resolve, reject) => {
1975
+ const chunks = []
1976
+ let total = 0
1977
+ req.on('data', (c) => {
1978
+ total += c.length
1979
+ if (total > maxBytes) {
1980
+ reject(new Error('请求体过大(>32MB)'))
1981
+ return
1982
+ }
1983
+ chunks.push(c)
1984
+ })
1985
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
1986
+ req.on('error', reject)
1987
+ })
1988
+ const json = (res, obj, status = 200) => {
1989
+ const body = JSON.stringify(obj)
1990
+ res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
1991
+ res.end(body)
1992
+ }
1993
+ ctx.effect(() => webServer.register({
1994
+ kind: 'exact',
1995
+ path: '/dsh-memes-api',
1996
+ async handler(req, res) {
1997
+ if (denyNonLoopback(req, res, allowLanAccess())) return
1998
+ if (req.method === 'GET') {
1999
+ const u = new URL(req.url || '/', 'http://localhost')
2000
+ if (u.searchParams.has('remoteDir')) {
2001
+ const dir = await fetchRemoteDirectory()
2002
+ let counts = {}
2003
+ try { counts = await fetchDownloadCounts(dir ? dir.entries : []) } catch { /* 只是少个数字 */ }
2004
+ const settingsNow = readSettings()
2005
+ json(res, {
2006
+ ok: true,
2007
+ // null = 彻底拉不到(前端显示错误 + 重试);走磁盘缓存时仍是数组
2008
+ remoteDir: dir ? dir.entries.map((e) => ({ ...e, downloads: counts[e.id] || 0 })) : null,
2009
+ remoteDirSource: remoteDirMeta.source,
2010
+ remoteDirCached: !!remoteDirMeta.cached,
2011
+ remoteDirError: remoteDirMeta.error || '',
2012
+ remoteDirUrl: remoteDirUrlList(),
2013
+ remoteDirUrlSetting: typeof settingsNow.remoteDirUrl === 'string' ? settingsNow.remoteDirUrl : '',
2014
+ })
2015
+ return
2016
+ }
2017
+ const packs = listAllPacks()
2018
+ const activeId = readSettings().packId
2019
+ || ((packs.find((p) => resolve(p.path) === resolve(memes.root)) || {}).id || '')
2020
+ // 图片 URL 的路径段要百分号编码:扫描入库保留原始文件名,名字里带 # ? %
2021
+ // 这类字符时浏览器会把 URL 截断,缩略图 404(用户反馈「都是 jpg 却不显示」;
2022
+ // 上传/学图是时间戳命名所以没事)。图片路由本来就先 decodeURIComponent(issue #28),
2023
+ // 编码后的 URL 落到白名单匹配刚好对上。
2024
+ const encPath = (rel) => String(rel || '').split('/').map(encodeURIComponent).join('/')
2025
+ const urlFor = (m, pid) => ({ ...m, url: ROUTE + '/' + pid + '/' + encPath(m.path) })
2026
+ const packList = () => packs.map((p) => ({ id: p.id, name: p.name, count: p.count }))
2027
+ // 面板的分类下拉要列图库里真实的 tag(按张数降序),不是写死的六个情绪桶;
2028
+ // 按 tag 筛选也改为精确匹配——桶展开(选「开心」混进 like/meow)对浏览图库
2029
+ // 的人类用户是反直觉的(用户反馈)。send_meme 工具侧保留情绪桶语义。
2030
+ const realTags = (rowsIn) => {
2031
+ const counts = new Map()
2032
+ for (const m of rowsIn) counts.set(m.tag, (counts.get(m.tag) || 0) + 1)
2033
+ return [...counts.entries()].sort((a, b) => b[1] - a[1]).map(([t]) => t)
2034
+ }
2035
+ const packId = u.searchParams.get('packId') || activeId
2036
+ // packId=all:合并全部包,url 带包前缀(悬浮窗配图索引用,跨包也能渲染/取图)
2037
+ if (packId === 'all') {
2038
+ const all = []
2039
+ for (const p of packs) {
2040
+ let store = null
2041
+ try {
2042
+ store = new MemesStore(p.path)
2043
+ for (const m of store.list().memes) all.push(urlFor(m, p.id))
2044
+ } catch { /* 坏库跳过 */ }
2045
+ finally { if (store) store.close() }
2046
+ }
2047
+ json(res, { ok: true, total: all.length, tags: [], packId: activeId, packs: packList(), memes: all, remoteSubs: remoteSubs(), remoteDirUrl: remoteDirUrlList(), layoutMode: normalizeLayoutMode(readSettings().layoutMode) })
2048
+ return
2049
+ }
2050
+ const pack = packs.find((p) => p.id === packId)
2051
+ let rows = []
2052
+ let tags = []
2053
+ if (pack) {
2054
+ let store = null
2055
+ try {
2056
+ store = new MemesStore(pack.path)
2057
+ const r = store.list(u.searchParams.get('tag') || undefined, u.searchParams.get('q') || undefined, true)
2058
+ rows = r.memes
2059
+ tags = realTags(store.list().memes)
2060
+ } catch { /* 坏库/缺索引 → 空列表 */ }
2061
+ finally { if (store) store.close() }
2062
+ } else {
2063
+ const r = memes.list(u.searchParams.get('tag') || undefined, u.searchParams.get('q') || undefined, true)
2064
+ rows = r.memes
2065
+ tags = realTags(memes.list().memes)
2066
+ }
2067
+ const pid = pack ? pack.id : activeId
2068
+ json(res, {
2069
+ ok: true, total: rows.length, tags,
2070
+ packId: pid,
2071
+ packs: packList(),
2072
+ memes: rows.map((m) => urlFor(m, pid)),
2073
+ remoteSubs: remoteSubs(),
2074
+ remoteDirUrl: remoteDirUrlList(),
2075
+ layoutMode: normalizeLayoutMode(readSettings().layoutMode),
2076
+ })
2077
+ return
2078
+ }
2079
+ // 状态变更请求:校验 Origin 与 Host 同源,防浏览器跨站触发(CSRF)。
2080
+ // 缺失 Origin 的本地脚本/curl 请求放行(兼容),不同源一律 403。
2081
+ const origin = req.headers.origin
2082
+ if (origin) {
2083
+ let sameOrigin = false
2084
+ try {
2085
+ const o = new URL(origin)
2086
+ sameOrigin = o.host === String(req.headers.host || '')
2087
+ } catch { sameOrigin = false }
2088
+ if (!sameOrigin) {
2089
+ json(res, { ok: false, error: '跨站请求被拒绝' }, 403)
2090
+ return
2091
+ }
2092
+ }
2093
+ let body
2094
+ try {
2095
+ body = JSON.parse(await readBody(req))
2096
+ } catch {
2097
+ json(res, { ok: false, error: '无效的 JSON 请求体' }, 400)
2098
+ return
2099
+ }
2100
+ try {
2101
+ const op = String(body.op || '')
2102
+ if (op === 'createMemePack') {
2103
+ const id = String(body.id || '').trim()
2104
+ const name = String(body.name || '').trim()
2105
+ if (!/^[a-z0-9][a-z0-9_-]{0,39}$/.test(id)) throw new Error('ID 须为 1–40 位小写字母、数字、横线或下划线')
2106
+ if (!name || name.length > 60) throw new Error('图库名称须为 1–60 字')
2107
+ if (listAllPacks().some(p => p.id === id)) throw new Error('图库 ID 已存在')
2108
+ const dir = join(resolve(packsDirNow()), id)
2109
+ mkdirSync(resolve(packsDirNow()), { recursive: true })
2110
+ mkdirSync(dir)
2111
+ writeFileSync(join(dir, 'manifest.json'), JSON.stringify({ id, name, description: String(body.description || '').slice(0, 200), version: '1.0.0' }, null, 2))
2112
+ // 保留已有开关状态,再把新建的图库打开(模型立即可用)
2113
+ const wasEnabled = enabledPackIds(readSettings(), listAllPacks(), activePackId())
2114
+ reloadMemeStore(dir, id)
2115
+ writeSettings({ enabledPacks: [...new Set([...wasEnabled, id])] })
2116
+ json(res, { ok: true, ...packPayload() })
2117
+ } else if (op === 'recognize') {
2118
+ // 上传弹窗的 AI 识别:只返回识别结果,不写入图库(用户确认后走 upload)
2119
+ const fileName = String(body.fileName || '').trim()
2120
+ const data = String(body.dataBase64 || '')
2121
+ if (!data) throw new Error('缺少图片数据')
2122
+ const buf = Buffer.from(data, 'base64')
2123
+ if (buf.byteLength === 0 || buf.byteLength > 8 * 1024 * 1024) throw new Error('图片大小超限(≤8MB)')
2124
+ const ext = fileName.includes('.') ? '.' + fileName.split('.').pop().toLowerCase() : ''
2125
+ if (!IMAGE_EXTS.includes(ext)) throw new Error('仅支持 jpg/png/gif/webp')
2126
+ const sel = ctx.agentDefaultModel && typeof ctx.agentDefaultModel.currentSelection === 'function'
2127
+ ? ctx.agentDefaultModel.currentSelection() : null
2128
+ const r = await recognizeImageBytes(ctx.get('llm'), sel, buf, MIME[ext.slice(1)] || 'image/jpeg', fileName)
2129
+ if (!r.tag || !validTagRe.test(r.tag)) throw new Error('AI 未识别出有效分类,请手动选择')
2130
+ json(res, { ok: true, tag: r.tag, caption: r.caption, keywords: r.keywords, animation: r.animation || null })
2131
+ } else if (op === 'upload') {
2132
+ const tag = String(body.tag || '').trim().toLowerCase()
2133
+ const fileName = String(body.fileName || '').trim()
2134
+ const data = String(body.dataBase64 || '')
2135
+ const caption = String(body.caption || '').trim().slice(0, 200)
2136
+ const keywords = String(body.keywords || '').trim().slice(0, 200)
2137
+ if (!tag || !validTagRe.test(tag)) throw new Error('tag 只能是小写字母/数字/-/_')
2138
+ const ext = fileName.includes('.') ? '.' + fileName.split('.').pop().toLowerCase() : ''
2139
+ if (!IMAGE_EXTS.includes(ext)) throw new Error('仅支持 jpg/png/gif/webp')
2140
+ if (!data) throw new Error('缺少图片数据')
2141
+ // 落点:当前图库在插件包内(升级会被清空)时改写「我的收藏」,原始字节
2142
+ // 原样落盘——动图 GIF 从这里上传可保动画,聊天附件通道才会压成单帧。
2143
+ const targetRoot = writeTarget()
2144
+ const redirected = resolve(targetRoot) !== resolve(memes.root)
2145
+ const name = Date.now() + '_' + Math.floor(Math.random() * 1000) + ext
2146
+ const rel = 'memes/' + tag + '/' + name
2147
+ mkdirSync(join(targetRoot, 'memes', tag), { recursive: true })
2148
+ writeFileSync(join(targetRoot, rel), Buffer.from(data, 'base64'))
2149
+ if (redirected) {
2150
+ const w = openIndexWriter(targetRoot)
2151
+ try {
2152
+ w.prepare('INSERT INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
2153
+ .run(rel, tag, name, caption, keywords, Date.now(), Date.now())
2154
+ } finally { try { w.close() } catch { /* 已关闭 */ } }
2155
+ } else {
2156
+ adminDb.prepare('INSERT INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
2157
+ .run(rel, tag, name, caption, keywords, Date.now(), Date.now())
2158
+ }
2159
+ memes.refresh()
2160
+ json(res, {
2161
+ ok: true,
2162
+ meme: { path: rel, tag, file_name: name, caption, keywords, url: ROUTE + '/' + (redirected ? USER_PACK_ID + '/' : '') + rel },
2163
+ // 重定向时带完整 payload:客户端要拿到「我的收藏」出现在图库列表且已启用
2164
+ ...(redirected ? packPayload() : {}),
2165
+ message: redirected ? '已上传到「' + USER_PACK_NAME + '」图库:内置图库随插件升级会被清空,收藏统一存包外' : '',
2166
+ })
2167
+ } else if (op === 'scanPack') {
2168
+ // 扫描图库目录:把手动拷进去、还没进索引的图片收进来。动图 GIF 走这条路
2169
+ // 保真——磁盘文件原始字节入库。扫描内置图库时新收的文件顺手搬去
2170
+ // 「我的收藏」(内置图库随插件升级会被清空)。
2171
+ // 同时清理失效行:文件被改名/删除后旧行永远留着,面板里就是一张永远
2172
+ // 加载不出缩略图的死条目(用户反馈「只有添加没有删除/修改」)。
2173
+ const wanted = String(body.packId || '').trim()
2174
+ const packs = listAllPacks()
2175
+ const pack = packs.find((p) => p.id === (wanted || packPayload().packId))
2176
+ if (!pack) throw new Error('图库不存在: ' + (wanted || '(当前)'))
2177
+ const known = packPaths(pack.path)
2178
+ const fresh = walkPackImages(pack.path).filter((relPath) => !known.includes(relPath))
2179
+ // 失效行 = 在索引里但磁盘上没有对应文件的(改名/删除之后的残留)
2180
+ const stale = known.filter((relPath) => !existsSync(join(pack.path, relPath)))
2181
+ let relocated = 0
2182
+ const w = openIndexWriter(pack.path)
2183
+ try {
2184
+ if (fresh.length) {
2185
+ const insert = w.prepare('INSERT OR IGNORE INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
2186
+ for (const relPath of fresh) {
2187
+ const row = scanRowFor(relPath)
2188
+ let mtime = Date.now()
2189
+ try { mtime = statSync(join(pack.path, relPath)).mtimeMs } catch { /* 用当前时间 */ }
2190
+ insert.run(row.path, row.tag, row.file_name, row.caption, '', mtime, null)
2191
+ }
2192
+ }
2193
+ if (stale.length) {
2194
+ const del = w.prepare('DELETE FROM memes WHERE path = ?')
2195
+ for (const relPath of stale) del.run(relPath)
2196
+ }
2197
+ } finally { try { w.close() } catch { /* 已关闭 */ } }
2198
+ if (fresh.length && isVolatileRoot(pack.path)) {
2199
+ const moved = movePackEntries(pack.path, ensureUserPack(), fresh)
2200
+ relocated = moved.moved.length
2201
+ }
2202
+ if (resolve(pack.path) === resolve(memes.root)) memes.refresh()
2203
+ const parts = []
2204
+ if (fresh.length) parts.push('新增 ' + fresh.length + ' 张')
2205
+ if (stale.length) parts.push('清理 ' + stale.length + ' 条失效记录(文件已改名或删除)')
2206
+ if (relocated) parts.push('已搬入「我的收藏」(内置图库随插件升级会被清空)')
2207
+ json(res, {
2208
+ ok: true, added: fresh.length, pruned: stale.length, relocated, ...packPayload(),
2209
+ message: parts.length
2210
+ ? parts.join(';') + (fresh.length ? ';描述默认取文件名,可到图库里编辑' : '')
2211
+ : '没有变化:目录里的图片都已入索引,索引里的文件都还在',
2212
+ })
2213
+ } else if (op === 'update') {
2214
+ const path = String(body.path || '')
2215
+ const row = memes.list().memes.find((m) => m.path === path)
2216
+ if (!row) throw new Error('未知路径: ' + path)
2217
+ const tag = body.tag != null ? String(body.tag).trim().toLowerCase() : row.tag
2218
+ if (!validTagRe.test(tag)) throw new Error('tag 只能是小写字母/数字/-/_')
2219
+ const caption = body.caption != null ? String(body.caption).trim() : row.caption
2220
+ const keywords = body.keywords != null ? String(body.keywords).trim() : row.keywords
2221
+ adminDb.prepare('UPDATE memes SET tag = ?, caption = ?, keywords = ? WHERE path = ?').run(tag, caption, keywords, path)
2222
+ memes.refresh()
2223
+ json(res, { ok: true })
2224
+ } else if (op === 'delete') {
2225
+ const path = String(body.path || '')
2226
+ if (!memes.list().memes.some((m) => m.path === path)) throw new Error('未知路径: ' + path)
2227
+ adminDb.prepare('DELETE FROM memes WHERE path = ?').run(path)
2228
+ memes.refresh()
2229
+ try { unlinkSync(join(memes.root, path)) } catch { /* 文件已不存在 */ }
2230
+ json(res, { ok: true })
2231
+ } else if (op === 'deleteTag') {
2232
+ const tag = String(body.tag || '').trim().toLowerCase()
2233
+ if (!tag || !validTagRe.test(tag)) throw new Error('tag 只能是小写字母/数字/-/_')
2234
+ const n = adminDb.prepare('DELETE FROM memes WHERE tag = ?').run(tag).changes
2235
+ memes.refresh()
2236
+ rmSync(join(memes.root, 'memes', tag), { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
2237
+ json(res, { ok: true, deleted: n })
2238
+ } else if (op === 'importMemePack') {
2239
+ const data = String(body.dataBase64 || '')
2240
+ if (!data) throw new Error('缺少 ZIP 数据')
2241
+ const entries = unzipStore(Buffer.from(data, 'base64'))
2242
+ // 图库 id:调用方给的名称优先;没给(或中文被清成空)时用 ZIP 里
2243
+ // manifest.json 的 id,再不行才回落 meme-pack
2244
+ let name = packSlug(body.name)
2245
+ if (!name) {
2246
+ try {
2247
+ const m = JSON.parse(String(entries.get('manifest.json') || '{}'))
2248
+ name = packSlug(m.id)
2249
+ } catch { /* 没有/坏 manifest → 走回落 */ }
2250
+ }
2251
+ name = name || 'meme-pack'
2252
+ // 纯图片 ZIP(没有 index.db):自动建索引收进来——分类取目录名、描述取文件名,
2253
+ // 和「扫描新增」同一套规则。此前这种包直接被拒,用户只能一张张上传(用户反馈)。
2254
+ if (!entries.get('index.db')) {
2255
+ const isImageEntry = (rel) => {
2256
+ if (!rel || /[\\\/]$/.test(rel)) return false
2257
+ if (rel.split('/').some((seg) => !seg || seg.startsWith('.') || seg === '__MACOSX')) return false
2258
+ const dot = rel.lastIndexOf('.')
2259
+ const ext = dot >= 0 ? rel.slice(dot).toLowerCase() : ''
2260
+ return SCAN_IMAGE_EXTS.includes(ext)
2261
+ }
2262
+ const images = [...entries.keys()].filter(isImageEntry)
2263
+ if (images.length === 0) throw new Error('ZIP 里没有 index.db,也没有可识别的图片(jpg/png/gif/webp)')
2264
+ const tmpDb = join(tmpdir(), 'dsh-meme-import-' + Date.now() + '-' + Math.random().toString(16).slice(2, 8) + '.db')
2265
+ const db = new DatabaseSync(tmpDb)
2266
+ try {
2267
+ db.exec('CREATE TABLE memes (path TEXT PRIMARY KEY, tag TEXT, file_name TEXT, caption TEXT, keywords TEXT, mtime REAL, captioned_at REAL)')
2268
+ const insert = db.prepare('INSERT INTO memes (path, tag, file_name, caption, keywords, mtime, captioned_at) VALUES (?, ?, ?, ?, ?, ?, ?)')
2269
+ for (const rel of images) {
2270
+ const row = scanRowFor(rel)
2271
+ insert.run(row.path, row.tag, row.file_name, row.caption, '', Date.now(), null)
2272
+ }
2273
+ } finally { db.close() }
2274
+ try {
2275
+ entries.set('index.db', readFileSync(tmpDb))
2276
+ } finally { rmSync(tmpDb, { force: true }) }
2277
+ }
2278
+ installZipEntries(entries, name)
2279
+ json(res, { ok: true, ...packPayload(), total: memes.list().memes.length, message: '导入成功,已切换到新图库' })
2280
+ } else if (op === 'installRemoteArchive') {
2281
+ const archiveUrl = String(body.archiveUrl || '').trim()
2282
+ const wanted = packSlug(body.packId)
2283
+ for (const j of remoteJobs.values()) {
2284
+ if (j.mode === 'archive' && j.state === 'running' && wanted && j.packId === wanted) {
2285
+ json(res, { ok: true, ...jobSnapshot(j), running: true, message: '该图库已在下载中' })
2286
+ return
2287
+ }
2288
+ }
2289
+ json(res, {
2290
+ ok: true,
2291
+ ...jobSnapshot(startArchiveJob({
2292
+ archiveUrl, sha256: body.sha256,
2293
+ requestedId: body.packId, name: body.name, version: body.version,
2294
+ })),
2295
+ })
2296
+ } else if (op === 'subscribeRemote') {
2297
+ const manifestUrl = String(body.manifestUrl || '').trim()
2298
+ const rawManifest = await fetchRemoteJson(manifestUrl)
2299
+ const manifest = normalizeRemoteManifest(rawManifest, String(body.packId || '').trim(), manifestUrl)
2300
+ for (const j of remoteJobs.values()) {
2301
+ if (j.packId === manifest.id && j.state === 'running') {
2302
+ json(res, { ok: true, ...jobSnapshot(j), running: true, message: '该图库已在下载中' })
2303
+ return
2304
+ }
2305
+ }
2306
+ json(res, { ok: true, ...jobSnapshot(startRemoteJob(manifest, manifestUrl, 'fresh')) })
2307
+ } else if (op === 'previewManifest') {
2308
+ // 清单热链的包没装也能预览:服务端读清单,把它列的图片地址交给前端
2309
+ // (前端直接 fetch 清单要受 CORS 限制,而且清单可能托管在任意主机)
2310
+ const manifestUrl = String(body.manifestUrl || '').trim()
2311
+ const raw = await fetchRemoteJson(manifestUrl)
2312
+ const manifest = normalizeRemoteManifest(raw, '', manifestUrl)
2313
+ json(res, {
2314
+ ok: true,
2315
+ total: manifest.items.length,
2316
+ urls: manifest.items.slice(0, PREVIEW_MAX).map((m) => m.url),
2317
+ })
2318
+ } else if (op === 'remoteJobStatus') {
2319
+ const job = remoteJobs.get(String(body.jobId || '').trim())
2320
+ if (!job) throw new Error('未知任务: ' + String(body.jobId || ''))
2321
+ json(res, { ok: true, ...jobSnapshot(job) })
2322
+ } else if (op === 'updateRemotePack') {
2323
+ const id = String(body.id || '').trim()
2324
+ const sub = remoteSubs().find((s) => s && s.id === id)
2325
+ if (!sub) throw new Error('未找到订阅: ' + id)
2326
+ if (sub.archiveUrl) {
2327
+ const downloaded = await fetchRemoteArchive(sub.archiveUrl, sub.sha256)
2328
+ const entries = unzipStore(downloaded.buf)
2329
+ let manifest = {}
2330
+ try { manifest = JSON.parse(String(entries.get('manifest.json') || '{}')) } catch { throw new Error('manifest.json 不是合法 JSON') }
2331
+ const manifestId = packSlug(manifest.id)
2332
+ if (manifestId && manifestId !== id) throw new Error('订阅 id 与 ZIP manifest id 不一致,已拒绝更新')
2333
+ const displayName = String(manifest.name || sub.name || id).trim().slice(0, 60) || id
2334
+ const version = String(manifest.version || sub.version || '').trim().slice(0, 40)
2335
+ installZipEntries(entries, id, {
2336
+ sourceType: 'archive', archiveUrl: sub.archiveUrl, sha256: downloaded.sha256,
2337
+ id, name: displayName, version, lastSync: Date.now(),
2338
+ })
2339
+ const total = memes.list().memes.length
2340
+ const next = remoteSubs().filter((s) => s && s.id !== id)
2341
+ next.unshift({ ...sub, sha256: downloaded.sha256, name: displayName, version, total, lastSync: Date.now() })
2342
+ writeSettings({ remoteSubs: next })
2343
+ json(res, { ok: true, ...packPayload(), total, message: '更新成功,已切换到「' + displayName + '」' })
2344
+ return
2345
+ }
2346
+ if (!sub.url) throw new Error('订阅缺少更新地址: ' + id)
2347
+ const rawManifest = await fetchRemoteJson(sub.url)
2348
+ const manifest = normalizeRemoteManifest(rawManifest, id, sub.url)
2349
+ manifest.id = id
2350
+ for (const j of remoteJobs.values()) {
2351
+ if (j.packId === id && j.state === 'running') {
2352
+ json(res, { ok: true, ...jobSnapshot(j), running: true, message: '该图库已在更新中' })
2353
+ return
2354
+ }
2355
+ }
2356
+ json(res, { ok: true, ...jobSnapshot(startRemoteJob(manifest, sub.url, 'update')) })
2357
+ } else if (op === 'getMemeRoot') {
2358
+
2359
+ json(res, { ok: true, ...packPayload() })
2360
+ } else if (op === 'setPack') {
2361
+ const packId = String(body.packId || '').trim()
2362
+ if (!packId) throw new Error('未指定图库')
2363
+ const hit = listAllPacks().find((p) => p.id === packId)
2364
+ if (!hit) throw new Error('未知图库: ' + packId)
2365
+ reloadMemeStore(hit.path, hit.id)
2366
+ json(res, { ok: true, ...packPayload(), message: '已切换图库,立即生效' })
2367
+ } else if (op === 'setPacksDir') {
2368
+ const dir = String(body.packsDir || '').trim()
2369
+ if (!dir) throw new Error('目录不能为空')
2370
+ // 扫描目录必须是「装图库的父目录」,不能是某个图库目录自己:那样之后导入/安装
2371
+ // 的图库会嵌进这个包里面(memes/<主库>/<子库>/),而主库自己会从列表里消失
2372
+ // ——历史上这么点一下就是 issue #23 那种「描述和图对不上」的现场。
2373
+ if (isPackDir(dir)) {
2374
+ throw new Error('这个目录本身就是一个图库(里面有 index.db),请选它的上级目录;否则新装的图库会嵌在它里面')
2375
+ }
2376
+ mkdirSync(dir, { recursive: true })
2377
+ writeSettings({ packsDir: resolve(dir) })
2378
+ json(res, { ok: true, ...packPayload(), message: '已更新扫描目录' })
2379
+ } else if (op === 'setMemeRoot') {
2380
+ const dir = String(body.memeRoot || '').trim()
2381
+ if (!dir) throw new Error('目录不能为空')
2382
+ reloadMemeStore(dir)
2383
+ json(res, { ok: true, ...packPayload(), message: '已切换图库,立即生效' })
2384
+ } else if (op === 'setRemoteDirUrl') {
2385
+ // 图库目录源:''/auto = 自动多镜像(推荐);'official'/'mirror' = 预设;http(s) URL = 自定义
2386
+ const rawValue = typeof body.remoteDirUrl === 'string' ? body.remoteDirUrl.trim() : ''
2387
+ let value = ''
2388
+ if (rawValue && rawValue.toLowerCase() !== 'auto') {
2389
+ const key = rawValue.toLowerCase()
2390
+ if (REMOTE_DIR_PRESETS.includes(key)) {
2391
+ value = key
2392
+ } else if (/^https?:\/\//i.test(rawValue)) {
2393
+ if (rawValue.length > 500) throw new Error('目录地址过长(不超过 500 字符)')
2394
+ value = rawValue
2395
+ } else {
2396
+ throw new Error('目录源只能是「官方源/镜像源」预设,或 http(s) 链接')
2397
+ }
2398
+ }
2399
+ writeSettings({ remoteDirUrl: value })
2400
+ // 立刻清缓存:前端保存后会马上重拉目录,不能等 60s 内存缓存过期
2401
+ remoteDirCache = null
2402
+ remoteDirMeta = { source: '', cached: false, error: '' }
2403
+ preferredMirrorPrefix = '' // 换源后旧的优先镜像链路也不再适用
2404
+ json(res, {
2405
+ ok: true,
2406
+ ...packPayload(),
2407
+ message: value ? '已保存图库目录源:' + dirSourceLabel(value) + ',立即生效' : '已恢复自动(内置多镜像)',
2408
+ })
2409
+ } else if (op === 'setCompanionPrompt') {
2410
+ const text = String(body.text || '').trim()
2411
+ writeSettings({ companionPrompt: text })
2412
+ json(res, { ok: true, ...packPayload(), message: text ? '已保存,下一条消息生效' : '已恢复默认提示词' })
2413
+ } else if (op === 'getAgentsMd') {
2414
+ // 面向 agent 的 AGENTS.md(插件包根目录):session 开局自动进上下文,
2415
+ // 设置页可查看/编辑(issue #53 附件诉求)
2416
+ const file = join(dirname(fileURLToPath(import.meta.url)), 'AGENTS.md')
2417
+ let content = ''
2418
+ try { content = readFileSync(file, 'utf8') } catch { /* 还没有这份文件 */ }
2419
+ json(res, { ok: true, content, path: file, exists: content !== '' })
2420
+ } else if (op === 'setAgentsMd') {
2421
+ const content = String(body.content == null ? '' : body.content)
2422
+ if (content.length > 1024 * 1024) throw new Error('内容超过 1MB 上限')
2423
+ const file = join(dirname(fileURLToPath(import.meta.url)), 'AGENTS.md')
2424
+ writeFileSync(file, content)
2425
+ json(res, { ok: true, path: file, message: 'AGENTS.md 已保存,新开的会话生效(进行中的会话不会热刷新)' })
2426
+ } else if (op === 'setPromptEnabled') {
2427
+ const enabled = body.enabled !== false
2428
+ writeSettings({ promptEnabled: enabled })
2429
+ json(res, { ok: true, ...packPayload(), message: enabled ? '已开启陪伴提示词,下一条消息生效' : '已关闭陪伴提示词,下一条消息生效' })
2430
+ } else if (op === 'setSendMode') {
2431
+ // AI 发送方式:auto = 按渠道自动(Web 配图 / IM 原生图片);text = 纯文字不发图;image = 总是发图
2432
+ const mode = String(body.sendMode == null ? '' : body.sendMode).trim()
2433
+ if (!SEND_MODES.includes(mode)) throw new Error('发送方式只能是 auto / text / image')
2434
+ writeSettings({ sendMode: mode })
2435
+ const label = mode === 'text' ? '纯文字' : mode === 'image' ? '图片' : '自动(按渠道)'
2436
+ json(res, { ok: true, ...packPayload(), message: '发送方式已改为「' + label + '」,下一条消息生效' })
2437
+ } else if (op === 'setLayoutMode') {
2438
+ // 表情排布:inline = 图与正文并排(默认);stacked = 图独占一行、正文铺开(issue #50)
2439
+ const mode = String(body.layoutMode == null ? '' : body.layoutMode).trim()
2440
+ if (!LAYOUT_MODES.includes(mode)) throw new Error('排布方式只能是 inline / stacked')
2441
+ writeSettings({ layoutMode: mode })
2442
+ const label = mode === 'stacked' ? '独占一行' : '并排'
2443
+ json(res, { ok: true, ...packPayload(), message: '表情排布已改为「' + label + '」' })
2444
+ } else if (op === 'setAllowLanAccess') {
2445
+ // 局域网访问图库(issue #54):默认关。打开后本机/局域网 IP 字面量 Host 的
2446
+ // 请求放行(图片/索引/导出/面板四条路由);域名形式 Host 始终拒绝(rebinding 防线)。
2447
+ const enabled = body.enabled === true
2448
+ writeSettings({ allowLanAccess: enabled })
2449
+ json(res, {
2450
+ ok: true, ...packPayload(),
2451
+ message: enabled
2452
+ ? '已允许局域网访问:手机/平板用电脑的局域网 IP 打开 DSH Web 即可看到表情包(同一 Wi-Fi;防火墙需放行该端口)'
2453
+ : '已关闭局域网访问:图库路由恢复只接受本机回环请求',
2454
+ })
2455
+ } else if (op === 'setPackEnabled') {
2456
+ // 每张卡片一个开关,可同时开多个;没设置过时以当前图库为初始值
2457
+ const target = String(body.packId || '').trim()
2458
+ const packs = listAllPacks()
2459
+ if (!packs.some((p) => p.id === target)) throw new Error('图库不存在: ' + target)
2460
+ const current = enabledPackIds(readSettings(), packs, packPayload().packId)
2461
+ const next = body.enabled !== false
2462
+ ? [...new Set([...current, target])]
2463
+ : current.filter((id) => id !== target)
2464
+ writeSettings({ enabledPacks: next })
2465
+ json(res, { ok: true, ...packPayload(), message: next.includes(target) ? '已打开「' + target + '」,模型可以用它发图' : '已关闭「' + target + '」' })
2466
+ } else if (op === 'deleteMemePack') {
2467
+ // 唯一的删除入口:内置、市场下载、自建/导入都走它。
2468
+ // 当前图库也能删——管理用的只读/可写连接挂在上面的包,不切走文件被占用
2469
+ // (Windows 下 rmSync 会 EBUSY 删一半),所以这里自动先切到别的图库再删。
2470
+ const target = String(body.packId || '').trim()
2471
+ const packs = listAllPacks()
2472
+ const hit = packs.find((p) => p.id === target)
2473
+ if (!hit) throw new Error('图库不存在: ' + target)
2474
+ const dir = packDeleteDir(hit, packsDirNow()) // 先过路径校验,再动运行时
2475
+ let switchedTo = ''
2476
+ if (resolve(hit.path) === resolve(memes.root)) {
2477
+ const enabled = enabledPackIds(readSettings(), packs, target)
2478
+ const others = packs.filter((p) => resolve(p.path) !== resolve(hit.path))
2479
+ // 优先切到还在开着的图库,其次任意一个
2480
+ const next = others.find((p) => enabled.includes(p.id)) || others[0]
2481
+ if (!next) throw new Error('这是最后一个图库,删掉就没有图库可用了')
2482
+ reloadMemeStore(next.path, next.id)
2483
+ switchedTo = next.name || next.id
2484
+ }
2485
+ const settingsNow = readSettings()
2486
+ if (remoteSubs().some((s) => s && s.id === target)) {
2487
+ writeSettings({ remoteSubs: remoteSubs().filter((s) => s && s.id !== target) })
2488
+ }
2489
+ // 删除的图库从开关列表里摘掉,别留脏 id
2490
+ if (Array.isArray(settingsNow.enabledPacks)) {
2491
+ writeSettings({ enabledPacks: settingsNow.enabledPacks.filter((id) => id !== target) })
2492
+ }
2493
+ // 重试:Windows 上刚写过的 index.db 常被杀软/索引器瞬时锁住,EPERM/EBUSY
2494
+ // 是一阵子的;带重试的删除比直接把整个图库删除搞成半删状态强。
2495
+ rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })
2496
+ json(res, {
2497
+ ok: true, ...packPayload(),
2498
+ message: '已删除图库「' + (hit.name || target) + '」'
2499
+ + (switchedTo ? ',当前图库已切到「' + switchedTo + '」' : '')
2500
+ + (hit.source === 'bundled' ? '(内置包,升级或重装后会回来)' : ''),
2501
+ })
2502
+ } else if (op === 'browse') {
2503
+ // 服务端列目录:宿主 0.1.5 的客户端没有 workspaces 服务,「选择目录」只能走自己的 API
2504
+ let dir = resolve(String(body.path || '').trim() || packsDirNow())
2505
+ if (!existsSync(dir)) dir = dshHome()
2506
+ const entries = readdirSync(dir, { withFileTypes: true })
2507
+ .filter((e) => e.isDirectory())
2508
+ .map((e) => ({ name: e.name, path: join(dir, e.name) }))
2509
+ .sort((a, b) => a.name.localeCompare(b.name))
2510
+ const crumbs = []
2511
+ for (let cur = dir; ;) {
2512
+ const parent = dirname(cur)
2513
+ crumbs.unshift({ name: cur === parent ? cur : basename(cur), path: cur })
2514
+ if (cur === parent) break
2515
+ cur = parent
2516
+ }
2517
+ json(res, { ok: true, path: dir, parent: dirname(dir) === dir ? '' : dirname(dir), entries, breadcrumbs: crumbs })
2518
+ } else {
2519
+ json(res, { ok: false, error: '未知操作: ' + op }, 400)
2520
+ }
2521
+ } catch (error) {
2522
+ json(res, { ok: false, error: error instanceof Error ? error.message : String(error) }, 400)
2523
+ }
2524
+ },
2525
+ }), 'dsh-expression: /dsh-memes-api 管理 API')
2526
+ // 导出图库为 ZIP 包(分享用):遍历图库目录全部文件打包
2527
+ ctx.effect(() => webServer.register({
2528
+ kind: 'exact',
2529
+ path: '/dsh-memes-export',
2530
+ handler(req, res) {
2531
+ if (denyNonLoopback(req, res, allowLanAccess())) return
2532
+ if (req.method !== 'GET') {
2533
+ res.writeHead(405, { allow: 'GET' })
2534
+ res.end()
2535
+ return
2536
+ }
2537
+ try {
2538
+ // packId 指定要导出哪个图库(图库页每张卡片都能导出),不传就导出当前图库
2539
+ const wanted = new URL(req.url || '/', 'http://localhost').searchParams.get('packId')
2540
+ const target = wanted ? listAllPacks().find((p) => p.id === wanted) : null
2541
+ if (wanted && !target) throw new Error('图库不存在: ' + wanted)
2542
+ const root = resolve(target ? target.path : memes.root)
2543
+ if (root === resolve(memes.root)) adminDb.exec('PRAGMA wal_checkpoint(FULL)')
2544
+ // 只导出索引内的文件(index.db + manifest.json + 索引图片),
2545
+ // 不打包 .git/备份/缩略图等无关内容(历史教训:整目录遍历会带出 200MB 杂物)
2546
+ let paths = []
2547
+ {
2548
+ const db = new DatabaseSync(join(root, 'index.db'))
2549
+ try {
2550
+ if (root !== resolve(memes.root)) { try { db.exec('PRAGMA wal_checkpoint(FULL)') } catch { /* 只读库 */ } }
2551
+ paths = db.prepare('SELECT path FROM memes').all().map((r) => String(r.path))
2552
+ } finally { db.close() }
2553
+ }
2554
+ if (paths.length === 0) throw new Error('空图库没有可导出的图片')
2555
+ const files = [{ name: 'index.db', data: readFileSync(join(root, 'index.db')) }]
2556
+ if (existsSync(join(root, 'manifest.json'))) {
2557
+ files.push({ name: 'manifest.json', data: readFileSync(join(root, 'manifest.json')) })
2558
+ }
2559
+ for (const rel of paths) {
2560
+ const full = join(root, rel)
2561
+ if (existsSync(full)) files.push({ name: rel, data: readFileSync(full) })
2562
+ }
2563
+ const zip = zipStore(files)
2564
+ const stamp = new Date().toISOString().slice(0, 10)
2565
+ res.writeHead(200, {
2566
+ 'Content-Type': 'application/zip',
2567
+ 'Content-Length': String(zip.byteLength),
2568
+ 'Content-Disposition': 'attachment; filename="dsh-meme-pack-' + stamp + '.zip"',
2569
+ })
2570
+ res.end(zip)
2571
+ } catch (error) {
2572
+ res.writeHead(500, { 'Content-Type': 'text/plain' })
2573
+ res.end('导出失败: ' + (error instanceof Error ? error.message : String(error)))
2574
+ }
2575
+ },
2576
+ }), 'dsh-expression: /dsh-memes-export 导出 ZIP')
2577
+
2578
+ // 自包含管理面板页面(无构建链、重启不丢)。
2579
+ ctx.effect(() => webServer.register({
2580
+ kind: 'exact',
2581
+ path: '/memes-panel',
2582
+ handler(req, res) {
2583
+ if (denyNonLoopback(req, res, allowLanAccess())) return
2584
+ try {
2585
+ const html = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'panel.html'))
2586
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })
2587
+ res.end(html)
2588
+ } catch (error) {
2589
+ res.writeHead(500, { 'Content-Type': 'text/plain' })
2590
+ res.end('panel.html 缺失: ' + (error instanceof Error ? error.message : String(error)))
2591
+ }
2592
+ },
2593
+ }), 'dsh-expression: /memes-panel 管理面板')
2594
+ // 对话里表情包小图展示:只限制 /dsh-memes 图片,避免大图贴脸,不影响其他 UI。
2595
+ // 选择器必须用 src*= 子串匹配:send_meme 返回的是绝对 URL
2596
+ // (http://host:port/dsh-memes/...),src^= 前缀匹配只对相对路径生效,
2597
+ // 会漏掉所有真实表情(历史教训:之前的 240px 规则因此从未生效)。
2598
+ // 尺寸可用 config.memeSize 覆盖(px,默认 160)。
2599
+ const memeSize = Number(config?.memeSize) > 0 ? Number(config.memeSize) : 160
2600
+ try {
2601
+ // data-plugin 必须打:宿主的客户端模块系统在工厂体跑完后按 claimStyles 认领「当下所有
2602
+ // 无主 style」,这条从文档加载起就存在,谁后物化谁就把它认到自己名下,之后那个模块一
2603
+ // 变更(改自己的 client.js / 热重载)就被 removeOwnedStyles 连标签删掉 —— 小图限高规则
2604
+ // 消失、表情包大图贴脸,而且极难查(issue #32)。值必须是模块注册 id(dsh-meme,与
2605
+ // __ModuleLoader__.load({ id }) 一致):宿主按同一个 id 摘标签,换个名字会在插件卸载后
2606
+ // 留下孤儿规则。
2607
+ ctx.effect(() => webServer.tapIndex((html) => html.replace(
2608
+ '</head>',
2609
+ '<style data-plugin="dsh-meme">img[src*="/dsh-memes/"]:not([data-meme-zoom-img]){max-width:' + memeSize + 'px!important;max-height:' + memeSize + 'px!important;width:auto!important;height:auto!important;object-fit:contain;border-radius:8px}</style></head>',
2610
+ )), 'dsh-expression: 小图 CSS')
2611
+ } catch (error) {
2612
+ console.error('[dsh-expression] tapIndex 失败:', error instanceof Error ? error.message : String(error))
2613
+ }
2614
+ console.log('[dsh-expression] 管理 API: /dsh-memes-api , 管理面板: /memes-panel , 小图 CSS 已注入(' + memeSize + 'px)')
2615
+ }
2616
+ }