dsh-hub-center 0.12.1 → 0.12.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.
- package/README.md +1 -1
- package/index.js +109 -2
- package/lib/platform.js +274 -0
- package/lib/restore.js +173 -0
- package/package.json +2 -1
package/README.md
CHANGED
package/index.js
CHANGED
|
@@ -9,16 +9,23 @@ 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 { createModuleHost, moduleDir } from './lib/platform.js'
|
|
12
14
|
|
|
13
15
|
export const name = 'dsh-hub-center'
|
|
14
16
|
export const inject = ['webServer']
|
|
15
17
|
|
|
16
|
-
const VERSION = '0.
|
|
18
|
+
const VERSION = '0.12.2'
|
|
19
|
+
// 这一版是对着哪代 DSH 调的,状态接口和首屏「关于」都带出去
|
|
20
|
+
const DSH_VERSION = '2.0.22-next'
|
|
17
21
|
const HOME = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
18
22
|
const BASE = join(HOME, 'plugins-data', 'dsh-hub')
|
|
19
23
|
const QQ_DATA = join(HOME, 'plugins-data', 'dsh-qq-hub')
|
|
20
24
|
const HALF_LIFE_DAYS = 60
|
|
21
25
|
const OUT_DIR = join(BASE, 'out')
|
|
26
|
+
// 解档:DSCTX 标签库在哪、还原出来的记录放哪
|
|
27
|
+
const DSCTX_DIR = process.env.DSH_DSCTX_DIR || 'D:\\AI\\memory\\state\\dsctx'
|
|
28
|
+
const RESTORE_OUT = join(BASE, 'restore')
|
|
22
29
|
|
|
23
30
|
// ===== 可配置路径:默认就是本机这套,别人改 paths.json 或设 DSH_AI_ROOT 即可 =====
|
|
24
31
|
const PATHS_FILE = join(BASE, 'paths.json')
|
|
@@ -1488,21 +1495,73 @@ async function onebotCall(action, timeoutMs = 2500) {
|
|
|
1488
1495
|
}
|
|
1489
1496
|
}
|
|
1490
1497
|
|
|
1498
|
+
|
|
1499
|
+
// ---- 按轮裁断(原型):每 N 轮把旧消息切成标签,模型只看到最近几条 ----
|
|
1500
|
+
function setupCtxCut(ctx, store) {
|
|
1501
|
+
const DIR = join(BASE, 'ctx-cut')
|
|
1502
|
+
const ROUNDS = 10 // 每 10 轮剪一次
|
|
1503
|
+
const KEEP = 12 // 保留最近 12 条消息
|
|
1504
|
+
let rounds = 0
|
|
1505
|
+
try {
|
|
1506
|
+
ctx.on('agent/pre-step', async ({ agent, step }, next) => {
|
|
1507
|
+
const decision = await next()
|
|
1508
|
+
try {
|
|
1509
|
+
if (!decision || decision.kind === 'reject') return decision
|
|
1510
|
+
if (step === 1) rounds += 1
|
|
1511
|
+
if (rounds < ROUNDS) return decision
|
|
1512
|
+
const msgs = Array.isArray(decision.messages) ? decision.messages : null
|
|
1513
|
+
if (!msgs || msgs.length <= KEEP + 4) { rounds = 0; return decision }
|
|
1514
|
+
rounds = 0
|
|
1515
|
+
const cutCount = msgs.length - KEEP
|
|
1516
|
+
const cut = msgs.slice(0, cutCount)
|
|
1517
|
+
let tag = ''
|
|
1518
|
+
try {
|
|
1519
|
+
mkdirSync(DIR, { recursive: true })
|
|
1520
|
+
tag = 'd-' + Date.now().toString(36)
|
|
1521
|
+
writeFileSync(join(DIR, tag + '.json'), JSON.stringify({ at: Date.now(), cutCount, msgs: cut }), 'utf8')
|
|
1522
|
+
} catch {}
|
|
1523
|
+
const mark = { role: 'user', content: '[较早的 ' + cutCount + ' 条对话已裁断' + (tag ? ',存为标签 ⟦' + tag + '⟧' : '') + ',需要时用标签取回原文]' }
|
|
1524
|
+
decision.messages = [mark, ...msgs.slice(cutCount)]
|
|
1525
|
+
try { store.emit({ module: 'hub', level: 'info', kind: 'cut', summary: '按轮裁断:切掉 ' + cutCount + ' 条' + (tag ? ',标签 ⟦' + tag + '⟧' : '') }) } catch {}
|
|
1526
|
+
} catch {}
|
|
1527
|
+
return decision
|
|
1528
|
+
})
|
|
1529
|
+
} catch (e) { try { console.warn('ctx-cut 挂不上:' + (e && e.message)) } catch {} }
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1491
1532
|
export async function apply(ctx, config) {
|
|
1492
1533
|
const store = await createStore()
|
|
1493
1534
|
hubStore = store
|
|
1494
1535
|
const startedAt = now()
|
|
1495
|
-
const api = { version: VERSION, store, emit: (ev) => store.emit(ev), modules: () => store.modules(), counts: () => store.counts(), base: BASE }
|
|
1536
|
+
const api = { version: VERSION, dshVersion: DSH_VERSION, store, emit: (ev) => store.emit(ev), modules: () => store.modules(), counts: () => store.counts(), base: BASE }
|
|
1496
1537
|
try { ctx.set('hubCenter', api) } catch {}
|
|
1497
1538
|
try { ctx.effect(() => () => store.close()) } catch {}
|
|
1498
1539
|
|
|
1499
1540
|
store.emit({ module: 'hub', level: 'info', kind: 'start', summary: '中枢内核已启动(' + store.kind + ')' })
|
|
1541
|
+
try { setupCtxCut(ctx, store) } catch (e) { try { store.emit({ module: 'hub', level: 'warn', kind: 'cut', summary: 'ctx-cut 没挂上:' + (e && e.message) }) } catch {} }
|
|
1500
1542
|
|
|
1501
1543
|
// 并进来的两个小插件:各自独立 try,坏一个不影响中枢本体
|
|
1502
1544
|
const sub = (config && config.sub) || {}
|
|
1503
1545
|
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
1546
|
try { applyVoice(ctx, sub.voice || {}) } catch (e) { store.emit({ module: 'hub', level: 'warn', kind: 'sub', summary: '语音朗读没起来:' + String(e && e.message || e) }) }
|
|
1505
1547
|
|
|
1548
|
+
// 模块平台:自己的功能都归这里,QQ 插件那边只留桥
|
|
1549
|
+
let platform = null
|
|
1550
|
+
try {
|
|
1551
|
+
platform = createModuleHost({
|
|
1552
|
+
dataRoot: BASE,
|
|
1553
|
+
shared: { store, base: BASE, qqData: QQ_DATA, paths: PATHS },
|
|
1554
|
+
log: (id, level, msg) => { try { store.emit({ module: 'mod:' + id, level, kind: 'module', summary: msg }) } catch {} },
|
|
1555
|
+
})
|
|
1556
|
+
try { ctx.set('hubPlatform', platform) } catch {}
|
|
1557
|
+
await platform.startAll()
|
|
1558
|
+
const up = platform.list().filter((m) => m.running).length
|
|
1559
|
+
store.emit({ module: 'hub', level: 'info', kind: 'platform', summary: '模块平台已启动:' + up + ' 个在跑,目录 ' + moduleDir(BASE) })
|
|
1560
|
+
try { ctx.effect(() => () => { try { platform.stop() } catch {} }) } catch {}
|
|
1561
|
+
} catch (e) {
|
|
1562
|
+
store.emit({ module: 'hub', level: 'warn', kind: 'platform', summary: '模块平台没起来:' + String((e && e.message) || e) })
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1506
1565
|
const qqBridge = createQqLogBridge(store)
|
|
1507
1566
|
const qqTimer = setInterval(() => { try { qqBridge.tick() } catch {} }, 10000)
|
|
1508
1567
|
try { ctx.effect(() => () => clearInterval(qqTimer)) } catch {}
|
|
@@ -1771,6 +1830,7 @@ export async function apply(ctx, config) {
|
|
|
1771
1830
|
send(res, 200, {
|
|
1772
1831
|
ok: true,
|
|
1773
1832
|
version: VERSION,
|
|
1833
|
+
dshVersion: DSH_VERSION,
|
|
1774
1834
|
alerts,
|
|
1775
1835
|
uptimeMs: now() - startedAt,
|
|
1776
1836
|
store: { kind: store.kind, file: store.file, base: BASE, fts: store.fts !== false },
|
|
@@ -1938,6 +1998,31 @@ export async function apply(ctx, config) {
|
|
|
1938
1998
|
send(res, 200, { ok: true, ...r })
|
|
1939
1999
|
})
|
|
1940
2000
|
|
|
2001
|
+
// ---- 解档:把被裁断(压缩)掉的原文按时间线拼回来 ----
|
|
2002
|
+
let restoreApi = null
|
|
2003
|
+
const getRestore = () => restoreApi || (restoreApi = createRestore({ storeDir: DSCTX_DIR, outDir: RESTORE_OUT }))
|
|
2004
|
+
|
|
2005
|
+
route('/hub-center/restore/tags', async (req, res) => {
|
|
2006
|
+
const tags = getRestore().listTags()
|
|
2007
|
+
send(res, 200, { ok: true, dir: DSCTX_DIR, dirOk: existsSync(DSCTX_DIR), outDir: RESTORE_OUT, count: tags.length, tags })
|
|
2008
|
+
})
|
|
2009
|
+
|
|
2010
|
+
// dry 默认 true,只预览不写盘;要真写出来得显式传 dry=false
|
|
2011
|
+
route('/hub-center/restore', async (req, res) => {
|
|
2012
|
+
const u = new URL(req.url, 'http://127.0.0.1')
|
|
2013
|
+
const body = req.method === 'POST' ? await readBody(req) : {}
|
|
2014
|
+
const opt = { ...body }
|
|
2015
|
+
for (const k of ['tag', 'session', 'since', 'format']) if (u.searchParams.get(k)) opt[k] = u.searchParams.get(k)
|
|
2016
|
+
if (u.searchParams.get('dry') === '1') opt.dry = true
|
|
2017
|
+
if (u.searchParams.get('sys') === '1') opt.withSys = true
|
|
2018
|
+
if (u.searchParams.get('max')) opt.max = Number(u.searchParams.get('max'))
|
|
2019
|
+
if (opt.tag === 'all') { opt.tag = ''; opt.all = true }
|
|
2020
|
+
if (!opt.tag && !opt.session) opt.all = true
|
|
2021
|
+
const r = getRestore().restore(opt)
|
|
2022
|
+
if (r.ok && !r.dry) store.emit({ module: 'memory', level: 'info', kind: 'restore', summary: `解档 ${r.base}:${r.stats.lines} 条` })
|
|
2023
|
+
send(res, r.ok ? 200 : 404, r)
|
|
2024
|
+
})
|
|
2025
|
+
|
|
1941
2026
|
// ---- 表情 ----
|
|
1942
2027
|
route('/hub-center/stickers', async (req, res) => {
|
|
1943
2028
|
const u = new URL(req.url, 'http://127.0.0.1')
|
|
@@ -1960,6 +2045,28 @@ export async function apply(ctx, config) {
|
|
|
1960
2045
|
send(res, ok ? 200 : 404, { ok })
|
|
1961
2046
|
})
|
|
1962
2047
|
|
|
2048
|
+
// ---- 表情图片直链:窗口里直接渲染,不用等对方甩链接 ----
|
|
2049
|
+
route('/hub-center/sticker/file', async (req, res) => {
|
|
2050
|
+
const u = new URL(req.url, 'http://127.0.0.1')
|
|
2051
|
+
let name = String(u.searchParams.get('f') || u.searchParams.get('file') || '').replace(/[^A-Za-z0-9._-]/g, '')
|
|
2052
|
+
const m = String(u.searchParams.get('m') || u.searchParams.get('md5') || '').replace(/[^A-Za-z0-9]/g, '')
|
|
2053
|
+
if (!name && m) {
|
|
2054
|
+
try {
|
|
2055
|
+
const idx = JSON.parse(readFileSync(join(QQ_DATA, 'stickers', 'index.json'), 'utf8'))
|
|
2056
|
+
const hit = (idx.items || []).find((it) => it && it.md5 === m)
|
|
2057
|
+
if (hit) name = String(hit.file || '').split(/[\\/]/).pop()
|
|
2058
|
+
} catch {}
|
|
2059
|
+
}
|
|
2060
|
+
if (!/^[A-Za-z0-9._-]+\.(png|jpe?g|gif|webp|bmp)$/i.test(name)) return send(res, 400, { ok: false, error: '文件名不对' })
|
|
2061
|
+
const p = join(QQ_DATA, 'stickers', name)
|
|
2062
|
+
if (!existsSync(p)) return send(res, 404, { ok: false, error: '没这个表情' })
|
|
2063
|
+
const ext = name.split('.').pop().toLowerCase()
|
|
2064
|
+
const mime = ext === 'png' ? 'image/png' : ext === 'gif' ? 'image/gif' : ext === 'webp' ? 'image/webp' : ext === 'bmp' ? 'image/bmp' : 'image/jpeg'
|
|
2065
|
+
const buf = readFileSync(p)
|
|
2066
|
+
res.writeHead(200, { 'Content-Type': mime, 'Content-Length': buf.length, 'Cache-Control': 'public, max-age=86400' })
|
|
2067
|
+
res.end(buf)
|
|
2068
|
+
})
|
|
2069
|
+
|
|
1963
2070
|
// ---- 梗百科词库 ----
|
|
1964
2071
|
route('/hub-center/meme/status', async (req, res) => {
|
|
1965
2072
|
send(res, 200, { ok: true, count: store.memeCount(), src: MEME_SRC, srcOk: existsSync(MEME_SRC) })
|
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.2",
|
|
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",
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
]
|
|
37
37
|
}
|
|
38
38
|
},
|
|
39
|
+
"dshVersion": "2.0.22-next",
|
|
39
40
|
"repository": {
|
|
40
41
|
"type": "git",
|
|
41
42
|
"url": "git+https://github.com/Yu1018/dsh-hub-center.git"
|