dsh-hub-center 0.12.1 → 0.12.3
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/CHANGELOG.md +26 -0
- package/README.md +4 -1
- package/index.js +143 -2
- package/lib/mem-audit.js +289 -0
- package/lib/platform.js +274 -0
- package/lib/restore.js +173 -0
- package/package.json +4 -2
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# 更新日志
|
|
2
|
+
|
|
3
|
+
中枢(dsh-hub-center)每次发版动了什么,按版本倒序记在这儿。
|
|
4
|
+
中枢面板里也有同一份记录:「更新」页能看到最近改了啥。
|
|
5
|
+
|
|
6
|
+
## 0.12.3 — 2026-11-23
|
|
7
|
+
|
|
8
|
+
### 新增
|
|
9
|
+
|
|
10
|
+
- 记忆质检:`GET /hub-center/memory/audit` 扫一遍库,给出分数和可修项(缺标签、缺权重、孤立条目之类)
|
|
11
|
+
- 记忆修复:`POST /hub-center/memory/repair` 按项修,支持 `dryRun` 先看再动,修完在事件日志里记一条 `audit`
|
|
12
|
+
- 中枢加「更新」页:按时间记每次新加了什么功能、修了什么,可以手动补记;任务页底部显示最近三条
|
|
13
|
+
- 设置页改成自适应网格:窗口宽两列、窄一列,不再一路拉长
|
|
14
|
+
|
|
15
|
+
### 修复
|
|
16
|
+
|
|
17
|
+
- 身体状态里「精神」写反了:原来醒着回精神、睡着掉精神,改成醒着耗、睡着回,不会再越睡越困
|
|
18
|
+
- 设置页「主动找你 / 群聊 / 自主行为」三块渲染不出来(前台引用了个没定义的变量,整段中断),现在都回来了
|
|
19
|
+
|
|
20
|
+
## 0.12.2 — 2026-11-21
|
|
21
|
+
|
|
22
|
+
- 对着 DSH 2.0.22-next 调;修了装不上 / 面板拉不起来的几个问题
|
|
23
|
+
|
|
24
|
+
## 更早
|
|
25
|
+
|
|
26
|
+
早期版本没有单独记录,改动都散在各次提交里。
|
package/README.md
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
# dsh-hub-center(左栏中枢)安装说明
|
|
2
2
|
|
|
3
3
|
> 这是一个 DSH 插件:装好后 DSH 左栏会多一个图标,点开是中枢界面(记忆、日记、表情、看板、设置)。
|
|
4
|
-
> 版本:0.12.
|
|
4
|
+
> 版本:0.12.3(对着 DSH 2.0.22-next 调的)· 许可:MIT(本包内代码与配置,含 presets\表情模板.yml)· 图标 icon.svg 为自绘
|
|
5
|
+
> 每次改了什么记在 [CHANGELOG.md](CHANGELOG.md)
|
|
5
6
|
|
|
6
7
|
---
|
|
7
8
|
|
|
@@ -166,5 +167,7 @@ POST /hub-center/paths 改路径
|
|
|
166
167
|
GET /hub-center/features 功能开关
|
|
167
168
|
POST /hub-center/features 改开关
|
|
168
169
|
GET /hub-center/setup 网页设置页(路径 + 功能开关)
|
|
170
|
+
GET /hub-center/memory/audit 记忆质检(分数 + 可修项)
|
|
171
|
+
POST /hub-center/memory/repair 记忆修复(body 里带 items / dryRun)
|
|
169
172
|
```
|
|
170
173
|
|
package/index.js
CHANGED
|
@@ -9,16 +9,24 @@ import { spawn } from 'node:child_process'
|
|
|
9
9
|
// 原来三个独立小插件并进来:跨窗口总线、语音朗读(客户端那个「任务」按钮在 client.js)
|
|
10
10
|
import { apply as applySessionBus } from './lib/session-bus.js'
|
|
11
11
|
import { apply as applyVoice } from './lib/voice.js'
|
|
12
|
+
import { createRestore } from './lib/restore.js'
|
|
13
|
+
import { createAudit } from './lib/mem-audit.js'
|
|
14
|
+
import { createModuleHost, moduleDir } from './lib/platform.js'
|
|
12
15
|
|
|
13
16
|
export const name = 'dsh-hub-center'
|
|
14
17
|
export const inject = ['webServer']
|
|
15
18
|
|
|
16
|
-
const VERSION = '0.
|
|
19
|
+
const VERSION = '0.12.3'
|
|
20
|
+
// 这一版是对着哪代 DSH 调的,状态接口和首屏「关于」都带出去
|
|
21
|
+
const DSH_VERSION = '2.0.22-next'
|
|
17
22
|
const HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
18
23
|
const BASE = join(HOME, 'plugins-data', 'dsh-hub')
|
|
19
24
|
const QQ_DATA = join(HOME, 'plugins-data', 'dsh-qq-hub')
|
|
20
25
|
const HALF_LIFE_DAYS = 60
|
|
21
26
|
const OUT_DIR = join(BASE, 'out')
|
|
27
|
+
// 解档:DSCTX 标签库在哪、还原出来的记录放哪
|
|
28
|
+
const DSCTX_DIR = process.env.DSH_DSCTX_DIR || 'D:\\AI\\memory\\state\\dsctx'
|
|
29
|
+
const RESTORE_OUT = join(BASE, 'restore')
|
|
22
30
|
|
|
23
31
|
// ===== 可配置路径:默认就是本机这套,别人改 paths.json 或设 DSH_AI_ROOT 即可 =====
|
|
24
32
|
const PATHS_FILE = join(BASE, 'paths.json')
|
|
@@ -1488,21 +1496,73 @@ async function onebotCall(action, timeoutMs = 2500) {
|
|
|
1488
1496
|
}
|
|
1489
1497
|
}
|
|
1490
1498
|
|
|
1499
|
+
|
|
1500
|
+
// ---- 按轮裁断(原型):每 N 轮把旧消息切成标签,模型只看到最近几条 ----
|
|
1501
|
+
function setupCtxCut(ctx, store) {
|
|
1502
|
+
const DIR = join(BASE, 'ctx-cut')
|
|
1503
|
+
const ROUNDS = 10 // 每 10 轮剪一次
|
|
1504
|
+
const KEEP = 12 // 保留最近 12 条消息
|
|
1505
|
+
let rounds = 0
|
|
1506
|
+
try {
|
|
1507
|
+
ctx.on('agent/pre-step', async ({ agent, step }, next) => {
|
|
1508
|
+
const decision = await next()
|
|
1509
|
+
try {
|
|
1510
|
+
if (!decision || decision.kind === 'reject') return decision
|
|
1511
|
+
if (step === 1) rounds += 1
|
|
1512
|
+
if (rounds < ROUNDS) return decision
|
|
1513
|
+
const msgs = Array.isArray(decision.messages) ? decision.messages : null
|
|
1514
|
+
if (!msgs || msgs.length <= KEEP + 4) { rounds = 0; return decision }
|
|
1515
|
+
rounds = 0
|
|
1516
|
+
const cutCount = msgs.length - KEEP
|
|
1517
|
+
const cut = msgs.slice(0, cutCount)
|
|
1518
|
+
let tag = ''
|
|
1519
|
+
try {
|
|
1520
|
+
mkdirSync(DIR, { recursive: true })
|
|
1521
|
+
tag = 'd-' + Date.now().toString(36)
|
|
1522
|
+
writeFileSync(join(DIR, tag + '.json'), JSON.stringify({ at: Date.now(), cutCount, msgs: cut }), 'utf8')
|
|
1523
|
+
} catch {}
|
|
1524
|
+
const mark = { role: 'user', content: '[较早的 ' + cutCount + ' 条对话已裁断' + (tag ? ',存为标签 ⟦' + tag + '⟧' : '') + ',需要时用标签取回原文]' }
|
|
1525
|
+
decision.messages = [mark, ...msgs.slice(cutCount)]
|
|
1526
|
+
try { store.emit({ module: 'hub', level: 'info', kind: 'cut', summary: '按轮裁断:切掉 ' + cutCount + ' 条' + (tag ? ',标签 ⟦' + tag + '⟧' : '') }) } catch {}
|
|
1527
|
+
} catch {}
|
|
1528
|
+
return decision
|
|
1529
|
+
})
|
|
1530
|
+
} catch (e) { try { console.warn('ctx-cut 挂不上:' + (e && e.message)) } catch {} }
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1491
1533
|
export async function apply(ctx, config) {
|
|
1492
1534
|
const store = await createStore()
|
|
1493
1535
|
hubStore = store
|
|
1494
1536
|
const startedAt = now()
|
|
1495
|
-
const api = { version: VERSION, store, emit: (ev) => store.emit(ev), modules: () => store.modules(), counts: () => store.counts(), base: BASE }
|
|
1537
|
+
const api = { version: VERSION, dshVersion: DSH_VERSION, store, emit: (ev) => store.emit(ev), modules: () => store.modules(), counts: () => store.counts(), base: BASE }
|
|
1496
1538
|
try { ctx.set('hubCenter', api) } catch {}
|
|
1497
1539
|
try { ctx.effect(() => () => store.close()) } catch {}
|
|
1498
1540
|
|
|
1499
1541
|
store.emit({ module: 'hub', level: 'info', kind: 'start', summary: '中枢内核已启动(' + store.kind + ')' })
|
|
1542
|
+
try { setupCtxCut(ctx, store) } catch (e) { try { store.emit({ module: 'hub', level: 'warn', kind: 'cut', summary: 'ctx-cut 没挂上:' + (e && e.message) }) } catch {} }
|
|
1500
1543
|
|
|
1501
1544
|
// 并进来的两个小插件:各自独立 try,坏一个不影响中枢本体
|
|
1502
1545
|
const sub = (config && config.sub) || {}
|
|
1503
1546
|
try { applySessionBus(ctx, sub.sessionBus !== false ? (sub.sessionBus || {}) : { enabled: false }) } catch (e) { store.emit({ module: 'hub', level: 'warn', kind: 'sub', summary: '跨窗口总线没起来:' + String(e && e.message || e) }) }
|
|
1504
1547
|
try { applyVoice(ctx, sub.voice || {}) } catch (e) { store.emit({ module: 'hub', level: 'warn', kind: 'sub', summary: '语音朗读没起来:' + String(e && e.message || e) }) }
|
|
1505
1548
|
|
|
1549
|
+
// 模块平台:自己的功能都归这里,QQ 插件那边只留桥
|
|
1550
|
+
let platform = null
|
|
1551
|
+
try {
|
|
1552
|
+
platform = createModuleHost({
|
|
1553
|
+
dataRoot: BASE,
|
|
1554
|
+
shared: { store, base: BASE, qqData: QQ_DATA, paths: PATHS },
|
|
1555
|
+
log: (id, level, msg) => { try { store.emit({ module: 'mod:' + id, level, kind: 'module', summary: msg }) } catch {} },
|
|
1556
|
+
})
|
|
1557
|
+
try { ctx.set('hubPlatform', platform) } catch {}
|
|
1558
|
+
await platform.startAll()
|
|
1559
|
+
const up = platform.list().filter((m) => m.running).length
|
|
1560
|
+
store.emit({ module: 'hub', level: 'info', kind: 'platform', summary: '模块平台已启动:' + up + ' 个在跑,目录 ' + moduleDir(BASE) })
|
|
1561
|
+
try { ctx.effect(() => () => { try { platform.stop() } catch {} }) } catch {}
|
|
1562
|
+
} catch (e) {
|
|
1563
|
+
store.emit({ module: 'hub', level: 'warn', kind: 'platform', summary: '模块平台没起来:' + String((e && e.message) || e) })
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1506
1566
|
const qqBridge = createQqLogBridge(store)
|
|
1507
1567
|
const qqTimer = setInterval(() => { try { qqBridge.tick() } catch {} }, 10000)
|
|
1508
1568
|
try { ctx.effect(() => () => clearInterval(qqTimer)) } catch {}
|
|
@@ -1771,6 +1831,7 @@ export async function apply(ctx, config) {
|
|
|
1771
1831
|
send(res, 200, {
|
|
1772
1832
|
ok: true,
|
|
1773
1833
|
version: VERSION,
|
|
1834
|
+
dshVersion: DSH_VERSION,
|
|
1774
1835
|
alerts,
|
|
1775
1836
|
uptimeMs: now() - startedAt,
|
|
1776
1837
|
store: { kind: store.kind, file: store.file, base: BASE, fts: store.fts !== false },
|
|
@@ -1938,6 +1999,64 @@ export async function apply(ctx, config) {
|
|
|
1938
1999
|
send(res, 200, { ok: true, ...r })
|
|
1939
2000
|
})
|
|
1940
2001
|
|
|
2002
|
+
// ---- 记忆质检:先扫一遍看分数,再按项修 ----
|
|
2003
|
+
let auditApi = null
|
|
2004
|
+
const getAudit = () => auditApi || (auditApi = createAudit({ dbPath: join(BASE, 'hub.db') }))
|
|
2005
|
+
|
|
2006
|
+
route('/hub-center/memory/audit', async (req, res) => {
|
|
2007
|
+
try {
|
|
2008
|
+
const r = await getAudit().audit()
|
|
2009
|
+
send(res, 200, { ok: true, ...r })
|
|
2010
|
+
} catch (e) {
|
|
2011
|
+
send(res, 500, { ok: false, error: e && e.message ? e.message : String(e) })
|
|
2012
|
+
}
|
|
2013
|
+
})
|
|
2014
|
+
|
|
2015
|
+
route('/hub-center/memory/repair', async (req, res) => {
|
|
2016
|
+
if (req.method !== 'POST') return send(res, 405, { ok: false, error: 'POST only' })
|
|
2017
|
+
const body = await readBody(req)
|
|
2018
|
+
try {
|
|
2019
|
+
const r = await getAudit().repair({
|
|
2020
|
+
items: Array.isArray(body.items) ? body.items : [],
|
|
2021
|
+
dryRun: !!body.dryRun,
|
|
2022
|
+
halfLifeDays: Number(body.halfLifeDays) || HALF_LIFE_DAYS,
|
|
2023
|
+
})
|
|
2024
|
+
if (!body.dryRun) {
|
|
2025
|
+
try {
|
|
2026
|
+
store.emit({ module: 'memory', level: 'info', kind: 'audit', summary: '质检修复:' + ((body.items || []).join('/') || '默认项') })
|
|
2027
|
+
} catch {}
|
|
2028
|
+
}
|
|
2029
|
+
send(res, 200, r)
|
|
2030
|
+
} catch (e) {
|
|
2031
|
+
send(res, 500, { ok: false, error: e && e.message ? e.message : String(e) })
|
|
2032
|
+
}
|
|
2033
|
+
})
|
|
2034
|
+
|
|
2035
|
+
// ---- 解档:把被裁断(压缩)掉的原文按时间线拼回来 ----
|
|
2036
|
+
let restoreApi = null
|
|
2037
|
+
const getRestore = () => restoreApi || (restoreApi = createRestore({ storeDir: DSCTX_DIR, outDir: RESTORE_OUT }))
|
|
2038
|
+
|
|
2039
|
+
route('/hub-center/restore/tags', async (req, res) => {
|
|
2040
|
+
const tags = getRestore().listTags()
|
|
2041
|
+
send(res, 200, { ok: true, dir: DSCTX_DIR, dirOk: existsSync(DSCTX_DIR), outDir: RESTORE_OUT, count: tags.length, tags })
|
|
2042
|
+
})
|
|
2043
|
+
|
|
2044
|
+
// dry 默认 true,只预览不写盘;要真写出来得显式传 dry=false
|
|
2045
|
+
route('/hub-center/restore', async (req, res) => {
|
|
2046
|
+
const u = new URL(req.url, 'http://127.0.0.1')
|
|
2047
|
+
const body = req.method === 'POST' ? await readBody(req) : {}
|
|
2048
|
+
const opt = { ...body }
|
|
2049
|
+
for (const k of ['tag', 'session', 'since', 'format']) if (u.searchParams.get(k)) opt[k] = u.searchParams.get(k)
|
|
2050
|
+
if (u.searchParams.get('dry') === '1') opt.dry = true
|
|
2051
|
+
if (u.searchParams.get('sys') === '1') opt.withSys = true
|
|
2052
|
+
if (u.searchParams.get('max')) opt.max = Number(u.searchParams.get('max'))
|
|
2053
|
+
if (opt.tag === 'all') { opt.tag = ''; opt.all = true }
|
|
2054
|
+
if (!opt.tag && !opt.session) opt.all = true
|
|
2055
|
+
const r = getRestore().restore(opt)
|
|
2056
|
+
if (r.ok && !r.dry) store.emit({ module: 'memory', level: 'info', kind: 'restore', summary: `解档 ${r.base}:${r.stats.lines} 条` })
|
|
2057
|
+
send(res, r.ok ? 200 : 404, r)
|
|
2058
|
+
})
|
|
2059
|
+
|
|
1941
2060
|
// ---- 表情 ----
|
|
1942
2061
|
route('/hub-center/stickers', async (req, res) => {
|
|
1943
2062
|
const u = new URL(req.url, 'http://127.0.0.1')
|
|
@@ -1960,6 +2079,28 @@ export async function apply(ctx, config) {
|
|
|
1960
2079
|
send(res, ok ? 200 : 404, { ok })
|
|
1961
2080
|
})
|
|
1962
2081
|
|
|
2082
|
+
// ---- 表情图片直链:窗口里直接渲染,不用等对方甩链接 ----
|
|
2083
|
+
route('/hub-center/sticker/file', async (req, res) => {
|
|
2084
|
+
const u = new URL(req.url, 'http://127.0.0.1')
|
|
2085
|
+
let name = String(u.searchParams.get('f') || u.searchParams.get('file') || '').replace(/[^A-Za-z0-9._-]/g, '')
|
|
2086
|
+
const m = String(u.searchParams.get('m') || u.searchParams.get('md5') || '').replace(/[^A-Za-z0-9]/g, '')
|
|
2087
|
+
if (!name && m) {
|
|
2088
|
+
try {
|
|
2089
|
+
const idx = JSON.parse(readFileSync(join(QQ_DATA, 'stickers', 'index.json'), 'utf8'))
|
|
2090
|
+
const hit = (idx.items || []).find((it) => it && it.md5 === m)
|
|
2091
|
+
if (hit) name = String(hit.file || '').split(/[\\/]/).pop()
|
|
2092
|
+
} catch {}
|
|
2093
|
+
}
|
|
2094
|
+
if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|gif|webp|bmp)$/i.test(name)) return send(res, 400, { ok: false, error: '文件名不对' })
|
|
2095
|
+
const p = join(QQ_DATA, 'stickers', name)
|
|
2096
|
+
if (!existsSync(p)) return send(res, 404, { ok: false, error: '没这个表情' })
|
|
2097
|
+
const ext = name.split('.').pop().toLowerCase()
|
|
2098
|
+
const mime = ext === 'png' ? 'image/png' : ext === 'gif' ? 'image/gif' : ext === 'webp' ? 'image/webp' : ext === 'bmp' ? 'image/bmp' : 'image/jpeg'
|
|
2099
|
+
const buf = readFileSync(p)
|
|
2100
|
+
res.writeHead(200, { 'Content-Type': mime, 'Content-Length': buf.length, 'Cache-Control': 'public, max-age=86400' })
|
|
2101
|
+
res.end(buf)
|
|
2102
|
+
})
|
|
2103
|
+
|
|
1963
2104
|
// ---- 梗百科词库 ----
|
|
1964
2105
|
route('/hub-center/meme/status', async (req, res) => {
|
|
1965
2106
|
send(res, 200, { ok: true, count: store.memeCount(), src: MEME_SRC, srcOk: existsSync(MEME_SRC) })
|
package/lib/mem-audit.js
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
// 记忆质检:扫库找毛病 + 按项修。
|
|
2
|
+
// 只改 eff / archived / importance / 索引,删数据的一律不做(要删走 /memory/delete)。
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
|
|
5
|
+
const HALF_LIFE_DAYS = 60
|
|
6
|
+
const LONG = 800
|
|
7
|
+
|
|
8
|
+
// 默认重要度:老数据一大片 0.4,等于没区分;按来源给个底分,再按使用痕迹微调
|
|
9
|
+
const SOURCE_BASE = {
|
|
10
|
+
publish: 0.78, diary: 0.72, dsh: 0.7, distill: 0.66, digest: 0.62, 'event-digest': 0.6,
|
|
11
|
+
qq: 0.6, fact: 0.62, 'asset-sync': 0.52, travel: 0.5, home: 0.5,
|
|
12
|
+
'dsh-session': 0.46, auto: 0.4, selfie: 0.34,
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function tagsToText(raw) {
|
|
16
|
+
if (!raw) return ''
|
|
17
|
+
try {
|
|
18
|
+
const v = JSON.parse(raw)
|
|
19
|
+
return Array.isArray(v) ? v.join(' ') : String(v)
|
|
20
|
+
} catch {
|
|
21
|
+
return String(raw).replace(/[\[\]",]/g, ' ')
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function createAudit({ dbPath, now = () => Date.now() }) {
|
|
26
|
+
let db = null
|
|
27
|
+
|
|
28
|
+
async function open() {
|
|
29
|
+
if (db) return db
|
|
30
|
+
const { DatabaseSync } = await import('node:sqlite')
|
|
31
|
+
db = new DatabaseSync(dbPath)
|
|
32
|
+
db.exec('PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;')
|
|
33
|
+
return db
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function hasTable(name) {
|
|
37
|
+
const r = db.prepare("SELECT 1 FROM sqlite_master WHERE type IN ('table','view') AND name=?").get(name)
|
|
38
|
+
return !!r
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ---------- 体检 ----------
|
|
42
|
+
async function audit() {
|
|
43
|
+
await open()
|
|
44
|
+
const total = Number(db.prepare('SELECT COUNT(*) c FROM memories').get().c)
|
|
45
|
+
const archived = Number(db.prepare('SELECT COUNT(*) c FROM memories WHERE archived=1').get().c)
|
|
46
|
+
const live = total - archived
|
|
47
|
+
|
|
48
|
+
const ftsRows = hasTable('memories_fts') ? Number(db.prepare('SELECT COUNT(*) c FROM memories_fts').get().c) : 0
|
|
49
|
+
|
|
50
|
+
// 该建索引却没建的
|
|
51
|
+
const missingFts = hasTable('memories_fts')
|
|
52
|
+
? Number(db.prepare('SELECT COUNT(*) c FROM memories WHERE id NOT IN (SELECT id FROM memories_fts)').get().c)
|
|
53
|
+
: live
|
|
54
|
+
|
|
55
|
+
// 索引里有、记忆里没有的(孤儿)
|
|
56
|
+
const orphanFts = hasTable('memories_fts')
|
|
57
|
+
? Number(db.prepare('SELECT COUNT(*) c FROM memories_fts WHERE id NOT IN (SELECT id FROM memories)').get().c)
|
|
58
|
+
: 0
|
|
59
|
+
|
|
60
|
+
// 重要度:还卡在默认档的有多少(老数据两种默认值:0.4 和 0.45)
|
|
61
|
+
const flat = Number(
|
|
62
|
+
db.prepare('SELECT COUNT(*) c FROM memories WHERE importance IS NULL OR ABS(importance-0.4) < 0.01 OR ABS(importance-0.45) < 0.01').get().c,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
// 有效权重塌陷:decay 跑过头,一堆 eff 贴在 0 附近,排序等于瞎排
|
|
66
|
+
const sunk = hasTable('memories') && db.prepare('PRAGMA table_info(memories)').all().some((r) => r.name === 'eff')
|
|
67
|
+
? Number(db.prepare('SELECT COUNT(*) c FROM memories WHERE archived=0 AND importance >= 0.3 AND (eff IS NULL OR eff < 0.15)').get().c)
|
|
68
|
+
: 0
|
|
69
|
+
|
|
70
|
+
const len = db.prepare('SELECT AVG(LENGTH(text)) a, COUNT(*) c FROM memories WHERE LENGTH(text) > ?').get(LONG)
|
|
71
|
+
|
|
72
|
+
const noTags = Number(db.prepare("SELECT COUNT(*) c FROM memories WHERE tags IS NULL OR tags='' OR tags='[]'").get().c)
|
|
73
|
+
|
|
74
|
+
const vecRows = hasTable('mem_vec') ? Number(db.prepare('SELECT COUNT(*) c FROM mem_vec').get().c) : 0
|
|
75
|
+
const missingVec = hasTable('mem_vec')
|
|
76
|
+
? Number(db.prepare('SELECT COUNT(*) c FROM memories WHERE id NOT IN (SELECT id FROM mem_vec)').get().c)
|
|
77
|
+
: 0
|
|
78
|
+
|
|
79
|
+
const dup = db.prepare('SELECT text, COUNT(*) c, SUM(CASE WHEN archived=0 THEN 1 ELSE 0 END) live FROM memories WHERE archived=0 GROUP BY text HAVING c > 1').all()
|
|
80
|
+
const dupExtra = dup.reduce((s, r) => s + (Number(r.c) - 1), 0)
|
|
81
|
+
|
|
82
|
+
const items = [
|
|
83
|
+
{
|
|
84
|
+
key: 'fts',
|
|
85
|
+
label: '全文索引',
|
|
86
|
+
count: missingFts,
|
|
87
|
+
severity: missingFts > live * 0.1 ? 'high' : missingFts > 0 ? 'mid' : 'ok',
|
|
88
|
+
hint: missingFts ? `${missingFts} 条记忆没进全文索引,按关键词搜基本搜不到;重建一次就好` : '索引齐',
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
key: 'importance',
|
|
92
|
+
label: '重要度分层',
|
|
93
|
+
count: flat,
|
|
94
|
+
severity: flat > live * 0.3 ? 'high' : flat > 0 ? 'mid' : 'ok',
|
|
95
|
+
hint: flat ? `${flat} 条还是默认的 0.4,排序时没有区分度;可按来源回填` : '分层正常',
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
key: 'eff',
|
|
99
|
+
label: '有效权重塌陷',
|
|
100
|
+
count: sunk,
|
|
101
|
+
severity: sunk > live * 0.3 ? 'high' : sunk > 0 ? 'mid' : 'ok',
|
|
102
|
+
hint: sunk ? `${sunk} 条 eff 贴在 0.15 以下(衰减跑过头),检索时几乎排不上号;重算一次并加下限` : '权重分布正常',
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
key: 'longtext',
|
|
106
|
+
label: '超长条目',
|
|
107
|
+
count: Number(len.c),
|
|
108
|
+
severity: Number(len.c) > 200 ? 'mid' : Number(len.c) > 0 ? 'low' : 'ok',
|
|
109
|
+
hint: Number(len.c) ? `${len.c} 条超过 ${LONG} 字,命中后会整段塞进上下文;建议切段(这一项只报不自动切)` : '长度合理',
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
key: 'tags',
|
|
113
|
+
label: '标签空缺',
|
|
114
|
+
count: noTags,
|
|
115
|
+
severity: noTags > live * 0.1 ? 'mid' : noTags > 0 ? 'low' : 'ok',
|
|
116
|
+
hint: noTags ? `${noTags} 条没有标签,分类找不着它们` : '都有标签',
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
key: 'dup',
|
|
120
|
+
label: '重复',
|
|
121
|
+
count: dupExtra,
|
|
122
|
+
severity: dupExtra > 20 ? 'mid' : dupExtra > 0 ? 'low' : 'ok',
|
|
123
|
+
hint: dupExtra ? `${dup.length} 组重复,多出 ${dupExtra} 条;保留重要的那条,其余归档` : '没有重复',
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
key: 'vec',
|
|
127
|
+
label: '向量覆盖',
|
|
128
|
+
count: missingVec,
|
|
129
|
+
severity: missingVec > live * 0.05 ? 'mid' : missingVec > 0 ? 'low' : 'ok',
|
|
130
|
+
hint: missingVec ? `${missingVec} 条没有向量,语义检索摸不到` : '全都有向量',
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
key: 'orphan',
|
|
134
|
+
label: '索引孤儿',
|
|
135
|
+
count: orphanFts,
|
|
136
|
+
severity: orphanFts > 0 ? 'low' : 'ok',
|
|
137
|
+
hint: orphanFts ? `${orphanFts} 条索引指向已不存在的记忆,清掉` : '没有孤儿',
|
|
138
|
+
},
|
|
139
|
+
]
|
|
140
|
+
|
|
141
|
+
const weight = { high: 22, mid: 10, low: 4, ok: 0 }
|
|
142
|
+
const penalty = items.reduce((s, it) => s + weight[it.severity], 0)
|
|
143
|
+
const score = Math.max(0, Math.min(100, 100 - penalty))
|
|
144
|
+
|
|
145
|
+
return {
|
|
146
|
+
score,
|
|
147
|
+
ok: score >= 85,
|
|
148
|
+
at: now(),
|
|
149
|
+
total,
|
|
150
|
+
live,
|
|
151
|
+
archived,
|
|
152
|
+
ftsRows,
|
|
153
|
+
vecRows,
|
|
154
|
+
avgLen: Math.round(Number(len.a) || 0),
|
|
155
|
+
items,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---------- 修 ----------
|
|
160
|
+
async function repair({ items = [], dryRun = false, halfLifeDays = HALF_LIFE_DAYS } = {}) {
|
|
161
|
+
await open()
|
|
162
|
+
const want = new Set(items.length ? items : ['fts', 'importance', 'decay', 'dup', 'orphan'])
|
|
163
|
+
if (want.has('eff')) { want.delete('eff'); want.add('decay') } // UI 里叫 eff,内部叫 decay
|
|
164
|
+
const report = {}
|
|
165
|
+
|
|
166
|
+
if (want.has('fts')) {
|
|
167
|
+
let n = 0
|
|
168
|
+
if (!hasTable('memories_fts')) {
|
|
169
|
+
db.exec("CREATE VIRTUAL TABLE memories_fts USING fts5(id UNINDEXED, text, tags)")
|
|
170
|
+
}
|
|
171
|
+
if (!dryRun) {
|
|
172
|
+
const rows = db.prepare('SELECT id, text, tags FROM memories').all()
|
|
173
|
+
const ins = db.prepare('INSERT INTO memories_fts (id,text,tags) VALUES (?,?,?)')
|
|
174
|
+
db.exec('BEGIN')
|
|
175
|
+
try {
|
|
176
|
+
db.exec('DELETE FROM memories_fts')
|
|
177
|
+
for (const r of rows) {
|
|
178
|
+
ins.run(r.id, String(r.text || ''), tagsToText(r.tags))
|
|
179
|
+
n++
|
|
180
|
+
}
|
|
181
|
+
db.exec('COMMIT')
|
|
182
|
+
} catch (e) {
|
|
183
|
+
db.exec('ROLLBACK')
|
|
184
|
+
throw e
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
report.fts = { rebuilt: n, dryRun }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (want.has('orphan')) {
|
|
191
|
+
let n = 0
|
|
192
|
+
if (hasTable('memories_fts')) {
|
|
193
|
+
if (!dryRun) {
|
|
194
|
+
const info = db.prepare('DELETE FROM memories_fts WHERE id NOT IN (SELECT id FROM memories)').run()
|
|
195
|
+
n = Number(info.changes || 0)
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
report.orphan = { removed: n, dryRun }
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
if (want.has('importance')) {
|
|
202
|
+
let n = 0
|
|
203
|
+
const rows = db.prepare('SELECT id, source, kind, tags, text, importance, use_count, created FROM memories').all()
|
|
204
|
+
const upd = db.prepare('UPDATE memories SET importance=? WHERE id=?')
|
|
205
|
+
if (!dryRun) db.exec('BEGIN')
|
|
206
|
+
try {
|
|
207
|
+
for (const r of rows) {
|
|
208
|
+
const cur = Number(r.importance)
|
|
209
|
+
const flatNow = !Number.isFinite(cur) || Math.abs(cur - 0.4) < 0.01 || Math.abs(cur - 0.45) < 0.01
|
|
210
|
+
if (!flatNow) continue
|
|
211
|
+
const base = SOURCE_BASE[r.source] ?? SOURCE_BASE[r.kind] ?? 0.5
|
|
212
|
+
let v = base
|
|
213
|
+
if (Number(r.use_count) > 0) v += Math.min(0.12, 0.03 * Number(r.use_count))
|
|
214
|
+
if (String(r.text || '').length > LONG) v -= 0.04
|
|
215
|
+
if (tagsToText(r.tags).trim()) v += 0.02
|
|
216
|
+
v = Math.max(0.15, Math.min(0.92, v))
|
|
217
|
+
if (!dryRun) upd.run(Number(v.toFixed(3)), r.id)
|
|
218
|
+
n++
|
|
219
|
+
}
|
|
220
|
+
if (!dryRun) db.exec('COMMIT')
|
|
221
|
+
} catch (e) {
|
|
222
|
+
if (!dryRun) db.exec('ROLLBACK')
|
|
223
|
+
throw e
|
|
224
|
+
}
|
|
225
|
+
report.importance = { filled: n, dryRun }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (want.has('dup')) {
|
|
229
|
+
let archived = 0
|
|
230
|
+
const groups = db.prepare('SELECT text, COUNT(*) c FROM memories GROUP BY text HAVING c > 1').all()
|
|
231
|
+
const getRows = db.prepare('SELECT id, importance, length(text) len, created, archived FROM memories WHERE text=?')
|
|
232
|
+
const arch = db.prepare('UPDATE memories SET archived=1, eff=COALESCE(eff,importance)*0.5 WHERE id=?')
|
|
233
|
+
if (!dryRun) db.exec('BEGIN')
|
|
234
|
+
try {
|
|
235
|
+
for (const g of groups) {
|
|
236
|
+
const rows = getRows.all(g.text)
|
|
237
|
+
const keep = rows
|
|
238
|
+
.filter((r) => !Number(r.archived))
|
|
239
|
+
.sort((a, b) => (Number(b.importance) - Number(a.importance)) || (Number(b.len) - Number(a.len)) || (Number(b.created) - Number(a.created)))[0]
|
|
240
|
+
|| rows[0]
|
|
241
|
+
for (const r of rows) {
|
|
242
|
+
if (r.id === keep.id) continue
|
|
243
|
+
if (Number(r.archived)) continue
|
|
244
|
+
if (!dryRun) arch.run(r.id)
|
|
245
|
+
archived++
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (!dryRun) db.exec('COMMIT')
|
|
249
|
+
} catch (e) {
|
|
250
|
+
if (!dryRun) db.exec('ROLLBACK')
|
|
251
|
+
throw e
|
|
252
|
+
}
|
|
253
|
+
report.dup = { groups: groups.length, archived, dryRun }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
if (want.has('decay')) {
|
|
257
|
+
let touched = 0
|
|
258
|
+
const rows = db.prepare('SELECT id, importance, last_used, created FROM memories').all()
|
|
259
|
+
const upd = db.prepare('UPDATE memories SET eff=? WHERE id=?')
|
|
260
|
+
const t = now()
|
|
261
|
+
if (!dryRun) db.exec('BEGIN')
|
|
262
|
+
try {
|
|
263
|
+
for (const r of rows) {
|
|
264
|
+
const base = Number(r.importance) || 0.4
|
|
265
|
+
const last = Number(r.last_used) || Number(r.created) || t
|
|
266
|
+
const days = Math.max(0, (t - last) / 86400000)
|
|
267
|
+
const floor = base * 0.35 // 不归零:衰减到底也留基准的 35%,免得一批记忆全趴到 0 附近,排序失去区分度
|
|
268
|
+
const eff = Math.max(floor, Math.min(1, base * Math.pow(0.5, days / halfLifeDays)))
|
|
269
|
+
if (!dryRun) upd.run(Number(eff.toFixed(4)), r.id)
|
|
270
|
+
touched++
|
|
271
|
+
}
|
|
272
|
+
if (!dryRun) db.exec('COMMIT')
|
|
273
|
+
} catch (e) {
|
|
274
|
+
if (!dryRun) db.exec('ROLLBACK')
|
|
275
|
+
throw e
|
|
276
|
+
}
|
|
277
|
+
report.decay = { updated: touched, halfLifeDays, dryRun }
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
return { ok: true, at: now(), report }
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function close() {
|
|
284
|
+
try { db?.close() } catch {}
|
|
285
|
+
db = null
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
return { audit, repair, close }
|
|
289
|
+
}
|
package/lib/platform.js
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// 中枢模块平台:自己的功能一律写成模块,放 .dsh\plugins-data\dsh-hub\modules\<id>\index.mjs
|
|
2
|
+
//
|
|
3
|
+
// 跟 QQ 插件那套一样的心气,但不依赖 QQ:
|
|
4
|
+
// - 每个模块能单独开关;同名模块就顶掉旧的
|
|
5
|
+
// - 模块之间用 api.use('模块id') 拿对方导出的东西,用的时候才拿
|
|
6
|
+
// - 模块注册的上下文行、工具、定时任务都记在模块名下,关掉 / 重新加载时一起撤掉
|
|
7
|
+
// - 一个模块出错只影响它自己:启动失败记下原因,别的照常跑
|
|
8
|
+
// - 保存就生效(按修改时间重新加载),不用重启 DSH
|
|
9
|
+
//
|
|
10
|
+
// 给写模块的人看的接口说明,见同目录 API.md(启动时自动铺到模块目录)
|
|
11
|
+
|
|
12
|
+
import { existsSync, readdirSync, statSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
import { pathToFileURL } from 'node:url'
|
|
15
|
+
|
|
16
|
+
export const API_VERSION = 1
|
|
17
|
+
export const MIN_API_VERSION = 1
|
|
18
|
+
|
|
19
|
+
const ENTRY = ['index.mjs', 'index.js']
|
|
20
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', '.aurabot-cache', '_disabled', 'templates', 'separator'])
|
|
21
|
+
const ID_RE = /^[a-z][a-z0-9-]{1,39}$/
|
|
22
|
+
|
|
23
|
+
const readJson = (p, fb) => { try { return JSON.parse(readFileSync(p, 'utf8')) } catch { return fb } }
|
|
24
|
+
const writeJson = (p, obj) => {
|
|
25
|
+
try { mkdirSync(join(p, '..'), { recursive: true }); writeFileSync(p, JSON.stringify(obj, null, 2), 'utf8'); return true } catch { return false }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 模块目录:数据目录下的 modules/,升级插件不会动这里 */
|
|
29
|
+
export const moduleDir = (dataRoot) => join(dataRoot, 'modules')
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 建一个模块宿主。
|
|
33
|
+
* @param {object} o
|
|
34
|
+
* @param {string} o.dataRoot 中枢数据目录(.dsh\plugins-data\dsh-hub)
|
|
35
|
+
* @param {(id:string, level:string, msg:string)=>void} [o.log]
|
|
36
|
+
* @param {object} [o.shared] 给所有模块共用的东西(比如 store、paths)
|
|
37
|
+
*/
|
|
38
|
+
export function createModuleHost({ dataRoot, log = () => {}, shared = {} }) {
|
|
39
|
+
const DIR = moduleDir(dataRoot)
|
|
40
|
+
const DATA = join(dataRoot, 'modules-data')
|
|
41
|
+
const CFG = join(dataRoot, 'config')
|
|
42
|
+
const states = new Map() // id -> 状态
|
|
43
|
+
const listeners = new Map() // 事件名 -> Set(fn)
|
|
44
|
+
const cleanups = new Map() // id -> [fn]
|
|
45
|
+
let timer = null
|
|
46
|
+
|
|
47
|
+
const ensure = (d) => { try { mkdirSync(d, { recursive: true }) } catch {} ; return d }
|
|
48
|
+
|
|
49
|
+
// ---- 事件总线:模块之间、桥跟模块之间都走这里 ----
|
|
50
|
+
function on(name, fn) {
|
|
51
|
+
const key = String(name)
|
|
52
|
+
if (typeof fn !== 'function') return () => {}
|
|
53
|
+
if (!listeners.has(key)) listeners.set(key, new Set())
|
|
54
|
+
listeners.get(key).add(fn)
|
|
55
|
+
return () => { try { listeners.get(key).delete(fn) } catch {} }
|
|
56
|
+
}
|
|
57
|
+
function emit(name, ...args) {
|
|
58
|
+
const key = String(name)
|
|
59
|
+
const set = listeners.get(key)
|
|
60
|
+
if (!set) return 0
|
|
61
|
+
let n = 0
|
|
62
|
+
for (const fn of [...set]) { try { fn(...args); n += 1 } catch (e) { log(key, 'warn', '监听出错:' + (e && e.message)) } }
|
|
63
|
+
return n
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// ---- 单个模块的配置:存在 config/<id>.json ----
|
|
67
|
+
const cfgFile = (id) => join(CFG, id + '.json')
|
|
68
|
+
const readCfg = (id) => readJson(cfgFile(id), {})
|
|
69
|
+
function settingsOf(id, defaults) {
|
|
70
|
+
const saved = readCfg(id)
|
|
71
|
+
return { ...(defaults || {}), ...(saved || {}) }
|
|
72
|
+
}
|
|
73
|
+
function patchCfg(id, patch) {
|
|
74
|
+
const next = { ...readCfg(id), ...(patch || {}) }
|
|
75
|
+
writeJson(cfgFile(id), next)
|
|
76
|
+
return next
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---- 给模块用的 api ----
|
|
80
|
+
function makeApi(id, mod) {
|
|
81
|
+
const defaults = mod.defaults || {}
|
|
82
|
+
const ctxFns = []
|
|
83
|
+
const tools = new Map()
|
|
84
|
+
const api = {
|
|
85
|
+
api: API_VERSION,
|
|
86
|
+
id,
|
|
87
|
+
version: mod.version || '0.0.0',
|
|
88
|
+
shared,
|
|
89
|
+
settings: () => settingsOf(id, defaults),
|
|
90
|
+
setSettings: (patch) => { const n = patchCfg(id, patch); emit('module/settings', { id, settings: n }); return n },
|
|
91
|
+
dataDir: () => ensure(join(DATA, id)),
|
|
92
|
+
file: (name) => join(ensure(join(DATA, id)), String(name)),
|
|
93
|
+
log: {
|
|
94
|
+
info: (m) => log(id, 'info', String(m)),
|
|
95
|
+
warn: (m) => log(id, 'warn', String(m)),
|
|
96
|
+
error: (m) => log(id, 'error', String(m)),
|
|
97
|
+
},
|
|
98
|
+
on,
|
|
99
|
+
emit,
|
|
100
|
+
use: (other) => {
|
|
101
|
+
const st = states.get(String(other))
|
|
102
|
+
return st && st.exports ? st.exports : null
|
|
103
|
+
},
|
|
104
|
+
/** 往对话上下文里塞一行:fn 返回字符串,返回空就不塞 */
|
|
105
|
+
context: (fn) => { if (typeof fn === 'function') { ctxFns.push(fn); return fn } return null },
|
|
106
|
+
/** 注册一个工具(中枢只管存,谁要用谁取) */
|
|
107
|
+
tool: (name, def) => {
|
|
108
|
+
if (!name) return () => {}
|
|
109
|
+
const key = String(name)
|
|
110
|
+
tools.set(key, def)
|
|
111
|
+
return () => tools.delete(key)
|
|
112
|
+
},
|
|
113
|
+
tools: () => Object.fromEntries(tools),
|
|
114
|
+
/** 定时任务:返回撤销函数 */
|
|
115
|
+
interval: (ms, fn) => {
|
|
116
|
+
const h = setInterval(() => { try { fn() } catch (e) { log(id, 'warn', '定时出错:' + (e && e.message)) } }, Math.max(1000, Number(ms) || 60000))
|
|
117
|
+
if (h.unref) h.unref()
|
|
118
|
+
return () => clearInterval(h)
|
|
119
|
+
},
|
|
120
|
+
cleanup: (fn) => { if (typeof fn === 'function') cleanups.get(id).push(fn) },
|
|
121
|
+
_ctxFns: ctxFns,
|
|
122
|
+
}
|
|
123
|
+
return api
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---- 扫目录 ----
|
|
127
|
+
function scan() {
|
|
128
|
+
if (!existsSync(DIR)) return []
|
|
129
|
+
const out = []
|
|
130
|
+
for (const e of readdirSync(DIR, { withFileTypes: true })) {
|
|
131
|
+
if (!e.isDirectory() || SKIP_DIRS.has(e.name) || !ID_RE.test(e.name)) continue
|
|
132
|
+
const dir = join(DIR, e.name)
|
|
133
|
+
const file = ENTRY.map((n) => join(dir, n)).find((p) => existsSync(p))
|
|
134
|
+
if (!file) continue
|
|
135
|
+
let mtime = 0
|
|
136
|
+
try { mtime = statSync(file).mtimeMs } catch {}
|
|
137
|
+
out.push({ id: e.name, dir, file, mtime })
|
|
138
|
+
}
|
|
139
|
+
return out
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function load(id, file) {
|
|
143
|
+
const url = pathToFileURL(file).href + '?v=' + Date.now()
|
|
144
|
+
const mod = await import(url)
|
|
145
|
+
const decl = mod.default || mod
|
|
146
|
+
if (!decl || typeof decl.setup !== 'function') throw new Error('模块没有 setup(api)')
|
|
147
|
+
const api = makeApi(id, decl)
|
|
148
|
+
cleanups.set(id, [])
|
|
149
|
+
const exports = await decl.setup(api)
|
|
150
|
+
return { decl, api, exports: exports || {} }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function unload(id) {
|
|
154
|
+
const st = states.get(id)
|
|
155
|
+
if (!st) return
|
|
156
|
+
for (const fn of cleanups.get(id) || []) { try { fn() } catch {} }
|
|
157
|
+
cleanups.delete(id)
|
|
158
|
+
for (const off of st.offs || []) { try { off() } catch {} }
|
|
159
|
+
states.delete(id)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function reload(id) {
|
|
163
|
+
const hit = scan().find((m) => m.id === id)
|
|
164
|
+
if (!hit) {
|
|
165
|
+
unload(id)
|
|
166
|
+
states.set(id, { id, error: '目录或入口文件没了', running: false, mtime: 0 })
|
|
167
|
+
log(id, 'warn', '找不到模块,已停')
|
|
168
|
+
return false
|
|
169
|
+
}
|
|
170
|
+
if (!enabled(id)) {
|
|
171
|
+
unload(id)
|
|
172
|
+
states.set(id, { id, running: false, mtime: hit.mtime, file: hit.file, disabled: true })
|
|
173
|
+
return false
|
|
174
|
+
}
|
|
175
|
+
unload(id)
|
|
176
|
+
try {
|
|
177
|
+
const { decl, api, exports } = await load(id, hit.file)
|
|
178
|
+
states.set(id, {
|
|
179
|
+
id, running: true, mtime: hit.mtime, file: hit.file,
|
|
180
|
+
name: decl.name || id, version: decl.version || '0.0.0',
|
|
181
|
+
description: decl.description || '', settingsDecl: decl.settings || [],
|
|
182
|
+
api, exports, error: '',
|
|
183
|
+
})
|
|
184
|
+
log(id, 'info', '已加载 ' + (decl.version || ''))
|
|
185
|
+
return true
|
|
186
|
+
} catch (e) {
|
|
187
|
+
states.set(id, { id, running: false, mtime: hit.mtime, file: hit.file, error: String((e && e.message) || e) })
|
|
188
|
+
log(id, 'error', '加载失败:' + String((e && e.message) || e))
|
|
189
|
+
return false
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// ---- 开关:存 modules-state.json ----
|
|
194
|
+
const STATE = () => join(dataRoot, 'modules-state.json')
|
|
195
|
+
const stateMap = () => readJson(STATE(), {})
|
|
196
|
+
const enabled = (id) => stateMap()[id] !== false
|
|
197
|
+
function setEnabled(id, on) {
|
|
198
|
+
const m = stateMap()
|
|
199
|
+
m[id] = !!on
|
|
200
|
+
writeJson(STATE(), m)
|
|
201
|
+
return reload(id)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ---- 热更新:5 秒看一眼修改时间 ----
|
|
205
|
+
function watchStart() {
|
|
206
|
+
if (timer) return
|
|
207
|
+
timer = setInterval(async () => {
|
|
208
|
+
try {
|
|
209
|
+
const now = scan()
|
|
210
|
+
const seen = new Set()
|
|
211
|
+
for (const m of now) {
|
|
212
|
+
seen.add(m.id)
|
|
213
|
+
const st = states.get(m.id)
|
|
214
|
+
if (!st || st.mtime !== m.mtime) await reload(m.id)
|
|
215
|
+
}
|
|
216
|
+
for (const id of [...states.keys()]) if (!seen.has(id)) await reload(id)
|
|
217
|
+
} catch {}
|
|
218
|
+
}, 5000)
|
|
219
|
+
if (timer.unref) timer.unref()
|
|
220
|
+
}
|
|
221
|
+
function watchStop() { if (timer) { clearInterval(timer); timer = null } }
|
|
222
|
+
|
|
223
|
+
async function startAll() {
|
|
224
|
+
ensure(DIR)
|
|
225
|
+
ensure(DATA)
|
|
226
|
+
for (const m of scan()) await reload(m.id)
|
|
227
|
+
watchStart()
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ---- 对外:状态、上下文行、工具池 ----
|
|
231
|
+
function list() {
|
|
232
|
+
return scan().map((m) => {
|
|
233
|
+
const st = states.get(m.id) || {}
|
|
234
|
+
return {
|
|
235
|
+
id: m.id,
|
|
236
|
+
name: st.name || m.id,
|
|
237
|
+
version: st.version || '',
|
|
238
|
+
description: st.description || '',
|
|
239
|
+
running: !!st.running,
|
|
240
|
+
enabled: enabled(m.id),
|
|
241
|
+
error: st.error || '',
|
|
242
|
+
mtime: m.mtime,
|
|
243
|
+
settings: st.settingsDecl || [],
|
|
244
|
+
settingsValues: settingsOf(m.id, {}),
|
|
245
|
+
tools: st.api ? Object.keys(st.api.tools()) : [],
|
|
246
|
+
}
|
|
247
|
+
})
|
|
248
|
+
}
|
|
249
|
+
function contextLines(extra = {}) {
|
|
250
|
+
const out = []
|
|
251
|
+
for (const st of states.values()) {
|
|
252
|
+
if (!st.running || !st.api) continue
|
|
253
|
+
for (const fn of st.api._ctxFns) {
|
|
254
|
+
try { const s = fn(extra); if (s && String(s).trim()) out.push(String(s).trim()) } catch (e) { log(st.id, 'warn', '上下文出错:' + (e && e.message)) }
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return out
|
|
258
|
+
}
|
|
259
|
+
function allTools() {
|
|
260
|
+
const out = {}
|
|
261
|
+
for (const st of states.values()) if (st.running && st.api) Object.assign(out, st.api.tools())
|
|
262
|
+
return out
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
return {
|
|
266
|
+
dir: () => DIR,
|
|
267
|
+
dataDir: () => DATA,
|
|
268
|
+
startAll, list, reload, setEnabled, scan,
|
|
269
|
+
contextLines, allTools, emit, on,
|
|
270
|
+
get: (id) => states.get(String(id))?.exports ?? null,
|
|
271
|
+
status: () => ({ apiVersion: API_VERSION, dir: DIR, count: states.size }),
|
|
272
|
+
stop: () => { watchStop(); for (const id of [...states.keys()]) unload(id) },
|
|
273
|
+
}
|
|
274
|
+
}
|
package/lib/restore.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// 解档:把裁断(压缩)掉的原文,按时间线拼回能读的完整记录
|
|
2
|
+
// 逻辑同 tools\dsctx-restore.mjs,那边给命令行用,这里给中枢面板调
|
|
3
|
+
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
const short = (s, n = 300) => (s.length > n ? s.slice(0, n) + '…' : s)
|
|
7
|
+
|
|
8
|
+
function flatten(c, textOnly = false) {
|
|
9
|
+
if (!c) return ''
|
|
10
|
+
if (typeof c === 'string') return c.trim()
|
|
11
|
+
if (Array.isArray(c)) {
|
|
12
|
+
return c
|
|
13
|
+
.map((p) => {
|
|
14
|
+
if (typeof p === 'string') return p
|
|
15
|
+
if (!p || typeof p !== 'object') return ''
|
|
16
|
+
const t = p.type || ''
|
|
17
|
+
if (textOnly && t && t !== 'text' && t !== 'output-text') return ''
|
|
18
|
+
return p.text || p.content || ''
|
|
19
|
+
})
|
|
20
|
+
.filter(Boolean)
|
|
21
|
+
.join('\n')
|
|
22
|
+
.trim()
|
|
23
|
+
}
|
|
24
|
+
if (typeof c === 'object') return String(c.text || c.content || '').trim()
|
|
25
|
+
return ''
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const NOISE = [/^Current runtime context\./, /^Time sampled while preparing turn/]
|
|
29
|
+
|
|
30
|
+
function speechOf(o, withSys) {
|
|
31
|
+
const d = o.data || {}
|
|
32
|
+
const type = o.type || ''
|
|
33
|
+
if (type === 'user/message') {
|
|
34
|
+
const body = flatten(d.content ?? d.message?.content)
|
|
35
|
+
if (!body || NOISE.some((r) => r.test(body))) return null
|
|
36
|
+
return { who: '主人', body, kind: 'say' }
|
|
37
|
+
}
|
|
38
|
+
if (type === 'assistant/message') {
|
|
39
|
+
const body = flatten(d.message?.content ?? d.content, true)
|
|
40
|
+
return body ? { who: '大肥鱼', body, kind: 'say' } : null
|
|
41
|
+
}
|
|
42
|
+
if (type === 'tool/call') {
|
|
43
|
+
const name = d.name || d.tool || d.toolName || '?'
|
|
44
|
+
const a = typeof d.arguments === 'string' ? d.arguments : JSON.stringify(d.arguments ?? '')
|
|
45
|
+
return { who: '工具', body: name + ' ' + short(a, 160), kind: 'tool' }
|
|
46
|
+
}
|
|
47
|
+
if ((type === 'system/message' || type === 'developer/message') && withSys) {
|
|
48
|
+
return { who: '系统', body: flatten(d.content ?? d.message?.content), kind: 'sys' }
|
|
49
|
+
}
|
|
50
|
+
return null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const stamp = (ms) => {
|
|
54
|
+
if (!ms) return ''
|
|
55
|
+
const d = new Date(Number(ms))
|
|
56
|
+
const p = (n) => String(n).padStart(2, '0')
|
|
57
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createRestore({ storeDir, outDir }) {
|
|
61
|
+
const INDEX = join(storeDir, 'index.json')
|
|
62
|
+
|
|
63
|
+
function readIndex() {
|
|
64
|
+
try {
|
|
65
|
+
const o = JSON.parse(readFileSync(INDEX, 'utf8'))
|
|
66
|
+
return Array.isArray(o.tags) ? o.tags : []
|
|
67
|
+
} catch {
|
|
68
|
+
return []
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function listTags() {
|
|
73
|
+
return readIndex()
|
|
74
|
+
.map((t) => ({
|
|
75
|
+
tag: t.tag,
|
|
76
|
+
events: t.events || 0,
|
|
77
|
+
created: t.created || '',
|
|
78
|
+
session: t.session || '',
|
|
79
|
+
cwd: t.cwd || '',
|
|
80
|
+
sizeKB: existsSync(join(storeDir, t.tag + '.jsonl'))
|
|
81
|
+
? Math.round(readFileSync(join(storeDir, t.tag + '.jsonl')).length / 1024)
|
|
82
|
+
: null,
|
|
83
|
+
}))
|
|
84
|
+
.sort((a, b) => String(a.created).localeCompare(String(b.created)))
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function loadTagFile(tag) {
|
|
88
|
+
const p = join(storeDir, tag + '.jsonl')
|
|
89
|
+
if (!existsSync(p)) return null
|
|
90
|
+
return readFileSync(p, 'utf8')
|
|
91
|
+
.split('\n')
|
|
92
|
+
.filter(Boolean)
|
|
93
|
+
.map((l) => {
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(l)
|
|
96
|
+
} catch {
|
|
97
|
+
return null
|
|
98
|
+
}
|
|
99
|
+
})
|
|
100
|
+
.filter(Boolean)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 解一段(或多段拼一起)。dry=true 只统计不写盘。 */
|
|
104
|
+
function restore({ tag, session, all, since, withSys = false, dry = true, max = 0, format = 'both' } = {}) {
|
|
105
|
+
const idx = readIndex()
|
|
106
|
+
let picked = []
|
|
107
|
+
if (tag) picked = idx.filter((x) => x.tag === String(tag))
|
|
108
|
+
else if (session) picked = idx.filter((x) => String(x.session || '').includes(String(session)))
|
|
109
|
+
else if (all) picked = idx.filter((x) => !since || String(x.created || '') >= String(since))
|
|
110
|
+
if (tag && !picked.length) picked = [{ tag: String(tag), session: '', created: '' }]
|
|
111
|
+
if (!picked.length) return { ok: false, error: '没有匹配的标签' }
|
|
112
|
+
|
|
113
|
+
const bySeq = new Map()
|
|
114
|
+
for (const t of picked) {
|
|
115
|
+
const evs = loadTagFile(t.tag)
|
|
116
|
+
if (!evs) continue
|
|
117
|
+
for (const o of evs) {
|
|
118
|
+
const k = Number(o.seq)
|
|
119
|
+
if (Number.isFinite(k) && !bySeq.has(k)) bySeq.set(k, o)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const events = [...bySeq.values()].sort((a, b) => Number(a.seq) - Number(b.seq))
|
|
123
|
+
const lines = []
|
|
124
|
+
for (const o of events) {
|
|
125
|
+
const s = speechOf(o, withSys)
|
|
126
|
+
if (!s || !s.body) continue
|
|
127
|
+
lines.push({ ...s, time: o.time, seq: o.seq })
|
|
128
|
+
}
|
|
129
|
+
const out = max > 0 ? lines.slice(0, max) : lines
|
|
130
|
+
const stats = {
|
|
131
|
+
tags: picked.map((x) => x.tag),
|
|
132
|
+
events: events.length,
|
|
133
|
+
lines: lines.length,
|
|
134
|
+
says: lines.filter((l) => l.kind === 'say').length,
|
|
135
|
+
tools: lines.filter((l) => l.kind === 'tool').length,
|
|
136
|
+
}
|
|
137
|
+
if (!events.length) return { ok: false, error: '标签文件是空的', stats }
|
|
138
|
+
if (dry) return { ok: true, dry: true, stats, preview: out.slice(0, 20) }
|
|
139
|
+
|
|
140
|
+
const base = tag
|
|
141
|
+
? String(tag)
|
|
142
|
+
: session
|
|
143
|
+
? 'sess-' + String(session).replace(/^session-/, '').slice(0, 8)
|
|
144
|
+
: 'all-' + new Date().toISOString().slice(0, 10)
|
|
145
|
+
mkdirSync(outDir, { recursive: true })
|
|
146
|
+
const files = []
|
|
147
|
+
if (format === 'md' || format === 'both') {
|
|
148
|
+
const md = [`# 解档记录 · ${base}`, '', `> 从裁断标签还原 · ${new Date().toLocaleString('zh-CN')} · 共 ${out.length} 条`, '']
|
|
149
|
+
let day = ''
|
|
150
|
+
for (const l of out) {
|
|
151
|
+
const dd = stamp(l.time).slice(0, 10)
|
|
152
|
+
if (dd && dd !== day) {
|
|
153
|
+
day = dd
|
|
154
|
+
md.push('', `## ${dd}`, '')
|
|
155
|
+
}
|
|
156
|
+
if (l.kind === 'tool') md.push(`- 🔧 \`${short(l.body, 160)}\``)
|
|
157
|
+
else if (l.kind === 'sys') md.push(`- *${short(l.body, 300)}`)
|
|
158
|
+
else md.push(`**${l.who}**:${l.body}`, '')
|
|
159
|
+
}
|
|
160
|
+
const p = join(outDir, base + '.md')
|
|
161
|
+
writeFileSync(p, md.join('\n'), 'utf8')
|
|
162
|
+
files.push(p)
|
|
163
|
+
}
|
|
164
|
+
if (format === 'jsonl' || format === 'both') {
|
|
165
|
+
const p = join(outDir, base + '.jsonl')
|
|
166
|
+
writeFileSync(p, out.map((l) => JSON.stringify(l)).join('\n') + '\n', 'utf8')
|
|
167
|
+
files.push(p)
|
|
168
|
+
}
|
|
169
|
+
return { ok: true, dry: false, stats, files, base }
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
return { listTags, restore }
|
|
173
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-hub-center",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.3",
|
|
4
4
|
"description": "Sidebar hub for DeepSeek Harness: memory store, diary, sticker library, status board and local-model scheduling.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
"locale/*.json",
|
|
20
20
|
"icon.svg",
|
|
21
21
|
"LICENSE",
|
|
22
|
-
"README.md"
|
|
22
|
+
"README.md",
|
|
23
|
+
"CHANGELOG.md"
|
|
23
24
|
],
|
|
24
25
|
"dsh": {
|
|
25
26
|
"bundle": {
|
|
@@ -36,6 +37,7 @@
|
|
|
36
37
|
]
|
|
37
38
|
}
|
|
38
39
|
},
|
|
40
|
+
"dshVersion": "2.0.22-next",
|
|
39
41
|
"repository": {
|
|
40
42
|
"type": "git",
|
|
41
43
|
"url": "git+https://github.com/Yu1018/dsh-hub-center.git"
|