dsh-memory-archivist 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +122 -2
- package/cordis.patch.yml +5 -0
- package/lib/index.js +557 -0
- package/lib/patches.js +231 -0
- package/package.json +52 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-memory-archivist contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,123 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-memory-archivist
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
QQ 群会话「被解散/被踢」时的自动归档 + 删除,以及第三方插件补丁的启动自愈。
|
|
4
|
+
|
|
5
|
+
> **针对 `@tencent-connect/dsh-qqbot` 与 `dsh-plugin-memory` 优化**
|
|
6
|
+
>
|
|
7
|
+
> - 群会话映射直接读 `dsh-qqbot` 的 `model-prefs.json`(`qqbot:<appId>:group:<group_openid>`),探测复用它的 access_token 打 `GET /v2/groups/{openid}/info`;
|
|
8
|
+
> - 归档产物完全按 `dsh-plugin-memory` 的目录协议落盘(`raw/sessions/`、`groups/`、`log.md`,群页按 frontmatter 的 `group_openid` 索引)。
|
|
9
|
+
>
|
|
10
|
+
> 两个宿主插件都不装时本插件不报错、只是没东西可归档(会记一条 `no group sessions`)。
|
|
11
|
+
> 另有一处**可选**依赖:`dsh-plugin-session-cleaner` —— 没有 `sessionCleaner` 服务时只归档、不删会话。
|
|
12
|
+
|
|
13
|
+
## 它解决什么
|
|
14
|
+
|
|
15
|
+
QQ 解散群**不会**下发事件(只有被踢才推 `GROUP_DEL_ROBOT`),所以靠事件监听必然漏。
|
|
16
|
+
本插件每 N 分钟用 `GET /v2/groups/{openid}/info` 探测所有已绑定群:
|
|
17
|
+
|
|
18
|
+
- 群还在 → 不动
|
|
19
|
+
- 群没了(code 11255 / 304003 / 304014,或消息含「已注销/不存在」)→ 依次:
|
|
20
|
+
1. 读该群会话全文,原样写进 `<记忆库>/raw/sessions/<日期>-<群8位>-<会话8位>.md`(T0)
|
|
21
|
+
2. 在 `<记忆库>/groups/<群8位>-<群名>.md` 的「历史」里追加去噪明细(T1,群页按 frontmatter 的 `group_openid` 找,不靠文件名)
|
|
22
|
+
3. 调 `sessionCleaner` 删掉会话
|
|
23
|
+
4. 清掉 `model-prefs.json` 里的对应键
|
|
24
|
+
|
|
25
|
+
任一步失败 → 保留会话,只记 warn。**宁可留会话,也不静默丢记录。**
|
|
26
|
+
|
|
27
|
+
## 路径怎么来的(可移植,不写死)
|
|
28
|
+
|
|
29
|
+
从小到大逐级解析,任何一级缺失就往下回落:
|
|
30
|
+
|
|
31
|
+
| 目录 | 解析顺序 |
|
|
32
|
+
|---|---|
|
|
33
|
+
| 记忆库根(`<记忆库>`) | `MEMORY_ARCHIVIST_MEMORY` → `<DSH_HOME>/memory.json` 的 `memoryDir` → `~/.memory` |
|
|
34
|
+
| T0 原文 | `MEMORY_ARCHIVIST_RAW` → `<记忆库>/raw/sessions` |
|
|
35
|
+
| 群页 | `MEMORY_ARCHIVIST_GROUPS` → `<记忆库>/groups` |
|
|
36
|
+
| QQ 数据目录 | `MEMORY_ARCHIVIST_QQ_DATA` → `~/.dsh-qqbot` |
|
|
37
|
+
| `model-prefs.json` | `MEMORY_ARCHIVIST_PREFS` → `<QQ 数据目录>/model-prefs.json` |
|
|
38
|
+
| 日志 | `MEMORY_ARCHIVIST_LOG` → `<QQ 数据目录>/memory-archivist.log` |
|
|
39
|
+
| 宿主 profile 目录 | `DSH_PROFILE_DIR` → `<DSH_HOME>/profiles` 下第一个含 `cordis.patch.yml` 的目录 → `<DSH_HOME>/profiles/desktop` |
|
|
40
|
+
|
|
41
|
+
- `DSH_HOME` 取环境变量,默认 `~/.dsh`。
|
|
42
|
+
- `~` 前缀会自动展开成当前用户家目录。
|
|
43
|
+
- `<DSH_HOME>/memory.json` 是 dsh-plugin-memory 的配置,键 `memoryDir` 就是记忆库位置 —— 本插件跟着它走,不自己另立一套。
|
|
44
|
+
- 换机器 / 换用户名 / 换 profile 名都不需要改代码;实际生效的路径随时可以在 `GET /api/memory-archivist/status` 的 `paths` 字段里核对。
|
|
45
|
+
|
|
46
|
+
## 补丁自愈
|
|
47
|
+
|
|
48
|
+
有几处行为长在第三方插件内部,没有对外钩子,只能改源码;插件一升级就丢。
|
|
49
|
+
启动时逐条检查(幂等,已打就跳过;锚点对不上只记日志,绝不拦启动):
|
|
50
|
+
|
|
51
|
+
| id | 目标 | 作用 |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| `qqbot.group-at-mention` | @tencent-connect/dsh-qqbot lib/gateway/middleware-setup.js | QQ 有时以纯文本 `@昵称` 下发群 @,SDK 误判成未提及 → 补 `isImplicitMention` |
|
|
54
|
+
| `qqbot.show-tool-errors` | 同插件 lib/config.js | 新增 `showToolErrors` 配置键 |
|
|
55
|
+
| `qqbot.tool-error-gate` | 同插件 lib/transport/outbound.js | 工具失败结果默认不再刷到 QQ |
|
|
56
|
+
| `help-me-to-ask.skip-group-sessions` | dsh-help-me-to-ask index.js | 群会话跳过提问引导(群聊里没有卡片可点,会卡住整轮) |
|
|
57
|
+
|
|
58
|
+
写前备份 `<文件>.bak-memory-archivist`。结果在 `GET /api/memory-archivist/status` 的 `patches` 字段里。
|
|
59
|
+
|
|
60
|
+
## 配置
|
|
61
|
+
|
|
62
|
+
配置文件在宿主 profile 目录下,文件名 `memory-archivist.json`:
|
|
63
|
+
|
|
64
|
+
```json
|
|
65
|
+
{
|
|
66
|
+
"enabled": true,
|
|
67
|
+
"dryRun": false,
|
|
68
|
+
"sweepMinutes": 5,
|
|
69
|
+
"firstSweepDelaySec": 60,
|
|
70
|
+
"probeGroups": true,
|
|
71
|
+
"maxPerSweep": 5,
|
|
72
|
+
"rawRetentionDays": 30
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`dryRun: true` 时只探测、只写日志,不归档不删会话、也不过期删除原文。
|
|
77
|
+
|
|
78
|
+
## T0 原文的 30 天过期
|
|
79
|
+
|
|
80
|
+
每次巡检开始时扫一遍 `<记忆库>/raw/sessions/`,按**文件名开头的日期**判断:
|
|
81
|
+
超过 `rawRetentionDays`(默认 30 天)的 `.md` 就删掉,并在 `<记忆库>/log.md` 追一条
|
|
82
|
+
`## [日期] forget | T0 原文过期清理(保留 N 天)`,列出删掉的文件——这是 `MEMORY.md`
|
|
83
|
+
里「raw/sessions 可过期删但要在 log.md 记录」的落地实现。
|
|
84
|
+
|
|
85
|
+
文件名不合 `YYYY-MM-DD-` 格式的一律不动。
|
|
86
|
+
|
|
87
|
+
## 路由
|
|
88
|
+
|
|
89
|
+
- `GET /api/memory-archivist/status` —— 配置、最近一次巡检、群列表、补丁状态、实际路径
|
|
90
|
+
- `POST /api/memory-archivist/sweep` —— 立刻巡检一次
|
|
91
|
+
|
|
92
|
+
## 日志
|
|
93
|
+
|
|
94
|
+
默认写在 `<QQ 数据目录>/memory-archivist.log`,可用 `MEMORY_ARCHIVIST_LOG` 改。
|
|
95
|
+
|
|
96
|
+
## 安装
|
|
97
|
+
|
|
98
|
+
三种方式,任选其一(装完都要把 `dsh-memory-archivist` 加进 profile `package.json` 的 `dsh.profile.bundles`):
|
|
99
|
+
|
|
100
|
+
```jsonc
|
|
101
|
+
// 1) 直接从 GitHub 装(推荐先试这个,不用等 npm)
|
|
102
|
+
"dsh-memory-archivist": "github:haidao128/dsh-plugin-"
|
|
103
|
+
|
|
104
|
+
// 2) 从 npm 装(发布之后)
|
|
105
|
+
"dsh-memory-archivist": "^0.1.0"
|
|
106
|
+
|
|
107
|
+
// 3) 本地开发用 link
|
|
108
|
+
"dsh-memory-archivist": "link:../../plugins/dsh-memory-archivist"
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
仓库根目录就是包根,所以 `github:` 这种写法不用带 `#path`。
|
|
112
|
+
|
|
113
|
+
源码改动后要**重启应用**才生效(ESM 模块缓存);只改 `cordis.patch.yml` 会热重载 fiber,但不会重载模块代码。
|
|
114
|
+
|
|
115
|
+
## 发布
|
|
116
|
+
|
|
117
|
+
仓库带了 `.github/workflows/publish.yml`:在 GitHub Settings → Secrets 里配一个 `NPM_TOKEN`(npm 的 Automation token),然后打 tag 就会自动 `npm publish`:
|
|
118
|
+
|
|
119
|
+
```bash
|
|
120
|
+
git tag v0.1.0 && git push origin v0.1.0
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
也可以在能连 npm 的机器上手动发:`npm publish --access public`。
|
package/cordis.patch.yml
ADDED
package/lib/index.js
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-memory-archivist —— 宿主半(v0.1.0)
|
|
3
|
+
*
|
|
4
|
+
* 职责:群会话要消失之前的那一段
|
|
5
|
+
* 1. 巡检已绑定的 QQ 群会话,看群还在不在(GET /v2/groups/{openid}/info)
|
|
6
|
+
* 2. 群没了(被踢 / 解散)→ T0 原文落 raw/sessions/,摘要追加进 groups/<openid8>-<群名>.md
|
|
7
|
+
* 3. 落盘成功后才删会话(sessionCleaner),并清掉 model-prefs.json 的映射
|
|
8
|
+
* 4. 顺手做 node_modules 补丁的启动自愈(锚点不匹配就跳过并记日志,绝不拦启动)
|
|
9
|
+
*
|
|
10
|
+
* 只 import node: 内置模块 —— link: 安装时裸包名解析不到,依赖一律从 Cordis 上下文拿。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import os from 'node:os'
|
|
16
|
+
|
|
17
|
+
import { repairPatches } from './patches.js'
|
|
18
|
+
|
|
19
|
+
export const name = 'memory-archivist'
|
|
20
|
+
|
|
21
|
+
export const inject = ["webServer"]
|
|
22
|
+
|
|
23
|
+
const API_PREFIX = '/api/memory-archivist'
|
|
24
|
+
const envPath = (name, fallback) => {
|
|
25
|
+
const value = process.env[name]
|
|
26
|
+
return typeof value === 'string' && value !== '' ? value : fallback
|
|
27
|
+
}
|
|
28
|
+
const DSH_HOME = envPath('DSH_HOME', path.join(os.homedir(), '.dsh'))
|
|
29
|
+
|
|
30
|
+
/** 支持 ~ 前缀;不认识的路径原样返回 */
|
|
31
|
+
function expandHome(value) {
|
|
32
|
+
if (value === '~') return os.homedir()
|
|
33
|
+
if (value.startsWith('~/') || value.startsWith('~\\')) return path.join(os.homedir(), value.slice(2))
|
|
34
|
+
return value
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 记忆库根目录:跟随 dsh-plugin-memory 的 memory.json 配置,没有配置就用默认 ~/.memory */
|
|
38
|
+
function memoryRoot() {
|
|
39
|
+
const fromEnv = process.env.MEMORY_ARCHIVIST_MEMORY
|
|
40
|
+
if (typeof fromEnv === 'string' && fromEnv !== '') return expandHome(fromEnv)
|
|
41
|
+
try {
|
|
42
|
+
const raw = JSON.parse(readFileSync(path.join(DSH_HOME, 'memory.json'), 'utf8'))
|
|
43
|
+
const dir = raw?.memoryDir
|
|
44
|
+
if (typeof dir === 'string' && dir.trim() !== '') return expandHome(dir.trim())
|
|
45
|
+
} catch { /* 没配置就回落到默认 */ }
|
|
46
|
+
return path.join(os.homedir(), '.memory')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const MEMORY_ROOT = memoryRoot()
|
|
50
|
+
const RAW_DIR = envPath('MEMORY_ARCHIVIST_RAW', path.join(MEMORY_ROOT, 'raw', 'sessions'))
|
|
51
|
+
const GROUPS_DIR = envPath('MEMORY_ARCHIVIST_GROUPS', path.join(MEMORY_ROOT, 'groups'))
|
|
52
|
+
const QQ_DATA_DIR = envPath('MEMORY_ARCHIVIST_QQ_DATA', path.join(os.homedir(), '.dsh-qqbot'))
|
|
53
|
+
const PREFS_FILE = envPath('MEMORY_ARCHIVIST_PREFS', path.join(QQ_DATA_DIR, 'model-prefs.json'))
|
|
54
|
+
const LOG_FILE = envPath('MEMORY_ARCHIVIST_LOG', path.join(QQ_DATA_DIR, 'memory-archivist.log'))
|
|
55
|
+
|
|
56
|
+
const DEFAULTS = Object.freeze({
|
|
57
|
+
enabled: true,
|
|
58
|
+
dryRun: true,
|
|
59
|
+
sweepMinutes: 5,
|
|
60
|
+
firstSweepDelaySec: 60,
|
|
61
|
+
probeGroups: true,
|
|
62
|
+
maxPerSweep: 5,
|
|
63
|
+
rawRetentionDays: 30,
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
function nowIso() { return new Date().toISOString() }
|
|
67
|
+
|
|
68
|
+
/** 当前 profile 目录:优先 DSH_PROFILE_DIR,否则在 DSH_HOME/profiles 下找带 cordis.patch.yml 的那个 */
|
|
69
|
+
function profileDir() {
|
|
70
|
+
const fromEnv = process.env.DSH_PROFILE_DIR
|
|
71
|
+
if (typeof fromEnv === 'string' && fromEnv !== '') return fromEnv
|
|
72
|
+
const base = path.join(DSH_HOME, 'profiles')
|
|
73
|
+
const preferred = path.join(base, 'desktop')
|
|
74
|
+
if (existsSync(path.join(preferred, 'cordis.patch.yml'))) return preferred
|
|
75
|
+
try {
|
|
76
|
+
for (const name of readdirSync(base)) {
|
|
77
|
+
const candidate = path.join(base, name)
|
|
78
|
+
if (existsSync(path.join(candidate, 'cordis.patch.yml'))) return candidate
|
|
79
|
+
}
|
|
80
|
+
} catch { /* 目录不存在就用默认值,让上层报 missing */ }
|
|
81
|
+
return preferred
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function configPath() { return path.join(profileDir(), 'memory-archivist.json') }
|
|
85
|
+
|
|
86
|
+
/** QQ 凭据始终读真实 profile 的 cordis.patch.yml(测试可单独覆盖) */
|
|
87
|
+
function qqProfileDir() { return envPath('MEMORY_ARCHIVIST_QQ_PROFILE', profileDir()) }
|
|
88
|
+
|
|
89
|
+
function log(line) {
|
|
90
|
+
const text = nowIso() + ' ' + line
|
|
91
|
+
try {
|
|
92
|
+
mkdirSync(path.dirname(LOG_FILE), { recursive: true })
|
|
93
|
+
appendFileSync(LOG_FILE, text + '\n')
|
|
94
|
+
} catch { /* 日志写不进去不影响主流程 */ }
|
|
95
|
+
return text
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function loadConfig() {
|
|
99
|
+
const base = { ...DEFAULTS }
|
|
100
|
+
try {
|
|
101
|
+
const raw = JSON.parse(readFileSync(configPath(), 'utf8'))
|
|
102
|
+
for (const key of Object.keys(DEFAULTS)) {
|
|
103
|
+
if (raw[key] !== undefined) base[key] = raw[key]
|
|
104
|
+
}
|
|
105
|
+
} catch { /* 没有配置文件就用默认值 */ }
|
|
106
|
+
return base
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** T0 原文过期清理:按文件名里的日期,超过 rawRetentionDays 天就删,并在记忆 log.md 记一笔 */
|
|
110
|
+
function pruneRawSessions(conf, reporter) {
|
|
111
|
+
const say = typeof reporter === 'function' ? reporter : (line) => log(line)
|
|
112
|
+
const out = { scanned: 0, removed: [], dryRun: (conf && conf.dryRun) === true }
|
|
113
|
+
let names = []
|
|
114
|
+
try { names = readdirSync(RAW_DIR) } catch { return out }
|
|
115
|
+
const days = Math.max(1, Number(conf && conf.rawRetentionDays) || 30)
|
|
116
|
+
const cutoff = Date.now() - days * 86400000
|
|
117
|
+
for (const name of names) {
|
|
118
|
+
if (!name.endsWith('.md')) continue
|
|
119
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})-/.exec(name)
|
|
120
|
+
if (m === null) continue
|
|
121
|
+
out.scanned += 1
|
|
122
|
+
const day = Date.parse(m[1] + '-' + m[2] + '-' + m[3] + 'T00:00:00Z')
|
|
123
|
+
if (!Number.isFinite(day) || day >= cutoff) continue
|
|
124
|
+
if (out.dryRun === true) { out.removed.push(name); continue }
|
|
125
|
+
try {
|
|
126
|
+
rmSync(path.join(RAW_DIR, name), { force: true })
|
|
127
|
+
out.removed.push(name)
|
|
128
|
+
} catch (error) {
|
|
129
|
+
say('raw 过期删除失败 ' + name + ': ' + (error instanceof Error ? error.message : String(error)))
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (out.removed.length > 0) {
|
|
133
|
+
say('[raw] 过期 T0 清理 ' + out.removed.length + ' 个' + (out.dryRun ? '(dryRun,未删)' : '') + ':' + out.removed.join(', '))
|
|
134
|
+
if (out.dryRun !== true) appendMemoryLog(out.removed, days, say)
|
|
135
|
+
}
|
|
136
|
+
return out
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** 按记忆库协议在 log.md 追一条 forget 记录 */
|
|
140
|
+
function appendMemoryLog(removed, days, say) {
|
|
141
|
+
try {
|
|
142
|
+
const file = path.join(MEMORY_ROOT, 'log.md')
|
|
143
|
+
const day = nowIso().slice(0, 10)
|
|
144
|
+
const lines = ['', '## [' + day + '] forget | T0 原文过期清理(保留 ' + days + ' 天)', '']
|
|
145
|
+
for (const name of removed) lines.push('- 删除 raw/sessions/' + name)
|
|
146
|
+
appendFileSync(file, lines.join('\n') + '\n')
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (typeof say === 'function') say('写记忆 log.md 失败: ' + (error instanceof Error ? error.message : String(error)))
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** model-prefs.json 里 qqbot:<appId>:group:<group_openid> → sessionId */
|
|
153
|
+
function listGroupSessions() {
|
|
154
|
+
let prefs
|
|
155
|
+
try {
|
|
156
|
+
prefs = JSON.parse(readFileSync(PREFS_FILE, 'utf8'))
|
|
157
|
+
} catch {
|
|
158
|
+
return []
|
|
159
|
+
}
|
|
160
|
+
const ids = prefs && prefs.sessionIds
|
|
161
|
+
if (ids === undefined || ids === null || typeof ids !== 'object') return []
|
|
162
|
+
const out = []
|
|
163
|
+
for (const [key, sessionId] of Object.entries(ids)) {
|
|
164
|
+
const m = /^qqbot:([^:]+):group:(.+)$/.exec(key)
|
|
165
|
+
if (m === null) continue
|
|
166
|
+
if (typeof sessionId !== 'string' || sessionId === '') continue
|
|
167
|
+
out.push({ key, appId: m[1], groupOpenid: m[2], sessionId })
|
|
168
|
+
}
|
|
169
|
+
return out
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** 清掉 model-prefs.json 里的某个群映射 */
|
|
173
|
+
function clearPrefsKey(key) {
|
|
174
|
+
try {
|
|
175
|
+
const prefs = JSON.parse(readFileSync(PREFS_FILE, 'utf8'))
|
|
176
|
+
if (!prefs || !prefs.sessionIds || prefs.sessionIds[key] === undefined) return false
|
|
177
|
+
delete prefs.sessionIds[key]
|
|
178
|
+
writeFileSync(PREFS_FILE + '.tmp', JSON.stringify(prefs, null, 2))
|
|
179
|
+
writeFileSync(PREFS_FILE, readFileSync(PREFS_FILE + '.tmp'))
|
|
180
|
+
return true
|
|
181
|
+
} catch {
|
|
182
|
+
return false
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 从 profile 的 cordis.patch.yml 取 appId/appSecret(只用于换 token,不落日志) */
|
|
187
|
+
function readQqCredentials() {
|
|
188
|
+
let text
|
|
189
|
+
try {
|
|
190
|
+
text = readFileSync(path.join(qqProfileDir(), 'cordis.patch.yml'), 'utf8')
|
|
191
|
+
} catch {
|
|
192
|
+
return null
|
|
193
|
+
}
|
|
194
|
+
const appId = /appId:\s*["\x27]?([0-9A-Za-z]+)["\x27]?/.exec(text);
|
|
195
|
+
const secret = /appSecret:\s*["\x27]?([0-9A-Za-z]+)["\x27]?/.exec(text);
|
|
196
|
+
if (appId === null || secret === null) return null
|
|
197
|
+
return { appId: appId[1], appSecret: secret[1] }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
async function fetchJson(url, init) {
|
|
201
|
+
const res = await fetch(url, init)
|
|
202
|
+
let body = null
|
|
203
|
+
try { body = await res.json() } catch { /* 非 JSON */ }
|
|
204
|
+
return { status: res.status, body }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function getAccessToken(creds) {
|
|
208
|
+
const { status, body } = await fetchJson('https://bots.qq.com/app/getAppAccessToken', {
|
|
209
|
+
method: 'POST',
|
|
210
|
+
headers: { 'Content-Type': 'application/json' },
|
|
211
|
+
body: JSON.stringify({ appId: creds.appId, clientSecret: creds.appSecret }),
|
|
212
|
+
})
|
|
213
|
+
const token = body && body.access_token
|
|
214
|
+
if (status !== 200 || typeof token !== 'string' || token === '') {
|
|
215
|
+
return { ok: false, message: String((body && body.message) || ('HTTP ' + status)) }
|
|
216
|
+
}
|
|
217
|
+
return { ok: true, token, expiresIn: (body && body.expires_in) || 0 }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
const GROUP_GONE_CODES = new Set([11255, 304003, 304014])
|
|
221
|
+
|
|
222
|
+
/** 200=在;11255=已注销;其余当不确定,不动手 */
|
|
223
|
+
async function probeGroup(token, groupOpenid) {
|
|
224
|
+
const url = 'https://api.sgroup.qq.com/v2/groups/' + groupOpenid + '/info'
|
|
225
|
+
const { status, body } = await fetchJson(url, { headers: { Authorization: 'QQBot ' + token } })
|
|
226
|
+
if (status === 200) return { state: 'alive' }
|
|
227
|
+
const code = body && body.code
|
|
228
|
+
const message = String((body && body.message) || '')
|
|
229
|
+
if (GROUP_GONE_CODES.has(code) || /已注销|不存在|not exist/i.test(message)) return { state: 'gone', code, message }
|
|
230
|
+
return { state: 'unknown', code, message: message || ('HTTP ' + status) }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** 按 frontmatter 的 group_openid 找群页,不靠文件名 */
|
|
234
|
+
function findGroupPage(groupOpenid) {
|
|
235
|
+
try {
|
|
236
|
+
for (const entry of readdirSync(GROUPS_DIR)) {
|
|
237
|
+
if (!entry.endsWith('.md')) continue
|
|
238
|
+
const full = path.join(GROUPS_DIR, entry)
|
|
239
|
+
const head = readFileSync(full, 'utf8').slice(0, 2000)
|
|
240
|
+
if (head.includes('group_openid: ' + groupOpenid)) return full
|
|
241
|
+
}
|
|
242
|
+
} catch { /* 目录不存在 */ }
|
|
243
|
+
return null
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function createState() {
|
|
247
|
+
return { startedAt: nowIso(), lastSweepAt: null, lastSweepResult: null, sweeps: 0, lastError: null }
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
export function apply(ctx) {
|
|
251
|
+
const logger = ctx.logger || console
|
|
252
|
+
const config = loadConfig()
|
|
253
|
+
const state = createState()
|
|
254
|
+
|
|
255
|
+
// 启动自愈:node_modules 里的补丁(QQ 插件升级会覆盖)
|
|
256
|
+
let patchResults = []
|
|
257
|
+
try {
|
|
258
|
+
patchResults = repairPatches(qqProfileDir())
|
|
259
|
+
} catch (error) {
|
|
260
|
+
patchResults = [{ id: 'all', status: 'error', error: error instanceof Error ? error.message : String(error) }]
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const cleaner = () => {
|
|
264
|
+
try {
|
|
265
|
+
return typeof ctx.get === 'function' ? ctx.get('sessionCleaner') : undefined
|
|
266
|
+
} catch {
|
|
267
|
+
return undefined
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const report = (line) => {
|
|
272
|
+
log(line)
|
|
273
|
+
try { if (logger && logger.info) logger.info('[memory-archivist] ' + line) } catch { /* 无所谓 */ }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async function sweepOnce(reason) {
|
|
277
|
+
const started = Date.now()
|
|
278
|
+
const result = { reason, at: nowIso(), raw: { scanned: 0, removed: [], dryRun: config.dryRun === true }, groups: [], archived: 0, skipped: 0, errors: [] }
|
|
279
|
+
try { result.raw = pruneRawSessions(config, report) } catch (error) {
|
|
280
|
+
result.errors.push('raw: ' + (error instanceof Error ? error.message : String(error)))
|
|
281
|
+
}
|
|
282
|
+
const groups = listGroupSessions()
|
|
283
|
+
report('sweep(' + reason + ') 开始:' + groups.length + ' 个群会话,dryRun=' + config.dryRun)
|
|
284
|
+
if (groups.length === 0) {
|
|
285
|
+
result.ms = Date.now() - started
|
|
286
|
+
state.sweeps += 1; state.lastSweepAt = nowIso(); state.lastSweepResult = result
|
|
287
|
+
return result
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
let tokenInfo = { ok: false, message: 'probeGroups=false' }
|
|
291
|
+
if (config.probeGroups) {
|
|
292
|
+
const creds = readQqCredentials()
|
|
293
|
+
tokenInfo = creds === null
|
|
294
|
+
? { ok: false, message: 'cordis.patch.yml 里找不到 appId/appSecret' }
|
|
295
|
+
: await getAccessToken(creds)
|
|
296
|
+
if (!tokenInfo.ok) result.errors.push('token: ' + tokenInfo.message)
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const batch = groups.slice(0, Math.max(1, Number(config.maxPerSweep) || 5))
|
|
300
|
+
for (const item of batch) {
|
|
301
|
+
const row = { groupOpenid: item.groupOpenid, sessionId: item.sessionId, state: 'unknown', action: 'none', page: findGroupPage(item.groupOpenid) }
|
|
302
|
+
if (tokenInfo.ok !== true) {
|
|
303
|
+
result.skipped += 1; result.groups.push(row); continue
|
|
304
|
+
}
|
|
305
|
+
try {
|
|
306
|
+
const probe = await probeGroup(tokenInfo.token, item.groupOpenid)
|
|
307
|
+
row.state = probe.state
|
|
308
|
+
if (probe.state !== 'gone') { result.skipped += 1; result.groups.push(row); continue }
|
|
309
|
+
row.action = config.dryRun ? 'would-archive' : 'archiving'
|
|
310
|
+
result.groups.push(row)
|
|
311
|
+
if (config.dryRun) {
|
|
312
|
+
report('[dryRun] 群 ' + item.groupOpenid + ' 已失效(' + (probe.code || '') + ' ' + (probe.message || '') + '),会归档并删会话 ' + item.sessionId)
|
|
313
|
+
continue
|
|
314
|
+
}
|
|
315
|
+
const done = await archiveAndDelete(item, probe, cleaner())
|
|
316
|
+
row.action = done.ok ? 'archived+deleted' : 'failed'
|
|
317
|
+
if (done.ok) result.archived += 1; else result.errors.push(item.groupOpenid + ': ' + done.reason)
|
|
318
|
+
} catch (error) {
|
|
319
|
+
result.errors.push(item.groupOpenid + ': ' + (error instanceof Error ? error.message : String(error)))
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
result.ms = Date.now() - started
|
|
324
|
+
state.sweeps += 1; state.lastSweepAt = nowIso(); state.lastSweepResult = result
|
|
325
|
+
report('sweep(' + reason + ') 结束:归档 ' + result.archived + ',跳过 ' + result.skipped + ',错误 ' + result.errors.length + ',耗时 ' + result.ms + 'ms')
|
|
326
|
+
return result
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function archiveAndDelete(item, probe) {
|
|
330
|
+
const service = cleaner()
|
|
331
|
+
if (service === undefined || service === null) {
|
|
332
|
+
return { ok: false, reason: 'sessionCleaner 不可用' }
|
|
333
|
+
}
|
|
334
|
+
let transcript
|
|
335
|
+
try {
|
|
336
|
+
transcript = await service.read(item.sessionId)
|
|
337
|
+
} catch (error) {
|
|
338
|
+
return { ok: false, reason: (error instanceof Error ? error.message : String(error)) }
|
|
339
|
+
}
|
|
340
|
+
if (!transcript || transcript.ok !== true) {
|
|
341
|
+
const msg = String((transcript && transcript.error) || '会话不可读')
|
|
342
|
+
if (/not ?found|ENOENT|does not exist|不存在/i.test(msg)) {
|
|
343
|
+
clearPrefsKey(item.key)
|
|
344
|
+
return { ok: true, reason: '会话早就不在了,已清理映射' }
|
|
345
|
+
}
|
|
346
|
+
return { ok: false, reason: '会话不可读:' + msg }
|
|
347
|
+
}
|
|
348
|
+
const rawPath = writeRawSession(item, transcript)
|
|
349
|
+
const pagePath = appendToGroupPage(item, transcript, probe, rawPath)
|
|
350
|
+
if (rawPath === null || pagePath === null) return { ok: false, reason: '归档写盘失败' }
|
|
351
|
+
let deleted
|
|
352
|
+
try {
|
|
353
|
+
deleted = await service.delete([item.sessionId], {})
|
|
354
|
+
} catch (error) {
|
|
355
|
+
return { ok: false, reason: '删除失败:' + (error instanceof Error ? error.message : String(error)) }
|
|
356
|
+
}
|
|
357
|
+
if (!deleted || deleted.ok !== true) return { ok: false, reason: '删除失败:' + String((deleted && deleted.error) || 'unknown') }
|
|
358
|
+
clearPrefsKey(item.key)
|
|
359
|
+
report('已归档 ' + item.groupOpenid + ' → ' + path.basename(rawPath) + ' / ' + path.basename(pagePath) + ',会话已删');
|
|
360
|
+
return { ok: true }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function rawFileName(item, day) {
|
|
364
|
+
const short = item.sessionId.replace(/^session-/, '').slice(0, 8)
|
|
365
|
+
return day + '-' + item.groupOpenid.slice(0, 8) + '-' + short + '.md'
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function writeRawSession(item, transcript) {
|
|
369
|
+
try {
|
|
370
|
+
mkdirSync(RAW_DIR, { recursive: true })
|
|
371
|
+
const day = nowIso().slice(0, 10)
|
|
372
|
+
const file = path.join(RAW_DIR, rawFileName(item, day))
|
|
373
|
+
const lines = []
|
|
374
|
+
lines.push('---')
|
|
375
|
+
lines.push('title: 群会话原文 ' + item.groupOpenid.slice(0, 8))
|
|
376
|
+
lines.push('date: ' + day)
|
|
377
|
+
lines.push('type: raw')
|
|
378
|
+
lines.push('group_openid: ' + item.groupOpenid)
|
|
379
|
+
lines.push('session_id: ' + item.sessionId)
|
|
380
|
+
lines.push('session_title: ' + String(transcript.title || ''))
|
|
381
|
+
lines.push('archived_at: ' + nowIso())
|
|
382
|
+
lines.push('messages: ' + (Array.isArray(transcript.messages) ? transcript.messages.length : 0))
|
|
383
|
+
lines.push('---', '')
|
|
384
|
+
const messages = Array.isArray(transcript.messages) ? transcript.messages : []
|
|
385
|
+
messages.forEach((msg, index) => {
|
|
386
|
+
if (index > 0 && index % 500 === 0) lines.push('', '<!-- seg ' + (index / 500) + ' -->', '')
|
|
387
|
+
const who = msg.role === 'user' ? '对方' : '鱼鱼'
|
|
388
|
+
const time = typeof msg.time === 'number' ? new Date(msg.time).toISOString() : ''
|
|
389
|
+
lines.push('**' + who + '**' + (time === '' ? '' : '(' + time + ')') + ':' + String(msg.text || '').replace(/\r/g, ''))
|
|
390
|
+
lines.push('')
|
|
391
|
+
})
|
|
392
|
+
writeFileSync(file, lines.join('\n'))
|
|
393
|
+
return file
|
|
394
|
+
} catch (error) {
|
|
395
|
+
report('写 T0 失败:' + (error instanceof Error ? error.message : String(error)))
|
|
396
|
+
return null
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function appendToGroupPage(item, transcript, probe, rawPath) {
|
|
401
|
+
try {
|
|
402
|
+
mkdirSync(GROUPS_DIR, { recursive: true })
|
|
403
|
+
const short = item.groupOpenid.slice(0, 8)
|
|
404
|
+
let page = findGroupPage(item.groupOpenid)
|
|
405
|
+
const messages = Array.isArray(transcript.messages) ? transcript.messages : []
|
|
406
|
+
const rawName = rawPath === null || rawPath === undefined ? '(T0 写盘失败)' : path.basename(rawPath)
|
|
407
|
+
const all = messages.map((msg) => {
|
|
408
|
+
const who = msg.role === 'user' ? '对方' : '鱼鱼'
|
|
409
|
+
const time = typeof msg.time === 'number' ? new Date(msg.time).toTimeString().slice(0, 5) : ''
|
|
410
|
+
return '- ' + time + ' ' + who + ':' + String(msg.text || '').replace(/\s+/g, ' ').slice(0, 400)
|
|
411
|
+
})
|
|
412
|
+
// T1:去噪明细。短群只留一行指向 T0;超预算的长群明细留在 T0,等 digest 提炼成 T2。
|
|
413
|
+
const DETAIL_BUDGET = 24 * 1024
|
|
414
|
+
let detail
|
|
415
|
+
if (messages.length <= 20) {
|
|
416
|
+
const head = all.slice(0, 5).join('\n')
|
|
417
|
+
detail = '- 共 ' + messages.length + ' 条,原文见 raw/sessions/' + rawName
|
|
418
|
+
if (head !== '') detail += '\n' + head + (all.length > 5 ? '\n- ……' : '')
|
|
419
|
+
} else if (all.join('\n').length > DETAIL_BUDGET) {
|
|
420
|
+
detail = [
|
|
421
|
+
'- 共 ' + messages.length + ' 条,超过单页预算,明细留在 raw/sessions/' + rawName,
|
|
422
|
+
'- 待精修:下次 digest 时按 T2 模板提炼(核心结论 / 已确认信息 / 未解决问题)',
|
|
423
|
+
'',
|
|
424
|
+
all.slice(0, 5).join('\n'),
|
|
425
|
+
'- ……',
|
|
426
|
+
all.slice(-5).join('\n'),
|
|
427
|
+
].join('\n')
|
|
428
|
+
} else {
|
|
429
|
+
detail = all.join('\n')
|
|
430
|
+
}
|
|
431
|
+
const section = [
|
|
432
|
+
'',
|
|
433
|
+
'### ' + nowIso().slice(0, 16).replace('T', ' ') + ' · 群失效(' + (probe.code || 'gone') + ')自动归档',
|
|
434
|
+
'',
|
|
435
|
+
'- 会话:' + item.sessionId + '(' + messages.length + ' 条)',
|
|
436
|
+
'- 原标题:' + String(transcript.title || ''),
|
|
437
|
+
'',
|
|
438
|
+
detail === '' ? '(无消息)' : detail,
|
|
439
|
+
'',
|
|
440
|
+
].join('\n')
|
|
441
|
+
if (page === null) {
|
|
442
|
+
page = path.join(GROUPS_DIR, short + '-待命名.md')
|
|
443
|
+
const head = [
|
|
444
|
+
'---',
|
|
445
|
+
'title: 群 ' + short,
|
|
446
|
+
'date: ' + nowIso().slice(0, 10),
|
|
447
|
+
'type: group',
|
|
448
|
+
'salience: 2',
|
|
449
|
+
'summary: QQ 群 ' + short + '(群名待补):自动归档的会话摘要。',
|
|
450
|
+
'group_openid: ' + item.groupOpenid,
|
|
451
|
+
'---',
|
|
452
|
+
'',
|
|
453
|
+
'# ' + short,
|
|
454
|
+
'',
|
|
455
|
+
'## 群档案',
|
|
456
|
+
'',
|
|
457
|
+
'- group_openid:' + item.groupOpenid,
|
|
458
|
+
'- 群名:(待补)',
|
|
459
|
+
'',
|
|
460
|
+
'## 长期结论',
|
|
461
|
+
'',
|
|
462
|
+
'_(T3,一行一条)_',
|
|
463
|
+
'',
|
|
464
|
+
'## 历史',
|
|
465
|
+
'',
|
|
466
|
+
].join('\n')
|
|
467
|
+
writeFileSync(page, head + section)
|
|
468
|
+
} else {
|
|
469
|
+
appendFileSync(page, section)
|
|
470
|
+
}
|
|
471
|
+
return page
|
|
472
|
+
} catch (error) {
|
|
473
|
+
report('写群页失败:' + (error instanceof Error ? error.message : String(error)))
|
|
474
|
+
return null
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
let timer = null
|
|
479
|
+
ctx.effect(() => {
|
|
480
|
+
if (config.enabled !== true) {
|
|
481
|
+
report('已禁用(config.enabled=false),不启动巡检')
|
|
482
|
+
return () => {}
|
|
483
|
+
}
|
|
484
|
+
const delay = Math.max(5, Number(config.firstSweepDelaySec) || 60) * 1000
|
|
485
|
+
const interval = Math.max(1, Number(config.sweepMinutes) || 5) * 60 * 1000
|
|
486
|
+
const kick = setTimeout(() => {
|
|
487
|
+
void sweepOnce('startup').catch((error) => {
|
|
488
|
+
state.lastError = String(error); report('启动巡检异常:' + (error instanceof Error ? error.message : String(error)))
|
|
489
|
+
})
|
|
490
|
+
timer = setInterval(() => {
|
|
491
|
+
void sweepOnce('timer').catch((error) => {
|
|
492
|
+
state.lastError = String(error); report('定时巡检异常:' + (error instanceof Error ? error.message : String(error)))
|
|
493
|
+
})
|
|
494
|
+
}, interval)
|
|
495
|
+
if (timer && timer.unref) timer.unref()
|
|
496
|
+
}, delay)
|
|
497
|
+
if (kick && kick.unref) kick.unref()
|
|
498
|
+
report('已启动:每 ' + config.sweepMinutes + ' 分钟巡检,首次 ' + config.firstSweepDelaySec + 's 后,dryRun=' + config.dryRun)
|
|
499
|
+
return () => {
|
|
500
|
+
clearTimeout(kick)
|
|
501
|
+
if (timer !== null) clearInterval(timer)
|
|
502
|
+
}
|
|
503
|
+
}, 'memory-archivist.sweeper')
|
|
504
|
+
|
|
505
|
+
const sendJson = (res, status, payload) => {
|
|
506
|
+
const body = JSON.stringify(payload, null, 2)
|
|
507
|
+
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' })
|
|
508
|
+
res.end(body)
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
ctx.effect(() => ctx.webServer.register({
|
|
512
|
+
kind: 'prefix',
|
|
513
|
+
path: API_PREFIX,
|
|
514
|
+
handler: async (req, res) => {
|
|
515
|
+
const route = (req.url || '/').split('?')[0].slice(API_PREFIX.length) || '/'
|
|
516
|
+
try {
|
|
517
|
+
if (route === '/status' && req.method === 'GET') {
|
|
518
|
+
const groups = listGroupSessions().map((item) => ({
|
|
519
|
+
groupOpenid: item.groupOpenid,
|
|
520
|
+
sessionId: item.sessionId,
|
|
521
|
+
page: findGroupPage(item.groupOpenid),
|
|
522
|
+
}))
|
|
523
|
+
return sendJson(res, 200, {
|
|
524
|
+
ok: true,
|
|
525
|
+
version: '0.1.0',
|
|
526
|
+
config,
|
|
527
|
+
patches: patchResults,
|
|
528
|
+
state,
|
|
529
|
+
groups,
|
|
530
|
+
paths: {
|
|
531
|
+
memory: MEMORY_ROOT,
|
|
532
|
+
raw: RAW_DIR,
|
|
533
|
+
groups: GROUPS_DIR,
|
|
534
|
+
qqData: QQ_DATA_DIR,
|
|
535
|
+
log: LOG_FILE,
|
|
536
|
+
config: configPath(),
|
|
537
|
+
profile: profileDir(),
|
|
538
|
+
},
|
|
539
|
+
cleaner: cleaner() === undefined ? 'missing' : 'ok',
|
|
540
|
+
})
|
|
541
|
+
}
|
|
542
|
+
if (route === '/sweep' && req.method === 'POST') {
|
|
543
|
+
const result = await sweepOnce('manual')
|
|
544
|
+
return sendJson(res, 200, { ok: true, result })
|
|
545
|
+
}
|
|
546
|
+
return sendJson(res, 404, { ok: false, error: 'not found' })
|
|
547
|
+
} catch (error) {
|
|
548
|
+
return sendJson(res, 500, { ok: false, error: error instanceof Error ? error.message : String(error) })
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
}), 'memory-archivist.routes')
|
|
552
|
+
|
|
553
|
+
for (const item of patchResults) {
|
|
554
|
+
if (item.status !== 'already') report('补丁 ' + item.id + ' → ' + item.status + (item.error ? '(' + item.error + ')' : ''))
|
|
555
|
+
}
|
|
556
|
+
report('已加载 v0.1.0:dryRun=' + config.dryRun + ',每 ' + config.sweepMinutes + ' 分钟巡检')
|
|
557
|
+
}
|
package/lib/patches.js
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-memory-archivist —— node_modules 补丁自愈
|
|
3
|
+
*
|
|
4
|
+
* 背景:有几处行为长在第三方插件内部(群纯文本 @ 识别、工具失败不上 QQ、
|
|
5
|
+
* 群会话跳过提问引导),这些插件没有对外钩子可用,只能改它们的源码。
|
|
6
|
+
* 插件一升级,改动就丢 —— 所以这里在每次启动时自检:
|
|
7
|
+
* - 已经打过的:跳过(幂等)
|
|
8
|
+
* - 没打的且锚点对得上:按顺序写入补丁,写完再读回校验
|
|
9
|
+
* - 锚点对不上(插件升级改了结构):只记一条日志并跳过,绝不拦启动、绝不瞎改
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { existsSync, readFileSync, writeFileSync, copyFileSync } from 'node:fs'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
|
|
15
|
+
const QQ_PLUGIN = path.join('node_modules', '@tencent-connect', 'dsh-qqbot', 'lib')
|
|
16
|
+
const HTA_PLUGIN = path.join('node_modules', 'dsh-help-me-to-ask')
|
|
17
|
+
|
|
18
|
+
/** 每一条:id、相对路径、已打标记、若干处 [锚点 → 替换] */
|
|
19
|
+
export const PATCHES = [
|
|
20
|
+
{
|
|
21
|
+
id: 'qqbot.group-at-mention',
|
|
22
|
+
title: '群聊纯文本 @ 也算提及本 bot',
|
|
23
|
+
file: path.join(QQ_PLUGIN, 'gateway', 'middleware-setup.js'),
|
|
24
|
+
marker: 'isImplicitMention:',
|
|
25
|
+
ops: [
|
|
26
|
+
{
|
|
27
|
+
anchor: [
|
|
28
|
+
' bot.use(mentionGate({',
|
|
29
|
+
' requireMentionInGroup: config.requireMention,',
|
|
30
|
+
' }));',
|
|
31
|
+
].join('\n'),
|
|
32
|
+
replacement: [
|
|
33
|
+
' bot.use(mentionGate({',
|
|
34
|
+
' requireMentionInGroup: config.requireMention,',
|
|
35
|
+
' // 兜底:QQ 有时以纯文本 "@昵称" 下发群 @(事件类型为 GROUP_MESSAGE_CREATE,',
|
|
36
|
+
' // 内容里没有 <@!appId> 标记),SDK 默认检测会误判为未 @,',
|
|
37
|
+
' // 这里把「消息开头就是 @」也视为提及本 bot。',
|
|
38
|
+
' isImplicitMention: (ctx) => {',
|
|
39
|
+
' const msg = ctx.message;',
|
|
40
|
+
' if (Array.isArray(msg.mentions) && msg.mentions.some((m) => m && m.is_you === true))',
|
|
41
|
+
' return true;',
|
|
42
|
+
" const c = String(msg.content ?? '').trim();",
|
|
43
|
+
" return c.startsWith('@') || c.startsWith('<@');",
|
|
44
|
+
' },',
|
|
45
|
+
' }));',
|
|
46
|
+
].join('\n'),
|
|
47
|
+
},
|
|
48
|
+
],
|
|
49
|
+
},
|
|
50
|
+
{
|
|
51
|
+
id: 'qqbot.show-tool-errors',
|
|
52
|
+
title: '工具失败结果默认不上 QQ(config 键)',
|
|
53
|
+
file: path.join(QQ_PLUGIN, 'config.js'),
|
|
54
|
+
marker: 'showToolErrors: Schema.boolean()',
|
|
55
|
+
ops: [
|
|
56
|
+
{
|
|
57
|
+
anchor: " showToolResults: Schema.boolean().default(false).description('是否展示工具调用成功结果(错误始终展示)'),",
|
|
58
|
+
replacement: [
|
|
59
|
+
" showToolResults: Schema.boolean().default(false).description('是否展示工具调用成功结果'),",
|
|
60
|
+
" showToolErrors: Schema.boolean().default(false).description('是否展示工具调用失败结果(默认关闭,避免报错刷到 QQ)'),",
|
|
61
|
+
].join('\n'),
|
|
62
|
+
},
|
|
63
|
+
],
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
id: 'qqbot.tool-error-gate',
|
|
67
|
+
title: '工具结果发送开关按成功/失败分别判断',
|
|
68
|
+
file: path.join(QQ_PLUGIN, 'transport', 'outbound.js'),
|
|
69
|
+
marker: 'showToolErrors !== true',
|
|
70
|
+
ops: [
|
|
71
|
+
{
|
|
72
|
+
anchor: [
|
|
73
|
+
' /** 工具结果:错误始终发送,成功结果按开关 */',
|
|
74
|
+
' onToolResult(record, event) {',
|
|
75
|
+
' const call = this.toolCalls.get(event.callId);',
|
|
76
|
+
' this.toolCalls.delete(event.callId);',
|
|
77
|
+
' if (call === undefined)',
|
|
78
|
+
' return;',
|
|
79
|
+
' if (event.error === undefined && !this.config.showToolResults)',
|
|
80
|
+
' return;',
|
|
81
|
+
].join('\n'),
|
|
82
|
+
replacement: [
|
|
83
|
+
' /** 工具结果:成功看 showToolResults、失败看 showToolErrors,默认都静默 */',
|
|
84
|
+
' onToolResult(record, event) {',
|
|
85
|
+
' const call = this.toolCalls.get(event.callId);',
|
|
86
|
+
' this.toolCalls.delete(event.callId);',
|
|
87
|
+
' if (call === undefined)',
|
|
88
|
+
' return;',
|
|
89
|
+
' // 成功结果看 showToolResults;失败结果看 showToolErrors(默认都关闭,避免刷屏)',
|
|
90
|
+
' if (event.error === undefined ? !this.config.showToolResults : this.config.showToolErrors !== true)',
|
|
91
|
+
' return;',
|
|
92
|
+
].join('\n'),
|
|
93
|
+
},
|
|
94
|
+
],
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
id: 'help-me-to-ask.skip-group-sessions',
|
|
98
|
+
title: '群会话跳过提问引导(没有桌面卡片可点)',
|
|
99
|
+
file: path.join(HTA_PLUGIN, 'index.js'),
|
|
100
|
+
marker: 'isExternalGroupSession',
|
|
101
|
+
ops: [
|
|
102
|
+
{
|
|
103
|
+
anchor: [
|
|
104
|
+
' cardClaimWaitMs: z.number().default(2500).volatile(),',
|
|
105
|
+
'})',
|
|
106
|
+
].join('\n'),
|
|
107
|
+
replacement: [
|
|
108
|
+
' cardClaimWaitMs: z.number().default(2500).volatile(),',
|
|
109
|
+
' skipGroupSessions: z.boolean().default(true).volatile(),',
|
|
110
|
+
'})',
|
|
111
|
+
].join('\n'),
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
anchor: [
|
|
115
|
+
'/**',
|
|
116
|
+
' * 一次性接管状态:global,不写进插件配置(宿主只能读配置,写回由客户端做)。',
|
|
117
|
+
' * armed=true 时,下一次符合条件的新对话会强制走一遍提问流程,随后自动关闭。',
|
|
118
|
+
' * fallback 记录激活前的模式,供界面回显/兜底。',
|
|
119
|
+
' */',
|
|
120
|
+
'function oncePath() {',
|
|
121
|
+
].join('\n'),
|
|
122
|
+
replacement: [
|
|
123
|
+
'/**',
|
|
124
|
+
' * 群聊会话没有桌面卡片可点:一旦弹提问卡,整轮会被卡住,群里看不到任何回馈。',
|
|
125
|
+
' * dsh-qqbot 会把每个对端最新的 sessionId 写进 ~/.dsh-qqbot/model-prefs.json,',
|
|
126
|
+
' * 键形如 qqbot:<appId>:group:<group_openid>,据此识别群会话(缓存 5s)。',
|
|
127
|
+
' */',
|
|
128
|
+
'const GROUP_SESSION_CACHE = { at: 0, ids: new Set() }',
|
|
129
|
+
'function isExternalGroupSession(sessionId) {',
|
|
130
|
+
' const now = Date.now()',
|
|
131
|
+
' if (now - GROUP_SESSION_CACHE.at > 5000) {',
|
|
132
|
+
' GROUP_SESSION_CACHE.at = now',
|
|
133
|
+
' const ids = new Set()',
|
|
134
|
+
' try {',
|
|
135
|
+
" const raw = JSON.parse(readFileSync(join(homedir(), '.dsh-qqbot', 'model-prefs.json'), 'utf8'))",
|
|
136
|
+
' for (const [key, value] of Object.entries(raw?.sessionIds ?? {})) {',
|
|
137
|
+
" if (typeof key === 'string' && key.includes(':group:') && typeof value === 'string') ids.add(value)",
|
|
138
|
+
' }',
|
|
139
|
+
' } catch {}',
|
|
140
|
+
' GROUP_SESSION_CACHE.ids = ids',
|
|
141
|
+
' }',
|
|
142
|
+
' return GROUP_SESSION_CACHE.ids.has(sessionId)',
|
|
143
|
+
'}',
|
|
144
|
+
'',
|
|
145
|
+
'/**',
|
|
146
|
+
' * 一次性接管状态:global,不写进插件配置(宿主只能读配置,写回由客户端做)。',
|
|
147
|
+
' * armed=true 时,下一次符合条件的新对话会强制走一遍提问流程,随后自动关闭。',
|
|
148
|
+
' * fallback 记录激活前的模式,供界面回显/兜底。',
|
|
149
|
+
' */',
|
|
150
|
+
'function oncePath() {',
|
|
151
|
+
].join('\n'),
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
anchor: [
|
|
155
|
+
' if (!isRootAgent(ctx, agent)) return next()',
|
|
156
|
+
' const store = sessions.get(sessionId)',
|
|
157
|
+
].join('\n'),
|
|
158
|
+
replacement: [
|
|
159
|
+
' if (!isRootAgent(ctx, agent)) return next()',
|
|
160
|
+
' if (config.skipGroupSessions.get() === true && isExternalGroupSession(sessionId)) {',
|
|
161
|
+
" diag('skip', { sessionId, reason: 'external-group-session' })",
|
|
162
|
+
' return next()',
|
|
163
|
+
' }',
|
|
164
|
+
' const store = sessions.get(sessionId)',
|
|
165
|
+
].join('\n'),
|
|
166
|
+
},
|
|
167
|
+
],
|
|
168
|
+
},
|
|
169
|
+
]
|
|
170
|
+
|
|
171
|
+
/** 把用 \n 写的锚点/替换按目标文件的换行风格重写 */
|
|
172
|
+
function toEol(text, eol) {
|
|
173
|
+
return eol === '\n' ? text : text.split('\n').join(eol)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* 逐条自检并修补。返回每条的结果,调用方只负责记日志。
|
|
178
|
+
* 任何异常都被吃掉 —— 补丁失败绝不影响 DSH 启动。
|
|
179
|
+
*/
|
|
180
|
+
export function repairPatches(profileDir) {
|
|
181
|
+
const results = []
|
|
182
|
+
for (const patch of PATCHES) {
|
|
183
|
+
const file = path.join(profileDir, patch.file)
|
|
184
|
+
if (!existsSync(file)) {
|
|
185
|
+
results.push({ id: patch.id, status: 'missing-file', file })
|
|
186
|
+
continue
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
let text = readFileSync(file, 'utf8')
|
|
190
|
+
if (text.includes(patch.marker)) {
|
|
191
|
+
results.push({ id: patch.id, status: 'already' })
|
|
192
|
+
continue
|
|
193
|
+
}
|
|
194
|
+
const eol = text.includes('\r\n') ? '\r\n' : '\n'
|
|
195
|
+
const ops = []
|
|
196
|
+
let mismatched = false
|
|
197
|
+
for (const op of patch.ops) {
|
|
198
|
+
const anchor = toEol(op.anchor, eol)
|
|
199
|
+
const first = text.indexOf(anchor)
|
|
200
|
+
if (first === -1 || text.indexOf(anchor, first + 1) !== -1) {
|
|
201
|
+
mismatched = true
|
|
202
|
+
break
|
|
203
|
+
}
|
|
204
|
+
ops.push({ anchor, replacement: toEol(op.replacement, eol) })
|
|
205
|
+
text = text.slice(0, first) + '\u0000' + text.slice(first + anchor.length)
|
|
206
|
+
}
|
|
207
|
+
if (mismatched) {
|
|
208
|
+
results.push({ id: patch.id, status: 'anchor-mismatch', file })
|
|
209
|
+
continue
|
|
210
|
+
}
|
|
211
|
+
// 用占位符先把所有锚点挖掉,再按顺序填回,避免替换文本被后续锚点误伤
|
|
212
|
+
let out = text
|
|
213
|
+
for (const op of ops) {
|
|
214
|
+
const at = out.indexOf('\u0000')
|
|
215
|
+
out = out.slice(0, at) + op.replacement + out.slice(at + 1)
|
|
216
|
+
}
|
|
217
|
+
const backup = file + '.bak-memory-archivist'
|
|
218
|
+
if (!existsSync(backup)) copyFileSync(file, backup)
|
|
219
|
+
writeFileSync(file, out)
|
|
220
|
+
const verify = readFileSync(file, 'utf8')
|
|
221
|
+
if (verify.includes(patch.marker)) {
|
|
222
|
+
results.push({ id: patch.id, status: 'applied' })
|
|
223
|
+
} else {
|
|
224
|
+
results.push({ id: patch.id, status: 'verify-failed', file })
|
|
225
|
+
}
|
|
226
|
+
} catch (error) {
|
|
227
|
+
results.push({ id: patch.id, status: 'error', error: error instanceof Error ? error.message : String(error) })
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return results
|
|
231
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-memory-archivist",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "QQ 群会话归档(针对 dsh-qqbot 与 dsh-plugin-memory 优化):群被踢/解散前先把 T0 原文与群页摘要落进记忆库,再删会话;同时负责 node_modules 补丁的启动自愈。",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"deepseek",
|
|
8
|
+
"deepseek-harness",
|
|
9
|
+
"dsh",
|
|
10
|
+
"dsh-plugin",
|
|
11
|
+
"dsh-qqbot",
|
|
12
|
+
"dsh-plugin-memory",
|
|
13
|
+
"memory",
|
|
14
|
+
"qqbot",
|
|
15
|
+
"qq-group",
|
|
16
|
+
"archive"
|
|
17
|
+
],
|
|
18
|
+
"main": "lib/index.js",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": "./lib/index.js",
|
|
21
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"lib",
|
|
26
|
+
"cordis.patch.yml",
|
|
27
|
+
"README.md",
|
|
28
|
+
"LICENSE"
|
|
29
|
+
],
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"@deepseek-ai/cordis": "^4.0.1"
|
|
32
|
+
},
|
|
33
|
+
"engines": {
|
|
34
|
+
"node": ">=20"
|
|
35
|
+
},
|
|
36
|
+
"dsh": {
|
|
37
|
+
"bundle": {
|
|
38
|
+
"patch": "./cordis.patch.yml"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"license": "MIT",
|
|
45
|
+
"repository": {
|
|
46
|
+
"type": "git",
|
|
47
|
+
"url": "git+https://github.com/haidao128/dsh-plugin-.git"
|
|
48
|
+
},
|
|
49
|
+
"homepage": "https://github.com/haidao128/dsh-plugin-#readme",
|
|
50
|
+
"bugs": {
|
|
51
|
+
"url": "https://github.com/haidao128/dsh-plugin-/issues"
|
|
52
|
+
},
|
|
53
|
+
"author": "ghaidao128"
|
|
54
|
+
}
|