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,88 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-world",
|
|
3
|
+
"version": "0.5.6-local.3",
|
|
4
|
+
"description": "Cross-session companion memory and life routines for DSH, with a world console, tool-free compaction and an independent Windows WeChat bridge",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/chenkezhen480/dsh-world.git"
|
|
9
|
+
},
|
|
10
|
+
"type": "module",
|
|
11
|
+
"main": "lib/index.js",
|
|
12
|
+
"types": "lib/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./lib/index.d.ts",
|
|
16
|
+
"default": "./lib/index.js"
|
|
17
|
+
},
|
|
18
|
+
"./compaction": {
|
|
19
|
+
"types": "./lib/compaction.d.ts",
|
|
20
|
+
"default": "./lib/compaction.js"
|
|
21
|
+
},
|
|
22
|
+
"./client": "./client/index.js",
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"lib",
|
|
27
|
+
"client",
|
|
28
|
+
"src/ecosystem/wechat/windows",
|
|
29
|
+
"src/ecosystem/README.md",
|
|
30
|
+
"templates",
|
|
31
|
+
"cordis.patch.yml",
|
|
32
|
+
"README.md",
|
|
33
|
+
"INSTALL.md",
|
|
34
|
+
"CONTRIBUTING.md",
|
|
35
|
+
"CHANGELOG.md",
|
|
36
|
+
"assets",
|
|
37
|
+
"scripts/enable-tool-free-compaction.ps1"
|
|
38
|
+
],
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=22.16.0"
|
|
41
|
+
},
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "node -e \"require('fs').rmSync('lib',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
|
|
44
|
+
"typecheck": "tsc --noEmit",
|
|
45
|
+
"test": "node --experimental-strip-types --disable-warning=ExperimentalWarning --test",
|
|
46
|
+
"prepack": "npm run typecheck && npm run build"
|
|
47
|
+
},
|
|
48
|
+
"dsh": {
|
|
49
|
+
"bundle": {
|
|
50
|
+
"patch": "./cordis.patch.yml"
|
|
51
|
+
},
|
|
52
|
+
"client": {
|
|
53
|
+
"inject": [
|
|
54
|
+
"@deepseek-ai/dsh-client-ui-settings"
|
|
55
|
+
],
|
|
56
|
+
"platform": "web"
|
|
57
|
+
},
|
|
58
|
+
"compatibility": {
|
|
59
|
+
"dshReleases": {
|
|
60
|
+
"0.2.1-rc.2": "compatible",
|
|
61
|
+
"0.2.1-rc.3": "compatible"
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"peerDependencies": {
|
|
66
|
+
"@deepseek-ai/cordis": "~4.0.5",
|
|
67
|
+
"@deepseek-ai/dsh-agent": ">=0.2.1-rc.2 <0.3.0-0",
|
|
68
|
+
"@deepseek-ai/dsh-attachment": ">=0.2.1-rc.2 <0.3.0-0",
|
|
69
|
+
"@deepseek-ai/dsh-compaction": ">=0.2.1-rc.2 <0.3.0-0",
|
|
70
|
+
"@deepseek-ai/dsh-home-paths": ">=0.2.1-rc.2 <0.3.0-0",
|
|
71
|
+
"@deepseek-ai/dsh-llm": ">=0.2.1-rc.2 <0.3.0-0",
|
|
72
|
+
"@deepseek-ai/dsh-session": ">=0.2.1-rc.2 <0.3.0-0",
|
|
73
|
+
"@deepseek-ai/dsh-session-persistence": ">=0.2.1-rc.2 <0.3.0-0",
|
|
74
|
+
"@deepseek-ai/dsh-tools": ">=0.2.1-rc.2 <0.3.0-0",
|
|
75
|
+
"@deepseek-ai/schemastery": "~3.18.5"
|
|
76
|
+
},
|
|
77
|
+
"devDependencies": {
|
|
78
|
+
"@deepseek-ai/dsh-agent-loop": "0.2.1-rc.2",
|
|
79
|
+
"@deepseek-ai/dsh-compaction-basic": "0.2.1-rc.2",
|
|
80
|
+
"@deepseek-ai/dsh-session-persistence-jsonl": "0.2.1-rc.2",
|
|
81
|
+
"@deepseek-ai/dsh-session-projection": "0.2.1-rc.2",
|
|
82
|
+
"@deepseek-ai/dsh-system-prompt": "0.2.1-rc.2",
|
|
83
|
+
"@deepseek-ai/dsh-token-meter": "0.2.1-rc.2",
|
|
84
|
+
"@deepseek-ai/dsh-tools": "0.2.1-rc.2",
|
|
85
|
+
"@types/node": "^22.16.0",
|
|
86
|
+
"typescript": "^5.9.3"
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[Parameter(Mandatory = $true)]
|
|
3
|
+
[string] $profilePath
|
|
4
|
+
)
|
|
5
|
+
|
|
6
|
+
$ErrorActionPreference = 'Stop'
|
|
7
|
+
try {
|
|
8
|
+
$resolvedProfile = (Resolve-Path -LiteralPath $profilePath).Path
|
|
9
|
+
$packagePath = Join-Path $resolvedProfile 'package.json'
|
|
10
|
+
$patchPath = Join-Path $resolvedProfile 'cordis.patch.yml'
|
|
11
|
+
$package = Get-Content -LiteralPath $packagePath -Raw | ConvertFrom-Json
|
|
12
|
+
if (-not $package.dependencies.'dsh-world') {
|
|
13
|
+
throw 'Install the built dsh-world package in this profile before enabling its compaction backend.'
|
|
14
|
+
}
|
|
15
|
+
$content = [System.IO.File]::ReadAllText($patchPath)
|
|
16
|
+
if ($content -match '(?m)^\s*name:\s*[''"'']?dsh-world/compaction[''"'']?\s*$') {
|
|
17
|
+
Write-Output 'Tool-free compaction is already configured.'
|
|
18
|
+
return
|
|
19
|
+
}
|
|
20
|
+
$pattern = '(?m)^(\s*name:\s*)([''"'']?)@deepseek-ai/dsh-compaction-basic\2([ \t]*(?:#.*)?\r?)$'
|
|
21
|
+
$matchesFound = [regex]::Matches($content, $pattern)
|
|
22
|
+
if ($matchesFound.Count -ne 1) {
|
|
23
|
+
throw "Expected exactly one explicit compaction-basic entry in cordis.patch.yml; found $($matchesFound.Count). No configuration was changed."
|
|
24
|
+
}
|
|
25
|
+
$updated = [regex]::Replace($content, $pattern, '${1}''dsh-world/compaction''${3}')
|
|
26
|
+
$backupPath = "$patchPath.dsh-world.$([Guid]::NewGuid().ToString('N')).bak"
|
|
27
|
+
$temporaryPath = "$patchPath.$([Guid]::NewGuid().ToString('N')).tmp"
|
|
28
|
+
[System.IO.File]::WriteAllText($temporaryPath, $updated, [System.Text.UTF8Encoding]::new($false))
|
|
29
|
+
[System.IO.File]::Replace($temporaryPath, $patchPath, $backupPath)
|
|
30
|
+
Write-Output "Configured tool-free compaction. Restart this DSH profile to load it. Backup: $backupPath"
|
|
31
|
+
} catch {
|
|
32
|
+
throw "Cannot configure dsh-world compaction: $($_.Exception.Message)"
|
|
33
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lastAssistantStreamChunk, type ContentBlock } from '@deepseek-ai/dsh-llm';
|
|
3
|
+
import { isAppendSurfaceEvent, type SessionEvent } from '@deepseek-ai/dsh-session';
|
|
4
|
+
import type { ArchiveScope, ConversationRecord } from './types.ts';
|
|
5
|
+
import { identityPrefix, speakerIdentity } from './ecosystem/shared/identity.ts';
|
|
6
|
+
import { replyMessages, replyText } from './ecosystem/wechat/messages.ts';
|
|
7
|
+
|
|
8
|
+
export const conversationRecordId = (worldId: string, sessionId: string, messageId: string) =>
|
|
9
|
+
createHash('sha256').update(JSON.stringify([worldId, sessionId, messageId])).digest('hex');
|
|
10
|
+
|
|
11
|
+
export function visibleText(content: readonly ContentBlock[]): string {
|
|
12
|
+
return content.flatMap(block => {
|
|
13
|
+
if (block.type === 'text') return [block.text];
|
|
14
|
+
if (block.type === 'image' || block.type === 'file') return [JSON.stringify({ type: block.type, attachment: block.attachment })];
|
|
15
|
+
return [];
|
|
16
|
+
}).join('\n');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function extractConversationRecords(event: SessionEvent, scope: ArchiveScope): ConversationRecord[] {
|
|
20
|
+
const { header } = scope;
|
|
21
|
+
if ((!scope.archiveScope && header.agentPreset !== scope.agentPreset) || header.origin === 'subagent' || (header.delegationDepth ?? 0) > 0 || event.seq < scope.inheritedEventCount) return [];
|
|
22
|
+
if (event.type !== 'user/message' && event.type !== 'assistant/message') return [];
|
|
23
|
+
if (!isAppendSurfaceEvent(event)) return [];
|
|
24
|
+
const message = event.type === 'user/message' ? event.data : event.data.message;
|
|
25
|
+
const outgoing = event.type === 'user/message' && event.data.source.kind === 'dsh-world-wechat-outgoing' ? event.data.source : undefined;
|
|
26
|
+
if (event.type === 'user/message' && message.source.kind !== 'user' && !outgoing) return [];
|
|
27
|
+
const identity = event.type === 'user/message' && 'identity' in message.source ? speakerIdentity(message.source.identity) : undefined;
|
|
28
|
+
const sentMessages = outgoing ? replyMessages(outgoing.messages) : undefined;
|
|
29
|
+
if (outgoing && (identity?.channel !== 'wechat' || identity.speakerId !== `wechat:${identity.accountId}`)) throw new Error('Invalid WeChat outgoing identity');
|
|
30
|
+
const visible = visibleText(message.content);
|
|
31
|
+
const prefix = identity ? identityPrefix(identity) : '';
|
|
32
|
+
const content = outgoing ? `微信待发送给 ${identity!.conversationId}(已生成,发送尚未确认):\n${replyText(sentMessages!)}` : prefix && visible.startsWith(prefix) ? visible.slice(prefix.length) : visible;
|
|
33
|
+
if (!content) return [];
|
|
34
|
+
const turn = event.type === 'assistant/message' ? event.data.turn : scope.turn;
|
|
35
|
+
if (!Number.isSafeInteger(turn) || turn < 1) throw new Error(`dsh-world: no host turn for ${header.id}/${event.seq}`);
|
|
36
|
+
return [{
|
|
37
|
+
schemaVersion: 1, worldId: scope.worldId,
|
|
38
|
+
recordId: conversationRecordId(scope.worldId, header.id, message.id),
|
|
39
|
+
sourceSessionId: header.id, sourceMessageId: message.id, sourceSeq: event.seq,
|
|
40
|
+
turnId: `${header.id}:${turn}`, role: event.type === 'user/message' && !outgoing ? 'user' : 'assistant',
|
|
41
|
+
occurredAt: new Date(event.time).toISOString(), content, ...identity,
|
|
42
|
+
...(sentMessages ? { wechatDelivery: { status: 'pending' as const, confirmed: 0, total: sentMessages.length } } : {}),
|
|
43
|
+
status: event.type === 'assistant/message' && (event.data.interrupted || lastAssistantStreamChunk(event.data.stream, 'finish')?.reason.kind === 'max-tokens') ? 'interrupted' : 'complete',
|
|
44
|
+
}];
|
|
45
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
2
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
3
|
+
import { inQqScope } from './qqScope.ts';
|
|
4
|
+
|
|
5
|
+
export type MemoryArchiveScope = 'home' | 'workspace';
|
|
6
|
+
export const validArchiveScope = (value: unknown): value is MemoryArchiveScope => value === 'home' || value === 'workspace';
|
|
7
|
+
|
|
8
|
+
/** Workspace membership comes from the host, never a preset or a display name. */
|
|
9
|
+
export function createArchiveSelection(
|
|
10
|
+
ctx: Context,
|
|
11
|
+
scope: MemoryArchiveScope,
|
|
12
|
+
isHome: (id: string) => boolean,
|
|
13
|
+
roomDir: string,
|
|
14
|
+
qq: { readonly scope?: string; readonly sessionsFile?: string } = {},
|
|
15
|
+
): (id: string) => boolean {
|
|
16
|
+
return id => {
|
|
17
|
+
// The QQ binding owns the memory: only the conversations it bound read and write this world.
|
|
18
|
+
if (qq.scope === 'qq') return inQqScope(id, qq.sessionsFile);
|
|
19
|
+
if (scope === 'home') return isHome(id);
|
|
20
|
+
const registry = ctx.get('workspaceRegistry') as { list(): { path: string; sessionIds: readonly string[] }[] } | undefined;
|
|
21
|
+
if (!registry) throw new Error('工作区归档需要宿主工作区服务');
|
|
22
|
+
const workspaces = registry.list();
|
|
23
|
+
const room = workspaces.find(workspace => workspace.sessionIds.some(isHome))
|
|
24
|
+
?? workspaces.find(workspace => workspace.path === (existsSync(roomDir) ? realpathSync(roomDir) : roomDir));
|
|
25
|
+
return room?.sessionIds.includes(id) ?? false;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis';
|
|
2
|
+
import z from '@deepseek-ai/schemastery';
|
|
3
|
+
import type {} from '@deepseek-ai/dsh-agent-loop';
|
|
4
|
+
import { CompactionEngine, ManualCompactionError, isCompactCheckpointSource, type CompactionAgentContext, type CompactionResult, type CompactionTrigger, type ManualCompactAgentContext } from '@deepseek-ai/dsh-compaction';
|
|
5
|
+
import type { CommandId } from '@deepseek-ai/dsh-commands/brand';
|
|
6
|
+
import { BlockAssembler, CONTEXT_WINDOW_EXCEEDED_CODE, LlmError, createUserMessage, type ContentBlock, type Message } from '@deepseek-ai/dsh-llm';
|
|
7
|
+
import { appendPluginRecord, type Session, type SessionSeq } from '@deepseek-ai/dsh-session';
|
|
8
|
+
import type {} from '@deepseek-ai/dsh-token-meter';
|
|
9
|
+
import { visibleText } from './archive.ts';
|
|
10
|
+
import { assertNoActiveCompaction, compactSurfaceRegion, selectWholeRange, type RegionAgent, type RegionDependencies, type SummaryResult } from './compactionRegion.ts';
|
|
11
|
+
import { formatTimeContext } from './timeContext.ts';
|
|
12
|
+
import './hostContract.ts';
|
|
13
|
+
|
|
14
|
+
const summaryInstruction = [
|
|
15
|
+
'现在暂停对话,改为执行上下文压缩:把上面这段会话中双方的交流整理成一段精炼的中文摘要,供你之后接着对话使用。',
|
|
16
|
+
'保留用户的意图、情绪与关系进展、明确要求、重要事实、已作决定、未完成事项和最近进展;最后一条用户发言尽量按原意完整保留。以“以下是此前交流的摘要”开头的消息是更早的摘要,请与新内容合并为同一段。',
|
|
17
|
+
'以【我的时间】(较早的是【你的时间】)开头的消息是你自己定的闹钟和留给自己的话,不是用户说的话;把它们当作你自己的安排来记,不要算作用户发言。',
|
|
18
|
+
'开头写着“这是我们最近的聊天记录”(较早的写着“最近的聊天记忆”或“最近的相处记忆”)的记忆资料、系统提示里的世界提示词(含「我是谁」)和“Time sampled”开头的时间块会在压缩后重新提供,不要写进摘要。工具调用过程已从会话中删除,不要提及工具。',
|
|
19
|
+
'保留准确的姓名、日期、数字和标识,分清每件事是谁说的、谁做的。不要标题、列表或分段,不要开头语,不要补写原文没有的事实,不要调用任何工具,直接输出摘要正文。',
|
|
20
|
+
].join('\n');
|
|
21
|
+
// The model tends to echo the checkpoint lead it saw on earlier summaries; the frame adds it once.
|
|
22
|
+
const leadEcho = /^以下是此前交流的摘要[^::]{0,40}[::]\s*/;
|
|
23
|
+
const checkpointLead ='以下是此前交流的摘要,工具调用过程已省略;请把它当作已知背景,直接接着当前对话继续:';
|
|
24
|
+
// Re-injected after every successful compaction by the memory runtime; replayed only as cacheable prefix.
|
|
25
|
+
const injectedSources = new Set(['time-context', 'dsh-world-history']);
|
|
26
|
+
|
|
27
|
+
interface SummaryAudit { policyVersion: 2; provider: string; model: string; maxTokens: number; instruction: string; timeContext: string; replayedMessageIds: string[] }
|
|
28
|
+
declare module '@deepseek-ai/dsh-session/types' {
|
|
29
|
+
interface PluginRecordMap { 'plugin:dsh-world/compaction-request': SummaryAudit }
|
|
30
|
+
}
|
|
31
|
+
interface Policy { thresholdRatio: number; headroomTokens: number; summarizationProvider: string; summarizationModel: string; maxTokens: number; maxOverflowRetries: number }
|
|
32
|
+
export interface ToolFreeCompactionConfig extends Partial<Policy> { timeZone?: string; auto?: boolean; modelPolicies?: (Partial<Policy> & { provider: string; model: string })[] }
|
|
33
|
+
interface Target { provider: string; model: string }
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The compacted span exactly as the conversation request sent it, minus every
|
|
37
|
+
* tool call and tool result, so the summary request shares the longest possible
|
|
38
|
+
* provider-cached prefix. Assistant text split around a removed call is rejoined.
|
|
39
|
+
*/
|
|
40
|
+
export function toolFreeMessages(messages: readonly Message[]): Message[] {
|
|
41
|
+
const kept: Message[] = [];
|
|
42
|
+
for (const message of messages) {
|
|
43
|
+
if (message.role === 'tool') continue;
|
|
44
|
+
if (message.role !== 'assistant') { kept.push(message); continue; }
|
|
45
|
+
const content = message.content.filter(block => block.type !== 'tool-call');
|
|
46
|
+
// A step that only reasoned before calling a tool has nothing left to say.
|
|
47
|
+
if (!content.some(block => block.type !== 'reasoning')) continue;
|
|
48
|
+
const previous = kept.at(-1);
|
|
49
|
+
if (previous?.role === 'assistant') kept[kept.length - 1] = { ...previous, content: [...previous.content, ...content] };
|
|
50
|
+
else kept.push(content.length === message.content.length ? message : { ...message, content });
|
|
51
|
+
}
|
|
52
|
+
return kept;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function hasConversation(messages: readonly Message[]): boolean {
|
|
56
|
+
return messages.some(message => (message.role === 'user' || message.role === 'assistant') && !injectedSources.has(message.source.kind) && !(message.role === 'user' && isCompactCheckpointSource(message.source)) && visibleText(message.content).trim());
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function routedTarget(session: Session): Target | undefined {
|
|
60
|
+
const config = session.requestHeader()?.config;
|
|
61
|
+
return config?.provider && config.model ? { provider: config.provider, model: config.model } : undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function resolvePolicy(config: ToolFreeCompactionConfig): Policy {
|
|
65
|
+
return {
|
|
66
|
+
thresholdRatio: config.thresholdRatio ?? 0.9, headroomTokens: config.headroomTokens ?? 65536,
|
|
67
|
+
summarizationProvider: config.summarizationProvider ?? '', summarizationModel: config.summarizationModel ?? '',
|
|
68
|
+
maxTokens: config.maxTokens ?? config.headroomTokens ?? 65536, maxOverflowRetries: config.maxOverflowRetries ?? 1,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Pressure failures specific to one routed model; warned once per target. */
|
|
73
|
+
class TargetConfigError extends Error {
|
|
74
|
+
readonly targetKey: string;
|
|
75
|
+
constructor(targetKey: string, message: string) { super(message); this.targetKey = targetKey; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Replacement for `@deepseek-ai/dsh-compaction-basic`: drops every tool call,
|
|
80
|
+
* tool result, tool schema and reasoning block from the compacted span, then
|
|
81
|
+
* replaces the whole conversation with one summary paragraph.
|
|
82
|
+
*/
|
|
83
|
+
export default class ToolFreeCompaction extends CompactionEngine {
|
|
84
|
+
static inject = ['llm', 'tokenMeter', 'sessions'];
|
|
85
|
+
static Config = z.object({
|
|
86
|
+
timeZone: z.string(), auto: z.boolean(),
|
|
87
|
+
thresholdRatio: z.number(), headroomTokens: z.natural(), summarizationProvider: z.string(), summarizationModel: z.string(),
|
|
88
|
+
maxTokens: z.natural(), maxOverflowRetries: z.natural(),
|
|
89
|
+
modelPolicies: z.array(z.object({ provider: z.string().required(), model: z.string().required(), thresholdRatio: z.number(), headroomTokens: z.natural(), summarizationProvider: z.string(), summarizationModel: z.string(), maxTokens: z.natural(), maxOverflowRetries: z.natural() })),
|
|
90
|
+
});
|
|
91
|
+
private readonly policy: Policy;
|
|
92
|
+
private readonly overrides: (Policy & Target)[];
|
|
93
|
+
private readonly timeZone: string;
|
|
94
|
+
private readonly warnedTargets = new Set<string>();
|
|
95
|
+
private readonly overflowRetries = new WeakMap<object, number>();
|
|
96
|
+
private readonly overflowAgents = new WeakMap<Session, object>();
|
|
97
|
+
|
|
98
|
+
constructor(ctx: Context, config: ToolFreeCompactionConfig = {}) {
|
|
99
|
+
super(ctx);
|
|
100
|
+
const source = Object.fromEntries(Object.entries(config).filter(([, value]) => value !== undefined)) as ToolFreeCompactionConfig;
|
|
101
|
+
this.timeZone = source.timeZone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
102
|
+
this.policy = resolvePolicy(source);
|
|
103
|
+
this.overrides = (source.modelPolicies ?? []).map(override => {
|
|
104
|
+
const entry = Object.fromEntries(Object.entries(override).filter(([, value]) => value !== undefined)) as typeof override;
|
|
105
|
+
const merged: ToolFreeCompactionConfig = { ...this.policy, ...entry };
|
|
106
|
+
if (entry.maxTokens === undefined && entry.headroomTokens !== undefined && source.maxTokens === undefined) merged.maxTokens = entry.headroomTokens;
|
|
107
|
+
return { ...resolvePolicy(merged), provider: entry.provider, model: entry.model };
|
|
108
|
+
});
|
|
109
|
+
if (source.auto ?? true) this.registerAutomaticCompaction();
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private policyFor(target: Target | undefined): Policy {
|
|
113
|
+
return (target && this.overrides.find(policy => policy.provider === target.provider && policy.model === target.model)) || this.policy;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
private registerAutomaticCompaction(): void {
|
|
117
|
+
const { ctx } = this;
|
|
118
|
+
const log = (result: CompactionResult, trigger: string) => ctx.logger.info(`compaction (${trigger}): replaced ${result.shadowedSeqs.length} surface nodes with one tool-free summary (~${result.shadowedTokenCount} tokens)`);
|
|
119
|
+
ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
|
|
120
|
+
if (!signal.aborted) try {
|
|
121
|
+
const result = await this.compactIfNeeded(agent, 'pressure', signal);
|
|
122
|
+
if (result) log(result, 'step pressure');
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error instanceof TargetConfigError) {
|
|
125
|
+
if (this.warnedTargets.has(error.targetKey)) return next();
|
|
126
|
+
this.warnedTargets.add(error.targetKey);
|
|
127
|
+
}
|
|
128
|
+
ctx.logger.warn(`step compaction failed: ${error instanceof Error ? error.message : String(error)}; continuing the turn`);
|
|
129
|
+
}
|
|
130
|
+
return next();
|
|
131
|
+
});
|
|
132
|
+
ctx.on('agent/status', ({ agent, status }) => { if (status === 'idle') this.overflowRetries.delete(agent); });
|
|
133
|
+
ctx.on('session/event', (session, event) => {
|
|
134
|
+
if (event.type !== 'assistant/message') return;
|
|
135
|
+
const agent = this.overflowAgents.get(session);
|
|
136
|
+
if (agent) this.overflowRetries.delete(agent);
|
|
137
|
+
});
|
|
138
|
+
ctx.on('agent/request-error', async ({ agent, failure, signal }, next) => {
|
|
139
|
+
if (failure.code !== CONTEXT_WINDOW_EXCEEDED_CODE || signal.aborted) return next();
|
|
140
|
+
this.overflowAgents.set(agent.session, agent);
|
|
141
|
+
const target = routedTarget(agent.session);
|
|
142
|
+
if (!target) return next();
|
|
143
|
+
const retries = this.overflowRetries.get(agent) ?? 0;
|
|
144
|
+
if (retries >= this.policyFor(target).maxOverflowRetries) return next();
|
|
145
|
+
const generation = agent.session.surface.replaceGeneration;
|
|
146
|
+
let result: CompactionResult | null;
|
|
147
|
+
try { result = await this.compactIfNeeded(agent, 'context-overflow', signal); } catch (error) {
|
|
148
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
149
|
+
if (!signal.aborted && agent.session.surface.replaceGeneration > generation) {
|
|
150
|
+
ctx.logger.warn(`context-overflow compaction failed after durable surface progress: ${message}; retrying from the replacement surface`);
|
|
151
|
+
this.overflowRetries.set(agent, retries + 1);
|
|
152
|
+
return { kind: 'retry' };
|
|
153
|
+
}
|
|
154
|
+
ctx.logger.warn(`context-overflow compaction failed: ${message}; ${signal.aborted ? 'cancellation prevents retry' : 'preserving the original request error'}`);
|
|
155
|
+
return next();
|
|
156
|
+
}
|
|
157
|
+
if (signal.aborted || agent.session.surface.replaceGeneration <= generation) return next();
|
|
158
|
+
if (result) log(result, 'context overflow recovery');
|
|
159
|
+
this.overflowRetries.set(agent, retries + 1);
|
|
160
|
+
return { kind: 'retry' };
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async compactIfNeeded(agent: CompactionAgentContext, trigger: CompactionTrigger, signal: AbortSignal): Promise<CompactionResult | null> {
|
|
165
|
+
const target = routedTarget(agent.session);
|
|
166
|
+
if (!target) return null;
|
|
167
|
+
const meter = this.ctx.tokenMeter;
|
|
168
|
+
if (trigger === 'context-overflow') {
|
|
169
|
+
const range = selectWholeRange(agent.session, meter.measure(agent.session));
|
|
170
|
+
return range && this.compactRegion(range.start, range.end, agent, signal);
|
|
171
|
+
}
|
|
172
|
+
const policy = this.policyFor(target);
|
|
173
|
+
const info = await this.ctx.llm.resolveModelInfo(target.provider, target.model, signal);
|
|
174
|
+
assertNoActiveCompaction(agent.session, 'automatic pressure compaction');
|
|
175
|
+
const key = `${target.provider}/${target.model}`;
|
|
176
|
+
if (!info.context) throw new TargetConfigError(key, `dsh-world/compaction: no context capacity for ${key}; configure contextWindow on that adapter model`);
|
|
177
|
+
const { contextWindow } = info.context;
|
|
178
|
+
const reserved = agent.session.requestHeader()?.config.maxTokens ?? info.defaultMaxTokens ?? 0;
|
|
179
|
+
const pressureBudget = contextWindow - reserved - policy.headroomTokens;
|
|
180
|
+
if (pressureBudget <= 0) throw new TargetConfigError(key, `dsh-world/compaction: ${key} reserves ${reserved} completion and ${policy.headroomTokens} headroom tokens of its ${contextWindow}-token window, leaving no pressure budget`);
|
|
181
|
+
const threshold = Math.floor(Math.min(contextWindow * policy.thresholdRatio, pressureBudget));
|
|
182
|
+
if (meter.measure(agent.session).totalTokens < threshold) return null;
|
|
183
|
+
const range = selectWholeRange(agent.session, meter.measure(agent.session));
|
|
184
|
+
if (!range) return null;
|
|
185
|
+
const result = await this.compactRegion(range.start, range.end, agent, signal);
|
|
186
|
+
const after = meter.measure(agent.session).totalTokens;
|
|
187
|
+
if (after >= threshold) throw new Error(`compaction still above threshold after summarizing the whole conversation (${after} estimated tokens >= threshold ${threshold})`);
|
|
188
|
+
return result;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
compactRegion(start: SessionSeq, end: SessionSeq, agent: CompactionAgentContext, signal?: AbortSignal): Promise<CompactionResult> {
|
|
192
|
+
return compactSurfaceRegion(this.dependencies(), agent, start, end, { owner: 'current-turn', stability: 'whole-surface' }, signal);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
compactNow(agent: ManualCompactAgentContext, signal: AbortSignal, sourceCommandId?: CommandId): Promise<CompactionResult | null> {
|
|
196
|
+
signal.throwIfAborted();
|
|
197
|
+
try {
|
|
198
|
+
return agent.runMaintenance(async agentSignal => {
|
|
199
|
+
const operationSignal = AbortSignal.any([agentSignal, signal]);
|
|
200
|
+
try {
|
|
201
|
+
operationSignal.throwIfAborted();
|
|
202
|
+
const range = selectWholeRange(agent.session, this.ctx.tokenMeter.measure(agent.session));
|
|
203
|
+
if (!range) return null;
|
|
204
|
+
return await compactSurfaceRegion(this.dependencies(), agent, range.start, range.end, {
|
|
205
|
+
owner: null, stability: 'selected-span', ...(sourceCommandId === undefined ? {} : { sourceCommandId }),
|
|
206
|
+
flush: async () => { await this.ctx.sessions.flush(agent.session); },
|
|
207
|
+
}, operationSignal);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
if (agentSignal.aborted && operationSignal.reason === agentSignal.reason) throw new ManualCompactionError('cancelled', 'manual compaction was cancelled', { cause: error });
|
|
210
|
+
operationSignal.throwIfAborted();
|
|
211
|
+
throw error;
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
} catch (error) {
|
|
215
|
+
throw new ManualCompactionError('busy', 'manual compaction requires an idle agent with no waking queued work', { cause: error });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
private dependencies(): RegionDependencies {
|
|
220
|
+
return {
|
|
221
|
+
meter: this.ctx.tokenMeter,
|
|
222
|
+
summarize: (messages, agent, signal) => this.summarize(messages, agent, signal),
|
|
223
|
+
frame: summary => [{ type: 'text', text: `${checkpointLead}${summary.map(block => block.type === 'text' ? block.text : '').join('')}` }],
|
|
224
|
+
recover: (error, agent, sourceEventSeqs, signal) => this.ctx.waterfall('compaction/summary-error', { session: agent.session, sourceEventSeqs, error, ...(signal === undefined ? {} : { signal }) }, () => false),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
protected async summarize(messages: Message[], agent: RegionAgent, signal?: AbortSignal): Promise<SummaryResult> {
|
|
229
|
+
signal?.throwIfAborted();
|
|
230
|
+
const routed = routedTarget(agent.session) ?? (agent.options.provider && agent.options.model ? { provider: agent.options.provider, model: agent.options.model } : undefined);
|
|
231
|
+
const policy = this.policyFor(routed);
|
|
232
|
+
const provider = policy.summarizationProvider || routed?.provider;
|
|
233
|
+
const model = policy.summarizationModel || routed?.model;
|
|
234
|
+
const { maxTokens } = policy;
|
|
235
|
+
if (!provider || !model) throw new Error('dsh-world: no provider/model configured for compaction');
|
|
236
|
+
const replayed = toolFreeMessages(messages);
|
|
237
|
+
if (!hasConversation(replayed)) throw new Error('dsh-world: no visible conversation remains to summarize');
|
|
238
|
+
const { session } = agent;
|
|
239
|
+
const head = session.surface.nodes[0] === undefined ? undefined : session.eventAt(session.surface.nodes[0]);
|
|
240
|
+
const system = head?.type === 'system/message' ? session.deriveEventMessage(head) : null;
|
|
241
|
+
const header = session.requestHeader();
|
|
242
|
+
const timeContext = formatTimeContext(new Date(), this.timeZone);
|
|
243
|
+
appendPluginRecord(session, 'plugin:dsh-world/compaction-request', { policyVersion: 2, provider, model, maxTokens, instruction: summaryInstruction, timeContext, replayedMessageIds: replayed.map(message => message.id) });
|
|
244
|
+
await this.ctx.sessions.flush(session);
|
|
245
|
+
const request = [
|
|
246
|
+
...(system ? [system] : []), ...replayed,
|
|
247
|
+
createUserMessage({ source: { kind: 'dsh-world-summary-input' }, content: [{ type: 'text', text: `${summaryInstruction}\n\n${timeContext}` }] }),
|
|
248
|
+
];
|
|
249
|
+
const assembler = new BlockAssembler();
|
|
250
|
+
for await (const chunk of this.ctx.llm.stream({ provider, model, maxTokens, messages: request, ...(header?.tools === undefined ? {} : { tools: [...header.tools] }), toolHistory: session.toolHistory(), sessionId: session.id, purpose: 'compaction', ...(signal === undefined ? {} : { signal }) })) assembler.push(chunk);
|
|
251
|
+
signal?.throwIfAborted();
|
|
252
|
+
const finish = assembler.finish;
|
|
253
|
+
if (finish.kind === 'error' || finish.kind === 'aborted') throw new LlmError(finish.failure.message, finish.failure.code, finish.failure);
|
|
254
|
+
if (finish.kind !== 'stop') throw new Error(`dsh-world: compaction summary truncated or invalid (${finish.kind})`);
|
|
255
|
+
const rawOutput: ContentBlock[] = assembler.blocks();
|
|
256
|
+
const text = rawOutput.flatMap(block => block.type === 'text' ? [block.text.trim()] : []).join(' ').replace(/\s*\r?\n\s*/g, ' ').trim().replace(leadEcho, '').trim();
|
|
257
|
+
if (!text) throw new Error('dsh-world: summarizer returned no paragraph');
|
|
258
|
+
return { summary: [{ type: 'text', text }], rawOutput, provider, model, maxTokens, ...(assembler.usage ? { usage: assembler.usage } : {}) };
|
|
259
|
+
}
|
|
260
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Surface transaction adapted from @deepseek-ai/dsh-compaction-basic@0.2.1-rc.2 (MIT, Copyright (c) 2026 DeepSeek).
|
|
2
|
+
// Kept local so the stock package is used unmodified; selection here always runs to the newest balanced cut.
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
5
|
+
import { CompactionId, ManualCompactionError, compactCheckpointSource, toolPairingBalancedAfter, toolPairingBalancedBefore, type CompactionResult } from '@deepseek-ai/dsh-compaction';
|
|
6
|
+
import type { CommandId } from '@deepseek-ai/dsh-commands/brand';
|
|
7
|
+
import { createUserMessage, errorChain, type ContentBlock, type Message, type TokenUsage, type UserMessage } from '@deepseek-ai/dsh-llm';
|
|
8
|
+
import { SessionSeq, type Session } from '@deepseek-ai/dsh-session';
|
|
9
|
+
import type { TokenMeasurement, TokenSurfaceNode } from '@deepseek-ai/dsh-token-meter';
|
|
10
|
+
|
|
11
|
+
export interface SummaryResult { summary: ContentBlock[]; rawOutput: ContentBlock[]; provider: string; model: string; maxTokens: number; usage?: TokenUsage }
|
|
12
|
+
export interface RegionAgent { session: Session; options: { provider?: string; model?: string } }
|
|
13
|
+
export interface RegionDependencies {
|
|
14
|
+
meter: { measure(session: Session): TokenMeasurement; estimateMessage(message: Message): number };
|
|
15
|
+
summarize(messages: Message[], agent: RegionAgent, signal?: AbortSignal): Promise<SummaryResult>;
|
|
16
|
+
frame(summary: ContentBlock[]): ContentBlock[];
|
|
17
|
+
recover(error: unknown, agent: RegionAgent, seqs: readonly SessionSeq[], signal?: AbortSignal): boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface RegionOptions { owner: 'current-turn' | null; stability: 'whole-surface' | 'selected-span'; sourceCommandId?: CommandId; flush?: () => Promise<void> }
|
|
20
|
+
interface Selection { start: SessionSeq; end: SessionSeq; startIdx: number; endIdx: number; shadowedSeqs: readonly SessionSeq[] }
|
|
21
|
+
interface Prepared extends Selection { measurement: TokenMeasurement; selectedNodes: readonly TokenSurfaceNode[]; shadowedTokenCount: number; shadowedRouteTokenCount: number; messages: Message[] }
|
|
22
|
+
type Summarized = Prepared & SummaryResult & { checkpointMessage: UserMessage };
|
|
23
|
+
|
|
24
|
+
function eventAt(session: Session, seq: SessionSeq) {
|
|
25
|
+
const event = session.eventAt(seq);
|
|
26
|
+
if (event === undefined) throw new Error(`compaction: session seq ${seq} has no event`);
|
|
27
|
+
return event;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
class SurfaceChangedError extends Error {}
|
|
31
|
+
|
|
32
|
+
/** Everything after the system head through the newest cut that splits no tool call from its result. */
|
|
33
|
+
export function selectWholeRange(session: Session, measurement: TokenMeasurement): { start: SessionSeq; end: SessionSeq } | null {
|
|
34
|
+
const nodes = session.surface.nodes;
|
|
35
|
+
if (!nodes.length) return null;
|
|
36
|
+
if (nodes.length !== measurement.nodes.length || nodes.some((seq, index) => seq !== measurement.nodes[index]?.seq)) throw new Error('compaction: token-meter surface does not match the current session surface');
|
|
37
|
+
const firstIdx = eventAt(session, nodes[0]).type === 'system/message' ? 1 : 0;
|
|
38
|
+
let endIdx = nodes.length - 1;
|
|
39
|
+
while (endIdx >= firstIdx && !toolPairingBalancedAfter(session, nodes[endIdx])) endIdx -= 1;
|
|
40
|
+
return endIdx < firstIdx ? null : { start: nodes[firstIdx], end: nodes[endIdx] };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export async function compactSurfaceRegion(deps: RegionDependencies, agent: RegionAgent, start: SessionSeq, end: SessionSeq, options: RegionOptions, signal?: AbortSignal): Promise<CompactionResult> {
|
|
44
|
+
const { session } = agent;
|
|
45
|
+
if (options.owner === null) signal?.throwIfAborted();
|
|
46
|
+
const selection = validateSurfaceRegion(session, start, end);
|
|
47
|
+
const entry = inspectEntryState(session);
|
|
48
|
+
assertInactive(entry, 'compaction');
|
|
49
|
+
if (options.owner === null && entry.openTurn !== null) throw new ManualCompactionError('busy', 'manual compaction: the session already has an open turn');
|
|
50
|
+
if (options.owner !== null && entry.openTurn === null) throw new Error('compactRegion: no open turn — automatic compaction events must be enclosed in a turn');
|
|
51
|
+
const lifecycle = { compactionId: CompactionId(randomUUID()), ...(options.sourceCommandId === undefined ? {} : { sourceCommandId: options.sourceCommandId }), turn: options.owner === null ? null : entry.openTurn };
|
|
52
|
+
const startEvent = session.append('compaction/start', lifecycle);
|
|
53
|
+
const assertStable = options.stability === 'whole-surface' ? assertWholeSurfaceUnchanged : assertSelectedSpanStable;
|
|
54
|
+
let failure: { error: unknown; stage: 'summary' | 'commit' } | undefined;
|
|
55
|
+
let flushFailure: unknown;
|
|
56
|
+
let result: CompactionResult | undefined;
|
|
57
|
+
let closed = false; let closing = false; let stage: 'summary' | 'commit' = 'summary';
|
|
58
|
+
try {
|
|
59
|
+
const summarized = await summarize(deps, prepare(deps, session, selection), agent, lifecycle.compactionId, options.sourceCommandId, assertStable, signal);
|
|
60
|
+
if (options.owner === null) signal?.throwIfAborted();
|
|
61
|
+
assertStable(deps, session, summarized);
|
|
62
|
+
stage = 'commit';
|
|
63
|
+
const pending = commitBody(session, startEvent.seq, lifecycle, summarized);
|
|
64
|
+
closing = true;
|
|
65
|
+
const endEvent = session.append('compaction/end', lifecycle);
|
|
66
|
+
closed = true;
|
|
67
|
+
result = { ...pending, endSeq: endEvent.seq };
|
|
68
|
+
} catch (error) {
|
|
69
|
+
failure = { error, stage: closing ? 'commit' : stage };
|
|
70
|
+
if (!closing) {
|
|
71
|
+
closing = true;
|
|
72
|
+
try { session.append('compaction/end', { ...lifecycle, error: errorChain(error) }); closed = true; } catch (closeError) { failure = { error: closeError, stage: 'commit' }; }
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (closed && options.flush) try { await options.flush(); } catch (error) { flushFailure = error; }
|
|
76
|
+
if (options.owner === null) signal?.throwIfAborted();
|
|
77
|
+
if (failure) {
|
|
78
|
+
if (options.owner !== null) throw failure.error;
|
|
79
|
+
if (failure.stage === 'commit') throw new ManualCompactionError('commit', 'manual compaction did not commit cleanly', { cause: failure.error });
|
|
80
|
+
if (failure.error instanceof SurfaceChangedError) throw new ManualCompactionError('changed', 'the compacted history changed during manual compaction', { cause: failure.error });
|
|
81
|
+
throw new ManualCompactionError('summary', 'manual compaction could not produce a smaller summary', { cause: failure.error });
|
|
82
|
+
}
|
|
83
|
+
if (flushFailure !== undefined) throw new ManualCompactionError('persistence', 'manual compaction durability checkpoint failed', { cause: flushFailure });
|
|
84
|
+
return result!;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function assertNoActiveCompaction(session: Session, stage: string): void { assertInactive(inspectEntryState(session), stage); }
|
|
88
|
+
|
|
89
|
+
function assertInactive(entry: ReturnType<typeof inspectEntryState>, stage: string): void {
|
|
90
|
+
if (entry.unmatchedStart === undefined || (entry.latestEndSeedSeq !== undefined && entry.latestEndSeedSeq > entry.unmatchedStart)) return;
|
|
91
|
+
throw new ManualCompactionError('busy', `${stage}: compaction already in progress; the session compaction lock is already active`);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function validateSurfaceRegion(session: Session, start: SessionSeq, end: SessionSeq): Selection {
|
|
95
|
+
const nodes = session.surface.nodes;
|
|
96
|
+
const startIdx = nodes.indexOf(start); const endIdx = nodes.indexOf(end);
|
|
97
|
+
if (startIdx === -1) throw new Error(`compactRegion: start seq ${start} not found in surface`);
|
|
98
|
+
if (endIdx === -1) throw new Error(`compactRegion: end seq ${end} not found in surface`);
|
|
99
|
+
if (startIdx > endIdx) throw new Error(`compactRegion: start seq ${start} is after end seq ${end} on the surface`);
|
|
100
|
+
if (!toolPairingBalancedBefore(session, nodes[startIdx])) throw new Error(`compactRegion: start seq ${start} would split a tool-call/result pair`);
|
|
101
|
+
if (!toolPairingBalancedAfter(session, nodes[endIdx])) throw new Error(`compactRegion: end seq ${end} would split a tool-call/result pair, or the step is still open`);
|
|
102
|
+
return { start, end, startIdx, endIdx, shadowedSeqs: nodes.slice(startIdx, endIdx + 1) };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function prepare(deps: RegionDependencies, session: Session, selection: Selection): Prepared {
|
|
106
|
+
const measurement = deps.meter.measure(session);
|
|
107
|
+
const selectedNodes = measurement.nodes.slice(selection.startIdx, selection.endIdx + 1);
|
|
108
|
+
if (selectedNodes.length !== selection.shadowedSeqs.length || selectedNodes.some((node, index) => node.seq !== selection.shadowedSeqs[index])) throw new SurfaceChangedError('compaction: selected surface changed before summarization began');
|
|
109
|
+
return {
|
|
110
|
+
...selection, measurement, selectedNodes,
|
|
111
|
+
shadowedTokenCount: selectedNodes.reduce((total, node) => total + node.heuristicTokens, 0),
|
|
112
|
+
shadowedRouteTokenCount: selectedNodes.reduce((total, node) => total + node.tokens, 0),
|
|
113
|
+
messages: selection.shadowedSeqs.map(seq => session.deriveEventMessage(eventAt(session, seq))).filter((message): message is Message => message !== null),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async function summarize(deps: RegionDependencies, prepared: Prepared, agent: RegionAgent, compactionId: CompactionId, sourceCommandId: CommandId | undefined, assertStable: typeof assertWholeSurfaceUnchanged, signal?: AbortSignal): Promise<Summarized> {
|
|
118
|
+
let summary: SummaryResult;
|
|
119
|
+
for (;;) {
|
|
120
|
+
signal?.throwIfAborted();
|
|
121
|
+
try { summary = await deps.summarize(prepared.messages, agent, signal); break; } catch (error) {
|
|
122
|
+
if (signal?.aborted) throw error;
|
|
123
|
+
assertStable(deps, agent.session, prepared);
|
|
124
|
+
if (!deps.recover(error, agent, prepared.shadowedSeqs, signal)) throw error;
|
|
125
|
+
prepared = prepare(deps, agent.session, validateSurfaceRegion(agent.session, prepared.start, prepared.end));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const checkpointMessage = createUserMessage({ content: deps.frame(summary.summary), source: compactCheckpointSource(compactionId, sourceCommandId) });
|
|
129
|
+
const framed = deps.meter.estimateMessage(checkpointMessage);
|
|
130
|
+
if (framed >= prepared.shadowedRouteTokenCount) throw new Error(`summary is not smaller than the shadowed content (${framed} estimated framed tokens >= ${prepared.shadowedRouteTokenCount})`);
|
|
131
|
+
return { ...prepared, ...summary, checkpointMessage };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function assertWholeSurfaceUnchanged(deps: RegionDependencies, session: Session, prepared: Prepared): void {
|
|
135
|
+
if (!isDeepStrictEqual(deps.meter.measure(session).nodes, prepared.measurement.nodes)) throw new SurfaceChangedError('compaction: session surface changed during summarization');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function assertSelectedSpanStable(deps: RegionDependencies, session: Session, prepared: Prepared): void {
|
|
139
|
+
let current: Selection;
|
|
140
|
+
try { current = validateSurfaceRegion(session, prepared.start, prepared.end); } catch (error) { throw new SurfaceChangedError('compaction: the selected span is no longer a valid replacement target', { cause: error }); }
|
|
141
|
+
if (!isDeepStrictEqual([...current.shadowedSeqs], [...prepared.shadowedSeqs])) throw new SurfaceChangedError('compaction: the selected span changed during summarization');
|
|
142
|
+
if (!isDeepStrictEqual(deps.meter.measure(session).nodes.slice(current.startIdx, current.endIdx + 1), prepared.selectedNodes)) throw new SurfaceChangedError('compaction: the selected span was rewritten during summarization');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function commitBody(session: Session, startSeq: SessionSeq, lifecycle: { compactionId: CompactionId; sourceCommandId?: CommandId }, summarized: Summarized): Omit<CompactionResult, 'endSeq'> {
|
|
146
|
+
const { start, end, shadowedSeqs, shadowedTokenCount, summary, rawOutput, provider, model, maxTokens, usage, checkpointMessage } = summarized;
|
|
147
|
+
const { compactionId, sourceCommandId } = lifecycle;
|
|
148
|
+
const command = sourceCommandId === undefined ? {} : { sourceCommandId };
|
|
149
|
+
const summaryEvent = session.append('compaction/summary', {
|
|
150
|
+
compactionId, ...command, summary, rawOutput, shadowedRange: { start, end }, shadowedSeqs: [...shadowedSeqs], shadowedTokenCount, provider, model, maxTokens, ...(usage === undefined ? {} : { usage }),
|
|
151
|
+
});
|
|
152
|
+
session.append('user/message', checkpointMessage, { surfaceOp: { op: 'replace', startSeq: start, endSeq: end }, sourceEventSeqs: [startSeq, summaryEvent.seq, ...shadowedSeqs] });
|
|
153
|
+
return { compactionId, ...command, startSeq, summarySeq: summaryEvent.seq, summary, shadowedRange: { start, end }, shadowedSeqs: [...shadowedSeqs], shadowedTokenCount };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function inspectEntryState(session: Session) {
|
|
157
|
+
let openTurn: number | null = null; let turnKnown = false;
|
|
158
|
+
let unmatchedStart: SessionSeq | undefined; let lockKnown = false;
|
|
159
|
+
let latestEndSeedSeq: SessionSeq | undefined;
|
|
160
|
+
for (let seq = session.seq - 1; seq >= 0; seq -= 1) {
|
|
161
|
+
const event = eventAt(session, SessionSeq(seq));
|
|
162
|
+
if (latestEndSeedSeq === undefined && event.type === 'session/end-seed') latestEndSeedSeq = event.seq;
|
|
163
|
+
if (!lockKnown) {
|
|
164
|
+
if (event.type === 'compaction/start') { unmatchedStart = event.seq; lockKnown = true; } else if (event.type === 'compaction/end') lockKnown = true;
|
|
165
|
+
}
|
|
166
|
+
if (!turnKnown) {
|
|
167
|
+
if (event.type === 'turn/start') { openTurn = event.data.turn; turnKnown = true; } else if (event.type === 'turn/end') turnKnown = true;
|
|
168
|
+
}
|
|
169
|
+
if (turnKnown && lockKnown && latestEndSeedSeq !== undefined) break;
|
|
170
|
+
}
|
|
171
|
+
return { openTurn, unmatchedStart, latestEndSeedSeq };
|
|
172
|
+
}
|