dsh-chat-comprehension 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (364) hide show
  1. package/NOTICE.md +20 -0
  2. package/README.md +20 -9
  3. package/client.js +41 -9
  4. package/lib/engines.mjs +136 -0
  5. package/lib/index.js +54 -4
  6. package/lib/qqbot-0.5.3-patches.json +75 -70
  7. package/lib/qqbot-patch.mjs +12 -7
  8. package/lib/video.mjs +11 -2
  9. package/package.json +7 -23
  10. package/vendor/dsh-agent-md/LICENSE +21 -0
  11. package/vendor/dsh-agent-md/cordis.patch.yml +8 -0
  12. package/vendor/dsh-agent-md/lib/index.js +775 -0
  13. package/vendor/dsh-agent-md/lib/persona.js +634 -0
  14. package/vendor/dsh-agent-md/lib/qq.js +527 -0
  15. package/vendor/dsh-agent-md/package.json +50 -0
  16. package/vendor/dsh-bili-scroll/LICENSE +21 -0
  17. package/vendor/dsh-bili-scroll/NOTICE.md +18 -0
  18. package/vendor/dsh-bili-scroll/cordis.patch.yml +20 -0
  19. package/vendor/dsh-bili-scroll/index.js +3293 -0
  20. package/vendor/dsh-bili-scroll/lib/asr.py +141 -0
  21. package/vendor/dsh-bili-scroll/lib/diagnose.mjs +95 -0
  22. package/vendor/dsh-bili-scroll/lib/dm.mjs +110 -0
  23. package/vendor/dsh-bili-scroll/lib/favops.py +90 -0
  24. package/vendor/dsh-bili-scroll/lib/hostdeps.mjs +148 -0
  25. package/vendor/dsh-bili-scroll/lib/login.mjs +141 -0
  26. package/vendor/dsh-bili-scroll/lib/mcp.mjs +144 -0
  27. package/vendor/dsh-bili-scroll/lib/state.mjs +236 -0
  28. package/vendor/dsh-bili-scroll/lib/uid.mjs +61 -0
  29. package/vendor/dsh-bili-scroll/lib/uvfetch.mjs +217 -0
  30. package/vendor/dsh-bili-scroll/lib/verify.mjs +184 -0
  31. package/vendor/dsh-bili-scroll/package.json +84 -0
  32. package/vendor/dsh-bili-scroll/profile-template/bili-duty/cordis.patch.yml +116 -0
  33. package/vendor/dsh-bili-scroll/profile-template/bili-duty/cordis.yml +4 -0
  34. package/vendor/dsh-bili-scroll/profile-template/bili-duty/package.json +13 -0
  35. package/vendor/dsh-bili-scroll/prompts/duty.md +296 -0
  36. package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/LICENSE +21 -0
  37. package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/README.md +176 -0
  38. package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/mcp_server.py +2015 -0
  39. package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/requirements.txt +10 -0
  40. package/vendor/dsh-meme/.dsh/skills/dsh-meme-maintenance/SKILL.md +50 -0
  41. package/vendor/dsh-meme/LICENSE +21 -0
  42. package/vendor/dsh-meme/anim.js +588 -0
  43. package/vendor/dsh-meme/cordis.patch.yml +13 -0
  44. package/vendor/dsh-meme/icon.jpg +0 -0
  45. package/vendor/dsh-meme/index.js +2616 -0
  46. package/vendor/dsh-meme/locale/en.json +6 -0
  47. package/vendor/dsh-meme/locale/zh.json +6 -0
  48. package/vendor/dsh-meme/memes/dafeiyu-001/index.db +0 -0
  49. package/vendor/dsh-meme/memes/dafeiyu-001/manifest.json +13 -0
  50. package/vendor/dsh-meme/memes/dafeiyu-001/memes/angry/shengqi.jpg +0 -0
  51. package/vendor/dsh-meme/memes/dafeiyu-001/memes/baka/xianqi.jpg +0 -0
  52. package/vendor/dsh-meme/memes/dafeiyu-001/memes/color/huachi.jpg +0 -0
  53. package/vendor/dsh-meme/memes/dafeiyu-001/memes/confused/jiazai.jpg +0 -0
  54. package/vendor/dsh-meme/memes/dafeiyu-001/memes/confused/wenhao.jpg +0 -0
  55. package/vendor/dsh-meme/memes/dafeiyu-001/memes/cpu/jiaban.jpg +0 -0
  56. package/vendor/dsh-meme/memes/dafeiyu-001/memes/daily/ganfan.jpg +0 -0
  57. package/vendor/dsh-meme/memes/dafeiyu-001/memes/fool/buyao.jpg +0 -0
  58. package/vendor/dsh-meme/memes/dafeiyu-001/memes/givemoney/yaoqian.jpg +0 -0
  59. package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/deyi.jpg +0 -0
  60. package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/ok.jpg +0 -0
  61. package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/piaole.jpg +0 -0
  62. package/vendor/dsh-meme/memes/dafeiyu-001/memes/like/bixin.jpg +0 -0
  63. package/vendor/dsh-meme/memes/dafeiyu-001/memes/meow/maozhua.jpg +0 -0
  64. package/vendor/dsh-meme/memes/dafeiyu-001/memes/morning/zaoshanghao.jpg +0 -0
  65. package/vendor/dsh-meme/memes/dafeiyu-001/memes/sad/qiurao.jpg +0 -0
  66. package/vendor/dsh-meme/memes/dafeiyu-001/memes/sad/yun.jpg +0 -0
  67. package/vendor/dsh-meme/memes/dafeiyu-001/memes/see/zhenjing.jpg +0 -0
  68. package/vendor/dsh-meme/memes/dafeiyu-001/memes/shy/haixiu.jpg +0 -0
  69. package/vendor/dsh-meme/memes/dafeiyu-001/memes/shy/toukan.jpg +0 -0
  70. package/vendor/dsh-meme/memes/dafeiyu-001/memes/sigh/wuyu.jpg +0 -0
  71. package/vendor/dsh-meme/memes/dafeiyu-001/memes/sleep/shuijiao.jpg +0 -0
  72. package/vendor/dsh-meme/memes/dafeiyu-001/memes/surprised/xia.jpg +0 -0
  73. package/vendor/dsh-meme/memes/dafeiyu-001/memes/work/tangping.jpg +0 -0
  74. package/vendor/dsh-meme/memes.js +998 -0
  75. package/vendor/dsh-meme/package.json +67 -0
  76. package/vendor/dsh-meme/panel.html +210 -0
  77. package/vendor/dsh-video-storyboard/LICENSE +21 -0
  78. package/vendor/dsh-video-storyboard/NOTICE +12 -0
  79. package/vendor/dsh-video-storyboard/bin/_args.mjs +16 -0
  80. package/vendor/dsh-video-storyboard/bin/asr-check.mjs +85 -0
  81. package/vendor/dsh-video-storyboard/bin/scan-stats.mjs +43 -0
  82. package/vendor/dsh-video-storyboard/bin/scan-video.mjs +38 -0
  83. package/vendor/dsh-video-storyboard/bin/storyboard.mjs +195 -0
  84. package/vendor/dsh-video-storyboard/cordis.patch.yml +3 -0
  85. package/vendor/dsh-video-storyboard/dsh.plugin.json +12 -0
  86. package/vendor/dsh-video-storyboard/package.json +88 -0
  87. package/vendor/dsh-video-storyboard/scripts/check-syntax.mjs +56 -0
  88. package/vendor/dsh-video-storyboard/scripts/install-dev.mjs +104 -0
  89. package/vendor/dsh-video-storyboard/src/flicker.js +104 -0
  90. package/vendor/dsh-video-storyboard/src/index.js +82 -0
  91. package/vendor/dsh-video-storyboard/src/ocr_bridge.py +103 -0
  92. package/vendor/dsh-video-storyboard/src/storyboard/asr-lifecycle.js +262 -0
  93. package/vendor/dsh-video-storyboard/src/storyboard/asr.js +488 -0
  94. package/vendor/dsh-video-storyboard/src/storyboard/audio.js +168 -0
  95. package/vendor/dsh-video-storyboard/src/storyboard/binaries.js +69 -0
  96. package/vendor/dsh-video-storyboard/src/storyboard/board.js +121 -0
  97. package/vendor/dsh-video-storyboard/src/storyboard/browser-time.js +504 -0
  98. package/vendor/dsh-video-storyboard/src/storyboard/cache.js +143 -0
  99. package/vendor/dsh-video-storyboard/src/storyboard/cells.js +70 -0
  100. package/vendor/dsh-video-storyboard/src/storyboard/density.js +545 -0
  101. package/vendor/dsh-video-storyboard/src/storyboard/direct-url.js +130 -0
  102. package/vendor/dsh-video-storyboard/src/storyboard/fetch.js +373 -0
  103. package/vendor/dsh-video-storyboard/src/storyboard/flash.js +180 -0
  104. package/vendor/dsh-video-storyboard/src/storyboard/format.js +573 -0
  105. package/vendor/dsh-video-storyboard/src/storyboard/frames.js +212 -0
  106. package/vendor/dsh-video-storyboard/src/storyboard/index.js +32 -0
  107. package/vendor/dsh-video-storyboard/src/storyboard/injection.js +76 -0
  108. package/vendor/dsh-video-storyboard/src/storyboard/layout-order.js +176 -0
  109. package/vendor/dsh-video-storyboard/src/storyboard/locate.js +113 -0
  110. package/vendor/dsh-video-storyboard/src/storyboard/media-store.js +106 -0
  111. package/vendor/dsh-video-storyboard/src/storyboard/memory.js +94 -0
  112. package/vendor/dsh-video-storyboard/src/storyboard/ocr-subs.js +107 -0
  113. package/vendor/dsh-video-storyboard/src/storyboard/ocr.js +167 -0
  114. package/vendor/dsh-video-storyboard/src/storyboard/pipeline.js +853 -0
  115. package/vendor/dsh-video-storyboard/src/storyboard/plan.js +400 -0
  116. package/vendor/dsh-video-storyboard/src/storyboard/probe.js +132 -0
  117. package/vendor/dsh-video-storyboard/src/storyboard/provenance.js +44 -0
  118. package/vendor/dsh-video-storyboard/src/storyboard/python.js +84 -0
  119. package/vendor/dsh-video-storyboard/src/storyboard/register.js +32 -0
  120. package/vendor/dsh-video-storyboard/src/storyboard/scan.js +486 -0
  121. package/vendor/dsh-video-storyboard/src/storyboard/segments.js +117 -0
  122. package/vendor/dsh-video-storyboard/src/storyboard/sheet.js +507 -0
  123. package/vendor/dsh-video-storyboard/src/storyboard/storage.js +93 -0
  124. package/vendor/dsh-video-storyboard/src/storyboard/subtitles.js +181 -0
  125. package/vendor/dsh-video-storyboard/src/storyboard/tool-spec.js +544 -0
  126. package/vendor/dsh-video-storyboard/src/storyboard/transcript-file.js +146 -0
  127. package/vendor/dsh-video-storyboard/src/storyboard/url.js +69 -0
  128. package/vendor/dsh-video-storyboard/src/storyboard/ytdlp.js +289 -0
  129. package/vendor/dsh-video-storyboard/src/tool-spec.js +17 -0
  130. package/vendor/dsh-video-storyboard/src/tools/locate.js +39 -0
  131. package/vendor/dsh-video-storyboard/src/tools/probe.js +23 -0
  132. package/vendor/dsh-video-storyboard/src/tools/shared.js +39 -0
  133. package/vendor/dsh-video-storyboard/src/tools/storyboard.js +20 -0
  134. package/vendor/dsh-video-storyboard/src/tools/zoom.js +56 -0
  135. package/vendor/dsh-world/LICENSE +21 -0
  136. package/vendor/dsh-world/assets/qq-card.png +0 -0
  137. package/vendor/dsh-world/cordis.patch.yml +6 -0
  138. package/vendor/dsh-world/lib/archive.d.ts +6 -0
  139. package/vendor/dsh-world/lib/archive.js +49 -0
  140. package/vendor/dsh-world/lib/archiveSelection.d.ts +8 -0
  141. package/vendor/dsh-world/lib/archiveSelection.js +20 -0
  142. package/vendor/dsh-world/lib/compaction.d.ts +124 -0
  143. package/vendor/dsh-world/lib/compaction.js +273 -0
  144. package/vendor/dsh-world/lib/compactionRegion.d.ts +42 -0
  145. package/vendor/dsh-world/lib/compactionRegion.js +210 -0
  146. package/vendor/dsh-world/lib/console/routes.d.ts +57 -0
  147. package/vendor/dsh-world/lib/console/routes.js +129 -0
  148. package/vendor/dsh-world/lib/console/snapshot.d.ts +39 -0
  149. package/vendor/dsh-world/lib/console/snapshot.js +51 -0
  150. package/vendor/dsh-world/lib/ecosystem/bridge/bridge.d.ts +36 -0
  151. package/vendor/dsh-world/lib/ecosystem/bridge/bridge.js +140 -0
  152. package/vendor/dsh-world/lib/ecosystem/bridge/route.d.ts +9 -0
  153. package/vendor/dsh-world/lib/ecosystem/bridge/route.js +46 -0
  154. package/vendor/dsh-world/lib/ecosystem/qq/bridge.d.ts +123 -0
  155. package/vendor/dsh-world/lib/ecosystem/qq/bridge.js +380 -0
  156. package/vendor/dsh-world/lib/ecosystem/qq/panel.d.ts +75 -0
  157. package/vendor/dsh-world/lib/ecosystem/qq/panel.js +187 -0
  158. package/vendor/dsh-world/lib/ecosystem/qq/route.d.ts +32 -0
  159. package/vendor/dsh-world/lib/ecosystem/qq/route.js +134 -0
  160. package/vendor/dsh-world/lib/ecosystem/qq/supervisor.d.ts +57 -0
  161. package/vendor/dsh-world/lib/ecosystem/qq/supervisor.js +188 -0
  162. package/vendor/dsh-world/lib/ecosystem/shared/context.d.ts +14 -0
  163. package/vendor/dsh-world/lib/ecosystem/shared/context.js +42 -0
  164. package/vendor/dsh-world/lib/ecosystem/shared/identity.d.ts +15 -0
  165. package/vendor/dsh-world/lib/ecosystem/shared/identity.js +36 -0
  166. package/vendor/dsh-world/lib/ecosystem/shared/outlets.d.ts +43 -0
  167. package/vendor/dsh-world/lib/ecosystem/shared/outlets.js +70 -0
  168. package/vendor/dsh-world/lib/ecosystem/shared/sessions.d.ts +16 -0
  169. package/vendor/dsh-world/lib/ecosystem/shared/sessions.js +52 -0
  170. package/vendor/dsh-world/lib/ecosystem/wechat/archive.d.ts +24 -0
  171. package/vendor/dsh-world/lib/ecosystem/wechat/archive.js +62 -0
  172. package/vendor/dsh-world/lib/ecosystem/wechat/home.d.ts +21 -0
  173. package/vendor/dsh-world/lib/ecosystem/wechat/home.js +111 -0
  174. package/vendor/dsh-world/lib/ecosystem/wechat/images.d.ts +5 -0
  175. package/vendor/dsh-world/lib/ecosystem/wechat/images.js +43 -0
  176. package/vendor/dsh-world/lib/ecosystem/wechat/index.d.ts +41 -0
  177. package/vendor/dsh-world/lib/ecosystem/wechat/index.js +166 -0
  178. package/vendor/dsh-world/lib/ecosystem/wechat/messages.d.ts +24 -0
  179. package/vendor/dsh-world/lib/ecosystem/wechat/messages.js +35 -0
  180. package/vendor/dsh-world/lib/ecosystem/wechat/sending.d.ts +30 -0
  181. package/vendor/dsh-world/lib/ecosystem/wechat/sending.js +216 -0
  182. package/vendor/dsh-world/lib/ecosystem/wechat/supervisor.d.ts +39 -0
  183. package/vendor/dsh-world/lib/ecosystem/wechat/supervisor.js +138 -0
  184. package/vendor/dsh-world/lib/faults.d.ts +10 -0
  185. package/vendor/dsh-world/lib/faults.js +13 -0
  186. package/vendor/dsh-world/lib/history.d.ts +16 -0
  187. package/vendor/dsh-world/lib/history.js +80 -0
  188. package/vendor/dsh-world/lib/hostContract.d.ts +19 -0
  189. package/vendor/dsh-world/lib/hostContract.js +1 -0
  190. package/vendor/dsh-world/lib/http.d.ts +18 -0
  191. package/vendor/dsh-world/lib/http.js +39 -0
  192. package/vendor/dsh-world/lib/index.d.ts +108 -0
  193. package/vendor/dsh-world/lib/index.js +356 -0
  194. package/vendor/dsh-world/lib/life/activity.d.ts +14 -0
  195. package/vendor/dsh-world/lib/life/activity.js +58 -0
  196. package/vendor/dsh-world/lib/life/alarm.d.ts +39 -0
  197. package/vendor/dsh-world/lib/life/alarm.js +132 -0
  198. package/vendor/dsh-world/lib/life/alarmTimer.d.ts +22 -0
  199. package/vendor/dsh-world/lib/life/alarmTimer.js +49 -0
  200. package/vendor/dsh-world/lib/life/diary.d.ts +4 -0
  201. package/vendor/dsh-world/lib/life/diary.js +9 -0
  202. package/vendor/dsh-world/lib/life/earlyStop.d.ts +19 -0
  203. package/vendor/dsh-world/lib/life/earlyStop.js +25 -0
  204. package/vendor/dsh-world/lib/life/home.d.ts +34 -0
  205. package/vendor/dsh-world/lib/life/home.js +91 -0
  206. package/vendor/dsh-world/lib/life/host.d.ts +22 -0
  207. package/vendor/dsh-world/lib/life/host.js +24 -0
  208. package/vendor/dsh-world/lib/life/journal.d.ts +20 -0
  209. package/vendor/dsh-world/lib/life/journal.js +59 -0
  210. package/vendor/dsh-world/lib/life/lifeStore.d.ts +16 -0
  211. package/vendor/dsh-world/lib/life/lifeStore.js +105 -0
  212. package/vendor/dsh-world/lib/life/messages.d.ts +17 -0
  213. package/vendor/dsh-world/lib/life/messages.js +53 -0
  214. package/vendor/dsh-world/lib/life/notify.d.ts +15 -0
  215. package/vendor/dsh-world/lib/life/notify.js +40 -0
  216. package/vendor/dsh-world/lib/life/pricing.d.ts +4 -0
  217. package/vendor/dsh-world/lib/life/pricing.js +30 -0
  218. package/vendor/dsh-world/lib/life/runtime.d.ts +52 -0
  219. package/vendor/dsh-world/lib/life/runtime.js +376 -0
  220. package/vendor/dsh-world/lib/life/toolRegistry.d.ts +22 -0
  221. package/vendor/dsh-world/lib/life/toolRegistry.js +64 -0
  222. package/vendor/dsh-world/lib/life/tools.d.ts +24 -0
  223. package/vendor/dsh-world/lib/life/tools.js +47 -0
  224. package/vendor/dsh-world/lib/life/types.d.ts +67 -0
  225. package/vendor/dsh-world/lib/life/types.js +1 -0
  226. package/vendor/dsh-world/lib/persona.d.ts +10 -0
  227. package/vendor/dsh-world/lib/persona.js +29 -0
  228. package/vendor/dsh-world/lib/promptSection.d.ts +30 -0
  229. package/vendor/dsh-world/lib/promptSection.js +81 -0
  230. package/vendor/dsh-world/lib/qqScope.d.ts +11 -0
  231. package/vendor/dsh-world/lib/qqScope.js +39 -0
  232. package/vendor/dsh-world/lib/runtime.d.ts +23 -0
  233. package/vendor/dsh-world/lib/runtime.js +206 -0
  234. package/vendor/dsh-world/lib/self.d.ts +10 -0
  235. package/vendor/dsh-world/lib/self.js +36 -0
  236. package/vendor/dsh-world/lib/sourceArchive.d.ts +28 -0
  237. package/vendor/dsh-world/lib/sourceArchive.js +156 -0
  238. package/vendor/dsh-world/lib/store.d.ts +30 -0
  239. package/vendor/dsh-world/lib/store.js +191 -0
  240. package/vendor/dsh-world/lib/timeContext.d.ts +3 -0
  241. package/vendor/dsh-world/lib/timeContext.js +13 -0
  242. package/vendor/dsh-world/lib/types.d.ts +118 -0
  243. package/vendor/dsh-world/lib/types.js +1 -0
  244. package/vendor/dsh-world/lib/worldPrompt.d.ts +47 -0
  245. package/vendor/dsh-world/lib/worldPrompt.js +49 -0
  246. package/vendor/dsh-world/lib/worldSwitch.d.ts +44 -0
  247. package/vendor/dsh-world/lib/worldSwitch.js +78 -0
  248. package/vendor/dsh-world/package-lock.json +1088 -0
  249. package/vendor/dsh-world/package.json +88 -0
  250. package/vendor/dsh-world/scripts/enable-tool-free-compaction.ps1 +33 -0
  251. package/vendor/dsh-world/src/archive.ts +45 -0
  252. package/vendor/dsh-world/src/archiveSelection.ts +27 -0
  253. package/vendor/dsh-world/src/compaction.ts +260 -0
  254. package/vendor/dsh-world/src/compactionRegion.ts +172 -0
  255. package/vendor/dsh-world/src/console/routes.ts +125 -0
  256. package/vendor/dsh-world/src/console/snapshot.ts +84 -0
  257. package/vendor/dsh-world/src/ecosystem/README.md +14 -0
  258. package/vendor/dsh-world/src/ecosystem/bridge/bridge.ts +121 -0
  259. package/vendor/dsh-world/src/ecosystem/bridge/route.ts +35 -0
  260. package/vendor/dsh-world/src/ecosystem/qq/bridge.ts +456 -0
  261. package/vendor/dsh-world/src/ecosystem/qq/panel.ts +178 -0
  262. package/vendor/dsh-world/src/ecosystem/qq/route.ts +130 -0
  263. package/vendor/dsh-world/src/ecosystem/qq/supervisor.ts +262 -0
  264. package/vendor/dsh-world/src/ecosystem/shared/context.ts +38 -0
  265. package/vendor/dsh-world/src/ecosystem/shared/identity.ts +42 -0
  266. package/vendor/dsh-world/src/ecosystem/shared/outlets.ts +75 -0
  267. package/vendor/dsh-world/src/ecosystem/shared/sessions.ts +47 -0
  268. package/vendor/dsh-world/src/ecosystem/wechat/archive.ts +66 -0
  269. package/vendor/dsh-world/src/ecosystem/wechat/home.ts +94 -0
  270. package/vendor/dsh-world/src/ecosystem/wechat/images.ts +38 -0
  271. package/vendor/dsh-world/src/ecosystem/wechat/index.ts +101 -0
  272. package/vendor/dsh-world/src/ecosystem/wechat/messages.ts +43 -0
  273. package/vendor/dsh-world/src/ecosystem/wechat/sending.ts +177 -0
  274. package/vendor/dsh-world/src/ecosystem/wechat/supervisor.ts +116 -0
  275. package/vendor/dsh-world/src/ecosystem/wechat/windows/README.md +117 -0
  276. package/vendor/dsh-world/src/ecosystem/wechat/windows/adapter.py +572 -0
  277. package/vendor/dsh-world/src/ecosystem/wechat/windows/binding.py +52 -0
  278. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/LICENSE +43 -0
  279. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/NOTICE.md +10 -0
  280. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/bridge.cpp +229 -0
  281. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/build.ps1 +19 -0
  282. package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/profile.json +28 -0
  283. package/vendor/dsh-world/src/ecosystem/wechat/windows/groups.py +42 -0
  284. package/vendor/dsh-world/src/ecosystem/wechat/windows/incoming.py +157 -0
  285. package/vendor/dsh-world/src/ecosystem/wechat/windows/native.py +168 -0
  286. package/vendor/dsh-world/src/ecosystem/wechat/windows/outgoing.py +95 -0
  287. package/vendor/dsh-world/src/ecosystem/wechat/windows/requirements.txt +1 -0
  288. package/vendor/dsh-world/src/ecosystem/wechat/windows/sender.py +157 -0
  289. package/vendor/dsh-world/src/ecosystem/wechat/windows/snapshot.py +32 -0
  290. package/vendor/dsh-world/src/ecosystem/wechat/windows/stickers.py +60 -0
  291. package/vendor/dsh-world/src/ecosystem/wechat/windows/wechat.ps1 +75 -0
  292. package/vendor/dsh-world/src/faults.ts +12 -0
  293. package/vendor/dsh-world/src/history.ts +77 -0
  294. package/vendor/dsh-world/src/hostContract.ts +9 -0
  295. package/vendor/dsh-world/src/http.ts +34 -0
  296. package/vendor/dsh-world/src/index.ts +286 -0
  297. package/vendor/dsh-world/src/life/activity.ts +48 -0
  298. package/vendor/dsh-world/src/life/alarm.ts +119 -0
  299. package/vendor/dsh-world/src/life/alarmTimer.ts +45 -0
  300. package/vendor/dsh-world/src/life/diary.ts +10 -0
  301. package/vendor/dsh-world/src/life/earlyStop.ts +27 -0
  302. package/vendor/dsh-world/src/life/home.ts +85 -0
  303. package/vendor/dsh-world/src/life/host.ts +50 -0
  304. package/vendor/dsh-world/src/life/journal.ts +44 -0
  305. package/vendor/dsh-world/src/life/lifeStore.ts +70 -0
  306. package/vendor/dsh-world/src/life/messages.ts +44 -0
  307. package/vendor/dsh-world/src/life/notify.ts +47 -0
  308. package/vendor/dsh-world/src/life/pricing.ts +37 -0
  309. package/vendor/dsh-world/src/life/runtime.ts +318 -0
  310. package/vendor/dsh-world/src/life/toolRegistry.ts +48 -0
  311. package/vendor/dsh-world/src/life/tools.ts +61 -0
  312. package/vendor/dsh-world/src/life/types.ts +19 -0
  313. package/vendor/dsh-world/src/persona.ts +26 -0
  314. package/vendor/dsh-world/src/promptSection.ts +71 -0
  315. package/vendor/dsh-world/src/qqScope.ts +51 -0
  316. package/vendor/dsh-world/src/runtime.ts +172 -0
  317. package/vendor/dsh-world/src/self.ts +32 -0
  318. package/vendor/dsh-world/src/sourceArchive.ts +132 -0
  319. package/vendor/dsh-world/src/store.ts +170 -0
  320. package/vendor/dsh-world/src/timeContext.ts +13 -0
  321. package/vendor/dsh-world/src/types.ts +112 -0
  322. package/vendor/dsh-world/src/worldPrompt.ts +64 -0
  323. package/vendor/dsh-world/src/worldSwitch.ts +82 -0
  324. package/vendor/dsh-world/templates/alarm.md +49 -0
  325. package/vendor/dsh-world/templates/world-prompt.md +7 -0
  326. package/vendor/dsh-world/tests/archive.test.ts +57 -0
  327. package/vendor/dsh-world/tests/archiveScope.test.ts +86 -0
  328. package/vendor/dsh-world/tests/bridge.test.ts +211 -0
  329. package/vendor/dsh-world/tests/channelSessions.test.ts +79 -0
  330. package/vendor/dsh-world/tests/clientHooks.test.ts +103 -0
  331. package/vendor/dsh-world/tests/compaction.test.ts +141 -0
  332. package/vendor/dsh-world/tests/console.test.ts +202 -0
  333. package/vendor/dsh-world/tests/consoleClient.test.ts +101 -0
  334. package/vendor/dsh-world/tests/enableCompaction.test.ts +19 -0
  335. package/vendor/dsh-world/tests/fixtures.ts +6 -0
  336. package/vendor/dsh-world/tests/history.test.ts +100 -0
  337. package/vendor/dsh-world/tests/hostFixture.ts +46 -0
  338. package/vendor/dsh-world/tests/lifeActivity.test.ts +70 -0
  339. package/vendor/dsh-world/tests/lifeAlarm.test.ts +87 -0
  340. package/vendor/dsh-world/tests/lifeDiary.test.ts +33 -0
  341. package/vendor/dsh-world/tests/lifeMessages.test.ts +61 -0
  342. package/vendor/dsh-world/tests/lifeNotify.test.ts +46 -0
  343. package/vendor/dsh-world/tests/lifeParts.test.ts +45 -0
  344. package/vendor/dsh-world/tests/lifeRuntime.test.ts +660 -0
  345. package/vendor/dsh-world/tests/lifeStore.test.ts +90 -0
  346. package/vendor/dsh-world/tests/lifeTools.test.ts +53 -0
  347. package/vendor/dsh-world/tests/outlets.test.ts +85 -0
  348. package/vendor/dsh-world/tests/panel.test.ts +85 -0
  349. package/vendor/dsh-world/tests/plugin.test.ts +614 -0
  350. package/vendor/dsh-world/tests/pricing.test.ts +21 -0
  351. package/vendor/dsh-world/tests/qq.test.ts +121 -0
  352. package/vendor/dsh-world/tests/qqSessionMode.test.ts +97 -0
  353. package/vendor/dsh-world/tests/qqSupervisor.test.ts +149 -0
  354. package/vendor/dsh-world/tests/sourceArchive.test.ts +58 -0
  355. package/vendor/dsh-world/tests/store.test.ts +82 -0
  356. package/vendor/dsh-world/tests/storeWriter.ts +5 -0
  357. package/vendor/dsh-world/tests/timeContext.test.ts +15 -0
  358. package/vendor/dsh-world/tests/wechat.test.ts +254 -0
  359. package/vendor/dsh-world/tests/wechatImages.test.ts +130 -0
  360. package/vendor/dsh-world/tests/wechatSending.test.ts +142 -0
  361. package/vendor/dsh-world/tests/wechatSupervisor.test.ts +91 -0
  362. package/vendor/dsh-world/tests/worldPrompt.test.ts +201 -0
  363. package/vendor/dsh-world/tsconfig.build.json +5 -0
  364. package/vendor/dsh-world/tsconfig.json +8 -0
@@ -0,0 +1,2015 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Bilibili MCP Server
4
+ B站数据采集 MCP 服务,支持 OpenClaw / Claude Code / Cursor / Cline
5
+
6
+ 功能:搜索视频、抓取评论、获取字幕、弹幕、回复评论
7
+ 首次运行需扫码登录B站,凭证自动保存复用
8
+ """
9
+
10
+ # ⭐ 这个文件是从上游 AGI_Ananas/bilibili-mcp(MIT,见同目录 LICENSE)vendor 进来的。
11
+ # 本插件在它上面只加了下面这几处 —— **将来重新 vendor 时,这几处要原样补回来**(漏一处就少一道闸 ✗):
12
+ # ① `_ALLOWED` + `tool()` 白名单替身:工具按名单注册,名单外的连名字都不出现(见下)
13
+ # ② `load_credential` 读取容错 + encoding="utf-8" + isinstance(data, dict) 校验
14
+ # ③ 登录成功后凭证**原子写**(先写 .tmp 再 os.replace)
15
+ # ④ `bili_comments` 把抓取异常带进返回(风控 -412 不再伪装成"这条视频 0 条评论")
16
+ # ⑤ `bili_reply` 回执带上 `rpid` / `rpid_str` / `root` / `parent`(判重表与评论复核要用)
17
+ # ⑥ `bili_cover` / `bili_frames`:封面和画面帧**作为图片**返回(上游没有;
18
+ # 图能不能进模型上下文由宿主判断)
19
+ import asyncio
20
+ import json
21
+ import re
22
+ import base64
23
+ import os
24
+ import struct
25
+ import sys
26
+ import tempfile
27
+ from pathlib import Path
28
+ from mcp.server.fastmcp import FastMCP
29
+ from mcp.types import ImageContent, TextContent
30
+
31
+ from bilibili_api import video, search, comment, Credential, dynamic, opus
32
+ from bilibili_api import hot, rank, user, session, favorite_list
33
+ from bilibili_api import homepage
34
+ from bilibili_api.video_uploader import (
35
+ VideoUploader, VideoUploaderPage, VideoMeta, Lines,
36
+ )
37
+ from bilibili_api.utils.picture import Picture
38
+ from bilibili_api.login_v2 import QrCodeLogin, QrCodeLoginEvents
39
+
40
+ # ========== 初始化 ==========
41
+
42
+ CRED_FILE = Path(__file__).parent / "bili_credential.json"
43
+
44
+ mcp = FastMCP("bilibili-mcp")
45
+
46
+ # ⭐ 工具白名单(2026-10-17 审查里的 H3):宿主通过 overlay 的 env 下发 BILI_MCP_TOOLS(逗号分隔)。
47
+ # · 不给这个变量 ⇒ **全放**(手工跑、或老配置,行为一点不变 ✓)
48
+ # · 给了 ⇒ 只注册名单里的;不在名单里的工具**连名字都不会出现在 list_tools 里**,
49
+ # 模型那边等于根本不存在 —— 这才是真的闸门(光靠提示词说"别用"不算)✓
50
+ _ALLOWED = {t.strip() for t in os.environ.get("BILI_MCP_TOOLS", "").split(",") if t.strip()}
51
+
52
+
53
+ def tool():
54
+ """@tool() 的替身:白名单里没有这个函数名,就原样返回、**不注册**。"""
55
+ def deco(fn):
56
+ if _ALLOWED and fn.__name__ not in _ALLOWED:
57
+ return fn
58
+ return mcp.tool()(fn)
59
+ return deco
60
+
61
+
62
+ # ⭐⭐ 2026-10-23 安全加固(issue #39):**白名单以前只挡"注册",不挡"直接调用"** ——
63
+ # agent 手里有 python/shell,可以自己写脚本 import 这个文件再调函数 ⇒ 闸门形同虚设。
64
+ # ⇒ 每个"会往 B站 写东西"的函数入口都过一遍 _guard();没开就直接返回、什么都不做 ✓
65
+ def _guard(name: str) -> str:
66
+ """没开这个工具就返回一句提示;开着返回空串。"""
67
+ if _ALLOWED and name not in _ALLOWED:
68
+ print(f"[bili-mcp] 拒绝调用 {name}(不在 BILI_MCP_TOOLS 白名单里)", file=sys.stderr)
69
+ return f"这个工具没开:{name}"
70
+ return ""
71
+
72
+
73
+ # ⭐⭐ 语感闸门(治"鱼八股"):**发评论之前,先在函数里拦一道**
74
+ # 背景:章程里写"要有具体细节、别客套",模型照样写"这条我认""值得一看" ——
75
+ # 禁令没有范例有效、自觉没有拦截可靠 ⇒ 在执行层做最后一道检查(跟 _guard 同一思路)。
76
+ # 三道检查(便宜、纯本地 / 一次轻请求):
77
+ # ① 开头八股黑名单(正则)
78
+ # ② 跟**自己以前发过的评论**太像(bigram 相似度)—— 治"每条一个味"
79
+ # ③ 跟**这条视频现有热评**太像 —— 治"跟别的鱼撞车"
80
+ # ⚠️ 撞了就**不发**,把原因和改法返回给模型,让它重写一句。
81
+ # ⚠️ 关掉:`BILI_STYLE_OFF=1`。
82
+ _STYLE_OFF = os.environ.get("BILI_STYLE_OFF", "") in ("1", "true", "yes")
83
+ _STYLE_LEAD = re.compile(
84
+ r"^\s*(?:"
85
+ r"这条(?:我认|我记下了|值得)|我记下了|值得一看|确实值得|不得不说|"
86
+ r"好家伙|这个(?:必须|真的要)|强烈推荐|感谢分享|学到了|受教了|"
87
+ r"作为一个|总之|综上"
88
+ r")"
89
+ )
90
+
91
+
92
+ def _bigrams(s: str) -> set:
93
+ t = re.sub(r"[^\w\u4e00-\u9fff]", "", "".join(ch for ch in str(s or "") if not ch.isspace()))
94
+ if len(t) < 2:
95
+ return set(t)
96
+ return {t[i:i + 2] for i in range(len(t) - 1)}
97
+
98
+
99
+ def _sim(a: str, b: str) -> float:
100
+ """bigram Jaccard —— 够用、够快、零依赖"""
101
+ x, y = _bigrams(a), _bigrams(b)
102
+ if not x or not y:
103
+ return 0.0
104
+ return len(x & y) / max(1, len(x | y))
105
+
106
+
107
+ def _ledger_path():
108
+ try:
109
+ return DUTY_HOME / "comments.md"
110
+ except Exception:
111
+ return Path(__file__).parent / "comments.md"
112
+
113
+
114
+ def _ledger_recent(n: int = 30):
115
+ """最近 n 条"自己发过的评论"正文(台账一行:`- 日期 BVID rpid=… · 正文`)"""
116
+ try:
117
+ p = _ledger_path()
118
+ if not p.exists():
119
+ return []
120
+ out = []
121
+ for ln in p.read_text(encoding="utf-8").splitlines():
122
+ ln = ln.strip()
123
+ if not ln.startswith("- "):
124
+ continue
125
+ body = ln.split("·", 1)[1].strip() if "·" in ln else ln[2:].strip()
126
+ if body:
127
+ out.append(body)
128
+ return out[-n:]
129
+ except Exception:
130
+ return []
131
+
132
+
133
+ def _ledger_append(text: str, bvid: str, rpid=None):
134
+ try:
135
+ p = _ledger_path()
136
+ p.parent.mkdir(parents=True, exist_ok=True)
137
+ with open(p, "a", encoding="utf-8") as f:
138
+ f.write(f"- {_dt.datetime.now().strftime('%Y-%m-%d %H:%M')} {bvid} rpid={rpid or 0} · {' '.join(str(text).split())}\n")
139
+ except Exception:
140
+ pass
141
+
142
+
143
+ async def _style_reason(text: str, bvid: str, cred) -> str:
144
+ """返回"为什么这句不能发";空串 = 可以发"""
145
+ if _STYLE_OFF:
146
+ return ""
147
+ body = " ".join(str(text or "").split())
148
+ if not body:
149
+ return "评论是空的。"
150
+ m = _STYLE_LEAD.match(body)
151
+ if m:
152
+ return (f"开头「{m.group(0).strip()}」是鱼八股。直接说这条视频里的具体东西:"
153
+ "「这期讲了什么 + 一个只有看了才说得出的细节」,开头别用套话。")
154
+ for old in _ledger_recent(30):
155
+ s = _sim(body, old)
156
+ if s >= 0.55:
157
+ return (f"这句跟你以前发过的「{old[:18]}…」太像了(相似度 {s:.2f})。"
158
+ "换开头、换关注点,别套同一个句式。")
159
+ try:
160
+ v = video.Video(bvid=bvid, credential=cred)
161
+ aid = (await v.get_info())["aid"]
162
+ resp = await comment.get_comments(
163
+ oid=aid, type_=comment.CommentResourceType.VIDEO, page_index=1,
164
+ order=comment.OrderType.LIKE, credential=cred,
165
+ )
166
+ for c in (resp.get("replies") or [])[:20]:
167
+ other = " ".join(str((c.get("content") or {}).get("message", "")).split())
168
+ if not other:
169
+ continue
170
+ s = _sim(body, other)
171
+ if s >= 0.5:
172
+ return (f"这条视频底下已经有一句很像的(相似度 {s:.2f}):{other[:24]}… "
173
+ "撞车了 —— 换个角度写,或者这一轮不发。")
174
+ except Exception:
175
+ pass # 读不到热评就不做这道检查(不能因为读不到就不让发)
176
+ return ""
177
+
178
+
179
+ def load_credential() -> Credential:
180
+ """从文件加载凭证"""
181
+ if not CRED_FILE.exists():
182
+ return None
183
+ try:
184
+ with open(CRED_FILE, encoding="utf-8") as f:
185
+ data = json.load(f)
186
+ except (OSError, ValueError) as e:
187
+ # ⚠️ 文件写坏一次(上一次写被打断)会让**所有**工具一起 JSONDecodeError:
188
+ # 这里退化成「没登录」,重新扫一次码就能恢复。(2026-10-16 审查修)
189
+ print(f"[bili-mcp] 凭证读不了({type(e).__name__}: {e}):{CRED_FILE}", file=sys.stderr)
190
+ return None
191
+ if not isinstance(data, dict):
192
+ return None
193
+ return Credential(
194
+ sessdata=data.get("sessdata", ""),
195
+ bili_jct=data.get("bili_jct", ""),
196
+ buvid3=data.get("buvid3") or "",
197
+ dedeuserid=data.get("dedeuserid", ""),
198
+ )
199
+
200
+
201
+ # ========== 登录会话(进程级缓存) ==========
202
+
203
+ _login_session: QrCodeLogin | None = None
204
+
205
+
206
+ def get_cred() -> Credential:
207
+ """获取凭证,未登录时引导用户调用 bili_login"""
208
+ cred = load_credential()
209
+ if not cred:
210
+ raise Exception("未登录B站!请先调用 bili_login 工具获取登录二维码,让用户扫码登录。")
211
+ return cred
212
+
213
+
214
+ # ========== Tool: 扫码登录(生成二维码) ==========
215
+
216
+ @tool()
217
+ async def bili_login() -> str:
218
+ """
219
+ 生成B站登录二维码,返回二维码图片(base64)供用户扫码。
220
+ 用户扫码后,调用 bili_login_check 检查登录状态。
221
+
222
+ Returns:
223
+ 包含二维码base64图片数据的JSON,前端可直接渲染为图片展示给用户
224
+ """
225
+ global _login_session
226
+
227
+ # 如果已有凭证,直接返回
228
+ cred = load_credential()
229
+ if cred:
230
+ return json.dumps({
231
+ "status": "already_logged_in",
232
+ "message": "已登录B站,无需重复登录",
233
+ }, ensure_ascii=False)
234
+
235
+ # 生成新的登录会话
236
+ _login_session = QrCodeLogin()
237
+ await _login_session.generate_qrcode()
238
+
239
+ # 获取二维码图片的 base64(无损PNG)
240
+ pic = _login_session.get_qrcode_picture()
241
+ img_base64 = base64.b64encode(pic.content).decode("utf-8")
242
+
243
+ # 保存二维码图片到项目根目录
244
+ qr_file = Path(__file__).parent / "qrcode_login.png"
245
+ with open(qr_file, "wb") as f:
246
+ f.write(pic.content)
247
+
248
+ # 获取终端文本版二维码(纯文本客户端备用)
249
+ terminal_qr = _login_session.get_qrcode_terminal()
250
+
251
+ # 获取原始扫码URL(用户也可以手动在B站App打开)
252
+ qr_url = getattr(_login_session, "_QrCodeLogin__qr_link", "")
253
+
254
+ return json.dumps({
255
+ "status": "qrcode_ready",
256
+ "message": "请用B站App扫描二维码登录(180秒内有效)",
257
+ "qrcode_image": f"data:image/png;base64,{img_base64}",
258
+ "qrcode_file": str(qr_file),
259
+ "qrcode_terminal": terminal_qr,
260
+ "qrcode_url": qr_url,
261
+ "next_step": "用户扫码后,请调用 bili_login_check 检查登录状态",
262
+ }, ensure_ascii=False)
263
+
264
+
265
+ # ========== Tool: 检查登录状态 ==========
266
+
267
+ @tool()
268
+ async def bili_login_check() -> str:
269
+ """
270
+ 检查B站扫码登录状态。在用户扫码后调用此工具。
271
+ 如果返回 "scanning" 或 "confirming",请等待几秒后再次调用。
272
+ 如果返回 "done",登录成功,可以使用其他工具了。
273
+ 如果返回 "timeout",需要重新调用 bili_login 生成新二维码。
274
+
275
+ Returns:
276
+ 当前登录状态
277
+ """
278
+ global _login_session
279
+
280
+ if not _login_session:
281
+ # 没有登录会话,检查是否已登录
282
+ cred = load_credential()
283
+ if cred:
284
+ return json.dumps({
285
+ "status": "already_logged_in",
286
+ "message": "已登录B站",
287
+ }, ensure_ascii=False)
288
+ return json.dumps({
289
+ "status": "no_session",
290
+ "message": "没有进行中的登录,请先调用 bili_login 生成二维码",
291
+ }, ensure_ascii=False)
292
+
293
+ state = await _login_session.check_state()
294
+
295
+ if state == QrCodeLoginEvents.SCAN:
296
+ return json.dumps({
297
+ "status": "scanning",
298
+ "message": "已扫码,等待用户在手机上确认...",
299
+ "next_step": "请等待3秒后再次调用 bili_login_check",
300
+ }, ensure_ascii=False)
301
+
302
+ elif state == QrCodeLoginEvents.CONF:
303
+ return json.dumps({
304
+ "status": "confirming",
305
+ "message": "用户已确认,正在处理...",
306
+ "next_step": "请等待2秒后再次调用 bili_login_check",
307
+ }, ensure_ascii=False)
308
+
309
+ elif state == QrCodeLoginEvents.TIMEOUT:
310
+ _login_session = None
311
+ # 清理二维码文件
312
+ qr_file = Path(__file__).parent / "qrcode_login.png"
313
+ if qr_file.exists():
314
+ qr_file.unlink()
315
+ return json.dumps({
316
+ "status": "timeout",
317
+ "message": "二维码已过期,请重新调用 bili_login 生成新二维码",
318
+ }, ensure_ascii=False)
319
+
320
+ elif state == QrCodeLoginEvents.DONE:
321
+ # 登录成功,保存凭证
322
+ cred = _login_session.get_credential()
323
+ # ⚠️ 原子写:原来直接 open(w) 先截断再 dump,写到一半被打断就毁掉旧凭证,
324
+ # 此后所有工具都读不了。(2026-10-16 审查修)
325
+ tmp_cred = CRED_FILE.with_name(CRED_FILE.name + ".tmp")
326
+ with open(tmp_cred, "w", encoding="utf-8") as f:
327
+ json.dump({
328
+ "sessdata": cred.sessdata,
329
+ "bili_jct": cred.bili_jct,
330
+ "buvid3": cred.buvid3,
331
+ "dedeuserid": cred.dedeuserid,
332
+ }, f)
333
+ os.replace(tmp_cred, CRED_FILE)
334
+ _login_session = None
335
+ # 清理二维码文件
336
+ qr_file = Path(__file__).parent / "qrcode_login.png"
337
+ if qr_file.exists():
338
+ qr_file.unlink()
339
+ return json.dumps({
340
+ "status": "done",
341
+ "message": "登录成功!凭证已保存,现在可以使用所有B站功能了",
342
+ }, ensure_ascii=False)
343
+
344
+ return json.dumps({
345
+ "status": "unknown",
346
+ "message": f"未知状态: {state}",
347
+ }, ensure_ascii=False)
348
+
349
+
350
+ # ========== Tool: 登录状态查询 ==========
351
+
352
+ @tool()
353
+ async def bili_check_credential() -> str:
354
+ """
355
+ 检查当前B站登录凭证是否有效
356
+
357
+ Returns:
358
+ 登录状态信息
359
+ """
360
+ cred = load_credential()
361
+ if not cred:
362
+ return json.dumps({
363
+ "logged_in": False,
364
+ "message": "未登录,请调用 bili_login 进行扫码登录",
365
+ }, ensure_ascii=False)
366
+
367
+ # 尝试用凭证请求一下,验证是否过期
368
+ try:
369
+ my_info = await user.User(
370
+ uid=int(cred.dedeuserid), credential=cred
371
+ ).get_user_info()
372
+ return json.dumps({
373
+ "logged_in": True,
374
+ "uid": cred.dedeuserid,
375
+ "username": my_info.get("name", ""),
376
+ "message": "凭证有效",
377
+ }, ensure_ascii=False)
378
+ except Exception as e:
379
+ return json.dumps({
380
+ "logged_in": False,
381
+ "message": f"凭证可能已过期: {str(e)},请重新调用 bili_login 登录",
382
+ }, ensure_ascii=False)
383
+
384
+
385
+ # ========== Tool 1: 搜索视频 ==========
386
+
387
+ @tool()
388
+ async def bili_search(keyword: str, num: int = 10, order: str = "totalrank") -> str:
389
+ """
390
+ 搜索B站视频
391
+
392
+ Args:
393
+ keyword: 搜索关键词,如"AI Agent"、"大模型教程"
394
+ num: 返回视频数量,默认10,最大50
395
+ order: 排序方式 totalrank=综合 click=播放量 pubdate=最新 dm=弹幕
396
+
397
+ Returns:
398
+ JSON格式的视频列表,包含标题、BV号、播放量、评论数、UP主等
399
+ """
400
+ order_map = {
401
+ "totalrank": search.OrderVideo.TOTALRANK,
402
+ "click": search.OrderVideo.CLICK,
403
+ "pubdate": search.OrderVideo.PUBDATE,
404
+ "dm": search.OrderVideo.DM,
405
+ }
406
+ order_enum = order_map.get(order, search.OrderVideo.TOTALRANK)
407
+
408
+ result = await search.search_by_type(
409
+ keyword=keyword,
410
+ search_type=search.SearchObjectType.VIDEO,
411
+ page=1,
412
+ order_type=order_enum,
413
+ )
414
+
415
+ videos = []
416
+ for item in result.get("result", [])[:num]:
417
+ title = item.get("title", "").replace('<em class="keyword">', "").replace("</em>", "")
418
+ videos.append({
419
+ "bvid": item.get("bvid", ""),
420
+ "aid": item.get("aid", 0),
421
+ "title": title,
422
+ "author": item.get("author", ""),
423
+ "play": item.get("play", 0),
424
+ "review": item.get("review", 0),
425
+ "danmaku": item.get("video_review", 0),
426
+ "duration": item.get("duration", ""),
427
+ "description": item.get("description", "")[:200],
428
+ })
429
+
430
+ return json.dumps({"keyword": keyword, "count": len(videos), "videos": videos}, ensure_ascii=False)
431
+
432
+
433
+ # ========== Tool 2: 获取评论 ==========
434
+
435
+ @tool()
436
+ async def bili_comments(bvid: str, num: int = 30) -> str:
437
+ """
438
+ 获取B站视频的热门评论
439
+
440
+ Args:
441
+ bvid: 视频BV号,如"BV1uNk1YxEJQ"
442
+ num: 获取评论数量,默认30
443
+
444
+ Returns:
445
+ JSON格式的评论列表,包含用户名、评论内容、点赞数、回复数
446
+ """
447
+ cred = get_cred()
448
+ v = video.Video(bvid=bvid, credential=cred)
449
+ info = await v.get_info()
450
+ aid = info["aid"]
451
+
452
+ comments = []
453
+ page = 1
454
+ fetch_error = None
455
+ while len(comments) < num:
456
+ try:
457
+ resp = await comment.get_comments(
458
+ oid=aid,
459
+ type_=comment.CommentResourceType.VIDEO,
460
+ page_index=page,
461
+ order=comment.OrderType.LIKE,
462
+ credential=cred,
463
+ )
464
+ replies = resp.get("replies") or []
465
+ if not replies:
466
+ break
467
+
468
+ for r in replies:
469
+ member = r.get("member", {})
470
+ content = r.get("content", {})
471
+ c = {
472
+ "rpid": r.get("rpid", 0),
473
+ "user": member.get("uname", ""),
474
+ "content": content.get("message", ""),
475
+ "like": r.get("like", 0),
476
+ "reply_count": r.get("rcount", 0),
477
+ "time": r.get("ctime", 0),
478
+ }
479
+ # 子评论
480
+ sub_replies = []
481
+ for sub in (r.get("replies") or [])[:2]:
482
+ sub_replies.append({
483
+ "user": sub.get("member", {}).get("uname", ""),
484
+ "content": sub.get("content", {}).get("message", ""),
485
+ "like": sub.get("like", 0),
486
+ })
487
+ if sub_replies:
488
+ c["top_replies"] = sub_replies
489
+ comments.append(c)
490
+
491
+ page += 1
492
+ await asyncio.sleep(0.5)
493
+ except Exception as e:
494
+ # ⚠️ 抓取失败(风控 -412 / 网络错)不能吞成「这条视频 0 条评论」:
495
+ # 调用方必须能分辨「真没评论」和「没抓到」,否则日报静默失真。(2026-10-16 审查修)
496
+ fetch_error = f"{type(e).__name__}: {e}"
497
+ break
498
+
499
+ out = {"bvid": bvid, "count": len(comments[:num]), "comments": comments[:num]}
500
+ if fetch_error:
501
+ out["error"] = fetch_error
502
+ return json.dumps(out, ensure_ascii=False)
503
+
504
+
505
+ # ========== Tool 3: 获取字幕 ==========
506
+
507
+ @tool()
508
+ async def bili_subtitle(bvid: str) -> str:
509
+ """
510
+ 获取B站视频的AI字幕(语音转文字)
511
+
512
+ Args:
513
+ bvid: 视频BV号,如"BV1uNk1YxEJQ"
514
+
515
+ Returns:
516
+ 视频的完整字幕文本
517
+ """
518
+ cred = get_cred()
519
+ v = video.Video(bvid=bvid, credential=cred)
520
+
521
+ info = await v.get_info()
522
+ cid = info.get("cid", 0)
523
+ if not cid and info.get("pages"):
524
+ cid = info["pages"][0].get("cid", 0)
525
+
526
+ if not cid:
527
+ return json.dumps({"error": "无法获取cid"}, ensure_ascii=False)
528
+
529
+ subtitle_list = await v.get_subtitle(cid=cid)
530
+ subtitles = subtitle_list.get("subtitles", [])
531
+
532
+ if not subtitles:
533
+ return json.dumps({"message": "该视频没有字幕"}, ensure_ascii=False)
534
+
535
+ # 优先AI中文字幕
536
+ target = None
537
+ for s in subtitles:
538
+ if s.get("lan") in ["ai-zh", "zh-CN", "zh"]:
539
+ target = s
540
+ break
541
+ if not target:
542
+ target = subtitles[0]
543
+
544
+ # 下载字幕
545
+ import aiohttp
546
+ sub_url = target.get("subtitle_url", "")
547
+ if sub_url.startswith("//"):
548
+ sub_url = "https:" + sub_url
549
+
550
+ async with aiohttp.ClientSession() as session:
551
+ async with session.get(sub_url) as resp:
552
+ sub_data = await resp.json()
553
+
554
+ texts = [item.get("content", "") for item in sub_data.get("body", [])]
555
+ full_text = "\n".join(texts)
556
+
557
+ return json.dumps({
558
+ "bvid": bvid,
559
+ "title": info.get("title", ""),
560
+ "language": target.get("lan_doc", ""),
561
+ "segments": len(texts),
562
+ "text": full_text,
563
+ }, ensure_ascii=False)
564
+
565
+
566
+ # ========== Tool 4: 获取弹幕 ==========
567
+
568
+ @tool()
569
+ async def bili_danmaku(bvid: str, num: int = 100) -> str:
570
+ """
571
+ 获取B站视频的弹幕
572
+
573
+ Args:
574
+ bvid: 视频BV号
575
+ num: 获取弹幕数量,默认100
576
+
577
+ Returns:
578
+ 弹幕列表,包含弹幕文本和出现时间
579
+ """
580
+ cred = get_cred()
581
+ v = video.Video(bvid=bvid, credential=cred)
582
+
583
+ danmakus = await v.get_danmakus(page_index=0)
584
+ result = []
585
+ for d in danmakus[:num]:
586
+ result.append({
587
+ "text": d.text,
588
+ "time": d.dm_time,
589
+ })
590
+
591
+ return json.dumps({"bvid": bvid, "count": len(result), "danmakus": result}, ensure_ascii=False)
592
+
593
+
594
+ # ========== Tool 5: 视频详情 ==========
595
+
596
+ @tool()
597
+ async def bili_video_info(bvid: str) -> str:
598
+ """
599
+ 获取B站视频的详细信息
600
+
601
+ Args:
602
+ bvid: 视频BV号
603
+
604
+ Returns:
605
+ 视频标题、描述、UP主、播放量、评论数、收藏数等详细数据
606
+ """
607
+ cred = get_cred()
608
+ v = video.Video(bvid=bvid, credential=cred)
609
+ info = await v.get_info()
610
+ stat = info.get("stat", {})
611
+
612
+ return json.dumps({
613
+ "bvid": info.get("bvid"),
614
+ "aid": info.get("aid"),
615
+ "title": info.get("title"),
616
+ "description": info.get("desc"),
617
+ "author": info.get("owner", {}).get("name"),
618
+ "duration": info.get("duration"),
619
+ "pages": len(info.get("pages", [])),
620
+ "tags": [t.get("tag_name") for t in info.get("tag", []) if t.get("tag_name")],
621
+ "stat": {
622
+ "view": stat.get("view", 0),
623
+ "danmaku": stat.get("danmaku", 0),
624
+ "reply": stat.get("reply", 0),
625
+ "favorite": stat.get("favorite", 0),
626
+ "coin": stat.get("coin", 0),
627
+ "like": stat.get("like", 0),
628
+ "share": stat.get("share", 0),
629
+ },
630
+ }, ensure_ascii=False)
631
+
632
+
633
+ # ========== Tool 6: 回复评论 ==========
634
+
635
+ @tool()
636
+ async def bili_reply(bvid: str, text: str, rpid: int = 0, root: int = 0) -> str:
637
+ """
638
+ 在B站视频下发表评论或回复某条评论
639
+
640
+ Args:
641
+ bvid: 视频BV号
642
+ text: 评论/回复的文本内容
643
+ rpid: 要回复的目标评论ID(0表示发表新评论)
644
+ root: 楼层根评论ID(回复一级评论时不用填,回复楼中楼时填根评论ID)
645
+
646
+ Returns:
647
+ 发表结果
648
+ """
649
+ _deny = _guard("bili_reply")
650
+ if _deny: return _deny
651
+ # ⭐ 语感闸门:撞八股 / 撞自己以前的 / 撞这条视频的热评 ⇒ 不发,把改法告诉模型
652
+ _style = await _style_reason(text, bvid, get_cred())
653
+ if _style:
654
+ return json.dumps({"ok": False, "sent": False, "blocked_by": "style", "error": _style}, ensure_ascii=False)
655
+ cred = get_cred()
656
+ v = video.Video(bvid=bvid, credential=cred)
657
+ info = await v.get_info()
658
+ aid = info["aid"]
659
+
660
+ try:
661
+ if rpid == 0:
662
+ # 发表新评论
663
+ result = await comment.send_comment(
664
+ text=text,
665
+ oid=aid,
666
+ type_=comment.CommentResourceType.VIDEO,
667
+ credential=cred,
668
+ )
669
+ else:
670
+ # 回复评论
671
+ # root=0 表示回复一级评论,root=rpid
672
+ # root!=0 表示回复楼中楼,root=根评论,parent=目标评论
673
+ actual_root = root if root != 0 else rpid
674
+ result = await comment.send_comment(
675
+ text=text,
676
+ oid=aid,
677
+ type_=comment.CommentResourceType.VIDEO,
678
+ root=actual_root,
679
+ parent=rpid,
680
+ credential=cred,
681
+ )
682
+
683
+ # ⭐ 把回执里的 rpid 带回去:判重表要靠它记「我们发过哪条」,宿主的评论复核
684
+ # (lib/verify.mjs)也要拿它去 B站 查公开可见性。只回 success 的话那条链是断的。
685
+ #(2026-10-16 审查修:原实现把上面的 result 丢掉了)
686
+ out = {"success": True, "message": "评论发送成功"}
687
+ _ledger_append(text, bvid, result.get("rpid") if isinstance(result, dict) else None)
688
+ if isinstance(result, dict):
689
+ for key in ("rpid", "rpid_str", "root", "parent"):
690
+ val = result.get(key)
691
+ if isinstance(val, (int, str)) and str(val).strip() and str(val) != "0":
692
+ out[key] = val
693
+ return json.dumps(out, ensure_ascii=False)
694
+ except Exception as e:
695
+ return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)
696
+
697
+
698
+ # ========== Tool 7: 批量采集 ==========
699
+
700
+ @tool()
701
+ async def bili_crawl(keyword: str, max_videos: int = 5, comments_per_video: int = 20, get_subtitles: bool = True) -> str:
702
+ """
703
+ 批量采集:搜索B站视频并抓取每个视频的评论和字幕
704
+
705
+ Args:
706
+ keyword: 搜索关键词
707
+ max_videos: 最多采集视频数,默认5
708
+ comments_per_video: 每个视频采集评论数,默认20
709
+ get_subtitles: 是否获取字幕,默认True
710
+
711
+ Returns:
712
+ 包含视频信息、评论和字幕的完整采集数据
713
+ """
714
+ cred = get_cred()
715
+
716
+ # 搜索
717
+ search_result = await search.search_by_type(
718
+ keyword=keyword,
719
+ search_type=search.SearchObjectType.VIDEO,
720
+ page=1,
721
+ order_type=search.OrderVideo.TOTALRANK,
722
+ )
723
+
724
+ results = []
725
+ for item in search_result.get("result", [])[:max_videos]:
726
+ bvid = item.get("bvid", "")
727
+ if not bvid:
728
+ continue
729
+
730
+ title = item.get("title", "").replace('<em class="keyword">', "").replace("</em>", "")
731
+ video_data = {
732
+ "bvid": bvid,
733
+ "title": title,
734
+ "author": item.get("author", ""),
735
+ "play": item.get("play", 0),
736
+ "review": item.get("review", 0),
737
+ }
738
+
739
+ # 评论
740
+ comments_json = await bili_comments(bvid=bvid, num=comments_per_video)
741
+ comments_data = json.loads(comments_json)
742
+
743
+ # 字幕
744
+ subtitle_text = ""
745
+ if get_subtitles:
746
+ try:
747
+ subtitle_json = await bili_subtitle(bvid=bvid)
748
+ subtitle_data = json.loads(subtitle_json)
749
+ subtitle_text = subtitle_data.get("text", "")
750
+ except:
751
+ pass
752
+
753
+ results.append({
754
+ "video": video_data,
755
+ "comments": comments_data.get("comments", []),
756
+ "subtitle_text": subtitle_text,
757
+ })
758
+
759
+ await asyncio.sleep(1)
760
+
761
+ return json.dumps({
762
+ "keyword": keyword,
763
+ "video_count": len(results),
764
+ "total_comments": sum(len(r["comments"]) for r in results),
765
+ "results": results,
766
+ }, ensure_ascii=False)
767
+
768
+
769
+ # ========== 辅助:封面处理 ==========
770
+
771
+ import subprocess
772
+
773
+
774
+ def _extract_cover_from_video(video_path: str) -> Picture:
775
+ """从视频第3秒截取一帧作为封面,返回 Picture 对象"""
776
+ tmp_cover = os.path.join(tempfile.gettempdir(), f"bili_cover_{os.getpid()}.png")
777
+ try:
778
+ subprocess.run(
779
+ ["ffmpeg", "-y", "-ss", "3", "-i", video_path,
780
+ "-vframes", "1", "-q:v", "2", tmp_cover],
781
+ capture_output=True, timeout=30,
782
+ )
783
+ if os.path.isfile(tmp_cover) and os.path.getsize(tmp_cover) > 0:
784
+ return Picture.from_file(tmp_cover)
785
+ finally:
786
+ if os.path.isfile(tmp_cover):
787
+ os.remove(tmp_cover)
788
+ # fallback: 第0秒
789
+ tmp_cover2 = os.path.join(tempfile.gettempdir(), f"bili_cover2_{os.getpid()}.png")
790
+ try:
791
+ subprocess.run(
792
+ ["ffmpeg", "-y", "-ss", "0", "-i", video_path,
793
+ "-vframes", "1", "-q:v", "2", tmp_cover2],
794
+ capture_output=True, timeout=30,
795
+ )
796
+ if os.path.isfile(tmp_cover2) and os.path.getsize(tmp_cover2) > 0:
797
+ return Picture.from_file(tmp_cover2)
798
+ finally:
799
+ if os.path.isfile(tmp_cover2):
800
+ os.remove(tmp_cover2)
801
+ raise RuntimeError(f"无法从视频截取封面: {video_path}")
802
+
803
+ @tool()
804
+ async def bili_video_zones() -> str:
805
+ """
806
+ 获取B站视频常用分区ID列表,供上传视频时选择tid参数
807
+
808
+ Returns:
809
+ 常用分区ID及名称
810
+ """
811
+ zones = {
812
+ "科技": {
813
+ 188: "科技资讯", 122: "野生技术协会", 95: "数码",
814
+ 208: "科技", 209: "手工",
815
+ },
816
+ "知识": {
817
+ 201: "科学", 124: "社科·法律·心理", 207: "财经商业",
818
+ 228: "人文历史", 36: "科技(知识)",
819
+ },
820
+ "生活": {
821
+ 21: "日常", 160: "生活记录", 230: "其他",
822
+ 231: "美食", 234: "健身", 161: "搞笑",
823
+ },
824
+ "游戏": {
825
+ 17: "单机游戏", 171: "电子竞技", 172: "手机游戏",
826
+ 65: "网络游戏",
827
+ },
828
+ "影视": {
829
+ 183: "影视杂谈", 138: "搞笑", 182: "影视剪辑",
830
+ },
831
+ "动画": {
832
+ 32: "完结动画", 33: "连载动画", 51: "MAD·AMV",
833
+ },
834
+ "音乐": {
835
+ 28: "原创音乐", 31: "翻唱", 59: "演奏",
836
+ },
837
+ }
838
+ return json.dumps(zones, ensure_ascii=False)
839
+
840
+
841
+ # ========================================================================
842
+ # V1.2 — 数据分析 & 互动运营
843
+ # ========================================================================
844
+
845
+
846
+ # ========== Tool 13: 热门视频 ==========
847
+
848
+ @tool()
849
+ async def bili_hot_videos(pn: int = 1, ps: int = 20) -> str:
850
+ """
851
+ 获取B站当前热门视频列表
852
+
853
+ Args:
854
+ pn: 页码,默认1
855
+ ps: 每页数量,默认20,最大50
856
+
857
+ Returns:
858
+ 热门视频列表,包含标题、播放量、UP主等
859
+ """
860
+ result = await hot.get_hot_videos(pn=pn, ps=min(ps, 50))
861
+ videos = []
862
+ for item in result.get("list", []):
863
+ stat = item.get("stat", {})
864
+ videos.append({
865
+ "bvid": item.get("bvid", ""),
866
+ "title": item.get("title", ""),
867
+ "author": item.get("owner", {}).get("name", ""),
868
+ "play": stat.get("view", 0),
869
+ "like": stat.get("like", 0),
870
+ "danmaku": stat.get("danmaku", 0),
871
+ "reply": stat.get("reply", 0),
872
+ "desc": (item.get("desc", "") or "")[:100],
873
+ "duration": item.get("duration", 0),
874
+ "tname": item.get("tname", ""),
875
+ })
876
+ return json.dumps({"page": pn, "count": len(videos), "videos": videos}, ensure_ascii=False)
877
+
878
+
879
+ # ========== Tool 14: 热搜关键词 ==========
880
+
881
+ @tool()
882
+ async def bili_hot_buzzwords(page_num: int = 1, page_size: int = 20) -> str:
883
+ """
884
+ 获取B站热搜词/热门关键词
885
+
886
+ Args:
887
+ page_num: 页码,默认1
888
+ page_size: 每页数量,默认20
889
+
890
+ Returns:
891
+ 热搜词列表
892
+ """
893
+ result = await hot.get_hot_buzzwords(page_num=page_num, page_size=page_size)
894
+ return json.dumps(result, ensure_ascii=False)
895
+
896
+
897
+ # ========== Tool 15: 每周必看 ==========
898
+
899
+ @tool()
900
+ async def bili_weekly_hot(week: int = 0) -> str:
901
+ """
902
+ 获取B站每周必看视频推荐
903
+
904
+ Args:
905
+ week: 期数(0表示获取期数列表,>0表示获取该期的视频)
906
+
907
+ Returns:
908
+ 每周必看期数列表或指定期的视频列表
909
+ """
910
+ if week <= 0:
911
+ result = await hot.get_weekly_hot_videos_list()
912
+ return json.dumps(result, ensure_ascii=False)
913
+ else:
914
+ result = await hot.get_weekly_hot_videos(week=week)
915
+ return json.dumps(result, ensure_ascii=False)
916
+
917
+
918
+ # ========== Tool 16: 排行榜 ==========
919
+
920
+ @tool()
921
+ async def bili_rank(category: str = "all", day: int = 3) -> str:
922
+ """
923
+ 获取B站各分区排行榜
924
+
925
+ Args:
926
+ category: 分区名,可选值:
927
+ all=全站 original=原创 rookie=新人
928
+ douga=动画 music=音乐 dance=舞蹈 game=游戏
929
+ knowledge=知识 technology=科技 sports=运动 car=汽车
930
+ life=生活 food=美食 animal=动物 fashion=时尚
931
+ ent=娱乐 cinephile=影视
932
+ day: 时间维度,3=三日 7=七日
933
+
934
+ Returns:
935
+ 排行榜视频列表
936
+ """
937
+ type_map = {
938
+ "all": rank.RankType.All, "original": rank.RankType.Original,
939
+ "rookie": rank.RankType.Rookie, "douga": rank.RankType.Douga,
940
+ "music": rank.RankType.Music, "dance": rank.RankType.Dance,
941
+ "game": rank.RankType.Game, "knowledge": rank.RankType.Knowledge,
942
+ "technology": rank.RankType.Technology, "sports": rank.RankType.Sports,
943
+ "car": rank.RankType.Car, "life": rank.RankType.Life,
944
+ "food": rank.RankType.Food, "animal": rank.RankType.Animal,
945
+ "fashion": rank.RankType.Fashion, "ent": rank.RankType.Ent,
946
+ "cinephile": rank.RankType.Cinephile,
947
+ }
948
+ day_map = {3: rank.RankDayType.THREE_DAY, 7: rank.RankDayType.WEEK}
949
+
950
+ rank_type = type_map.get(category.lower(), rank.RankType.All)
951
+ rank_day = day_map.get(day, rank.RankDayType.THREE_DAY)
952
+
953
+ result = await rank.get_rank(type_=rank_type, day=rank_day)
954
+ videos = []
955
+ for item in result.get("list", []):
956
+ stat = item.get("stat", {})
957
+ videos.append({
958
+ "bvid": item.get("bvid", ""),
959
+ "title": item.get("title", ""),
960
+ "author": item.get("owner", {}).get("name", ""),
961
+ "play": stat.get("view", 0),
962
+ "like": stat.get("like", 0),
963
+ "coin": stat.get("coin", 0),
964
+ "score": item.get("score", 0),
965
+ "tname": item.get("tname", ""),
966
+ })
967
+ return json.dumps({"category": category, "day": day, "count": len(videos), "videos": videos}, ensure_ascii=False)
968
+
969
+
970
+ # ========== Tool 17: 用户信息 ==========
971
+
972
+ @tool()
973
+ async def bili_user_info(uid: int) -> str:
974
+ """
975
+ 获取B站用户的详细信息
976
+
977
+ Args:
978
+ uid: 用户UID
979
+
980
+ Returns:
981
+ 用户昵称、粉丝数、关注数、签名、等级、视频数等
982
+ """
983
+ cred = get_cred()
984
+ u = user.User(uid=uid, credential=cred)
985
+ info = await u.get_user_info()
986
+
987
+ # 尝试获取UP主数据
988
+ up_stat = {}
989
+ try:
990
+ up_stat = await u.get_up_stat()
991
+ except:
992
+ pass
993
+
994
+ relation = {}
995
+ try:
996
+ relation = await u.get_relation_info()
997
+ except:
998
+ pass
999
+
1000
+ return json.dumps({
1001
+ "uid": uid,
1002
+ "name": info.get("name", ""),
1003
+ "sign": info.get("sign", ""),
1004
+ "level": info.get("level", 0),
1005
+ "face": info.get("face", ""),
1006
+ "fans": relation.get("follower", info.get("follower", 0)),
1007
+ "following": relation.get("following", info.get("following", 0)),
1008
+ "likes": up_stat.get("likes", 0),
1009
+ "archive_view": up_stat.get("archive", {}).get("view", 0),
1010
+ "article_view": up_stat.get("article", {}).get("view", 0),
1011
+ "is_senior_member": info.get("is_senior_member", 0),
1012
+ "top_photo": info.get("top_photo", ""),
1013
+ }, ensure_ascii=False)
1014
+
1015
+
1016
+ # ========== Tool 18: 用户视频列表 ==========
1017
+
1018
+ @tool()
1019
+ async def bili_user_videos(uid: int, pn: int = 1, ps: int = 30, order: str = "pubdate", keyword: str = "") -> str:
1020
+ """
1021
+ 获取B站用户的投稿视频列表
1022
+
1023
+ Args:
1024
+ uid: 用户UID
1025
+ pn: 页码,默认1
1026
+ ps: 每页数量,默认30
1027
+ order: 排序方式 pubdate=最新 click=播放量 stow=收藏
1028
+ keyword: 搜索关键词(在该用户视频中搜索)
1029
+
1030
+ Returns:
1031
+ 视频列表
1032
+ """
1033
+ cred = get_cred()
1034
+ u = user.User(uid=uid, credential=cred)
1035
+
1036
+ order_map = {
1037
+ "pubdate": user.VideoOrder.PUBDATE,
1038
+ "click": user.VideoOrder.VIEW,
1039
+ "stow": user.VideoOrder.FAVORITE,
1040
+ }
1041
+ order_enum = order_map.get(order, user.VideoOrder.PUBDATE)
1042
+
1043
+ result = await u.get_videos(pn=pn, ps=ps, order=order_enum, keyword=keyword)
1044
+ videos = []
1045
+ for item in result.get("list", {}).get("vlist", []):
1046
+ videos.append({
1047
+ "bvid": item.get("bvid", ""),
1048
+ "title": item.get("title", ""),
1049
+ "play": item.get("play", 0),
1050
+ "comment": item.get("comment", 0),
1051
+ "created": item.get("created", 0),
1052
+ "length": item.get("length", ""),
1053
+ "description": (item.get("description", "") or "")[:100],
1054
+ })
1055
+ return json.dumps({
1056
+ "uid": uid,
1057
+ "page": pn,
1058
+ "total": result.get("page", {}).get("count", 0),
1059
+ "count": len(videos),
1060
+ "videos": videos,
1061
+ }, ensure_ascii=False)
1062
+
1063
+
1064
+ # ========== Tool 19: 收藏夹列表 ==========
1065
+
1066
+ @tool()
1067
+ async def bili_favorite_lists(uid: int = 0) -> str:
1068
+ """
1069
+ 获取用户的收藏夹列表
1070
+
1071
+ Args:
1072
+ uid: 用户UID(0表示获取自己的收藏夹)
1073
+
1074
+ Returns:
1075
+ 收藏夹列表,包含ID、名称、视频数量
1076
+ """
1077
+ cred = get_cred()
1078
+ if uid == 0:
1079
+ # 从凭证获取自己的UID
1080
+ import json as _json
1081
+ with open(CRED_FILE) as f:
1082
+ data = _json.load(f)
1083
+ uid = int(data.get("dedeuserid", 0))
1084
+
1085
+ result = await favorite_list.get_video_favorite_list(uid=uid, credential=cred)
1086
+ fav_lists = []
1087
+ for item in (result.get("list", []) or []):
1088
+ fav_lists.append({
1089
+ "id": item.get("id", 0),
1090
+ "title": item.get("title", ""),
1091
+ "media_count": item.get("media_count", 0),
1092
+ "fav_state": item.get("fav_state", 0),
1093
+ })
1094
+ return json.dumps({"uid": uid, "count": len(fav_lists), "lists": fav_lists}, ensure_ascii=False)
1095
+
1096
+
1097
+ # ========== Tool 20: 收藏夹内容 ==========
1098
+
1099
+ @tool()
1100
+ async def bili_favorite_content(media_id: int, page: int = 1, keyword: str = "") -> str:
1101
+ """
1102
+ 获取收藏夹内的视频列表
1103
+
1104
+ Args:
1105
+ media_id: 收藏夹ID(从 bili_favorite_lists 获取)
1106
+ page: 页码,默认1
1107
+ keyword: 搜索关键词(在收藏夹内搜索)
1108
+
1109
+ Returns:
1110
+ 收藏夹内的视频列表
1111
+ """
1112
+ cred = get_cred()
1113
+ result = await favorite_list.get_video_favorite_list_content(
1114
+ media_id=media_id,
1115
+ page=page,
1116
+ keyword=keyword if keyword else None,
1117
+ credential=cred,
1118
+ )
1119
+ medias = []
1120
+ for item in (result.get("medias", []) or []):
1121
+ medias.append({
1122
+ "bvid": item.get("bvid", ""),
1123
+ "title": item.get("title", ""),
1124
+ "play": item.get("cnt_info", {}).get("play", 0),
1125
+ "collect": item.get("cnt_info", {}).get("collect", 0),
1126
+ "author": item.get("upper", {}).get("name", ""),
1127
+ "duration": item.get("duration", 0),
1128
+ "fav_time": item.get("fav_time", 0),
1129
+ })
1130
+ return json.dumps({
1131
+ "media_id": media_id,
1132
+ "page": page,
1133
+ "has_more": result.get("has_more", False),
1134
+ "count": len(medias),
1135
+ "medias": medias,
1136
+ }, ensure_ascii=False)
1137
+
1138
+
1139
+ # ========== Tool 21: 发私信 ==========
1140
+
1141
+ @tool()
1142
+ async def bili_send_message(receiver_uid: int, text: str) -> str:
1143
+ """
1144
+ 给B站用户发送私信
1145
+
1146
+ Args:
1147
+ receiver_uid: 接收者的UID
1148
+ text: 私信文本内容
1149
+
1150
+ Returns:
1151
+ 发送结果
1152
+ """
1153
+ _deny = _guard("bili_send_message")
1154
+ if _deny: return _deny
1155
+ cred = get_cred()
1156
+
1157
+ if not text or not text.strip():
1158
+ return json.dumps({"success": False, "error": "text 不能为空"}, ensure_ascii=False)
1159
+
1160
+ try:
1161
+ result = await session.send_msg(
1162
+ credential=cred,
1163
+ receiver_id=receiver_uid,
1164
+ msg_type=session.EventType.TEXT,
1165
+ content=text.strip(),
1166
+ )
1167
+ # ⭐ 2.0.4(issue #35):**接口没抛异常 ≠ 真的送到了** ——
1168
+ # 以前只要不抛就报 success: True,而 B站 可能出现 code=0 却没给投递回执(msg_key)的情况 ✗
1169
+ # 回执就在返回值里:有 msg_key 才算发出去;code 非 0 直接算失败 ✓
1170
+ data = result if isinstance(result, dict) else {}
1171
+ code = data.get("code", 0)
1172
+ inner = data.get("data")
1173
+ msg_key = data.get("msg_key") or (inner.get("msg_key") if isinstance(inner, dict) else None)
1174
+ if code not in (0, None):
1175
+ return json.dumps({
1176
+ "success": False,
1177
+ "error": f"接口拒绝(code={code}):{data.get('message') or data.get('msg') or '未知原因'}",
1178
+ "data": data,
1179
+ }, ensure_ascii=False)
1180
+ if not msg_key:
1181
+ return json.dumps({
1182
+ "success": False,
1183
+ "error": "接口回了成功,但**没有投递回执(msg_key)** ⇒ 可能没真正送到(常见于:对方不接受陌生人私信 / 被风控)",
1184
+ "data": data,
1185
+ }, ensure_ascii=False)
1186
+ return json.dumps({
1187
+ "success": True,
1188
+ "message": f"私信已投递(回执 {str(msg_key)[:12]}…)",
1189
+ "data": data,
1190
+ }, ensure_ascii=False)
1191
+ except Exception as e:
1192
+ return json.dumps({"success": False, "error": str(e)}, ensure_ascii=False)
1193
+
1194
+
1195
+ # ========== Tool 22: 未读消息 ==========
1196
+
1197
+ @tool()
1198
+ async def bili_unread_messages() -> str:
1199
+ """
1200
+ 获取B站未读消息数(私信、@、回复、点赞等)
1201
+
1202
+ Returns:
1203
+ 各类未读消息数量
1204
+ """
1205
+ cred = get_cred()
1206
+ try:
1207
+ result = await session.get_unread_messages(credential=cred)
1208
+ return json.dumps(result, ensure_ascii=False)
1209
+ except Exception as e:
1210
+ return json.dumps({"error": str(e)}, ensure_ascii=False)
1211
+
1212
+
1213
+ # ========== Tool 23: 最近收到的回复 ==========
1214
+
1215
+ @tool()
1216
+ async def bili_received_replies() -> str:
1217
+ """
1218
+ 获取最近收到的评论回复通知
1219
+
1220
+ Returns:
1221
+ 回复列表
1222
+ """
1223
+ cred = get_cred()
1224
+ try:
1225
+ result = await session.get_replies(credential=cred)
1226
+ return json.dumps(result, ensure_ascii=False)
1227
+ except Exception as e:
1228
+ return json.dumps({"error": str(e)}, ensure_ascii=False)
1229
+
1230
+
1231
+ # ========== Tool 24: 最近收到的@和点赞 ==========
1232
+
1233
+ @tool()
1234
+ async def bili_received_at_and_likes() -> str:
1235
+ """
1236
+ 获取最近收到的@提及和点赞通知
1237
+
1238
+ Returns:
1239
+ 包含 at 和 likes 两部分的通知数据
1240
+ """
1241
+ cred = get_cred()
1242
+ result = {}
1243
+ try:
1244
+ result["at"] = await session.get_at(credential=cred)
1245
+ except Exception as e:
1246
+ result["at_error"] = str(e)
1247
+ try:
1248
+ result["likes"] = await session.get_likes(credential=cred)
1249
+ except Exception as e:
1250
+ result["likes_error"] = str(e)
1251
+ return json.dumps(result, ensure_ascii=False)
1252
+
1253
+
1254
+ # ========== 值班轮窄口 IO(2026-10-24 · issue #96 安全加固)==========
1255
+ # ⭐ 值班轮现在跑在「最小权限 profile」上:**没有文件系统、没有 shell、没有 web**。
1256
+ # 但它还得写日报 / 判重表 / 归档、还得能转写 —— 所以这几件事做成**固定路径的窄口工具**:
1257
+ # · 只写 <家>/out/<日期>.md、<家>/seen.md、<家>/digest/<年-月>.md
1258
+ # · **不接受任何路径参数**(想写别处也写不了)✓
1259
+ # · 输入里的竖线会被转义,标题带 | 也不会把表格弄坏
1260
+ import datetime as _dt
1261
+
1262
+ DUTY_HOME = Path(os.environ.get("BILI_DUTY_HOME") or (Path.home() / ".dsh" / "bili-duty"))
1263
+
1264
+
1265
+ def _duty_today() -> str:
1266
+ return _dt.datetime.now().strftime("%Y-%m-%d")
1267
+
1268
+
1269
+ _DUTY_DATE_RE = re.compile(r"^(?:(\d{4})[-/.])?(\d{1,2})[-/.](\d{1,2})(?:[ T]\d{1,2}:\d{2}(?::\d{2})?)?$")
1270
+
1271
+
1272
+ def _duty_norm_date(raw: str) -> str:
1273
+ """模型给的日期 → YYYY-MM-DD;认不出来就用今天(#133:以前 `10-23` 原样写进判重表,宿主解析不了)。
1274
+ 没写年份按今年补,补出来比今天晚就算去年 —— 跟宿主 lib/state.mjs 的 seenDay 同一套规则。"""
1275
+ today = _dt.date.today()
1276
+ m = _DUTY_DATE_RE.match(str(raw or "").strip())
1277
+ if not m:
1278
+ return today.isoformat()
1279
+ y = int(m.group(1)) if m.group(1) else today.year
1280
+ try:
1281
+ d = _dt.date(y, int(m.group(2)), int(m.group(3)))
1282
+ if not m.group(1) and d > today:
1283
+ d = d.replace(year=y - 1)
1284
+ except ValueError:
1285
+ return today.isoformat()
1286
+ return d.isoformat()
1287
+
1288
+
1289
+ def _cell(s: str, limit: int = 60) -> str:
1290
+ """表格单元格:去换行、转义竖线、截断。"""
1291
+ t = " ".join(str(s or "").split())
1292
+ return t.replace("|", "\\|")[:limit]
1293
+
1294
+
1295
+ def _append(path: Path, text: str) -> str:
1296
+ path.parent.mkdir(parents=True, exist_ok=True)
1297
+ with open(path, "a", encoding="utf-8", newline="\n") as f:
1298
+ f.write(text)
1299
+ return str(path)
1300
+
1301
+
1302
+ @tool()
1303
+ def duty_paths() -> str:
1304
+ """
1305
+ 这一轮允许写的三个位置(绝对路径)—— 想写东西只能通过这些 duty_* 工具,不要找别的路。
1306
+
1307
+ Returns:
1308
+ 报告 / 判重表 / 归档 的绝对路径
1309
+ """
1310
+ out = {
1311
+ "home": str(DUTY_HOME),
1312
+ "report": str(DUTY_HOME / "out" / (_duty_today() + ".md")),
1313
+ "seen": str(DUTY_HOME / "seen.md"),
1314
+ "digest": str(DUTY_HOME / "digest" / (_dt.datetime.now().strftime("%Y-%m") + ".md")),
1315
+ }
1316
+ return json.dumps(out, ensure_ascii=False)
1317
+
1318
+
1319
+ @tool()
1320
+ def duty_report_append(text: str) -> str:
1321
+ """
1322
+ 往**今天的日报**末尾追加一段(文件不存在会自动建)。
1323
+
1324
+ Args:
1325
+ text: 要追加的内容(markdown 纯文本)
1326
+
1327
+ Returns:
1328
+ 写到了哪个文件
1329
+ """
1330
+ body = str(text or "").replace("\r\n", "\n").strip()
1331
+ if not body:
1332
+ return "没写:内容是空的"
1333
+ p = DUTY_HOME / "out" / (_duty_today() + ".md")
1334
+ fresh = not p.exists()
1335
+ payload = body + "\n"
1336
+ if fresh:
1337
+ payload = "# 刷B站日报 " + _duty_today() + "\n\n" + payload
1338
+ return "已追加到 " + _append(p, payload)
1339
+
1340
+
1341
+ @tool()
1342
+ def duty_seen_append(bvid: str, title: str, up: str, status: str, date: str = "") -> str:
1343
+ """
1344
+ 往判重表追加一行(「挑了」= 进过报告 / 「跳过」= 看过但没进 / 「评论」= 本轮 @ 过)。
1345
+
1346
+ Args:
1347
+ bvid: BV 号
1348
+ title: 标题
1349
+ up: UP 主
1350
+ status: 挑了 / 跳过 / 评论
1351
+ date: 日期(YYYY-MM-DD,一般留空=今天)
1352
+
1353
+ Returns:
1354
+ 写到了哪个文件
1355
+ """
1356
+ bv = str(bvid or "").strip()
1357
+ if not bv:
1358
+ return "没写:bvid 是空的"
1359
+ d = _duty_norm_date(date)
1360
+ row = f"| {_cell(d, 10)} | {_cell(bv, 16)} | {_cell(title)} | {_cell(up, 30)} | {_cell(status, 8)} |\n"
1361
+ return "已追加到 " + _append(DUTY_HOME / "seen.md", row)
1362
+
1363
+
1364
+ @tool()
1365
+ def duty_seen_recent(limit: int = 40, bvid: str = "") -> str:
1366
+ """
1367
+ 读判重表的最近若干行(只读,只读插件自己那份 seen.md)。
1368
+
1369
+ Args:
1370
+ limit: 取最近多少行(默认 40,上限 200)
1371
+ bvid: 只查某个 BV(留空=看全部)
1372
+
1373
+ Returns:
1374
+ 表格行(日期 | BV | 标题 | UP | 状态);空 = 这份表还没内容
1375
+ """
1376
+ f = DUTY_HOME / "seen.md"
1377
+ if not f.exists():
1378
+ return "(判重表还不存在)"
1379
+ try:
1380
+ lines = f.read_text(encoding="utf-8", errors="replace").splitlines()
1381
+ except Exception as e:
1382
+ return "读不到判重表:" + str(e)
1383
+ rows = [ln for ln in lines if ln.strip().startswith("|") and "---" not in ln and not ln.strip().startswith("| 日期")]
1384
+ if bvid:
1385
+ bv = str(bvid).strip()
1386
+ rows = [ln for ln in rows if bv in ln]
1387
+ n = max(1, min(int(limit or 40), 200))
1388
+ tail = rows[-n:]
1389
+ if not tail:
1390
+ return "(最近没有记录)"
1391
+ return "共 " + str(len(rows)) + " 行,最近 " + str(len(tail)) + " 行:\n" + "\n".join(tail)
1392
+
1393
+
1394
+ @tool()
1395
+ def duty_digest_append(text: str) -> str:
1396
+ """
1397
+ 往**本月归档**末尾追加一段(「digest/<年-月>.md」,给"后来翻旧账"用的)。
1398
+
1399
+ Args:
1400
+ text: 要追加的内容
1401
+
1402
+ Returns:
1403
+ 写到了哪个文件
1404
+ """
1405
+ body = str(text or "").replace("\r\n", "\n").strip()
1406
+ if not body:
1407
+ return "没写:内容是空的"
1408
+ p = DUTY_HOME / "digest" / (_dt.datetime.now().strftime("%Y-%m") + ".md")
1409
+ return "已追加到 " + _append(p, body + "\n")
1410
+
1411
+
1412
+ # ========== 转写:非阻塞 + 单条排队 + 可取回的结果 ==========
1413
+ #
1414
+ # ⭐⭐ 2026-10-25 修(群友报的真 bug,附了 MCP SDK 源码依据):
1415
+ # 原来的 `bili_transcribe` 是**同步 def**,里面 `subprocess.run(timeout=1800)`。
1416
+ # mcp 1.30.0 的 func_metadata.py:114 对同步函数是**直接在事件循环里调用**(不是丢线程池),
1417
+ # 于是整条 stdio 会话被这一句占住 ⇒ 同一轮里其它工具(发私信 / 写判重表)全部 60s 超时,
1418
+ # 一整轮拖成 20 分钟,最后私信没发出去 ✗
1419
+ #
1420
+ # 所以改成两条路:
1421
+ # · `bili_transcribe(bvid)` —— 仍然是"要全文",但**不再阻塞事件循环**(async + create_subprocess_exec)
1422
+ # 并且用信号量限制"一次只有一条",避免几路 whisper 互相拖死
1423
+ # · `bili_transcribe_start(bvid)` / `bili_transcribe_result(job_id)`
1424
+ # —— **推荐用法**:立刻返回 job_id,轮次继续干别的;
1425
+ # 下一轮或收尾时再来取结果。慢活不该挂在一个工具调用的超时上。
1426
+ _TRANSCRIBE_SEM = asyncio.Semaphore(1)
1427
+ _TRANSCRIBE_JOBS = {} # job_id -> {"state": running|done|error, "text": str, "bvid": str, "started": ts}
1428
+ _TRANSCRIBE_TIMEOUT = 900 # 15 分钟硬顶(原来是 1800,太长)
1429
+ _TRANSCRIBE_WAIT = 25 # 直接调用时最多等这么久(客户端单次调用常见 60s 超时)
1430
+ _TRANSCRIBE_KEEP = 8 # 只留最近 8 个 job 的结果,避免内存里堆一堆长文本
1431
+
1432
+
1433
+ def _transcribe_paths(bv: str):
1434
+ """返回 (python, script, out_path);缺东西时返回 (None, 原因, None)"""
1435
+ py_candidates = [
1436
+ DUTY_HOME / ".venv-asr" / "Scripts" / "python.exe",
1437
+ DUTY_HOME / ".venv-asr" / "bin" / "python",
1438
+ ]
1439
+ py = next((str(p) for p in py_candidates if p.exists()), "")
1440
+ if not py:
1441
+ return None, "转写环境没装好(设置页里有「装转写依赖」)", None
1442
+ script = DUTY_HOME / "asr.py"
1443
+ if not script.exists():
1444
+ return None, "找不到 asr.py(家目录里没有转写脚本)", None
1445
+ out = DUTY_HOME / "tmp" / (bv + ".txt")
1446
+ out.parent.mkdir(parents=True, exist_ok=True)
1447
+ return py, script, out
1448
+
1449
+
1450
+ def _transcribe_read(out) -> str:
1451
+ """把产物读成"给模型看的结果"(空的 / 只有署名 ⇒ 当作没有语音)"""
1452
+ try:
1453
+ if not out.exists():
1454
+ return "转写没产出文件 —— 这条按「读不到」处理,跳过它"
1455
+ text = out.read_text(encoding="utf-8", errors="replace").strip()
1456
+ if not text:
1457
+ return "(空)—— 这条没有语音,跳过它"
1458
+ if len(text) <= 40 and ("字幕by" in text or "字幕BY" in text):
1459
+ return "(只有署名「" + text[:40] + "」)—— 当没有语音处理,跳过"
1460
+ return text[:12000]
1461
+ except Exception as e:
1462
+ return "读转写结果失败:" + str(e)
1463
+
1464
+
1465
+ async def _transcribe_run(bv: str) -> str:
1466
+ """真正跑转写(非阻塞)。信号量保证同一时间只有一条在跑。"""
1467
+ py, script, out = _transcribe_paths(bv)
1468
+ if not py:
1469
+ return str(script) # script 位置放的是错误文案
1470
+ async with _TRANSCRIBE_SEM:
1471
+ try:
1472
+ proc = await asyncio.create_subprocess_exec(
1473
+ py, str(script), bv, "-o", str(out),
1474
+ stdout=asyncio.subprocess.PIPE,
1475
+ stderr=asyncio.subprocess.PIPE,
1476
+ env={**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
1477
+ )
1478
+ except Exception as e:
1479
+ return "转写启动失败:" + str(e)
1480
+ try:
1481
+ _, err = await asyncio.wait_for(proc.communicate(), timeout=_TRANSCRIBE_TIMEOUT)
1482
+ except asyncio.TimeoutError:
1483
+ try:
1484
+ proc.kill()
1485
+ except Exception:
1486
+ pass
1487
+ return f"转写超时({_TRANSCRIBE_TIMEOUT // 60} 分钟)—— 这条按「读不到」处理,跳过它"
1488
+ if not out.exists():
1489
+ tail = (err or b"")[-400:].decode("utf-8", "replace")
1490
+ return "转写没产出文件(exit " + str(proc.returncode) + "):" + tail
1491
+ return _transcribe_read(out)
1492
+
1493
+
1494
+ def _job_prune():
1495
+ if len(_TRANSCRIBE_JOBS) <= _TRANSCRIBE_KEEP:
1496
+ return
1497
+ for k in list(_TRANSCRIBE_JOBS.keys())[: len(_TRANSCRIBE_JOBS) - _TRANSCRIBE_KEEP]:
1498
+ _TRANSCRIBE_JOBS.pop(k, None)
1499
+
1500
+
1501
+ async def _job_run(job_id: str, bv: str):
1502
+ try:
1503
+ text = await _transcribe_run(bv)
1504
+ _TRANSCRIBE_JOBS[job_id] = {"state": "done", "text": text, "bvid": bv, "started": _TRANSCRIBE_JOBS.get(job_id, {}).get("started", 0)}
1505
+ except Exception as e:
1506
+ _TRANSCRIBE_JOBS[job_id] = {"state": "error", "text": "转写异常:" + str(e), "bvid": bv, "started": 0}
1507
+
1508
+
1509
+ @tool()
1510
+ async def bili_transcribe(bvid: str) -> str:
1511
+ """
1512
+ 用本地 ASR 把一条**没有字幕**的视频转成文字(慢,几分钟)。
1513
+
1514
+ ⚠️ 这个调用会**等到跑完**才返回(不再阻塞别的工具,但它自己会慢)。
1515
+ 更好的用法是先 `bili_transcribe_start` 拿 job_id,这一轮先干别的,之后用 `bili_transcribe_result` 取。
1516
+
1517
+ Args:
1518
+ bvid: BV 号
1519
+
1520
+ Returns:
1521
+ 转写出来的文字(截断到 12000 字);空的 / 只有署名 ⇒ 当作这条没有语音
1522
+ """
1523
+ denied = _guard("bili_transcribe")
1524
+ if denied:
1525
+ return denied
1526
+ bv = str(bvid or "").strip()
1527
+ if not bv.startswith("BV"):
1528
+ return "参数不对:要给 BV 号"
1529
+ # ⭐ 2026-10-25 二次修(真机实测):直接 await 整条转写 ⇒ 客户端 60s 超时,
1530
+ # 那一轮白等一次、还记了句"转写超时"✗
1531
+ # ⇒ 现在只等 _TRANSCRIBE_WAIT 秒:跑完就回文本,没跑完就**把 job_id 交回去**,
1532
+ # 由模型下一轮用 bili_transcribe_result 取(比"超时"有用得多)
1533
+ py, why, _out = _transcribe_paths(bv)
1534
+ if not py:
1535
+ return str(why)
1536
+ job_id = "tj" + _dt.datetime.now().strftime("%H%M%S") + "-" + bv[-4:]
1537
+ _TRANSCRIBE_JOBS[job_id] = {"state": "running", "text": "", "bvid": bv, "started": _dt.datetime.now().timestamp()}
1538
+ _job_prune()
1539
+ task = asyncio.create_task(_job_run(job_id, bv))
1540
+ try:
1541
+ await asyncio.wait_for(asyncio.shield(task), timeout=_TRANSCRIBE_WAIT)
1542
+ except asyncio.TimeoutError:
1543
+ return (f"转写还没跑完(超过 {_TRANSCRIBE_WAIT} 秒),已排进后台:job_id={job_id}。\n"
1544
+ "**这一轮别等它** —— 先把报告 / 判重表 / 归档 / 私信做完;"
1545
+ "下一轮或收尾前用 bili_transcribe_result(job_id) 取结果(还 running 就记「已排队,下一轮再判」)。")
1546
+ job = _TRANSCRIBE_JOBS.get(job_id) or {}
1547
+ if job.get("state") == "error":
1548
+ return str(job.get("text") or "转写失败")
1549
+ return str(job.get("text") or "转写没拿到内容")
1550
+
1551
+
1552
+ @tool()
1553
+ async def bili_transcribe_start(bvid: str) -> str:
1554
+ """
1555
+ 开始一条转写任务,**立刻返回 job_id**(推荐用这个 —— 慢活不该占住这一轮)。
1556
+
1557
+ Args:
1558
+ bvid: BV 号
1559
+
1560
+ Returns:
1561
+ JSON:{"ok": true, "job_id": "…", "hint": "…"}
1562
+ """
1563
+ denied = _guard("bili_transcribe_start")
1564
+ if denied:
1565
+ return json.dumps({"ok": False, "error": denied}, ensure_ascii=False)
1566
+ bv = str(bvid or "").strip()
1567
+ if not bv.startswith("BV"):
1568
+ return json.dumps({"ok": False, "error": "参数不对:要给 BV 号"}, ensure_ascii=False)
1569
+ py, why, _out = _transcribe_paths(bv)
1570
+ if not py:
1571
+ return json.dumps({"ok": False, "error": why}, ensure_ascii=False)
1572
+ job_id = "tj" + _dt.datetime.now().strftime("%H%M%S") + "-" + bv[-4:]
1573
+ _TRANSCRIBE_JOBS[job_id] = {"state": "running", "text": "", "bvid": bv, "started": _dt.datetime.now().timestamp()}
1574
+ _job_prune()
1575
+ asyncio.create_task(_job_run(job_id, bv))
1576
+ return json.dumps({
1577
+ "ok": True,
1578
+ "job_id": job_id,
1579
+ "hint": "已排队。这一轮**别等**:先把报告 / 判重表 / 私信做完;下一轮或收尾时用 bili_transcribe_result 取结果。",
1580
+ }, ensure_ascii=False)
1581
+
1582
+
1583
+ @tool()
1584
+ async def bili_transcribe_result(job_id: str) -> str:
1585
+ """
1586
+ 取一条转写任务的结果(没有就返回 running)。
1587
+
1588
+ Args:
1589
+ job_id: `bili_transcribe_start` 返回的那个 id
1590
+
1591
+ Returns:
1592
+ JSON:{"state": "running|done|error", "text": "…"}
1593
+ """
1594
+ denied = _guard("bili_transcribe_result")
1595
+ if denied:
1596
+ return json.dumps({"ok": False, "error": denied}, ensure_ascii=False)
1597
+ jid = str(job_id or "").strip()
1598
+ job = _TRANSCRIBE_JOBS.get(jid)
1599
+ if not job:
1600
+ return json.dumps({"ok": False, "state": "unknown", "error": "没有这个 job(可能已经过期,或者 id 打错了)"}, ensure_ascii=False)
1601
+ return json.dumps({
1602
+ "ok": True,
1603
+ "state": job["state"],
1604
+ "bvid": job["bvid"],
1605
+ "text": job.get("text", "") if job["state"] != "running" else "",
1606
+ "hint": "还在跑,这一轮先干别的" if job["state"] == "running" else "",
1607
+ }, ensure_ascii=False)
1608
+
1609
+ # ========== Tool 25: 看画面(封面) ==========
1610
+ #
1611
+ # 图作为 MCP image content 返回,由宿主决定能否进模型上下文。
1612
+ # 缩图交给 B 站图片 CDN(URL 后缀 @512w.jpg),不引 Pillow、不落临时文件。
1613
+
1614
+ _WEB_UA = (
1615
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
1616
+ "(KHTML, like Gecko) Chrome/124.0 Safari/537.36"
1617
+ )
1618
+ _COVER_WIDTH = 512
1619
+ _HTTP_TIMEOUT = 25 # 图床 / 快照下载统一超时(秒)
1620
+ # 防御性上限:实测封面 23–36KB、帧 2.6–29KB,正常走不到这一行
1621
+ _MAX_IMAGE_BYTES = 1_500_000
1622
+
1623
+
1624
+ def _https(url: str) -> str:
1625
+ """把 B 站的图片/资源地址统一成 https。
1626
+
1627
+ view 接口给的 `pic` 实测 10/10 都是 `http://`,而 http 不会跳转 https;
1628
+ 图床请求再带上 SESSDATA 就等于把登录凭据明文发出去。
1629
+ """
1630
+ u = str(url or "")
1631
+ if u.startswith("//"):
1632
+ return "https:" + u
1633
+ if u.startswith("http://"):
1634
+ return "https://" + u[len("http://"):]
1635
+ return u
1636
+
1637
+
1638
+ def _cover_url(pic: str, width: int = _COVER_WIDTH) -> str:
1639
+ """封面原图地址 → 带 CDN 缩放后缀(@<宽>w.jpg)的地址,等比不裁切。"""
1640
+ base = _https(str(pic).split("@", 1)[0])
1641
+ return f"{base}@{width}w.jpg"
1642
+
1643
+
1644
+ def _image_headers() -> dict:
1645
+ """图床请求头:只给 UA + Referer,**不带 Cookie**(图床不需要登录态)。"""
1646
+ return {"User-Agent": _WEB_UA, "Referer": "https://www.bilibili.com/"}
1647
+
1648
+
1649
+ def _text_only(payload: dict) -> list:
1650
+ return [TextContent(type="text", text=json.dumps(payload, ensure_ascii=False))]
1651
+
1652
+
1653
+ @tool()
1654
+ async def bili_cover(bvid: str) -> list:
1655
+ """
1656
+ 看这个视频的封面(等比缩到 512px 宽)
1657
+
1658
+ 最便宜的一档"看一眼":能看出风格、标题美术、大致题材,但看不出具体发生了什么。
1659
+
1660
+ Args:
1661
+ bvid: 视频BV号,如"BV1uNk1YxEJQ"
1662
+
1663
+ Returns:
1664
+ 封面图 + 一句说明(标题、时长、图多大)。
1665
+ 图能不能真被看见取决于当前模型是否支持图片输入;不支持时会被降级成文字。
1666
+ """
1667
+ import aiohttp
1668
+
1669
+ cred = load_credential() # 封面是公开的,没登录也取得到
1670
+ try:
1671
+ v = video.Video(bvid=bvid, credential=cred) # 格式不对时**构造时就抛**
1672
+ info = await v.get_info()
1673
+ except Exception as e:
1674
+ # ⚠️ 2026-10-23 实测两种失败:`62002 稿件不可见`(BV 不存在)
1675
+ # 和 `ArgsException`(格式不对,构造时就抛)。都收成 ok:false。
1676
+ return _text_only({"bvid": bvid, "ok": False, "error": f"取视频信息失败:{e}"})
1677
+
1678
+ pic = str(info.get("pic") or "")
1679
+ if not pic:
1680
+ return _text_only({"bvid": bvid, "ok": False, "error": "这个视频没有封面地址"})
1681
+
1682
+ url = _cover_url(pic)
1683
+ try:
1684
+ timeout = aiohttp.ClientTimeout(total=_HTTP_TIMEOUT)
1685
+ async with aiohttp.ClientSession(timeout=timeout) as s:
1686
+ async with s.get(url, headers=_image_headers()) as resp:
1687
+ if resp.status != 200:
1688
+ raise RuntimeError(f"HTTP {resp.status}")
1689
+ raw = await resp.read()
1690
+ mime = (resp.headers.get("Content-Type") or "image/jpeg").split(";")[0].strip()
1691
+ except Exception as e:
1692
+ return _text_only({"bvid": bvid, "ok": False, "error": f"下载封面失败:{e}"})
1693
+
1694
+ allowed = ("image/jpeg", "image/png", "image/webp", "image/gif")
1695
+ if mime not in allowed:
1696
+ return _text_only({"bvid": bvid, "ok": False, "error": f"封面不是可用的图片类型:{mime}"})
1697
+ if len(raw) > _MAX_IMAGE_BYTES:
1698
+ return _text_only({
1699
+ "bvid": bvid, "ok": False,
1700
+ "error": f"封面太大({len(raw) // 1024}KB),没放进来",
1701
+ })
1702
+
1703
+ return [
1704
+ TextContent(type="text", text=json.dumps({
1705
+ "bvid": bvid,
1706
+ "ok": True,
1707
+ "title": info.get("title"),
1708
+ "duration": info.get("duration"),
1709
+ "cover_kb": round(len(raw) / 1024, 1),
1710
+ }, ensure_ascii=False)),
1711
+ ImageContent(
1712
+ type="image",
1713
+ data=base64.b64encode(raw).decode("ascii"),
1714
+ mimeType=mime,
1715
+ ),
1716
+ ]
1717
+
1718
+
1719
+ # ========== Tool 26: 看画面(画面帧) ==========
1720
+ #
1721
+ # 画面来自 B 站自带的故事板(x/player/videoshot),不解码视频、不用 ffmpeg。
1722
+ # Video.get_video_snapshot() 有封装,但 pvideo 默认 True 会走老接口,必须传 False。
1723
+ # 裁切用 Pillow(requirements 里的 qrcode[pil] 已经带进来)。
1724
+
1725
+ _FRAME_MAX = 6
1726
+ _TILE_W_DEFAULT = 480
1727
+ _TILE_H_DEFAULT = 270
1728
+
1729
+
1730
+ def _snapshot_entries(data: dict, duration: float = 0.0) -> list:
1731
+ """把 videoshot 的 index 归一成 [(秒, 块序号), ...]。
1732
+
1733
+ 时间单位实测两种都出现过(秒 / 毫秒),只能靠和时长比较来判断:
1734
+ 超过时长 1.5 倍才当毫秒。⚠️ 别再加"绝对值大于某个数就当毫秒"这类判据 ——
1735
+ 6 小时视频的秒数(22163)会被误判成毫秒,三帧全塌到同一块、时间缩小 1000 倍。
1736
+ """
1737
+ raws = []
1738
+ for i, item in enumerate(data.get("index") or []):
1739
+ ts = item.get("timestamp") if isinstance(item, dict) else item
1740
+ try:
1741
+ raws.append((float(ts), i))
1742
+ except (TypeError, ValueError):
1743
+ continue
1744
+ if not raws:
1745
+ return []
1746
+
1747
+ biggest = max(v for v, _ in raws)
1748
+ looks_ms = duration > 0 and biggest > duration * 1.5
1749
+ scale = 1000.0 if looks_ms else 1.0
1750
+ return [(v / scale, i) for v, i in raws]
1751
+
1752
+
1753
+ async def _entries_from_pvdata(data: dict) -> list:
1754
+ """index 为空时的兜底:pvdata 指向一个大端 uint16 秒数数组,与 index 逐项相同。"""
1755
+ url = _https(data.get("pvdata") or "")
1756
+ if not url:
1757
+ return []
1758
+ try:
1759
+ raw = await _fetch_bytes(url, _image_headers())
1760
+ except Exception:
1761
+ return []
1762
+ if not raw or len(raw) % 2:
1763
+ return []
1764
+ count = len(raw) // 2
1765
+ if count > 20000: # 明显不对,别乱解
1766
+ return []
1767
+ return [(float(sec), i) for i, sec in enumerate(struct.unpack(f">{count}H", raw))]
1768
+
1769
+
1770
+ async def _fetch_bytes(url: str, headers: dict) -> bytes:
1771
+ import aiohttp
1772
+
1773
+ timeout = aiohttp.ClientTimeout(total=_HTTP_TIMEOUT)
1774
+ async with aiohttp.ClientSession(timeout=timeout) as s:
1775
+ async with s.get(_https(url), headers=headers) as resp:
1776
+ if resp.status != 200:
1777
+ raise RuntimeError(f"HTTP {resp.status}")
1778
+ return await resp.read()
1779
+
1780
+
1781
+ def _crop_tile(sheet: bytes, tile_index: int, tw: int, th: int) -> bytes:
1782
+ """从拼图里裁出第 tile_index 块,返回 jpeg 字节。"""
1783
+ import io
1784
+
1785
+ from PIL import Image
1786
+
1787
+ img = Image.open(io.BytesIO(sheet))
1788
+ cols = max(1, img.width // tw)
1789
+ rows = max(1, img.height // th)
1790
+ if tile_index >= cols * rows:
1791
+ raise RuntimeError(f"第 {tile_index} 块超出拼图(只有 {cols}×{rows})")
1792
+ col, row = tile_index % cols, tile_index // cols
1793
+ tile = img.crop((col * tw, row * th, (col + 1) * tw, (row + 1) * th)).convert("RGB")
1794
+ buf = io.BytesIO()
1795
+ tile.save(buf, format="JPEG", quality=85)
1796
+ return buf.getvalue()
1797
+
1798
+
1799
+ @tool()
1800
+ async def bili_frames(bvid: str, num: int = 3, at: list | None = None) -> list:
1801
+ """
1802
+ 看这个视频里的画面(从 B 站自带的故事板里裁几帧)
1803
+
1804
+ 想看"它到底拍了什么"就用它。默认按时长均匀取 3 帧;
1805
+ 想盯某个时刻(比如字幕里提到的那一段)就传 at(单位:秒),会取**最接近的那一块**。
1806
+
1807
+ Args:
1808
+ bvid: 视频BV号,如"BV1uNk1YxEJQ"
1809
+ num: 取几帧,1-6,默认 3
1810
+ at: 指定时间点(秒)的列表;传了就以它为准,忽略 num
1811
+
1812
+ Returns:
1813
+ 若干张 480×270 的画面 + 一句说明(时长、实际取到的那一刻、哪几帧失败)。
1814
+ 失败会写进 failed。**多P 视频的故事板通常只覆盖第 1P**,返回里会用
1815
+ covered_sec / pages 标明实际覆盖范围。图能否被看见取决于模型是否支持图片输入。
1816
+ """
1817
+ cred = load_credential() # 故事板不登录也能取
1818
+ try:
1819
+ v = video.Video(bvid=bvid, credential=cred)
1820
+ info = await v.get_info()
1821
+ except Exception as e:
1822
+ return _text_only({"bvid": bvid, "ok": False, "error": f"取视频信息失败:{e}"})
1823
+ duration = float(info.get("duration") or 0)
1824
+ pages = info.get("pages") or []
1825
+ cid = info.get("cid") or ((pages or [{}])[0].get("cid") or 0)
1826
+ if not cid:
1827
+ return _text_only({"bvid": bvid, "ok": False, "error": "拿不到 cid"})
1828
+
1829
+ # 故事板只覆盖第 1P:目标时间点按"实际覆盖的长度"算,别落到没采样的 P2 上
1830
+ covered = float(pages[0].get("duration") or duration) if pages else duration
1831
+ covered = covered or duration
1832
+
1833
+ # index 会偶发返回空(实测约 25%):先用 pvdata 兜底,两个都空才重试
1834
+ snap = {}
1835
+ entries = []
1836
+ last_err = None
1837
+ for attempt in range(2):
1838
+ try:
1839
+ snap = await v.get_video_snapshot(cid=cid, json_index=True, pvideo=False) or {}
1840
+ last_err = None
1841
+ except Exception as e:
1842
+ snap, last_err = {}, e
1843
+ entries = _snapshot_entries(snap, covered)
1844
+ if not entries:
1845
+ entries = await _entries_from_pvdata(snap)
1846
+ if entries and (snap.get("image") or []):
1847
+ break
1848
+ if attempt < 1:
1849
+ await asyncio.sleep(1.0)
1850
+
1851
+ sheets = snap.get("image") or []
1852
+ if not entries or not sheets:
1853
+ err = f"(最后一次错误:{last_err})" if last_err is not None else ""
1854
+ return _text_only({
1855
+ "bvid": bvid, "ok": False,
1856
+ "error": f"取不到画面快照(试了 2 次){err}",
1857
+ })
1858
+
1859
+ # 覆盖长度以**故事板实测到的那一刻**为准(比 P1 的标称时长保守,通常短 1–10%)
1860
+ story_max = max((e[0] for e in entries), default=0.0)
1861
+ if story_max > 0:
1862
+ covered = min(covered, story_max)
1863
+
1864
+ # 目标时间点:传了 at 就用它;否则按"覆盖长度"均分
1865
+ if at:
1866
+ targets = [min(max(0.0, float(t)), max(0.0, covered - 0.1)) for t in at][:_FRAME_MAX]
1867
+ else:
1868
+ n = max(1, min(int(num or 3), _FRAME_MAX))
1869
+ targets = [covered * (i + 1) / (n + 1) for i in range(n)]
1870
+
1871
+ picked = []
1872
+ for t in targets:
1873
+ ts, tile = min(entries, key=lambda e: abs(e[0] - t))
1874
+ picked.append((round(t, 1), round(ts, 1), tile))
1875
+
1876
+ tw = int(snap.get("img_x_size") or _TILE_W_DEFAULT)
1877
+ th = int(snap.get("img_y_size") or _TILE_H_DEFAULT)
1878
+ headers = _image_headers()
1879
+
1880
+ cache = {}
1881
+
1882
+ async def get_sheet(no: int) -> bytes:
1883
+ if no not in cache:
1884
+ if no >= len(sheets):
1885
+ raise RuntimeError(f"拼图 {no} 不存在(共 {len(sheets)} 张)")
1886
+ cache[no] = await _fetch_bytes(str(sheets[no]), headers)
1887
+ return cache[no]
1888
+
1889
+ # 每张拼图装几块要等第一张下来才知道(列数 = 宽 // 块宽)
1890
+ blocks, frames, failed = [], [], []
1891
+ cap = None
1892
+ for i, (want, got, tile) in enumerate(picked):
1893
+ try:
1894
+ if cap is None:
1895
+ first = await get_sheet(0)
1896
+ import io
1897
+
1898
+ from PIL import Image
1899
+
1900
+ im = Image.open(io.BytesIO(first))
1901
+ cap = max(1, (im.width // tw) * (im.height // th))
1902
+ sheet_no, pos = tile // cap, tile % cap
1903
+ raw = _crop_tile(await get_sheet(sheet_no), pos, tw, th)
1904
+ if len(raw) > _MAX_IMAGE_BYTES:
1905
+ raise RuntimeError(f"这一帧太大({len(raw) // 1024}KB)")
1906
+ blocks.append(ImageContent(
1907
+ type="image",
1908
+ data=base64.b64encode(raw).decode("ascii"),
1909
+ mimeType="image/jpeg",
1910
+ ))
1911
+ frames.append({"index": i, "want_sec": want, "got_sec": got,
1912
+ "kb": round(len(raw) / 1024, 1)})
1913
+ except Exception as e:
1914
+ failed.append({"index": i, "want_sec": want, "got_sec": got, "reason": str(e)})
1915
+
1916
+ if not blocks:
1917
+ return _text_only({
1918
+ "bvid": bvid, "ok": False,
1919
+ "error": "一帧都没取到", "failed": failed,
1920
+ })
1921
+
1922
+ return [
1923
+ TextContent(type="text", text=json.dumps({
1924
+ "bvid": bvid,
1925
+ "ok": True,
1926
+ "title": info.get("title"),
1927
+ "duration": duration,
1928
+ "covered_sec": round(covered, 1),
1929
+ "pages": max(1, len(pages)),
1930
+ "tile": f"{tw}x{th}",
1931
+ "frames": frames,
1932
+ "failed": failed, # 空列表 = 全成
1933
+ "note": "want_sec 是想要的时刻,got_sec 是实际取到的那一块(故事板按固定间隔切);"
1934
+ "多P 视频只覆盖第 1P,看 covered_sec",
1935
+ }, ensure_ascii=False)),
1936
+ *blocks,
1937
+ ]
1938
+
1939
+
1940
+ # ========== Tool: 首页推荐流(不填关键词时用它,替代固定关键词搜索) ==========
1941
+ # ⭐ 为什么要它(2026-10-23 主人拍板):
1942
+ # 以前不填关键词就用内置那几组(DeepSeek Harness / DSH 插件 …)⇒ **所有装了插件的人刷的是同一批视频**
1943
+ # ⇒ 相关视频的评论区必然堆成一片"同款插件在互相报到" ✗
1944
+ # 推荐流按各自账号画像推,天然散开 ✓ —— 这是结构性解法,比"每轮少发几条"靠谱得多。
1945
+ #
1946
+ # ⚠️ 它需要登录凭证(匿名也能拿到一部分,但带凭证才是"这个账号的推荐"),
1947
+ # 所以这里用 load_credential();拿不到就退成匿名(仍然能用,只是不那么"散")。
1948
+ @tool()
1949
+ async def bili_recommend(ps: int = 20) -> str:
1950
+ """
1951
+ 获取「首页推荐流」的视频(按当前登录账号的画像)
1952
+
1953
+ Args:
1954
+ ps: 返回几条,默认 20,最多 40
1955
+
1956
+ Returns:
1957
+ JSON 格式的视频列表,字段与 bili_search 对齐(bvid / title / author / play / danmaku / duration…)
1958
+ """
1959
+ denied = _guard("bili_recommend")
1960
+ if denied:
1961
+ return json.dumps({"ok": False, "error": denied}, ensure_ascii=False)
1962
+
1963
+ cred = None
1964
+ try:
1965
+ cred = load_credential()
1966
+ except Exception:
1967
+ cred = None
1968
+
1969
+ try:
1970
+ data = await homepage.get_videos(credential=cred)
1971
+ except Exception as e: # noqa: BLE001 - 统一收成 ok:false,别把原始异常甩给模型
1972
+ return json.dumps({"ok": False, "error": f"取推荐流失败:{e}"}, ensure_ascii=False)
1973
+
1974
+ items = []
1975
+ if isinstance(data, dict):
1976
+ items = data.get("item") or data.get("data") or []
1977
+ elif isinstance(data, list):
1978
+ items = data
1979
+
1980
+ videos = []
1981
+ for it in items[: max(1, min(int(ps), 40))]:
1982
+ if not isinstance(it, dict):
1983
+ continue
1984
+ # 只留视频(推荐流里会混进直播 / 番剧 / 广告卡片)
1985
+ if it.get("goto") and it.get("goto") != "av":
1986
+ continue
1987
+ if not it.get("bvid"):
1988
+ continue
1989
+ owner = it.get("owner") or {}
1990
+ stat = it.get("stat") or {}
1991
+ dur = it.get("duration")
1992
+ videos.append({
1993
+ "bvid": it.get("bvid", ""),
1994
+ "title": str(it.get("title", "")).strip(),
1995
+ "author": owner.get("name", ""),
1996
+ "play": stat.get("view", 0),
1997
+ "danmaku": stat.get("danmaku", 0),
1998
+ "like": stat.get("like", 0),
1999
+ "duration": f"{int(dur) // 60}:{int(dur) % 60:02d}" if isinstance(dur, (int, float)) else str(dur or ""),
2000
+ "pubdate": it.get("pubdate", 0),
2001
+ "reason": (it.get("rcmd_reason") or {}).get("content", "") if isinstance(it.get("rcmd_reason"), dict) else "",
2002
+ })
2003
+
2004
+ return json.dumps({
2005
+ "ok": True,
2006
+ "source": "recommend",
2007
+ "count": len(videos),
2008
+ "videos": videos,
2009
+ }, ensure_ascii=False)
2010
+
2011
+
2012
+ # ========== 启动 ==========
2013
+
2014
+ if __name__ == "__main__":
2015
+ mcp.run(transport="stdio")