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.
- package/NOTICE.md +20 -0
- package/README.md +20 -9
- package/client.js +30 -9
- package/lib/engines.mjs +136 -0
- package/lib/index.js +37 -4
- package/lib/qqbot-0.5.3-patches.json +75 -70
- package/lib/qqbot-patch.mjs +12 -7
- package/lib/video.mjs +11 -2
- package/package.json +7 -23
- package/vendor/dsh-agent-md/LICENSE +21 -0
- package/vendor/dsh-agent-md/cordis.patch.yml +8 -0
- package/vendor/dsh-agent-md/lib/index.js +775 -0
- package/vendor/dsh-agent-md/lib/persona.js +634 -0
- package/vendor/dsh-agent-md/lib/qq.js +527 -0
- package/vendor/dsh-agent-md/package.json +50 -0
- package/vendor/dsh-bili-scroll/LICENSE +21 -0
- package/vendor/dsh-bili-scroll/NOTICE.md +18 -0
- package/vendor/dsh-bili-scroll/cordis.patch.yml +20 -0
- package/vendor/dsh-bili-scroll/index.js +3278 -0
- package/vendor/dsh-bili-scroll/lib/asr.py +141 -0
- package/vendor/dsh-bili-scroll/lib/diagnose.mjs +95 -0
- package/vendor/dsh-bili-scroll/lib/dm.mjs +110 -0
- package/vendor/dsh-bili-scroll/lib/favops.py +90 -0
- package/vendor/dsh-bili-scroll/lib/hostdeps.mjs +148 -0
- package/vendor/dsh-bili-scroll/lib/login.mjs +141 -0
- package/vendor/dsh-bili-scroll/lib/mcp.mjs +144 -0
- package/vendor/dsh-bili-scroll/lib/state.mjs +236 -0
- package/vendor/dsh-bili-scroll/lib/uid.mjs +61 -0
- package/vendor/dsh-bili-scroll/lib/uvfetch.mjs +217 -0
- package/vendor/dsh-bili-scroll/lib/verify.mjs +184 -0
- package/vendor/dsh-bili-scroll/package.json +84 -0
- package/vendor/dsh-bili-scroll/profile-template/bili-duty/cordis.patch.yml +116 -0
- package/vendor/dsh-bili-scroll/profile-template/bili-duty/cordis.yml +4 -0
- package/vendor/dsh-bili-scroll/profile-template/bili-duty/package.json +13 -0
- package/vendor/dsh-bili-scroll/prompts/duty.md +296 -0
- package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/LICENSE +21 -0
- package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/README.md +176 -0
- package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/mcp_server.py +2015 -0
- package/vendor/dsh-bili-scroll/vendor/bilibili-mcp/requirements.txt +10 -0
- package/vendor/dsh-meme/.dsh/skills/dsh-meme-maintenance/SKILL.md +50 -0
- package/vendor/dsh-meme/LICENSE +21 -0
- package/vendor/dsh-meme/anim.js +588 -0
- package/vendor/dsh-meme/cordis.patch.yml +13 -0
- package/vendor/dsh-meme/icon.jpg +0 -0
- package/vendor/dsh-meme/index.js +2616 -0
- package/vendor/dsh-meme/locale/en.json +6 -0
- package/vendor/dsh-meme/locale/zh.json +6 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/index.db +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/manifest.json +13 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/angry/shengqi.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/baka/xianqi.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/color/huachi.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/confused/jiazai.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/confused/wenhao.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/cpu/jiaban.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/daily/ganfan.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/fool/buyao.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/givemoney/yaoqian.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/deyi.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/ok.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/happy/piaole.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/like/bixin.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/meow/maozhua.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/morning/zaoshanghao.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/sad/qiurao.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/sad/yun.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/see/zhenjing.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/shy/haixiu.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/shy/toukan.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/sigh/wuyu.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/sleep/shuijiao.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/surprised/xia.jpg +0 -0
- package/vendor/dsh-meme/memes/dafeiyu-001/memes/work/tangping.jpg +0 -0
- package/vendor/dsh-meme/memes.js +998 -0
- package/vendor/dsh-meme/package.json +67 -0
- package/vendor/dsh-meme/panel.html +210 -0
- package/vendor/dsh-video-storyboard/LICENSE +21 -0
- package/vendor/dsh-video-storyboard/NOTICE +12 -0
- package/vendor/dsh-video-storyboard/bin/_args.mjs +16 -0
- package/vendor/dsh-video-storyboard/bin/asr-check.mjs +85 -0
- package/vendor/dsh-video-storyboard/bin/scan-stats.mjs +43 -0
- package/vendor/dsh-video-storyboard/bin/scan-video.mjs +38 -0
- package/vendor/dsh-video-storyboard/bin/storyboard.mjs +195 -0
- package/vendor/dsh-video-storyboard/cordis.patch.yml +3 -0
- package/vendor/dsh-video-storyboard/dsh.plugin.json +12 -0
- package/vendor/dsh-video-storyboard/package.json +88 -0
- package/vendor/dsh-video-storyboard/scripts/check-syntax.mjs +56 -0
- package/vendor/dsh-video-storyboard/scripts/install-dev.mjs +104 -0
- package/vendor/dsh-video-storyboard/src/flicker.js +104 -0
- package/vendor/dsh-video-storyboard/src/index.js +82 -0
- package/vendor/dsh-video-storyboard/src/ocr_bridge.py +103 -0
- package/vendor/dsh-video-storyboard/src/storyboard/asr-lifecycle.js +262 -0
- package/vendor/dsh-video-storyboard/src/storyboard/asr.js +488 -0
- package/vendor/dsh-video-storyboard/src/storyboard/audio.js +168 -0
- package/vendor/dsh-video-storyboard/src/storyboard/binaries.js +69 -0
- package/vendor/dsh-video-storyboard/src/storyboard/board.js +121 -0
- package/vendor/dsh-video-storyboard/src/storyboard/browser-time.js +504 -0
- package/vendor/dsh-video-storyboard/src/storyboard/cache.js +143 -0
- package/vendor/dsh-video-storyboard/src/storyboard/cells.js +70 -0
- package/vendor/dsh-video-storyboard/src/storyboard/density.js +545 -0
- package/vendor/dsh-video-storyboard/src/storyboard/direct-url.js +130 -0
- package/vendor/dsh-video-storyboard/src/storyboard/fetch.js +373 -0
- package/vendor/dsh-video-storyboard/src/storyboard/flash.js +180 -0
- package/vendor/dsh-video-storyboard/src/storyboard/format.js +573 -0
- package/vendor/dsh-video-storyboard/src/storyboard/frames.js +212 -0
- package/vendor/dsh-video-storyboard/src/storyboard/index.js +32 -0
- package/vendor/dsh-video-storyboard/src/storyboard/injection.js +76 -0
- package/vendor/dsh-video-storyboard/src/storyboard/layout-order.js +176 -0
- package/vendor/dsh-video-storyboard/src/storyboard/locate.js +113 -0
- package/vendor/dsh-video-storyboard/src/storyboard/media-store.js +106 -0
- package/vendor/dsh-video-storyboard/src/storyboard/memory.js +94 -0
- package/vendor/dsh-video-storyboard/src/storyboard/ocr-subs.js +107 -0
- package/vendor/dsh-video-storyboard/src/storyboard/ocr.js +167 -0
- package/vendor/dsh-video-storyboard/src/storyboard/pipeline.js +853 -0
- package/vendor/dsh-video-storyboard/src/storyboard/plan.js +400 -0
- package/vendor/dsh-video-storyboard/src/storyboard/probe.js +132 -0
- package/vendor/dsh-video-storyboard/src/storyboard/provenance.js +44 -0
- package/vendor/dsh-video-storyboard/src/storyboard/python.js +84 -0
- package/vendor/dsh-video-storyboard/src/storyboard/register.js +32 -0
- package/vendor/dsh-video-storyboard/src/storyboard/scan.js +486 -0
- package/vendor/dsh-video-storyboard/src/storyboard/segments.js +117 -0
- package/vendor/dsh-video-storyboard/src/storyboard/sheet.js +507 -0
- package/vendor/dsh-video-storyboard/src/storyboard/storage.js +93 -0
- package/vendor/dsh-video-storyboard/src/storyboard/subtitles.js +181 -0
- package/vendor/dsh-video-storyboard/src/storyboard/tool-spec.js +544 -0
- package/vendor/dsh-video-storyboard/src/storyboard/transcript-file.js +146 -0
- package/vendor/dsh-video-storyboard/src/storyboard/url.js +69 -0
- package/vendor/dsh-video-storyboard/src/storyboard/ytdlp.js +289 -0
- package/vendor/dsh-video-storyboard/src/tool-spec.js +17 -0
- package/vendor/dsh-video-storyboard/src/tools/locate.js +39 -0
- package/vendor/dsh-video-storyboard/src/tools/probe.js +23 -0
- package/vendor/dsh-video-storyboard/src/tools/shared.js +39 -0
- package/vendor/dsh-video-storyboard/src/tools/storyboard.js +20 -0
- package/vendor/dsh-video-storyboard/src/tools/zoom.js +56 -0
- package/vendor/dsh-world/LICENSE +21 -0
- package/vendor/dsh-world/assets/qq-card.png +0 -0
- package/vendor/dsh-world/cordis.patch.yml +6 -0
- package/vendor/dsh-world/lib/archive.d.ts +6 -0
- package/vendor/dsh-world/lib/archive.js +49 -0
- package/vendor/dsh-world/lib/archiveSelection.d.ts +8 -0
- package/vendor/dsh-world/lib/archiveSelection.js +20 -0
- package/vendor/dsh-world/lib/compaction.d.ts +124 -0
- package/vendor/dsh-world/lib/compaction.js +273 -0
- package/vendor/dsh-world/lib/compactionRegion.d.ts +42 -0
- package/vendor/dsh-world/lib/compactionRegion.js +210 -0
- package/vendor/dsh-world/lib/console/routes.d.ts +57 -0
- package/vendor/dsh-world/lib/console/routes.js +129 -0
- package/vendor/dsh-world/lib/console/snapshot.d.ts +39 -0
- package/vendor/dsh-world/lib/console/snapshot.js +51 -0
- package/vendor/dsh-world/lib/ecosystem/bridge/bridge.d.ts +36 -0
- package/vendor/dsh-world/lib/ecosystem/bridge/bridge.js +140 -0
- package/vendor/dsh-world/lib/ecosystem/bridge/route.d.ts +9 -0
- package/vendor/dsh-world/lib/ecosystem/bridge/route.js +46 -0
- package/vendor/dsh-world/lib/ecosystem/qq/bridge.d.ts +123 -0
- package/vendor/dsh-world/lib/ecosystem/qq/bridge.js +380 -0
- package/vendor/dsh-world/lib/ecosystem/qq/panel.d.ts +75 -0
- package/vendor/dsh-world/lib/ecosystem/qq/panel.js +187 -0
- package/vendor/dsh-world/lib/ecosystem/qq/route.d.ts +32 -0
- package/vendor/dsh-world/lib/ecosystem/qq/route.js +134 -0
- package/vendor/dsh-world/lib/ecosystem/qq/supervisor.d.ts +57 -0
- package/vendor/dsh-world/lib/ecosystem/qq/supervisor.js +188 -0
- package/vendor/dsh-world/lib/ecosystem/shared/context.d.ts +14 -0
- package/vendor/dsh-world/lib/ecosystem/shared/context.js +42 -0
- package/vendor/dsh-world/lib/ecosystem/shared/identity.d.ts +15 -0
- package/vendor/dsh-world/lib/ecosystem/shared/identity.js +36 -0
- package/vendor/dsh-world/lib/ecosystem/shared/outlets.d.ts +43 -0
- package/vendor/dsh-world/lib/ecosystem/shared/outlets.js +70 -0
- package/vendor/dsh-world/lib/ecosystem/shared/sessions.d.ts +16 -0
- package/vendor/dsh-world/lib/ecosystem/shared/sessions.js +52 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/archive.d.ts +24 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/archive.js +62 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/home.d.ts +21 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/home.js +111 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/images.d.ts +5 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/images.js +43 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/index.d.ts +41 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/index.js +166 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/messages.d.ts +24 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/messages.js +35 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/sending.d.ts +30 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/sending.js +216 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/supervisor.d.ts +39 -0
- package/vendor/dsh-world/lib/ecosystem/wechat/supervisor.js +138 -0
- package/vendor/dsh-world/lib/faults.d.ts +10 -0
- package/vendor/dsh-world/lib/faults.js +13 -0
- package/vendor/dsh-world/lib/history.d.ts +16 -0
- package/vendor/dsh-world/lib/history.js +80 -0
- package/vendor/dsh-world/lib/hostContract.d.ts +19 -0
- package/vendor/dsh-world/lib/hostContract.js +1 -0
- package/vendor/dsh-world/lib/http.d.ts +18 -0
- package/vendor/dsh-world/lib/http.js +39 -0
- package/vendor/dsh-world/lib/index.d.ts +108 -0
- package/vendor/dsh-world/lib/index.js +356 -0
- package/vendor/dsh-world/lib/life/activity.d.ts +14 -0
- package/vendor/dsh-world/lib/life/activity.js +58 -0
- package/vendor/dsh-world/lib/life/alarm.d.ts +39 -0
- package/vendor/dsh-world/lib/life/alarm.js +132 -0
- package/vendor/dsh-world/lib/life/alarmTimer.d.ts +22 -0
- package/vendor/dsh-world/lib/life/alarmTimer.js +49 -0
- package/vendor/dsh-world/lib/life/diary.d.ts +4 -0
- package/vendor/dsh-world/lib/life/diary.js +9 -0
- package/vendor/dsh-world/lib/life/earlyStop.d.ts +19 -0
- package/vendor/dsh-world/lib/life/earlyStop.js +25 -0
- package/vendor/dsh-world/lib/life/home.d.ts +34 -0
- package/vendor/dsh-world/lib/life/home.js +91 -0
- package/vendor/dsh-world/lib/life/host.d.ts +22 -0
- package/vendor/dsh-world/lib/life/host.js +24 -0
- package/vendor/dsh-world/lib/life/journal.d.ts +20 -0
- package/vendor/dsh-world/lib/life/journal.js +59 -0
- package/vendor/dsh-world/lib/life/lifeStore.d.ts +16 -0
- package/vendor/dsh-world/lib/life/lifeStore.js +105 -0
- package/vendor/dsh-world/lib/life/messages.d.ts +17 -0
- package/vendor/dsh-world/lib/life/messages.js +53 -0
- package/vendor/dsh-world/lib/life/notify.d.ts +15 -0
- package/vendor/dsh-world/lib/life/notify.js +40 -0
- package/vendor/dsh-world/lib/life/pricing.d.ts +4 -0
- package/vendor/dsh-world/lib/life/pricing.js +30 -0
- package/vendor/dsh-world/lib/life/runtime.d.ts +52 -0
- package/vendor/dsh-world/lib/life/runtime.js +376 -0
- package/vendor/dsh-world/lib/life/toolRegistry.d.ts +22 -0
- package/vendor/dsh-world/lib/life/toolRegistry.js +64 -0
- package/vendor/dsh-world/lib/life/tools.d.ts +24 -0
- package/vendor/dsh-world/lib/life/tools.js +47 -0
- package/vendor/dsh-world/lib/life/types.d.ts +67 -0
- package/vendor/dsh-world/lib/life/types.js +1 -0
- package/vendor/dsh-world/lib/persona.d.ts +10 -0
- package/vendor/dsh-world/lib/persona.js +29 -0
- package/vendor/dsh-world/lib/promptSection.d.ts +30 -0
- package/vendor/dsh-world/lib/promptSection.js +81 -0
- package/vendor/dsh-world/lib/qqScope.d.ts +11 -0
- package/vendor/dsh-world/lib/qqScope.js +39 -0
- package/vendor/dsh-world/lib/runtime.d.ts +23 -0
- package/vendor/dsh-world/lib/runtime.js +206 -0
- package/vendor/dsh-world/lib/self.d.ts +10 -0
- package/vendor/dsh-world/lib/self.js +36 -0
- package/vendor/dsh-world/lib/sourceArchive.d.ts +28 -0
- package/vendor/dsh-world/lib/sourceArchive.js +156 -0
- package/vendor/dsh-world/lib/store.d.ts +30 -0
- package/vendor/dsh-world/lib/store.js +191 -0
- package/vendor/dsh-world/lib/timeContext.d.ts +3 -0
- package/vendor/dsh-world/lib/timeContext.js +13 -0
- package/vendor/dsh-world/lib/types.d.ts +118 -0
- package/vendor/dsh-world/lib/types.js +1 -0
- package/vendor/dsh-world/lib/worldPrompt.d.ts +47 -0
- package/vendor/dsh-world/lib/worldPrompt.js +49 -0
- package/vendor/dsh-world/lib/worldSwitch.d.ts +44 -0
- package/vendor/dsh-world/lib/worldSwitch.js +78 -0
- package/vendor/dsh-world/package-lock.json +1088 -0
- package/vendor/dsh-world/package.json +88 -0
- package/vendor/dsh-world/scripts/enable-tool-free-compaction.ps1 +33 -0
- package/vendor/dsh-world/src/archive.ts +45 -0
- package/vendor/dsh-world/src/archiveSelection.ts +27 -0
- package/vendor/dsh-world/src/compaction.ts +260 -0
- package/vendor/dsh-world/src/compactionRegion.ts +172 -0
- package/vendor/dsh-world/src/console/routes.ts +125 -0
- package/vendor/dsh-world/src/console/snapshot.ts +84 -0
- package/vendor/dsh-world/src/ecosystem/README.md +14 -0
- package/vendor/dsh-world/src/ecosystem/bridge/bridge.ts +121 -0
- package/vendor/dsh-world/src/ecosystem/bridge/route.ts +35 -0
- package/vendor/dsh-world/src/ecosystem/qq/bridge.ts +456 -0
- package/vendor/dsh-world/src/ecosystem/qq/panel.ts +178 -0
- package/vendor/dsh-world/src/ecosystem/qq/route.ts +130 -0
- package/vendor/dsh-world/src/ecosystem/qq/supervisor.ts +262 -0
- package/vendor/dsh-world/src/ecosystem/shared/context.ts +38 -0
- package/vendor/dsh-world/src/ecosystem/shared/identity.ts +42 -0
- package/vendor/dsh-world/src/ecosystem/shared/outlets.ts +75 -0
- package/vendor/dsh-world/src/ecosystem/shared/sessions.ts +47 -0
- package/vendor/dsh-world/src/ecosystem/wechat/archive.ts +66 -0
- package/vendor/dsh-world/src/ecosystem/wechat/home.ts +94 -0
- package/vendor/dsh-world/src/ecosystem/wechat/images.ts +38 -0
- package/vendor/dsh-world/src/ecosystem/wechat/index.ts +101 -0
- package/vendor/dsh-world/src/ecosystem/wechat/messages.ts +43 -0
- package/vendor/dsh-world/src/ecosystem/wechat/sending.ts +177 -0
- package/vendor/dsh-world/src/ecosystem/wechat/supervisor.ts +116 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/README.md +117 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/adapter.py +572 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/binding.py +52 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/LICENSE +43 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/NOTICE.md +10 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/bridge.cpp +229 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/build.ps1 +19 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/engine/profile.json +28 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/groups.py +42 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/incoming.py +157 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/native.py +168 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/outgoing.py +95 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/requirements.txt +1 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/sender.py +157 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/snapshot.py +32 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/stickers.py +60 -0
- package/vendor/dsh-world/src/ecosystem/wechat/windows/wechat.ps1 +75 -0
- package/vendor/dsh-world/src/faults.ts +12 -0
- package/vendor/dsh-world/src/history.ts +77 -0
- package/vendor/dsh-world/src/hostContract.ts +9 -0
- package/vendor/dsh-world/src/http.ts +34 -0
- package/vendor/dsh-world/src/index.ts +286 -0
- package/vendor/dsh-world/src/life/activity.ts +48 -0
- package/vendor/dsh-world/src/life/alarm.ts +119 -0
- package/vendor/dsh-world/src/life/alarmTimer.ts +45 -0
- package/vendor/dsh-world/src/life/diary.ts +10 -0
- package/vendor/dsh-world/src/life/earlyStop.ts +27 -0
- package/vendor/dsh-world/src/life/home.ts +85 -0
- package/vendor/dsh-world/src/life/host.ts +50 -0
- package/vendor/dsh-world/src/life/journal.ts +44 -0
- package/vendor/dsh-world/src/life/lifeStore.ts +70 -0
- package/vendor/dsh-world/src/life/messages.ts +44 -0
- package/vendor/dsh-world/src/life/notify.ts +47 -0
- package/vendor/dsh-world/src/life/pricing.ts +37 -0
- package/vendor/dsh-world/src/life/runtime.ts +318 -0
- package/vendor/dsh-world/src/life/toolRegistry.ts +48 -0
- package/vendor/dsh-world/src/life/tools.ts +61 -0
- package/vendor/dsh-world/src/life/types.ts +19 -0
- package/vendor/dsh-world/src/persona.ts +26 -0
- package/vendor/dsh-world/src/promptSection.ts +71 -0
- package/vendor/dsh-world/src/qqScope.ts +51 -0
- package/vendor/dsh-world/src/runtime.ts +172 -0
- package/vendor/dsh-world/src/self.ts +32 -0
- package/vendor/dsh-world/src/sourceArchive.ts +132 -0
- package/vendor/dsh-world/src/store.ts +170 -0
- package/vendor/dsh-world/src/timeContext.ts +13 -0
- package/vendor/dsh-world/src/types.ts +112 -0
- package/vendor/dsh-world/src/worldPrompt.ts +64 -0
- package/vendor/dsh-world/src/worldSwitch.ts +82 -0
- package/vendor/dsh-world/templates/alarm.md +49 -0
- package/vendor/dsh-world/templates/world-prompt.md +7 -0
- package/vendor/dsh-world/tests/archive.test.ts +57 -0
- package/vendor/dsh-world/tests/archiveScope.test.ts +86 -0
- package/vendor/dsh-world/tests/bridge.test.ts +211 -0
- package/vendor/dsh-world/tests/channelSessions.test.ts +79 -0
- package/vendor/dsh-world/tests/clientHooks.test.ts +103 -0
- package/vendor/dsh-world/tests/compaction.test.ts +141 -0
- package/vendor/dsh-world/tests/console.test.ts +202 -0
- package/vendor/dsh-world/tests/consoleClient.test.ts +101 -0
- package/vendor/dsh-world/tests/enableCompaction.test.ts +19 -0
- package/vendor/dsh-world/tests/fixtures.ts +6 -0
- package/vendor/dsh-world/tests/history.test.ts +100 -0
- package/vendor/dsh-world/tests/hostFixture.ts +46 -0
- package/vendor/dsh-world/tests/lifeActivity.test.ts +70 -0
- package/vendor/dsh-world/tests/lifeAlarm.test.ts +87 -0
- package/vendor/dsh-world/tests/lifeDiary.test.ts +33 -0
- package/vendor/dsh-world/tests/lifeMessages.test.ts +61 -0
- package/vendor/dsh-world/tests/lifeNotify.test.ts +46 -0
- package/vendor/dsh-world/tests/lifeParts.test.ts +45 -0
- package/vendor/dsh-world/tests/lifeRuntime.test.ts +660 -0
- package/vendor/dsh-world/tests/lifeStore.test.ts +90 -0
- package/vendor/dsh-world/tests/lifeTools.test.ts +53 -0
- package/vendor/dsh-world/tests/outlets.test.ts +85 -0
- package/vendor/dsh-world/tests/panel.test.ts +85 -0
- package/vendor/dsh-world/tests/plugin.test.ts +614 -0
- package/vendor/dsh-world/tests/pricing.test.ts +21 -0
- package/vendor/dsh-world/tests/qq.test.ts +121 -0
- package/vendor/dsh-world/tests/qqSessionMode.test.ts +97 -0
- package/vendor/dsh-world/tests/qqSupervisor.test.ts +149 -0
- package/vendor/dsh-world/tests/sourceArchive.test.ts +58 -0
- package/vendor/dsh-world/tests/store.test.ts +82 -0
- package/vendor/dsh-world/tests/storeWriter.ts +5 -0
- package/vendor/dsh-world/tests/timeContext.test.ts +15 -0
- package/vendor/dsh-world/tests/wechat.test.ts +254 -0
- package/vendor/dsh-world/tests/wechatImages.test.ts +130 -0
- package/vendor/dsh-world/tests/wechatSending.test.ts +142 -0
- package/vendor/dsh-world/tests/wechatSupervisor.test.ts +91 -0
- package/vendor/dsh-world/tests/worldPrompt.test.ts +201 -0
- package/vendor/dsh-world/tsconfig.build.json +5 -0
- package/vendor/dsh-world/tsconfig.json +8 -0
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { jsonObject, knownHost, readBody, sendJson, type JsonResult } from '../../http.ts';
|
|
3
|
+
import type { QqBridge } from './bridge.ts';
|
|
4
|
+
import type { ConsoleDoors } from './panel.ts';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The QQ module's few doors, on the same webServer as the console. The `/dsh-world/qq` prefix is never eaten
|
|
8
|
+
* by the console's `/dsh-world` prefix (the host matches the longer one first).
|
|
9
|
+
*
|
|
10
|
+
* Read: GET /dsh-world/qq is the bridge up, is it talking to DSH, which entries are bound
|
|
11
|
+
* GET /dsh-world/qq/proactive the proactive-chat numbers (calls, tokens, sent, suppressed)
|
|
12
|
+
* GET /dsh-world/qq/console the two consoles' addresses, tokens in hand: qq-bridge (its token is a
|
|
13
|
+
* file) and SnowLuma (a fresh session token traded for the panel password)
|
|
14
|
+
* Write: POST /dsh-world/qq/start bring it up if it is down
|
|
15
|
+
* POST /dsh-world/qq/stop ask it to exit gracefully (flushes state first)
|
|
16
|
+
* POST /dsh-world/qq/halt stop it and mean it: the bridge records intent=stopped and no handoff
|
|
17
|
+
* process is spawned, so the supervisor will not bring it back
|
|
18
|
+
* POST /dsh-world/qq/bind { key, sessionId } points a QQ entry at a session
|
|
19
|
+
* POST /dsh-world/qq/unbind { key }
|
|
20
|
+
* POST /dsh-world/qq/panel-password { username, password } remembers SnowLuma's panel password and
|
|
21
|
+
* trades it for a session token right away
|
|
22
|
+
* POST /dsh-world/qq/proactive { enabled?, dryRun? } flips the two switches; the bridge writes them into
|
|
23
|
+
* its own config.json and applies them on the spot, so nothing restarts
|
|
24
|
+
*
|
|
25
|
+
* Writes require the `x-dsh-world` header: a cross-site page cannot add it (that would trigger a preflight,
|
|
26
|
+
* and no preflight is answered here).
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
export const QQ_PREFIX = '/dsh-world/qq';
|
|
30
|
+
export const WRITE_HEADER = 'x-dsh-world';
|
|
31
|
+
const MAX_BODY_BYTES = 8 * 1024;
|
|
32
|
+
const ok = (body: unknown = { ok: true }): JsonResult => ({ status: 200, body });
|
|
33
|
+
const bad = (error: string): JsonResult => ({ status: 400, body: { error } });
|
|
34
|
+
|
|
35
|
+
function allowed(req: IncomingMessage, allowedHosts: readonly string[]): boolean {
|
|
36
|
+
if (req.headers['sec-fetch-site'] === 'cross-site') return false;
|
|
37
|
+
return knownHost(req.headers.host, allowedHosts);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function write(qq: QqBridge, doors: ConsoleDoors | undefined, path: string, body: Record<string, unknown> | undefined): Promise<JsonResult | undefined> {
|
|
41
|
+
switch (path) {
|
|
42
|
+
case '/start': return ok(await qq.start());
|
|
43
|
+
case '/stop': return ok(await qq.stop());
|
|
44
|
+
case '/halt': return ok(await qq.halt());
|
|
45
|
+
case '/open': {
|
|
46
|
+
if (!doors) return bad('控制台地址没有接上');
|
|
47
|
+
const kind = body?.kind === 'qq' ? 'qq' : body?.kind === 'snowluma' ? 'snowluma' : '';
|
|
48
|
+
if (kind === '') return bad('kind 只能是 qq 或 snowluma');
|
|
49
|
+
return ok(await doors.open(kind));
|
|
50
|
+
}
|
|
51
|
+
case '/panel-password': {
|
|
52
|
+
if (!doors) return bad('控制台地址没有接上');
|
|
53
|
+
const username = typeof body?.username === 'string' ? body.username.trim() : '';
|
|
54
|
+
const password = typeof body?.password === 'string' ? body.password : '';
|
|
55
|
+
if (password === '') return bad('密码不能为空');
|
|
56
|
+
return ok({ snowluma: await doors.remember(username, password) });
|
|
57
|
+
}
|
|
58
|
+
case '/proactive': {
|
|
59
|
+
const patch: { enabled?: boolean; dryRun?: boolean } = {};
|
|
60
|
+
if (typeof body?.enabled === 'boolean') patch.enabled = body.enabled;
|
|
61
|
+
if (typeof body?.dryRun === 'boolean') patch.dryRun = body.dryRun;
|
|
62
|
+
if (patch.enabled === undefined && patch.dryRun === undefined) return bad('enabled 和 dryRun 至少要给一个布尔');
|
|
63
|
+
return ok(await qq.setProactive(patch));
|
|
64
|
+
}
|
|
65
|
+
case '/bind': {
|
|
66
|
+
const key = typeof body?.key === 'string' ? body.key.trim() : '';
|
|
67
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
|
|
68
|
+
if (!key || !sessionId) return bad('key 和 sessionId 都必须是非空字符串');
|
|
69
|
+
if (!/^(group|private):\d+$/.test(key)) return bad('key 形如 group:123 或 private:123');
|
|
70
|
+
return ok(await qq.bind(key, sessionId));
|
|
71
|
+
}
|
|
72
|
+
case '/unbind': {
|
|
73
|
+
const key = typeof body?.key === 'string' ? body.key.trim() : '';
|
|
74
|
+
if (!key) return bad('key 必填');
|
|
75
|
+
return ok(await qq.unbind(key));
|
|
76
|
+
}
|
|
77
|
+
default: return undefined;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function qqRoute(qq: QqBridge, allowedHosts: readonly string[] = [], doors?: ConsoleDoors) {
|
|
82
|
+
return {
|
|
83
|
+
kind: 'prefix' as const, path: QQ_PREFIX,
|
|
84
|
+
handler: async (req: IncomingMessage, res: ServerResponse) => {
|
|
85
|
+
if (!allowed(req, allowedHosts)) {
|
|
86
|
+
sendJson(res, { status: 403, body: { error: 'forbidden' } });
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const url = new URL(req.url ?? QQ_PREFIX, 'http://localhost');
|
|
90
|
+
const path = url.pathname.slice(QQ_PREFIX.length) || '/';
|
|
91
|
+
try {
|
|
92
|
+
if (req.method === 'GET' && (path === '/' || path === '')) {
|
|
93
|
+
sendJson(res, ok(await qq.status()));
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (req.method === 'GET' && path === '/proactive') {
|
|
97
|
+
const data = await qq.proactive();
|
|
98
|
+
if (!data) {
|
|
99
|
+
sendJson(res, { status: 503, body: { error: '桥没在跑,统计读不到' } });
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
sendJson(res, ok(data));
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (req.method === 'GET' && path === '/console') {
|
|
106
|
+
if (!doors) {
|
|
107
|
+
sendJson(res, { status: 404, body: { error: '控制台地址没有接上' } });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const qqDoor = doors.qq();
|
|
111
|
+
sendJson(res, ok({ qq: qqDoor, snowluma: await doors.snowluma() }));
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
if (req.method !== 'POST') {
|
|
115
|
+
sendJson(res, { status: 405, body: { error: 'method not allowed' }, headers: { allow: 'GET, POST' } });
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (String(req.headers[WRITE_HEADER] ?? '') === '') {
|
|
119
|
+
sendJson(res, { status: 400, body: { error: `写操作必须带 ${WRITE_HEADER} 请求头` } });
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
const body = jsonObject(await readBody(req, MAX_BODY_BYTES));
|
|
123
|
+
const result = await write(qq, doors, path, body);
|
|
124
|
+
sendJson(res, result ?? { status: 404, body: { error: 'not found' } });
|
|
125
|
+
} catch (error) {
|
|
126
|
+
sendJson(res, { status: 500, body: { error: String(error instanceof Error ? error.message : error) } });
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
};
|
|
130
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { readConsoleToken } from './bridge.ts';
|
|
2
|
+
import type { QqBridge, QqIntent, QqLogger } from './bridge.ts';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* QQ:看着那个外部进程,别让它悄悄死掉。
|
|
6
|
+
*
|
|
7
|
+
* 为什么需要一层巡检:桥是独立进程(`spawn` 出去的、detached),插件这边除了启动时的一次
|
|
8
|
+
* `ensureRunning()` 之外对它一无所知。它崩了、被任务管理器结束、DSH 换端口后它连不上——
|
|
9
|
+
* 三种情况在界面上长得一模一样:QQ 不说话了。2026-10-26 那次「链路死了四小时」就是这么来的。
|
|
10
|
+
*
|
|
11
|
+
* 这层只做三件事:探测、判断该不该拉、拉的时候别把自己拉爆。它不碰桥的业务逻辑,
|
|
12
|
+
* 也不接管桥的启停实现(那是 `bridge.ts` 的事)。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export type SupervisorState = 'stopped' | 'starting' | 'healthy' | 'degraded' | 'recovering' | 'failed';
|
|
16
|
+
|
|
17
|
+
export interface SupervisorSnapshot {
|
|
18
|
+
state: SupervisorState;
|
|
19
|
+
/** 连续探测失败次数;成功一次清零。 */
|
|
20
|
+
consecutiveFailures: number;
|
|
21
|
+
/** 最近 10 分钟内真正发起的自动拉起次数。 */
|
|
22
|
+
restartsInWindow: number;
|
|
23
|
+
/** 下次探测的间隔(恢复失败后会变长)。 */
|
|
24
|
+
backoffMs: number;
|
|
25
|
+
/** 桥在线且 `dshReady`——false 时桥在跑但连不上 DSH,那是端点问题,重启桥治不了。 */
|
|
26
|
+
dshReady?: boolean;
|
|
27
|
+
lastError?: string;
|
|
28
|
+
lastProbeAt?: number;
|
|
29
|
+
lastRestartAt?: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SupervisorOptions {
|
|
33
|
+
/** qq-bridge 目录;`state/bridge.intent.json` 也从这里读。 */
|
|
34
|
+
dir: string;
|
|
35
|
+
port?: number;
|
|
36
|
+
/** 只用到 start / halt / intent 三个动作,方便测试塞假桥。 */
|
|
37
|
+
bridge: Pick<QqBridge, 'start' | 'halt' | 'intent'>;
|
|
38
|
+
logger?: QqLogger;
|
|
39
|
+
/** 探测间隔,默认 5s。 */
|
|
40
|
+
intervalMs?: number;
|
|
41
|
+
/** 单次探测超时,默认 1.5s。 */
|
|
42
|
+
probeTimeoutMs?: number;
|
|
43
|
+
/** 连续失败到几次才尝试恢复,默认 3。 */
|
|
44
|
+
failuresBeforeRestart?: number;
|
|
45
|
+
/** 10 分钟内最多自动拉起几次,默认 5。 */
|
|
46
|
+
maxRestartsPerWindow?: number;
|
|
47
|
+
/** 退避基数,默认 2s;第 n 次失败后等 base * 2^(n-1),上限 60s。 */
|
|
48
|
+
backoffBaseMs?: number;
|
|
49
|
+
/** 注入时钟与随机源,测试用。 */
|
|
50
|
+
now?: () => number;
|
|
51
|
+
random?: () => number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface QqSupervisor {
|
|
55
|
+
/** 开始巡检。不会立刻拉起桥——「该不该跑」是调用方先决定的事。 */
|
|
56
|
+
start(): void;
|
|
57
|
+
/** 停止巡检。不影响桥本身。 */
|
|
58
|
+
stop(): void;
|
|
59
|
+
/** 立刻探一次,可用于控制台刷新或测试。 */
|
|
60
|
+
probeOnce(): Promise<SupervisorSnapshot>;
|
|
61
|
+
snapshot(): SupervisorSnapshot;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const DEFAULT_INTERVAL_MS = 5000;
|
|
65
|
+
const DEFAULT_PROBE_TIMEOUT_MS = 1500;
|
|
66
|
+
const DEFAULT_FAILURES_BEFORE_RESTART = 3;
|
|
67
|
+
const DEFAULT_MAX_RESTARTS = 5;
|
|
68
|
+
const DEFAULT_BACKOFF_BASE_MS = 2000;
|
|
69
|
+
const MAX_BACKOFF_MS = 60000;
|
|
70
|
+
const RESTART_WINDOW_MS = 10 * 60 * 1000;
|
|
71
|
+
|
|
72
|
+
const sleep = (ms: number): Promise<void> => new Promise(resolve => { setTimeout(resolve, ms); });
|
|
73
|
+
const messageOf = (error: unknown): string => error instanceof Error ? error.message : String(error);
|
|
74
|
+
|
|
75
|
+
type ProbeResult = { ok: true; body: Record<string, any> } | { ok: false; error: string };
|
|
76
|
+
|
|
77
|
+
export function createQqSupervisor(options: SupervisorOptions): QqSupervisor {
|
|
78
|
+
const {
|
|
79
|
+
dir,
|
|
80
|
+
bridge,
|
|
81
|
+
logger,
|
|
82
|
+
port = 3100,
|
|
83
|
+
intervalMs = DEFAULT_INTERVAL_MS,
|
|
84
|
+
probeTimeoutMs = DEFAULT_PROBE_TIMEOUT_MS,
|
|
85
|
+
failuresBeforeRestart = DEFAULT_FAILURES_BEFORE_RESTART,
|
|
86
|
+
maxRestartsPerWindow = DEFAULT_MAX_RESTARTS,
|
|
87
|
+
backoffBaseMs = DEFAULT_BACKOFF_BASE_MS,
|
|
88
|
+
now = () => Date.now(),
|
|
89
|
+
random = () => Math.random(),
|
|
90
|
+
} = options;
|
|
91
|
+
|
|
92
|
+
const base = `http://127.0.0.1:${port}`;
|
|
93
|
+
let state: SupervisorState = 'stopped';
|
|
94
|
+
let consecutiveFailures = 0;
|
|
95
|
+
/** 本轮连续发起恢复的次数;成功或被探到桥好了就清零。退避按它算。 */
|
|
96
|
+
let recoverAttempts = 0;
|
|
97
|
+
let backoffMs = 0;
|
|
98
|
+
let restartsInWindow = 0;
|
|
99
|
+
let lastError: string | undefined;
|
|
100
|
+
let lastProbeAt: number | undefined;
|
|
101
|
+
let lastRestartAt: number | undefined;
|
|
102
|
+
let dshReady: boolean | undefined;
|
|
103
|
+
const restartTimes: number[] = [];
|
|
104
|
+
/** 单飞:探测和恢复共用这把锁,避免慢探测叠在恢复上。 */
|
|
105
|
+
let inFlight = false;
|
|
106
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
107
|
+
|
|
108
|
+
function pruneWindow(at: number): void {
|
|
109
|
+
const cutoff = at - RESTART_WINDOW_MS;
|
|
110
|
+
while (restartTimes.length > 0 && restartTimes[0]! < cutoff) restartTimes.shift();
|
|
111
|
+
restartsInWindow = restartTimes.length;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function nextBackoff(): number {
|
|
115
|
+
// 按「第几次发起恢复」算,不按「连续探测失败几次」算:
|
|
116
|
+
// 阈值是 3,用探测次数会让第一次恢复就先等 4 倍基数。
|
|
117
|
+
const raw = backoffBaseMs * 2 ** Math.min(Math.max(0, recoverAttempts - 1), 5);
|
|
118
|
+
// ±20% 抖动:几个实例同时恢复时不至于踩着同一个节奏互相抢锁。
|
|
119
|
+
const jitter = 0.8 + random() * 0.4;
|
|
120
|
+
return Math.min(MAX_BACKOFF_MS, Math.round(raw * jitter));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function probe(): Promise<ProbeResult> {
|
|
124
|
+
const token = readConsoleToken(dir);
|
|
125
|
+
const url = `${base}/api/status${token ? `?token=${encodeURIComponent(token)}` : ''}`;
|
|
126
|
+
try {
|
|
127
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(probeTimeoutMs) });
|
|
128
|
+
if (response.status !== 200) return { ok: false, error: `status ${response.status}` };
|
|
129
|
+
const body = await response.json() as Record<string, any>;
|
|
130
|
+
return { ok: true, body: body ?? {} };
|
|
131
|
+
} catch (error) {
|
|
132
|
+
return { ok: false, error: messageOf(error) };
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function intent(): QqIntent {
|
|
137
|
+
try {
|
|
138
|
+
return bridge.intent();
|
|
139
|
+
} catch {
|
|
140
|
+
// 读意图失败按「想跑」处理:未知状态不该变成永久不启动。
|
|
141
|
+
return { desired: 'running', at: 0, by: '' };
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function attemptRecovery(at: number): Promise<void> {
|
|
146
|
+
const wanted = intent();
|
|
147
|
+
if (wanted.desired === 'stopped') {
|
|
148
|
+
// 用户主动停的:报状态就够了,别把手伸回去。
|
|
149
|
+
state = 'stopped';
|
|
150
|
+
logger?.info?.('[qq] 桥是用户主动停止的(desired=stopped),巡检不自动拉起');
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
pruneWindow(at);
|
|
154
|
+
if (restartsInWindow >= maxRestartsPerWindow) {
|
|
155
|
+
state = 'failed';
|
|
156
|
+
lastError = `${RESTART_WINDOW_MS / 60000} 分钟内已自动拉起 ${restartsInWindow} 次,停止重试(修好再手动启动)`;
|
|
157
|
+
logger?.warn?.(`[qq] ${lastError}`);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
state = 'starting';
|
|
161
|
+
logger?.warn?.(`[qq] 桥连续 ${consecutiveFailures} 次探测失败,尝试拉起`);
|
|
162
|
+
try {
|
|
163
|
+
const result = await bridge.start();
|
|
164
|
+
if (result.started) {
|
|
165
|
+
restartTimes.push(now());
|
|
166
|
+
restartsInWindow = restartTimes.length;
|
|
167
|
+
lastRestartAt = now();
|
|
168
|
+
state = 'healthy';
|
|
169
|
+
consecutiveFailures = 0;
|
|
170
|
+
recoverAttempts = 0;
|
|
171
|
+
backoffMs = 0;
|
|
172
|
+
lastError = undefined;
|
|
173
|
+
logger?.info?.('[qq] 桥已拉起');
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
lastError = `拉起没成功:${result.reason ?? '未知原因'}`;
|
|
177
|
+
} catch (error) {
|
|
178
|
+
lastError = `拉起失败:${messageOf(error)}`;
|
|
179
|
+
}
|
|
180
|
+
// 失败:进入退避等待,期间不再尝试;等待结束才回到 degraded 让下一轮重新判定。
|
|
181
|
+
// 计数必须清零——否则「连续失败 3 次」这个闸门永远开着,退避等待一结束,
|
|
182
|
+
// 下一次探测就直接又拉一遍,退避等于没做。
|
|
183
|
+
state = 'recovering';
|
|
184
|
+
consecutiveFailures = 0;
|
|
185
|
+
recoverAttempts += 1;
|
|
186
|
+
backoffMs = nextBackoff();
|
|
187
|
+
logger?.warn?.(`[qq] ${lastError};${Math.round(backoffMs / 1000)}s 后再试`);
|
|
188
|
+
await sleep(backoffMs);
|
|
189
|
+
if (state === 'recovering') state = 'degraded';
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async function tick(): Promise<void> {
|
|
193
|
+
if (inFlight) return;
|
|
194
|
+
inFlight = true;
|
|
195
|
+
try {
|
|
196
|
+
const at = now();
|
|
197
|
+
lastProbeAt = at;
|
|
198
|
+
const result = await probe();
|
|
199
|
+
if (result.ok) {
|
|
200
|
+
consecutiveFailures = 0;
|
|
201
|
+
recoverAttempts = 0;
|
|
202
|
+
backoffMs = 0;
|
|
203
|
+
lastError = undefined;
|
|
204
|
+
dshReady = result.body.dshReady === true;
|
|
205
|
+
// 桥在跑但连不上 DSH:那是 baseUrl 过期,重启桥解决不了,交给 syncEndpoint。
|
|
206
|
+
// 这里只把它标成 degraded,让人在界面上看得出来。
|
|
207
|
+
state = dshReady ? 'healthy' : 'degraded';
|
|
208
|
+
if (!dshReady) lastError = '桥在线,但 dshReady=false(多半是 DSH 换了端口,跑一次 syncEndpoint)';
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
dshReady = undefined;
|
|
212
|
+
// 用户主动停的桥不在线是**预期状态**,不该算故障:否则界面上先跳十几秒的
|
|
213
|
+
// 「degraded / 连续失败 2 次」才变回 stopped,看着像巡检在犹豫要不要动手。
|
|
214
|
+
if (intent().desired === 'stopped') {
|
|
215
|
+
state = 'stopped';
|
|
216
|
+
consecutiveFailures = 0;
|
|
217
|
+
recoverAttempts = 0;
|
|
218
|
+
lastError = undefined;
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
consecutiveFailures += 1;
|
|
222
|
+
lastError = result.error;
|
|
223
|
+
state = 'degraded';
|
|
224
|
+
if (consecutiveFailures >= failuresBeforeRestart) await attemptRecovery(at);
|
|
225
|
+
} finally {
|
|
226
|
+
inFlight = false;
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
start(): void {
|
|
232
|
+
if (timer) return;
|
|
233
|
+
// 先探一次,别让界面在头 5 秒里显示「未知」。
|
|
234
|
+
void tick();
|
|
235
|
+
timer = setInterval(() => { void tick(); }, intervalMs);
|
|
236
|
+
// 巡检不该成为进程退出的阻碍。
|
|
237
|
+
(timer as { unref?: () => void }).unref?.();
|
|
238
|
+
},
|
|
239
|
+
stop(): void {
|
|
240
|
+
if (timer) clearInterval(timer);
|
|
241
|
+
timer = undefined;
|
|
242
|
+
state = 'stopped';
|
|
243
|
+
},
|
|
244
|
+
async probeOnce(): Promise<SupervisorSnapshot> {
|
|
245
|
+
await tick();
|
|
246
|
+
return this.snapshot();
|
|
247
|
+
},
|
|
248
|
+
snapshot(): SupervisorSnapshot {
|
|
249
|
+
pruneWindow(now());
|
|
250
|
+
return {
|
|
251
|
+
state,
|
|
252
|
+
consecutiveFailures,
|
|
253
|
+
restartsInWindow,
|
|
254
|
+
backoffMs,
|
|
255
|
+
...(dshReady === undefined ? {} : { dshReady }),
|
|
256
|
+
...(lastError ? { lastError } : {}),
|
|
257
|
+
...(lastProbeAt === undefined ? {} : { lastProbeAt }),
|
|
258
|
+
...(lastRestartAt === undefined ? {} : { lastRestartAt }),
|
|
259
|
+
};
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { conversationKey, speakerIdentity, type SpeakerIdentity } from './identity.ts';
|
|
2
|
+
|
|
3
|
+
export interface ChannelImage { file: string; quality: 'original' | 'cached' | 'thumbnail' }
|
|
4
|
+
export interface ChannelContextMessage { id: string; occurredAt: string; text: string; identity: SpeakerIdentity; image?: ChannelImage }
|
|
5
|
+
|
|
6
|
+
export function channelContext(value: unknown, current: SpeakerIdentity, limit = 8): ChannelContextMessage[] {
|
|
7
|
+
if (value === undefined || (Array.isArray(value) && value.length === 0)) return [];
|
|
8
|
+
if (current.conversationType !== 'group') throw new Error('Invalid group context');
|
|
9
|
+
return contextMessages(value, current, limit);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function channelMedia(value: unknown, current: SpeakerIdentity): ChannelContextMessage[] {
|
|
13
|
+
if (value === undefined || (Array.isArray(value) && value.length === 0)) return [];
|
|
14
|
+
if (current.conversationType !== 'private') throw new Error('Invalid private media');
|
|
15
|
+
const messages = contextMessages(value, current, 2);
|
|
16
|
+
if (messages.some(message => message.identity.speakerId !== current.speakerId)) throw new Error('Media belongs to another speaker');
|
|
17
|
+
if (new Set(messages.map(message => message.id)).size !== messages.length) throw new Error('Duplicate media message');
|
|
18
|
+
return messages;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function contextMessages(value: unknown, current: SpeakerIdentity, limit: number): ChannelContextMessage[] {
|
|
22
|
+
if (!Array.isArray(value) || value.length > limit || Buffer.byteLength(JSON.stringify(value)) > 16 * 1024) throw new Error('Invalid channel context');
|
|
23
|
+
let images = 0;
|
|
24
|
+
return value.map(item => {
|
|
25
|
+
if (!item || typeof item !== 'object' || typeof item.id !== 'string' || !item.id || item.id.length > 256 || /[\u0000-\u001f\u007f]/.test(item.id)
|
|
26
|
+
|| typeof item.occurredAt !== 'string' || item.occurredAt.length > 40 || !Number.isFinite(Date.parse(item.occurredAt))
|
|
27
|
+
|| typeof item.text !== 'string' || !item.text.trim() || [...item.text].length > 2000) throw new Error('Invalid context message');
|
|
28
|
+
const identity = speakerIdentity(item.identity);
|
|
29
|
+
if (conversationKey(identity) !== conversationKey(current)) throw new Error('Context belongs to another conversation');
|
|
30
|
+
let image: ChannelImage | undefined;
|
|
31
|
+
if (item.image !== undefined) {
|
|
32
|
+
if (!item.image || typeof item.image !== 'object' || typeof item.image.file !== 'string' || !/^[a-f0-9]{64}\.png$/.test(item.image.file)
|
|
33
|
+
|| !['original', 'cached', 'thumbnail'].includes(item.image.quality) || ++images > 2) throw new Error('Invalid group image');
|
|
34
|
+
image = { file: item.image.file, quality: item.image.quality };
|
|
35
|
+
}
|
|
36
|
+
return { id: item.id, occurredAt: item.occurredAt, text: item.text, identity, ...(image ? { image } : {}) };
|
|
37
|
+
});
|
|
38
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
export interface SpeakerIdentity {
|
|
2
|
+
channel: string;
|
|
3
|
+
accountId: string;
|
|
4
|
+
conversationId: string;
|
|
5
|
+
speakerId: string;
|
|
6
|
+
speakerName?: string;
|
|
7
|
+
conversationType?: 'private' | 'group';
|
|
8
|
+
conversationName?: string;
|
|
9
|
+
platformMessageId?: string;
|
|
10
|
+
mentionIds?: string[];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Structured adapter metadata only; message text is never an identity source. */
|
|
14
|
+
export function speakerIdentity(value: unknown): SpeakerIdentity {
|
|
15
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('invalid identity');
|
|
16
|
+
const input = value as Record<string, unknown>;
|
|
17
|
+
for (const key of ['channel', 'accountId', 'conversationId', 'speakerId']) {
|
|
18
|
+
const field = input[key];
|
|
19
|
+
if (typeof field !== 'string' || !field.trim() || field.length > 256 || /[\u0000-\u001f\u007f]/.test(field)) throw new TypeError(`invalid ${key}`);
|
|
20
|
+
}
|
|
21
|
+
const channel = input.channel as string;
|
|
22
|
+
const speakerId = input.speakerId as string;
|
|
23
|
+
if (!/^[a-z][a-z0-9-]*$/.test(channel) || !speakerId.startsWith(`${channel}:`) || speakerId.length === channel.length + 1) throw new TypeError('invalid speakerId namespace');
|
|
24
|
+
for (const key of ['speakerName', 'conversationName']) if (input[key] !== undefined && (typeof input[key] !== 'string' || input[key].length > 256 || /[\u0000-\u001f\u007f]/.test(input[key]))) throw new TypeError(`invalid ${key}`);
|
|
25
|
+
if (input.conversationType !== undefined && input.conversationType !== 'private' && input.conversationType !== 'group') throw new TypeError('invalid conversationType');
|
|
26
|
+
if (input.platformMessageId !== undefined && (typeof input.platformMessageId !== 'string' || !input.platformMessageId.trim() || input.platformMessageId.length > 256 || /[\u0000-\u001f\u007f]/.test(input.platformMessageId))) throw new TypeError('invalid platformMessageId');
|
|
27
|
+
if (input.mentionIds !== undefined && (!Array.isArray(input.mentionIds) || input.mentionIds.length > 64 || input.mentionIds.some(id => typeof id !== 'string' || !id.startsWith(`${channel}:`) || id.length <= channel.length + 1 || id.length > 256 || /[\u0000-\u001f\u007f]/.test(id)))) throw new TypeError('invalid mentionIds');
|
|
28
|
+
return { channel, accountId: input.accountId as string, conversationId: input.conversationId as string, speakerId,
|
|
29
|
+
...(input.speakerName === undefined ? {} : { speakerName: input.speakerName as string }),
|
|
30
|
+
...(input.conversationType === undefined ? {} : { conversationType: input.conversationType as 'private' | 'group' }),
|
|
31
|
+
...(input.platformMessageId === undefined ? {} : { platformMessageId: input.platformMessageId as string }),
|
|
32
|
+
...(input.mentionIds === undefined ? {} : { mentionIds: [...input.mentionIds as string[]] }),
|
|
33
|
+
...(input.conversationName === undefined ? {} : { conversationName: input.conversationName as string }) };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function conversationKey(identity: SpeakerIdentity): string {
|
|
37
|
+
return JSON.stringify([identity.channel, identity.accountId, identity.conversationType ?? 'private', identity.conversationId]);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function identityPrefix(identity: SpeakerIdentity): string {
|
|
41
|
+
return `【消息来源 ${JSON.stringify(identity)}】\n`;
|
|
42
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Outlets: where her words go outside DSH. dsh-world knows no app by name; each outlet is a URL from the
|
|
5
|
+
* config that receives the documented push below. Any local app (a desktop pet, a tray app) can be one.
|
|
6
|
+
*/
|
|
7
|
+
export type PushKind = 'reply' | 'busy' | 'reach';
|
|
8
|
+
const PUSH_KINDS: readonly PushKind[] = ['reply', 'busy', 'reach'];
|
|
9
|
+
/** The body every outlet receives as JSON. `images` are picture URLs from her markdown; `image` is the expression name reach_out was given. */
|
|
10
|
+
export interface Push { text: string; kind: PushKind; name: string; images?: string[]; image?: string }
|
|
11
|
+
export interface OutletConfig {
|
|
12
|
+
name: string;
|
|
13
|
+
/** The full URL; `{origin}` is the DSH web server's own origin. */
|
|
14
|
+
url?: string;
|
|
15
|
+
/** A JSON file holding `baseUrl` (read before every push, so a new port is picked up), joined with `path`. */
|
|
16
|
+
urlFile?: string;
|
|
17
|
+
path?: string;
|
|
18
|
+
/** What it receives; all kinds when absent. */
|
|
19
|
+
kinds?: PushKind[];
|
|
20
|
+
}
|
|
21
|
+
export interface Outlet { name: string; kinds: readonly PushKind[]; send(push: Push): Promise<void> }
|
|
22
|
+
export const busyText = (name: string) => `${name}在忙,忙完会在家里回你`;
|
|
23
|
+
const message = (error: unknown) => error instanceof Error ? error.message : String(error);
|
|
24
|
+
|
|
25
|
+
/** `` or ``; one level of parentheses inside the URL is kept. */
|
|
26
|
+
const imagePattern = /!\[([^\]]*)\]\(\s*(<[^>]*>|(?:[^\s()]|\([^\s()]*\))+)(?:\s+"[^"]*")?\s*\)/g;
|
|
27
|
+
function imageUrl(raw: string, origin?: string): string | undefined {
|
|
28
|
+
const url = raw.startsWith('<') ? raw.slice(1, -1).trim() : raw;
|
|
29
|
+
// A sticker without an origin points at the DSH web server, which an outside app cannot reach by path alone.
|
|
30
|
+
const absolute = url.startsWith('/') && !url.startsWith('//') ? (origin ? new URL(url, origin).href : undefined) : url;
|
|
31
|
+
return absolute && /^https?:\/\//i.test(absolute) ? absolute : undefined;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Her markdown as an outlet shows it: sticker images apart, the text plain with its line breaks.
|
|
35
|
+
* A reply that is only stickers keeps their alt text, because an outlet may drop a push without text.
|
|
36
|
+
*/
|
|
37
|
+
export function plainMessage(markdown: string, origin?: string): { text: string; images: string[] } {
|
|
38
|
+
const images: string[] = [], alts: string[] = [];
|
|
39
|
+
const stripped = markdown.replace(imagePattern, (_match, alt: string, raw: string) => { const url = imageUrl(raw, origin); if (url) images.push(url); alts.push(alt.trim()); return ''; });
|
|
40
|
+
const text = stripped.replace(/\r\n?/g, '\n').replace(/\*\*|__|`/g, '').split('\n').map(line => line.replace(/^\s*#{1,6}\s+/, '').trim()).join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
41
|
+
return { text: text || (alts.length ? alts.filter(Boolean).join(' ') || '(表情包)' : ''), images };
|
|
42
|
+
}
|
|
43
|
+
export function pushOf(markdown: string, kind: PushKind, name: string, origin?: string, image?: string): Push {
|
|
44
|
+
const { text, images } = plainMessage(markdown, origin);
|
|
45
|
+
return { text, kind, name, ...(images.length ? { images } : {}), ...(image ? { image } : {}) };
|
|
46
|
+
}
|
|
47
|
+
export function readBaseUrl(file: string): string {
|
|
48
|
+
let raw: string;
|
|
49
|
+
try { raw = readFileSync(file, 'utf8'); } catch (error) { throw new Error(`${file} 读不到:${message(error)}`); }
|
|
50
|
+
let parsed: { baseUrl?: unknown };
|
|
51
|
+
// PowerShell's UTF-8 writer puts a BOM in front.
|
|
52
|
+
try { parsed = JSON.parse(raw.charCodeAt(0) === 0xfeff ? raw.slice(1) : raw); } catch { throw new Error(`${file} 不是有效的 JSON`); }
|
|
53
|
+
const baseUrl = typeof parsed?.baseUrl === 'string' ? parsed.baseUrl.trim() : '';
|
|
54
|
+
if (!/^https?:\/\/[^/]/i.test(baseUrl)) throw new Error(`${file} 里没有可用的 baseUrl`);
|
|
55
|
+
return baseUrl.replace(/\/+$/, '');
|
|
56
|
+
}
|
|
57
|
+
/** Resolved before every push: the DSH origin and an app's port can both change between runs. */
|
|
58
|
+
export function outletUrl(config: OutletConfig, origin: () => string): string {
|
|
59
|
+
if (config.url) return config.url.replace('{origin}', () => origin());
|
|
60
|
+
if (config.urlFile) return `${readBaseUrl(config.urlFile)}${config.path ?? ''}`;
|
|
61
|
+
throw new Error(`推送目标「${config.name}」没有 url 也没有 urlFile`);
|
|
62
|
+
}
|
|
63
|
+
/** A push counts as delivered on a 2xx whose JSON, if any, does not say `ok: false`. */
|
|
64
|
+
export function createOutlet(config: OutletConfig, origin: () => string, fetchImpl: typeof fetch = fetch): Outlet {
|
|
65
|
+
return {
|
|
66
|
+
name: config.name, kinds: config.kinds?.length ? config.kinds : PUSH_KINDS,
|
|
67
|
+
async send(push) {
|
|
68
|
+
const response = await fetchImpl(outletUrl(config, origin), {
|
|
69
|
+
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(push), signal: AbortSignal.timeout(5000),
|
|
70
|
+
});
|
|
71
|
+
const result = await response.json().catch(() => undefined) as { ok?: boolean; message?: string } | undefined;
|
|
72
|
+
if (!response.ok || result?.ok === false) throw new Error(result?.message ?? `HTTP ${response.status}`);
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import type { Agent } from '@deepseek-ai/dsh-agent';
|
|
3
|
+
import type {} from '@deepseek-ai/dsh-session';
|
|
4
|
+
import { conversationKey, type SpeakerIdentity } from './identity.ts';
|
|
5
|
+
import type { LifeHost } from '../../life/host.ts';
|
|
6
|
+
import type { ArchiveStore } from '../../store.ts';
|
|
7
|
+
|
|
8
|
+
export function createChannelSessions(deps: { ctx: Context; host: LifeHost; store: Pick<ArchiveStore, 'channelSession' | 'bindChannelSession'>; roomDir: string; roomTitle: string; agentPreset: string }) {
|
|
9
|
+
const opening = new Map<string, Promise<Agent>>();
|
|
10
|
+
const firstTitles = new Map<string, string>();
|
|
11
|
+
let stopped = false;
|
|
12
|
+
const dispose = deps.ctx.on('session/event', (session, event) => {
|
|
13
|
+
const title = firstTitles.get(session.id);
|
|
14
|
+
if (event.type !== 'turn/end' || !title || stopped) return;
|
|
15
|
+
firstTitles.delete(session.id);
|
|
16
|
+
void deps.host.rename(session.id, title).catch(error => deps.ctx.logger.error(error));
|
|
17
|
+
});
|
|
18
|
+
async function resolve(identity: SpeakerIdentity): Promise<Agent> {
|
|
19
|
+
if (stopped) throw new Error('Channel sessions stopped');
|
|
20
|
+
const key = conversationKey(identity);
|
|
21
|
+
const title = `${identity.channel === 'wechat' ? '微信' : identity.channel === 'qq' ? 'QQ' : identity.channel} · ${identity.conversationName || identity.conversationId}`;
|
|
22
|
+
const workspace = await deps.host.workspace(deps.roomDir, deps.roomTitle);
|
|
23
|
+
if (!workspace) throw new Error('群聊需要支持工作区的宿主');
|
|
24
|
+
let id = deps.store.channelSession(key);
|
|
25
|
+
let agent = id && !deps.host.isArchived(id) ? await deps.host.resolveAgent(id) : undefined;
|
|
26
|
+
if (!agent) {
|
|
27
|
+
if (stopped) throw new Error('Channel sessions stopped');
|
|
28
|
+
id = await deps.host.createSession(deps.roomDir, deps.agentPreset, workspace.id);
|
|
29
|
+
deps.store.bindChannelSession(key, id);
|
|
30
|
+
firstTitles.set(id, title);
|
|
31
|
+
agent = await deps.host.resolveAgent(id);
|
|
32
|
+
if (!agent) throw new Error('新建群聊会话无法打开');
|
|
33
|
+
} else if (!workspace.sessionIds.includes(agent.id)) await workspace.attachSession(agent.id);
|
|
34
|
+
if (stopped) throw new Error('Channel sessions stopped');
|
|
35
|
+
await deps.host.rename(agent.id, title);
|
|
36
|
+
return agent;
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
open(identity: SpeakerIdentity): Promise<Agent> {
|
|
40
|
+
const key = conversationKey(identity);
|
|
41
|
+
let pending = opening.get(key);
|
|
42
|
+
if (!pending) { pending = resolve(identity).finally(() => opening.delete(key)); opening.set(key, pending); }
|
|
43
|
+
return pending;
|
|
44
|
+
},
|
|
45
|
+
stop() { stopped = true; dispose(); firstTitles.clear(); },
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { ArchiveStore } from '../../store.ts';
|
|
2
|
+
import { conversationRecordId } from '../../archive.ts';
|
|
3
|
+
import type { SpeakerIdentity } from '../shared/identity.ts';
|
|
4
|
+
import type { WechatMessage } from './messages.ts';
|
|
5
|
+
import { replyText } from './messages.ts';
|
|
6
|
+
import type { ConversationRecord, DeliveryState } from '../../types.ts';
|
|
7
|
+
|
|
8
|
+
export interface WechatReceipt { id: string; confirmed: number; status: 'sent' | 'uncertain' | 'failed' }
|
|
9
|
+
|
|
10
|
+
export interface PreparedReply {
|
|
11
|
+
sessionId: string; messageId: string; seq: number; turn: number; time: number;
|
|
12
|
+
identity: SpeakerIdentity; messages: WechatMessage[];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function wechatDeliveryPatch(record: ConversationRecord, delivery: DeliveryState): Pick<ConversationRecord, 'content' | 'wechatDelivery'> {
|
|
16
|
+
if (delivery.status === 'pending') return { content: record.content, wechatDelivery: delivery };
|
|
17
|
+
const detail = delivery.status === 'sent' ? '整批已确认' : delivery.status === 'failed' ? '整批未发送' : `第 ${delivery.confirmed + 1} 条结果不明,后续未发送`;
|
|
18
|
+
return { content: `微信回复给 ${record.conversationId}(已确认发送 ${delivery.confirmed}/${delivery.total};${detail}):\n${record.content.slice(record.content.indexOf('\n') + 1)}`, wechatDelivery: delivery };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Preserve the generated words, not the tool protocol; delivery is confirmed separately by the adapter. */
|
|
22
|
+
export function createWechatRecorder(store: Pick<ArchiveStore, 'commitRecords' | 'hasRecord' | 'updateRecord' | 'delivery' | 'registerDelivery' | 'updateDelivery'>, worldId: string, archived: (sessionId: string) => boolean = () => true) {
|
|
23
|
+
async function record(reply: PreparedReply): Promise<string> {
|
|
24
|
+
const sourceMessageId = reply.messageId;
|
|
25
|
+
const recordId = conversationRecordId(worldId, reply.sessionId, sourceMessageId);
|
|
26
|
+
if (!archived(reply.sessionId)) { store.registerDelivery(recordId, reply.messages.length); return recordId; }
|
|
27
|
+
const content = `微信待发送给 ${reply.identity.conversationId}(已生成,发送尚未确认):\n` + replyText(reply.messages);
|
|
28
|
+
const projection: ConversationRecord = {
|
|
29
|
+
schemaVersion: 1, worldId, recordId,
|
|
30
|
+
sourceSessionId: reply.sessionId, sourceMessageId, sourceSeq: reply.seq,
|
|
31
|
+
turnId: `${reply.sessionId}:${reply.turn}`, role: 'assistant', occurredAt: new Date(reply.time).toISOString(),
|
|
32
|
+
content, status: 'complete', channel: 'wechat', accountId: reply.identity.accountId,
|
|
33
|
+
conversationId: reply.identity.conversationId, speakerId: `wechat:${reply.identity.accountId}`,
|
|
34
|
+
conversationType: reply.identity.conversationType, conversationName: reply.identity.conversationName,
|
|
35
|
+
wechatDelivery: { status: 'pending', confirmed: 0, total: reply.messages.length },
|
|
36
|
+
};
|
|
37
|
+
await store.commitRecords([projection]);
|
|
38
|
+
// Source archiving may win the insert; enrich the same final message in either order.
|
|
39
|
+
await store.updateRecord(recordId, current => current.wechatDelivery ? { content: current.content, wechatDelivery: current.wechatDelivery } : {
|
|
40
|
+
content, wechatDelivery: projection.wechatDelivery, channel: projection.channel, accountId: projection.accountId,
|
|
41
|
+
conversationId: projection.conversationId, speakerId: projection.speakerId,
|
|
42
|
+
conversationType: projection.conversationType, conversationName: projection.conversationName,
|
|
43
|
+
});
|
|
44
|
+
return recordId;
|
|
45
|
+
}
|
|
46
|
+
function confirmedDelivery(previous: DeliveryState, receipt: WechatReceipt): DeliveryState {
|
|
47
|
+
const { confirmed, status } = receipt;
|
|
48
|
+
if (!Number.isSafeInteger(confirmed) || confirmed < previous.confirmed || confirmed > previous.total
|
|
49
|
+
|| !['sent', 'uncertain', 'failed'].includes(status) || (status === 'sent') !== (confirmed === previous.total)
|
|
50
|
+
|| (status === 'failed' && confirmed !== 0) || (previous.status === 'sent' && status !== 'sent')) throw new Error('Invalid or stale WeChat receipt');
|
|
51
|
+
return { status, confirmed, total: previous.total };
|
|
52
|
+
}
|
|
53
|
+
async function receipt(receipt: WechatReceipt): Promise<void> {
|
|
54
|
+
if (store.delivery(receipt.id)) {
|
|
55
|
+
if (!store.hasRecord(receipt.id)) { store.updateDelivery(receipt.id, previous => confirmedDelivery(previous, receipt)); return; }
|
|
56
|
+
confirmedDelivery(store.delivery(receipt.id)!, receipt);
|
|
57
|
+
}
|
|
58
|
+
await store.updateRecord(receipt.id, record => {
|
|
59
|
+
const previous = record.wechatDelivery;
|
|
60
|
+
if (record.worldId !== worldId || record.channel !== 'wechat' || !previous) throw new Error('Not a WeChat reply');
|
|
61
|
+
const wechatDelivery = confirmedDelivery(previous, receipt);
|
|
62
|
+
return wechatDeliveryPatch(record, wechatDelivery);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
return { record, receipt };
|
|
66
|
+
}
|