dsh-world 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +379 -347
  2. package/INSTALL.md +314 -314
  3. package/LICENSE +21 -21
  4. package/NOTES.md +32 -10
  5. package/README.md +7 -6
  6. package/client/index.js +58 -3
  7. package/cordis.patch.yml +6 -6
  8. package/lib/archive.d.ts +3 -1
  9. package/lib/archive.js +6 -4
  10. package/lib/console/routes.d.ts +7 -0
  11. package/lib/console/routes.js +26 -8
  12. package/lib/console/snapshot.d.ts +7 -0
  13. package/lib/console/snapshot.js +3 -2
  14. package/lib/ecosystem/qq/route.d.ts +2 -1
  15. package/lib/ecosystem/qq/route.js +10 -2
  16. package/lib/ecosystem/qq-native/batch.d.ts +2 -0
  17. package/lib/ecosystem/qq-native/batch.js +3 -1
  18. package/lib/ecosystem/qq-native/home.d.ts +1 -0
  19. package/lib/ecosystem/qq-native/home.js +10 -3
  20. package/lib/ecosystem/qq-native/index.d.ts +2 -0
  21. package/lib/ecosystem/qq-native/index.js +21 -4
  22. package/lib/ecosystem/qq-native/native-bridge.js +5 -2
  23. package/lib/ecosystem/qq-native/replies.d.ts +7 -1
  24. package/lib/ecosystem/qq-native/replies.js +30 -1
  25. package/lib/ecosystem/shared/context.d.ts +6 -1
  26. package/lib/ecosystem/shared/context.js +6 -1
  27. package/lib/ecosystem/shared/identity.d.ts +12 -0
  28. package/lib/ecosystem/shared/identity.js +17 -1
  29. package/lib/ecosystem/shared/turn.d.ts +8 -5
  30. package/lib/ecosystem/shared/turn.js +16 -17
  31. package/lib/ecosystem/wechat/archive.d.ts +2 -0
  32. package/lib/ecosystem/wechat/archive.js +3 -1
  33. package/lib/ecosystem/wechat/home.js +9 -4
  34. package/lib/ecosystem/wechat/messages.d.ts +11 -0
  35. package/lib/ecosystem/wechat/messages.js +9 -1
  36. package/lib/ecosystem/wechat/sending.js +36 -9
  37. package/lib/ecosystem/wechat/supervisor.d.ts +11 -2
  38. package/lib/ecosystem/wechat/supervisor.js +90 -9
  39. package/lib/history.d.ts +6 -4
  40. package/lib/history.js +61 -12
  41. package/lib/hostContract.d.ts +4 -1
  42. package/lib/index.d.ts +1 -0
  43. package/lib/index.js +27 -7
  44. package/lib/life/activity.d.ts +2 -0
  45. package/lib/life/activity.js +1 -1
  46. package/lib/life/alarm.d.ts +12 -4
  47. package/lib/life/alarm.js +21 -6
  48. package/lib/life/diary.d.ts +6 -0
  49. package/lib/life/diary.js +23 -2
  50. package/lib/life/runtime.d.ts +1 -0
  51. package/lib/life/runtime.js +57 -9
  52. package/lib/life/toolRegistry.d.ts +4 -3
  53. package/lib/life/toolRegistry.js +13 -3
  54. package/lib/life/types.d.ts +6 -1
  55. package/lib/memory.js +1 -4
  56. package/lib/memoryFiles.d.ts +1 -4
  57. package/lib/memoryFiles.js +18 -43
  58. package/lib/memoryStore.d.ts +1 -3
  59. package/lib/memoryStore.js +1 -1
  60. package/lib/memoryTools.js +2 -2
  61. package/lib/promptSection.d.ts +5 -4
  62. package/lib/promptSection.js +9 -8
  63. package/lib/runtime.d.ts +8 -3
  64. package/lib/runtime.js +60 -94
  65. package/lib/sourceArchive.js +4 -5
  66. package/lib/store.d.ts +1 -1
  67. package/lib/store.js +1 -1
  68. package/lib/types.d.ts +1 -4
  69. package/lib/worldPrompt.js +1 -1
  70. package/lib/worldSwitch.d.ts +15 -1
  71. package/lib/worldSwitch.js +24 -1
  72. package/package.json +1 -1
  73. package/scripts/compact-home.mjs +29 -29
  74. package/scripts/enable-tool-free-compaction.ps1 +33 -33
  75. package/scripts/import-stickers.mjs +17 -17
  76. package/scripts/update-world.mjs +2 -2
  77. package/src/ecosystem/wechat/windows/README.md +5 -3
  78. package/src/ecosystem/wechat/windows/adapter.py +6 -0
  79. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  80. package/src/ecosystem/wechat/windows/engine/build.ps1 +8 -2
  81. package/src/ecosystem/wechat/windows/engine/profiles.json +142 -114
  82. package/src/ecosystem/wechat/windows/presence.py +109 -109
  83. package/src/ecosystem/wechat/windows/sender.py +17 -5
  84. package/templates/alarm.md +1 -1
@@ -1,17 +1,17 @@
1
- // One-time import of the older sticker plugin's library (catalog.json + assets/) into the world's own sticker library.
2
- // Usage: node scripts/import-stickers.mjs <older library folder, e.g. ~/.dsh/memes> <world folder, e.g. ~/.dsh/worlds/<id>>
3
- // Ids, names and tags carry over; packs and long meanings do not. Running it again adds nothing. The older folder is only read.
4
- import { join, resolve } from 'node:path';
5
- import { pathToFileURL, fileURLToPath } from 'node:url';
6
-
7
- const [legacy, world] = process.argv.slice(2);
8
- if (!legacy || !world) {
9
- console.error('用法:node scripts/import-stickers.mjs <旧表情包目录> <世界目录>');
10
- process.exit(2);
11
- }
12
- const modulePath = join(fileURLToPath(new URL('..', import.meta.url)), 'lib', 'ecosystem', 'wechat', 'stickerLibrary.js');
13
- const { createStickerLibrary, importLegacyStickers } = await import(pathToFileURL(modulePath).href);
14
- const library = createStickerLibrary(join(resolve(world), 'stickers'));
15
- const report = await importLegacyStickers(resolve(legacy), library);
16
- console.log(`导入 ${report.imported} 张,已在库里的 ${report.duplicates} 张,跳过 ${report.skipped.length} 张;表情库现有 ${(await library.list()).length} 张。`);
17
- for (const line of report.skipped) console.log(` 跳过 ${line}`);
1
+ // One-time import of the older sticker plugin's library (catalog.json + assets/) into the world's own sticker library.
2
+ // Usage: node scripts/import-stickers.mjs <older library folder, e.g. ~/.dsh/memes> <world folder, e.g. ~/.dsh/worlds/<id>>
3
+ // Ids, names and tags carry over; packs and long meanings do not. Running it again adds nothing. The older folder is only read.
4
+ import { join, resolve } from 'node:path';
5
+ import { pathToFileURL, fileURLToPath } from 'node:url';
6
+
7
+ const [legacy, world] = process.argv.slice(2);
8
+ if (!legacy || !world) {
9
+ console.error('用法:node scripts/import-stickers.mjs <旧表情包目录> <世界目录>');
10
+ process.exit(2);
11
+ }
12
+ const modulePath = join(fileURLToPath(new URL('..', import.meta.url)), 'lib', 'ecosystem', 'wechat', 'stickerLibrary.js');
13
+ const { createStickerLibrary, importLegacyStickers } = await import(pathToFileURL(modulePath).href);
14
+ const library = createStickerLibrary(join(resolve(world), 'stickers'));
15
+ const report = await importLegacyStickers(resolve(legacy), library);
16
+ console.log(`导入 ${report.imported} 张,已在库里的 ${report.duplicates} 张,跳过 ${report.skipped.length} 张;表情库现有 ${(await library.list()).length} 张。`);
17
+ for (const line of report.skipped) console.log(` 跳过 ${line}`);
@@ -7,8 +7,8 @@ import { fileURLToPath } from 'node:url';
7
7
  import { isDeepStrictEqual, parseArgs, promisify } from 'node:util';
8
8
 
9
9
  const execute = promisify(execFile);
10
- const command = (file, args, options = {}) => execute(file, args, { windowsHide: true, maxBuffer: 16 * 1024 * 1024, ...options });
11
- // GNU tar (the one Git Bash puts first) reads the `C:` of an archive path as a remote host; naming the archive from its own folder works with every tar.
10
+ const command = (file, args, options = {}) => execute(file, args, { windowsHide: true, maxBuffer: 16 * 1024 * 1024, ...options });
11
+ // GNU tar (the one Git Bash puts first) reads the `C:` of an archive path as a remote host; naming the archive from its own folder works with every tar.
12
12
  const readArchive = (run, archive, args, options = {}) => run('tar', [args[0], basename(archive), ...args.slice(1)], { ...options, cwd: dirname(archive) });
13
13
  const json = async file => JSON.parse((await readFile(file, 'utf8')).replace(/^\uFEFF/, ''));
14
14
  async function exists(file) {
@@ -10,7 +10,7 @@ DSH 端代码在 `src/ecosystem/wechat/`,此目录只负责 Windows 微信收
10
10
  - 收到要交给她的消息后先缓冲(默认 3 秒,`bufferSeconds`):同一聊天、同一发言人在等待中又发来文字(私聊还包括图片),就重新计时,安静下来后合并为一次模型请求;最长等 30 秒、最多 16 条、合并文字不超过 2000 字,私聊最多两张图片。别人发言、引用、表情包等其他类型让批次立即结束。群聊只有 @ 她的消息会等待,同一人随后的文字合并进来,身份仍是 @ 她的那条。批次开始处理后才收到的消息留在微信数据库中,下一轮按序读取,不中断当前回复。
11
11
  - 批次成员保留原平台消息 ID,在同一事务中进入待处理与完成状态;缓冲期间不推进游标,处理中断后保留待核对状态,不自动重跑模型。图片单发仅进入会话图片上下文;图片加文字时只把真实文字按原范围归档。图片及附件引用不写入共享记忆块,是否另行留存其中信息由她自己判断。
12
12
  - 暂不接收视频号分享卡片:卡片会被跳过,不进入宿主会话或共享记忆。视频号卡片解析、视频内容读取,以及朋友圈浏览/发布,均预留为微信模块后续扩展,尚未实现;朋友圈发布需要独立接口,不能复用私聊/群聊发送接口。
13
- - 后台原生发送文字、图片及 GIF 表情,不操作窗口、鼠标、键盘或剪贴板。按 `engine/profiles.json` 中的文件大小与 SHA256 自动选择 Windows x64 微信 4.1.15.13 / 4.1.15.56 / 4.2.0.11 / 4.2.0.12 的指定构建(4.2 不能发原生 GIF 表情,表情包改为截取一帧作为图片发送,见下);未知或匹配不唯一的构建会在加载原生桥前报错,不能只凭版本号判断兼容。
13
+ - 后台原生发送文字、图片及 GIF 表情,不操作窗口、鼠标、键盘或剪贴板。按 `engine/profiles.json` 中的文件大小与 SHA256 自动选择 Windows x64 微信 4.1.15.13 / 4.1.15.56 / 4.2.0.11 / 4.2.0.12 / 4.2.0.13 的指定构建(4.2 的表情包截取一帧作为图片发送,见下)。未知或匹配不唯一的构建会在加载原生桥前报错。
14
14
  - 发言人使用真实 wxid,消息保持 `role: user`;昵称只作显示。
15
15
  - 每个群按平台、登录账号、聊天类型和群 ID 绑定独立会话,列在原房间工作区下,重启继续复用;群名变化不产生新会话。QQ 的相同参数可使用同一映射结构,但本模块仍只提供微信传输。
16
16
  - 群消息只在微信来源元数据的 `atuserlist` 包含她的真实 wxid 时触发,正文里手打 `@昵称` 不触发。回复携带当前消息之前默认 5 条(控制台可调,1–20)、最多 16KB 的同群上下文,保留各自的发言人 ID;每轮最多读取其中最近两张图片。
@@ -142,9 +142,11 @@ node <dsh-world 包目录>scriptsimport-stickers.mjs C:Usersyou.dshmemes C:Users
142
142
 
143
143
  这不是微信官方 API。版本变更需重新校准,锁屏和群聊等实际条件必须分别验证。`engine/` 基于第三方原生 ABI 研究定制,保留独立的非商业许可与来源说明;该目录不适用仓库根目录的 MIT 许可。
144
144
 
145
- 4.1.15.56 的指纹与 19 个原生地址映射来自 [helper 的版本表](https://github.com/Prometheus-first/helper/blob/main/native/core_version.h)。两版沿用相同请求 ABI、账号核对和消息对象字段布局;版本表选择、地址编码及未知构建拒绝由离线测试覆盖。上游已实测新版文字收发及桥接加载卸载,媒体未逐项重做真实网络操作,详见其 [验证范围](https://github.com/Prometheus-first/helper/blob/main/native/README.md);本项目实测范围见下方日期记录。本次仅更新 Python 和版本表,无须重新编译未改动的 C++ 桥;新增构建或结构发生变化时仍需校准并实测。
145
+ 4.1.15.56 的指纹与 19 个原生地址映射来自 [helper 的版本表](https://github.com/Prometheus-first/helper/blob/main/native/core_version.h)。两版沿用相同请求 ABI、账号核对和消息对象字段布局;版本表选择、地址编码及未知构建拒绝由离线测试覆盖。上游已实测新版文字收发及桥接加载卸载,媒体未逐项重做真实网络操作,详见其 [验证范围](https://github.com/Prometheus-first/helper/blob/main/native/README.md);本项目实测范围见下方日期记录。本次仅更新 Python 和版本表,无须重新编译未改动的 C++ 桥;新增构建或结构发生变化时仍需校准并实测。
146
+
147
+ 4.2.0.11 与 4.2.0.12 的指纹和地址取自 helper 的版本表。4.2.0.13 的地址由本项目从腾讯签名的 `Weixin.dll` 独立比对得出,基准是从安装包离线解出的 4.2.0.12 DLL。三个 4.2 构建都沿用静态表情发送方式。适配器取 GIF 第一帧转为 PNG,第一帧完全透明或只有一种颜色时改取最后一帧。4.2.0.13 仅更新版本表,已构建当前原生桥的环境可直接使用。来源见 [NOTICE](engine/NOTICE.md)。
146
148
 
147
- 4.2.0.11 与 4.2.0.12 的指纹和地址同样取自 helper 的版本表(按同一方法推出的 4.1.15.56 地址与已实测的配置逐项一致)。上游 4.2 只映射了文字、撤回和图片收发路径,原生 GIF 表情的 5 个地址没有映射,上游自己的表情发送在 4.2 上也直接拒绝;所以这两个构建的这 5 项为 null,原生桥只在发表情包时要求它们,文字和图片照常发送。在 4.2 上发表情包时,适配器把 GIF 转成一张静态 PNG 按图片发送:取第一帧,第一帧完全透明或只有一种颜色时改取最后一帧。**本项目没有 4.2 实机,以上未经真实微信验证**;首次使用请先向测试私聊各发一次文字、图片和表情包核对。原生桥源码因此改动,升级后需要重新运行 `wechat.ps1 Build`,否则适配器会以“原生桥源码已变化”拒绝加载。
149
+ 2026-11-04 已在 Windows 微信 4.2.0.13 上通过 `Probe`,核对了构建指纹、绑定账号及原生调度。实际文字、图片、表情包投递及 DSH 收发联动待验证。
148
150
 
149
151
  2026-10-25 已在绑定的专用账号私聊中确认两条独立文字及一条原生表情(类型 47),并在选定家庭群补发确认一张原生表情和一条文字;均核对服务器消息编号,媒体内容同时核对 MD5。首次群会话的技能目录误判已修复并有回归测试。2026-10-26 已确认家庭群真实 @ 触发时读取两张缓存图片、模型描述图片并回群发送成功,附件引用保存在群会话日志,该群共享归档记录数仍为 0。该轮未测独立图片发送和锁屏运行。
150
152
 
@@ -17,6 +17,7 @@ from snapshot import NotSent, SnapshotBusy
17
17
  from groups import DEFAULT_CONTEXT_MESSAGES, mentionedIds, recentContext
18
18
  from incoming import ImageUnavailable, admitReference
19
19
  from binding import WechatOffline
20
+ from sender import BuildStale
20
21
  from messages import messageKey, messageOrder, normalizeMessage, messageNormalizer, messageEntry, displayMessage
21
22
  from quotes import MessageContentError, isAppMessage
22
23
  from reading import readHistory
@@ -32,6 +33,8 @@ CONTROL_TIMEOUT_SECONDS = 5
32
33
  REPLY_TIMEOUT_SECONDS = 190
33
34
  # Exit code for "a person must check WeChat and run acknowledge"; the plugin stops restarting the adapter on it.
34
35
  EXIT_NEEDS_HUMAN = 2
36
+ # Exit code for "the native bridge must be built again"; the plugin builds it and starts the adapter again.
37
+ EXIT_NEEDS_BUILD = 3
35
38
  # A reply whose send never started (no stable snapshot of the chat) is handed out again this many times in all.
36
39
  SEND_ATTEMPTS = 3
37
40
 
@@ -682,6 +685,9 @@ if __name__ == '__main__':
682
685
  except NeedsHuman as error:
683
686
  print(f'微信适配器停止:{error}', file=sys.stderr)
684
687
  sys.exit(EXIT_NEEDS_HUMAN)
688
+ except BuildStale as error:
689
+ print(f'微信适配器停止:{error}', file=sys.stderr)
690
+ sys.exit(EXIT_NEEDS_BUILD)
685
691
  except Exception as error:
686
692
  print(f'微信适配器停止:{error}', file=sys.stderr)
687
693
  sys.exit(1)
@@ -11,3 +11,9 @@ hooks, recall handling, account discovery or group management.
11
11
 
12
12
  profiles.json contains the fingerprint-locked 4.1.15.13, 4.1.15.56, 4.2.0.11 and 4.2.0.12
13
13
  address mappings from https://github.com/Prometheus-first/helper/blob/main/native/core_version.h.
14
+
15
+ The 4.2.0.13 mapping was derived by dsh-world from the Tencent-signed Windows
16
+ x64 Weixin.dll. The comparison used the 4.2.0.12 DLL extracted from Tencent's
17
+ installer and verified against the existing profile. Function disassembly,
18
+ references to the account root, and the context vtable were compared between
19
+ the two builds.
@@ -1,6 +1,8 @@
1
- $ErrorActionPreference = 'Stop'
1
+ # OutDir: where the adapter looks for the build (the `engine` folder beside its config.json); the repo's own by default.
2
+ param([string]$OutDir)
3
+ $ErrorActionPreference = 'Stop'
2
4
  $workspaceRoot = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../../../../..'))
3
- $runtimeDir = Join-Path $workspaceRoot '.host\wechat\engine'
5
+ $runtimeDir = if ($OutDir) { [IO.Path]::GetFullPath($OutDir) } else { Join-Path $workspaceRoot '.host\wechat\engine' }
4
6
  $source = Join-Path $PSScriptRoot 'bridge.cpp'
5
7
  $sourceHash = (Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash.ToLowerInvariant()
6
8
  $outputDir = Join-Path $runtimeDir $sourceHash.Substring(0,12)
@@ -16,4 +18,8 @@ $buildScript = Join-Path $outputDir 'build.cmd'
16
18
  & $env:ComSpec /d /c $buildScript
17
19
  if ($LASTEXITCODE -ne 0) { throw '原生桥构建失败' }
18
20
  @{file=$dll; sha256=(Get-FileHash -LiteralPath $dll -Algorithm SHA256).Hash.ToLowerInvariant(); sourceSha256=$sourceHash} | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $runtimeDir 'current.json') -Encoding utf8
21
+ # Older builds are never loaded again (current.json names only this one); one WeChat still holds open is left for next time.
22
+ Get-ChildItem -LiteralPath $runtimeDir -Directory | Where-Object { $_.Name -match '^[0-9a-f]{12}$' -and $_.FullName -ne $outputDir } | ForEach-Object {
23
+ try { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction Stop } catch { Write-Output "旧构建暂时删不掉,下次再删:$($_.Exception.Message)" }
24
+ }
19
25
  Write-Output $dll
@@ -1,114 +1,142 @@
1
- [
2
- {
3
- "version": "4.1.15.13",
4
- "size": 201552944,
5
- "sha256": "10f8e995453e2da46d4f2b5080cd6da1f13cc5147746adc119ceae38cb039de5",
6
- "timestamp": 1789961080,
7
- "imageSize": 202039296,
8
- "addresses": {
9
- "application": 285968,
10
- "scheduler": 291600,
11
- "schedule": 3125264,
12
- "context": 291360,
13
- "provider": 3589952,
14
- "manager": 7294352,
15
- "text": 88802032,
16
- "image": 64608656,
17
- "emoticon": 29340096,
18
- "copyWide": 636368,
19
- "validateGif": 15182048,
20
- "probeGif": 5441984,
21
- "releaseProbe": 5137248,
22
- "send": 24703232,
23
- "allocate": 122337436,
24
- "free": 122337504,
25
- "accountRoot": 194061968,
26
- "contextVtable": 148890360,
27
- "emoticonVtable": 151891960
28
- }
29
- },
30
- {
31
- "version": "4.1.15.56",
32
- "size": 204305968,
33
- "sha256": "e0428a7b691853de496532523c2c09aa095f90941c37c9f4cfb3f137f3c66556",
34
- "timestamp": 1792050120,
35
- "imageSize": 204795904,
36
- "addresses": {
37
- "application": 285968,
38
- "scheduler": 291600,
39
- "schedule": 3208272,
40
- "context": 291360,
41
- "provider": 3679184,
42
- "manager": 7377536,
43
- "text": 90112896,
44
- "image": 65154416,
45
- "emoticon": 29436416,
46
- "copyWide": 636384,
47
- "validateGif": 15343584,
48
- "probeGif": 5528896,
49
- "releaseProbe": 5224160,
50
- "send": 24788000,
51
- "allocate": 122993884,
52
- "free": 122993952,
53
- "accountRoot": 196685728,
54
- "contextVtable": 150803560,
55
- "emoticonVtable": 153824520
56
- }
57
- },
58
- {
59
- "version": "4.2.0.11",
60
- "size": 205929008,
61
- "sha256": "745cdf2955fa5128cdb00c056c97571156a5f107406a9bb15ac0754f3246b201",
62
- "timestamp": 1793108177,
63
- "imageSize": 206422016,
64
- "addresses": {
65
- "application": 285968,
66
- "scheduler": 291600,
67
- "schedule": 3217808,
68
- "context": 291360,
69
- "provider": 3688240,
70
- "manager": 7456256,
71
- "text": 91356448,
72
- "image": 65819968,
73
- "emoticon": null,
74
- "copyWide": 636384,
75
- "validateGif": null,
76
- "probeGif": null,
77
- "releaseProbe": null,
78
- "send": 24965648,
79
- "allocate": 124404668,
80
- "free": 124404736,
81
- "accountRoot": 198233648,
82
- "contextVtable": 151867272,
83
- "emoticonVtable": null
84
- }
85
- },
86
- {
87
- "version": "4.2.0.12",
88
- "size": 205932072,
89
- "sha256": "2b3677c3f932daaa4ef84c8b2acd0aee12cbe5a779ff9e740c370761e5c291ce",
90
- "timestamp": 1793275655,
91
- "imageSize": 206417920,
92
- "addresses": {
93
- "application": 285968,
94
- "scheduler": 291600,
95
- "schedule": 3217808,
96
- "context": 291360,
97
- "provider": 3688240,
98
- "manager": 7451520,
99
- "text": 91361344,
100
- "image": 65824848,
101
- "emoticon": null,
102
- "copyWide": 636384,
103
- "validateGif": null,
104
- "probeGif": null,
105
- "releaseProbe": null,
106
- "send": 24962240,
107
- "allocate": 124408764,
108
- "free": 124408832,
109
- "accountRoot": 198233648,
110
- "contextVtable": 151871336,
111
- "emoticonVtable": null
112
- }
113
- }
114
- ]
1
+ [
2
+ {
3
+ "version": "4.1.15.13",
4
+ "size": 201552944,
5
+ "sha256": "10f8e995453e2da46d4f2b5080cd6da1f13cc5147746adc119ceae38cb039de5",
6
+ "timestamp": 1789961080,
7
+ "imageSize": 202039296,
8
+ "addresses": {
9
+ "application": 285968,
10
+ "scheduler": 291600,
11
+ "schedule": 3125264,
12
+ "context": 291360,
13
+ "provider": 3589952,
14
+ "manager": 7294352,
15
+ "text": 88802032,
16
+ "image": 64608656,
17
+ "emoticon": 29340096,
18
+ "copyWide": 636368,
19
+ "validateGif": 15182048,
20
+ "probeGif": 5441984,
21
+ "releaseProbe": 5137248,
22
+ "send": 24703232,
23
+ "allocate": 122337436,
24
+ "free": 122337504,
25
+ "accountRoot": 194061968,
26
+ "contextVtable": 148890360,
27
+ "emoticonVtable": 151891960
28
+ }
29
+ },
30
+ {
31
+ "version": "4.1.15.56",
32
+ "size": 204305968,
33
+ "sha256": "e0428a7b691853de496532523c2c09aa095f90941c37c9f4cfb3f137f3c66556",
34
+ "timestamp": 1792050120,
35
+ "imageSize": 204795904,
36
+ "addresses": {
37
+ "application": 285968,
38
+ "scheduler": 291600,
39
+ "schedule": 3208272,
40
+ "context": 291360,
41
+ "provider": 3679184,
42
+ "manager": 7377536,
43
+ "text": 90112896,
44
+ "image": 65154416,
45
+ "emoticon": 29436416,
46
+ "copyWide": 636384,
47
+ "validateGif": 15343584,
48
+ "probeGif": 5528896,
49
+ "releaseProbe": 5224160,
50
+ "send": 24788000,
51
+ "allocate": 122993884,
52
+ "free": 122993952,
53
+ "accountRoot": 196685728,
54
+ "contextVtable": 150803560,
55
+ "emoticonVtable": 153824520
56
+ }
57
+ },
58
+ {
59
+ "version": "4.2.0.11",
60
+ "size": 205929008,
61
+ "sha256": "745cdf2955fa5128cdb00c056c97571156a5f107406a9bb15ac0754f3246b201",
62
+ "timestamp": 1793108177,
63
+ "imageSize": 206422016,
64
+ "addresses": {
65
+ "application": 285968,
66
+ "scheduler": 291600,
67
+ "schedule": 3217808,
68
+ "context": 291360,
69
+ "provider": 3688240,
70
+ "manager": 7456256,
71
+ "text": 91356448,
72
+ "image": 65819968,
73
+ "emoticon": null,
74
+ "copyWide": 636384,
75
+ "validateGif": null,
76
+ "probeGif": null,
77
+ "releaseProbe": null,
78
+ "send": 24965648,
79
+ "allocate": 124404668,
80
+ "free": 124404736,
81
+ "accountRoot": 198233648,
82
+ "contextVtable": 151867272,
83
+ "emoticonVtable": null
84
+ }
85
+ },
86
+ {
87
+ "version": "4.2.0.12",
88
+ "size": 205932072,
89
+ "sha256": "2b3677c3f932daaa4ef84c8b2acd0aee12cbe5a779ff9e740c370761e5c291ce",
90
+ "timestamp": 1793275655,
91
+ "imageSize": 206417920,
92
+ "addresses": {
93
+ "application": 285968,
94
+ "scheduler": 291600,
95
+ "schedule": 3217808,
96
+ "context": 291360,
97
+ "provider": 3688240,
98
+ "manager": 7451520,
99
+ "text": 91361344,
100
+ "image": 65824848,
101
+ "emoticon": null,
102
+ "copyWide": 636384,
103
+ "validateGif": null,
104
+ "probeGif": null,
105
+ "releaseProbe": null,
106
+ "send": 24962240,
107
+ "allocate": 124408764,
108
+ "free": 124408832,
109
+ "accountRoot": 198233648,
110
+ "contextVtable": 151871336,
111
+ "emoticonVtable": null
112
+ }
113
+ },
114
+ {
115
+ "version": "4.2.0.13",
116
+ "size": 205943848,
117
+ "sha256": "afe3d02c58bada3c35009c0cd58ee1f57b2a00fe53237d0dce649107fddb9a20",
118
+ "timestamp": 1793604862,
119
+ "imageSize": 206430208,
120
+ "addresses": {
121
+ "application": 285968,
122
+ "scheduler": 291600,
123
+ "schedule": 3228064,
124
+ "context": 291360,
125
+ "provider": 3690048,
126
+ "manager": 7465840,
127
+ "text": 91370832,
128
+ "image": 65862832,
129
+ "emoticon": null,
130
+ "copyWide": 636384,
131
+ "validateGif": null,
132
+ "probeGif": null,
133
+ "releaseProbe": null,
134
+ "send": 25014992,
135
+ "allocate": 124417292,
136
+ "free": 124417360,
137
+ "accountRoot": 198245872,
138
+ "contextVtable": 151879656,
139
+ "emoticonVtable": null
140
+ }
141
+ }
142
+ ]
@@ -1,109 +1,109 @@
1
- """One durable metadata row per account/group; no message body, wake or model call."""
2
- from datetime import datetime, timezone
3
- import json
4
- from messages import messageKey, messageOrder, recentEntries
5
- from snapshot import SnapshotBusy
6
-
7
-
8
- class GroupPresence:
9
- def __init__(self, db):
10
- self.db = db
11
- db.execute('''CREATE TABLE IF NOT EXISTS groupPresence(
12
- accountId TEXT, chatId TEXT, count INTEGER NOT NULL,
13
- seq INTEGER, shard TEXT, localId INTEGER, lastAt TEXT, speaker TEXT, self INTEGER,
14
- readSeq INTEGER NOT NULL DEFAULT 0, readShard TEXT NOT NULL DEFAULT '', readId INTEGER NOT NULL DEFAULT 0,
15
- seen TEXT NOT NULL DEFAULT '[]', readSeen TEXT NOT NULL DEFAULT '[]',
16
- PRIMARY KEY(accountId,chatId))''')
17
-
18
- def _get(self, account, chat):
19
- return self.db.execute('SELECT count,seq,shard,localId,lastAt,speaker,self,readSeq,readShard,readId,seen,readSeen '
20
- 'FROM groupPresence WHERE accountId=? AND chatId=? LIMIT 1', (account, chat)).fetchone()
21
-
22
- def observe(self, account, chat, row, speaker, *, unread=True):
23
- if row['type'] == '系统消息': return
24
- if not row.get('sender_username'): raise ValueError('群动态缺少真实发言人')
25
- order = messageOrder(row)
26
- previous = self._get(account, chat)
27
- if previous and order[0] < previous[1]: return
28
- sameSeq = bool(previous and order[0] == previous[1])
29
- seen = set(json.loads(previous[10])) if sameSeq else set()
30
- key = messageKey(row)
31
- if key in seen: return
32
- seen.add(key)
33
- read = tuple(previous[7:10]) if previous else (0, '', 0)
34
- own = row['sender_username'] == account
35
- count = (previous[0] if previous else 0) + int(unread and not own and (order > read or (sameSeq and order[0] == read[0])))
36
- at = datetime.fromtimestamp(int(row['create_time']), timezone.utc).isoformat()
37
- metadata = (at, str(speaker)[:80], int(own))
38
- if sameSeq and order < tuple(previous[1:4]):
39
- order, metadata = tuple(previous[1:4]), tuple(previous[4:7])
40
- with self.db:
41
- self.db.execute('INSERT INTO groupPresence VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) '
42
- 'ON CONFLICT(accountId,chatId) DO UPDATE SET count=excluded.count,seq=excluded.seq,'
43
- 'shard=excluded.shard,localId=excluded.localId,lastAt=excluded.lastAt,speaker=excluded.speaker,self=excluded.self,seen=excluded.seen',
44
- (account, chat, count, *order, *metadata, *read, json.dumps(sorted(seen)), previous[11] if previous else '[]'))
45
-
46
- def markRead(self, account, chat, through, countRemaining=None, seenKeys=()):
47
- previous = self._get(account, chat)
48
- boundary = tuple(through)
49
- if not previous:
50
- with self.db:
51
- self.db.execute('INSERT INTO groupPresence(accountId,chatId,count,seq,shard,localId,readSeq,readShard,readId,readSeen) VALUES (?,?,0,0,\'\',0,?,?,?,?)', (account, chat, *boundary, json.dumps(sorted(seenKeys))))
52
- return
53
- read = max(tuple(previous[7:10]), boundary)
54
- seen = set(json.loads(previous[10]))
55
- if boundary[0] == previous[1]: seen.update(seenKeys)
56
- readSeen = set(json.loads(previous[11])) if boundary[0] == previous[7] else set()
57
- if boundary < tuple(previous[7:10]) or (boundary == tuple(previous[7:10]) and not set(seenKeys) - readSeen): return
58
- readSeen.update(seenKeys)
59
- remaining = 0
60
- if boundary < tuple(previous[1:4]):
61
- if countRemaining is None: raise ValueError('旧读取结果需要核对尚未读到的群消息')
62
- remaining = min(previous[0], countRemaining(boundary, tuple(previous[1:4])))
63
- with self.db:
64
- self.db.execute('UPDATE groupPresence SET count=?,readSeq=?,readShard=?,readId=?,seen=?,readSeen=? WHERE accountId=? AND chatId=?',
65
- (remaining, *read, json.dumps(sorted(seen)), json.dumps(sorted(readSeen)), account, chat))
66
-
67
- def snapshot(self, config):
68
- groups = []
69
- for chat in config['chats']:
70
- if not chat['id'].endswith('@chatroom'): continue
71
- row = self._get(config['selfId'], chat['id'])
72
- if row and row[4]:
73
- groups.append(dict(chatId=chat['id'], count=min(100, row[0]), lastAt=row[4], lastSpeaker=row[5], lastSelf=bool(row[6])))
74
- # Keep the existing control poll bounded even with many configured groups.
75
- return sorted(groups, key=lambda item: (item['count'] > 0, item['lastAt']), reverse=True)[:8]
76
-
77
-
78
- def speakerName(database, config, row):
79
- sender = row.get('sender_username')
80
- if not sender: raise ValueError('群动态缺少真实发言人')
81
- return config.get('people', {}).get(sender) or database.get_nickname(sender) or sender
82
-
83
-
84
- def seedPresence(database, store, config, chat):
85
- presence = store.presence
86
- previous = presence._get(config['selfId'], chat['id'])
87
- if not chat['id'].endswith('@chatroom') or (previous and previous[4]): return
88
- cursor = store.cursor(chat['id'])
89
- if cursor is None: return
90
- found = recentEntries(database, chat['id'], lambda row: row if int(row['sort_seq']) <= cursor and row['type'] != '系统消息' else None,
91
- config.get('pageSize', 50), 1)
92
- if found:
93
- latest = next(reversed(found.values()))
94
- presence.observe(config['selfId'], chat['id'], latest, speakerName(database, config, latest), unread=False)
95
-
96
-
97
- def unreadAfter(database, config, chat, after, until):
98
- offset, size, found = 0, config.get('pageSize', 50), set()
99
- while True:
100
- rows = database.get_messages(chat, limit=size, offset=offset)
101
- if offset == 0 and (not rows or max(int(row['sort_seq']) for row in rows) < until[0]):
102
- raise SnapshotBusy('群消息快照落后于已观察位置,保留未读等待重读')
103
- for row in rows:
104
- order = messageOrder(row)
105
- if after < order <= until and row['type'] != '系统消息':
106
- if not row.get('sender_username'): raise ValueError('群动态缺少真实发言人')
107
- if row['sender_username'] != config['selfId']: found.add(order)
108
- if len(rows) < size or any(int(row['sort_seq']) < after[0] for row in rows): return len(found)
109
- offset += len(rows)
1
+ """One durable metadata row per account/group; no message body, wake or model call."""
2
+ from datetime import datetime, timezone
3
+ import json
4
+ from messages import messageKey, messageOrder, recentEntries
5
+ from snapshot import SnapshotBusy
6
+
7
+
8
+ class GroupPresence:
9
+ def __init__(self, db):
10
+ self.db = db
11
+ db.execute('''CREATE TABLE IF NOT EXISTS groupPresence(
12
+ accountId TEXT, chatId TEXT, count INTEGER NOT NULL,
13
+ seq INTEGER, shard TEXT, localId INTEGER, lastAt TEXT, speaker TEXT, self INTEGER,
14
+ readSeq INTEGER NOT NULL DEFAULT 0, readShard TEXT NOT NULL DEFAULT '', readId INTEGER NOT NULL DEFAULT 0,
15
+ seen TEXT NOT NULL DEFAULT '[]', readSeen TEXT NOT NULL DEFAULT '[]',
16
+ PRIMARY KEY(accountId,chatId))''')
17
+
18
+ def _get(self, account, chat):
19
+ return self.db.execute('SELECT count,seq,shard,localId,lastAt,speaker,self,readSeq,readShard,readId,seen,readSeen '
20
+ 'FROM groupPresence WHERE accountId=? AND chatId=? LIMIT 1', (account, chat)).fetchone()
21
+
22
+ def observe(self, account, chat, row, speaker, *, unread=True):
23
+ if row['type'] == '系统消息': return
24
+ if not row.get('sender_username'): raise ValueError('群动态缺少真实发言人')
25
+ order = messageOrder(row)
26
+ previous = self._get(account, chat)
27
+ if previous and order[0] < previous[1]: return
28
+ sameSeq = bool(previous and order[0] == previous[1])
29
+ seen = set(json.loads(previous[10])) if sameSeq else set()
30
+ key = messageKey(row)
31
+ if key in seen: return
32
+ seen.add(key)
33
+ read = tuple(previous[7:10]) if previous else (0, '', 0)
34
+ own = row['sender_username'] == account
35
+ count = (previous[0] if previous else 0) + int(unread and not own and (order > read or (sameSeq and order[0] == read[0])))
36
+ at = datetime.fromtimestamp(int(row['create_time']), timezone.utc).isoformat()
37
+ metadata = (at, str(speaker)[:80], int(own))
38
+ if sameSeq and order < tuple(previous[1:4]):
39
+ order, metadata = tuple(previous[1:4]), tuple(previous[4:7])
40
+ with self.db:
41
+ self.db.execute('INSERT INTO groupPresence VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) '
42
+ 'ON CONFLICT(accountId,chatId) DO UPDATE SET count=excluded.count,seq=excluded.seq,'
43
+ 'shard=excluded.shard,localId=excluded.localId,lastAt=excluded.lastAt,speaker=excluded.speaker,self=excluded.self,seen=excluded.seen',
44
+ (account, chat, count, *order, *metadata, *read, json.dumps(sorted(seen)), previous[11] if previous else '[]'))
45
+
46
+ def markRead(self, account, chat, through, countRemaining=None, seenKeys=()):
47
+ previous = self._get(account, chat)
48
+ boundary = tuple(through)
49
+ if not previous:
50
+ with self.db:
51
+ self.db.execute('INSERT INTO groupPresence(accountId,chatId,count,seq,shard,localId,readSeq,readShard,readId,readSeen) VALUES (?,?,0,0,\'\',0,?,?,?,?)', (account, chat, *boundary, json.dumps(sorted(seenKeys))))
52
+ return
53
+ read = max(tuple(previous[7:10]), boundary)
54
+ seen = set(json.loads(previous[10]))
55
+ if boundary[0] == previous[1]: seen.update(seenKeys)
56
+ readSeen = set(json.loads(previous[11])) if boundary[0] == previous[7] else set()
57
+ if boundary < tuple(previous[7:10]) or (boundary == tuple(previous[7:10]) and not set(seenKeys) - readSeen): return
58
+ readSeen.update(seenKeys)
59
+ remaining = 0
60
+ if boundary < tuple(previous[1:4]):
61
+ if countRemaining is None: raise ValueError('旧读取结果需要核对尚未读到的群消息')
62
+ remaining = min(previous[0], countRemaining(boundary, tuple(previous[1:4])))
63
+ with self.db:
64
+ self.db.execute('UPDATE groupPresence SET count=?,readSeq=?,readShard=?,readId=?,seen=?,readSeen=? WHERE accountId=? AND chatId=?',
65
+ (remaining, *read, json.dumps(sorted(seen)), json.dumps(sorted(readSeen)), account, chat))
66
+
67
+ def snapshot(self, config):
68
+ groups = []
69
+ for chat in config['chats']:
70
+ if not chat['id'].endswith('@chatroom'): continue
71
+ row = self._get(config['selfId'], chat['id'])
72
+ if row and row[4]:
73
+ groups.append(dict(chatId=chat['id'], count=min(100, row[0]), lastAt=row[4], lastSpeaker=row[5], lastSelf=bool(row[6])))
74
+ # Keep the existing control poll bounded even with many configured groups.
75
+ return sorted(groups, key=lambda item: (item['count'] > 0, item['lastAt']), reverse=True)[:8]
76
+
77
+
78
+ def speakerName(database, config, row):
79
+ sender = row.get('sender_username')
80
+ if not sender: raise ValueError('群动态缺少真实发言人')
81
+ return config.get('people', {}).get(sender) or database.get_nickname(sender) or sender
82
+
83
+
84
+ def seedPresence(database, store, config, chat):
85
+ presence = store.presence
86
+ previous = presence._get(config['selfId'], chat['id'])
87
+ if not chat['id'].endswith('@chatroom') or (previous and previous[4]): return
88
+ cursor = store.cursor(chat['id'])
89
+ if cursor is None: return
90
+ found = recentEntries(database, chat['id'], lambda row: row if int(row['sort_seq']) <= cursor and row['type'] != '系统消息' else None,
91
+ config.get('pageSize', 50), 1)
92
+ if found:
93
+ latest = next(reversed(found.values()))
94
+ presence.observe(config['selfId'], chat['id'], latest, speakerName(database, config, latest), unread=False)
95
+
96
+
97
+ def unreadAfter(database, config, chat, after, until):
98
+ offset, size, found = 0, config.get('pageSize', 50), set()
99
+ while True:
100
+ rows = database.get_messages(chat, limit=size, offset=offset)
101
+ if offset == 0 and (not rows or max(int(row['sort_seq']) for row in rows) < until[0]):
102
+ raise SnapshotBusy('群消息快照落后于已观察位置,保留未读等待重读')
103
+ for row in rows:
104
+ order = messageOrder(row)
105
+ if after < order <= until and row['type'] != '系统消息':
106
+ if not row.get('sender_username'): raise ValueError('群动态缺少真实发言人')
107
+ if row['sender_username'] != config['selfId']: found.add(order)
108
+ if len(rows) < size or any(int(row['sort_seq']) < after[0] for row in rows): return len(found)
109
+ offset += len(rows)