dsh-verbatim 0.1.0 → 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/CHANGELOG.md +14 -0
- package/LICENSE +1 -1
- package/README.en.md +24 -22
- package/README.md +24 -22
- package/bin/cli.mjs +2 -1
- package/bin/mcp-memory.mjs +130 -62
- package/client.js +8880 -8857
- package/cordis.patch.yml +1 -1
- package/docs/ARCHITECTURE.md +1 -1
- package/icon.svg +1 -1
- package/index.js +613 -2558
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -3
- package/src/config/exclude-range.js +1 -1
- package/src/config/global-config.js +3 -1
- package/src/config/session-config.js +12 -10
- package/src/config/session-config.test.js +375 -375
- package/src/derive/fact.js +6 -6
- package/src/derive/gist.js +2 -1
- package/src/host/config-views.js +2 -0
- package/src/host/db-admin.js +78 -15
- package/src/host/panel-api.js +1109 -0
- package/src/host/panel-http.js +322 -0
- package/src/host/panel-search.js +236 -0
- package/src/host/panel-session-store.js +411 -0
- package/src/host/rebuild.js +11 -3
- package/src/host/scene-ops.js +75 -6
- package/src/host/session-sync.js +91 -0
- package/src/index.js +2 -1
- package/src/ingest/cli.js +8 -7
- package/src/ingest/export.js +28 -18
- package/src/ingest/package.json +1 -1
- package/src/ingest/reader.js +181 -7
- package/src/model/embedding.js +3 -2
- package/src/model/llm.js +3 -2
- package/src/model/rerank.js +7 -4
- package/src/pipeline.js +159 -763
- package/src/scene/link.js +4 -4
- package/src/scene/package.json +1 -1
- package/src/scene/split.js +11 -11
- package/src/search/_fixtures.js +1 -0
- package/src/search/bench.js +4 -2
- package/src/search/chunk.js +6 -4
- package/src/search/dedupe.js +8 -8
- package/src/search/indexer.js +889 -879
- package/src/search/note-rank.js +64 -12
- package/src/search/regression.test.js +2 -1
- package/src/search/rrf.js +11 -11
- package/src/search/session-shape.js +3 -1
- package/src/search/thread.js +8 -8
- package/src/search/vector-fallback.js +509 -0
- package/src/search/vector-hydrate.js +309 -0
- package/src/search/vector-math.js +125 -0
- package/src/search/vector-store.js +1065 -1598
- package/src/search/vector-store.test.js +30 -0
- package/src/search/window.js +8 -8
- package/src/store/db.js +803 -715
- package/src/store/repo-extras-meta.js +430 -0
- package/src/store/repo-extras-search.js +580 -0
- package/src/store/repo.js +1024 -2133
- package/src/store/repo.test.js +39 -1
- package/src/store/schema.sql +15 -1
- package/src/tools/format.js +594 -503
- package/src/tools/index.js +7 -15
- package/src/tools/memory-forget.js +43 -32
- package/src/tools/memory-remember.js +11 -7
- package/src/tools/memory-search.js +721 -2206
- package/src/tools/remember-forget.test.js +19 -0
- package/src/tools/scope.js +7 -6
- package/src/tools/search-render.js +502 -0
- package/src/tools/time-route.js +71 -66
- package/src/tools/vector-route.js +655 -0
- package/sessions/qqb-p-0000000000-00000000000000000000000000000000.json +0 -12
|
@@ -0,0 +1,1109 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* panel-api.js —— 面板 RPC 业务层与 HTTP 适配层
|
|
3
|
+
*
|
|
4
|
+
* 从 index.js 拆出,使 Host 插件入口与面板 RPC 契约职责分离。
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
|
|
10
|
+
import { createExtras, createRepo } from '../store/repo.js';
|
|
11
|
+
import {
|
|
12
|
+
assertSessionId,
|
|
13
|
+
defaultSessionConfig,
|
|
14
|
+
normalizeRanges,
|
|
15
|
+
setSessionExcludeRanges,
|
|
16
|
+
setSessionFlag,
|
|
17
|
+
} from '../config/session-config.js';
|
|
18
|
+
import { ConfigError } from '../config/exclude-range.js';
|
|
19
|
+
import { importSession } from '../pipeline.js';
|
|
20
|
+
import { gistHeadline } from '../derive/gist.js';
|
|
21
|
+
import {
|
|
22
|
+
dayKeyInZone,
|
|
23
|
+
stripBridgeMetadata,
|
|
24
|
+
} from '../ingest/export.js';
|
|
25
|
+
import { loadGlobalConfig, saveGlobalConfig, globalConfigPath } from '../config/global-config.js';
|
|
26
|
+
import {
|
|
27
|
+
createConfigResolver,
|
|
28
|
+
sanitizeGlobalConfig,
|
|
29
|
+
buildEmbeddingView,
|
|
30
|
+
buildLlmView,
|
|
31
|
+
buildRerankView,
|
|
32
|
+
buildVecExtView,
|
|
33
|
+
} from './config-views.js';
|
|
34
|
+
import { createModelProber } from './probe.js';
|
|
35
|
+
import { createDbAdmin } from './db-admin.js';
|
|
36
|
+
import { createRebuildManager } from './rebuild.js';
|
|
37
|
+
import { createSceneOps } from './scene-ops.js';
|
|
38
|
+
import { createSessionLock } from './session-lock.js';
|
|
39
|
+
import {
|
|
40
|
+
API_PREFIX,
|
|
41
|
+
PANEL_METHODS,
|
|
42
|
+
PanelError,
|
|
43
|
+
createPanelHandler,
|
|
44
|
+
} from './panel-http.js';
|
|
45
|
+
import { findSessionFile, findLatestSession } from './session-sync.js';
|
|
46
|
+
import {
|
|
47
|
+
TIME_MAX,
|
|
48
|
+
ALL_ROWS,
|
|
49
|
+
intParam,
|
|
50
|
+
boolParam,
|
|
51
|
+
instantParam,
|
|
52
|
+
createPanelSessionStore,
|
|
53
|
+
} from './panel-session-store.js';
|
|
54
|
+
import { createPanelSearch } from './panel-search.js';
|
|
55
|
+
|
|
56
|
+
export {
|
|
57
|
+
API_PREFIX,
|
|
58
|
+
PANEL_METHODS,
|
|
59
|
+
PanelError,
|
|
60
|
+
createPanelHandler,
|
|
61
|
+
findSessionFile,
|
|
62
|
+
findLatestSession,
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
/** 依赖 DSH 的工具注册表与 HTTP 载体 */
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* 创建面板 RPC 的**业务层**(不依赖 HTTP,便于测试与复用)。
|
|
69
|
+
*
|
|
70
|
+
* @param {{
|
|
71
|
+
* handle: any, repo?: any, extras?: any,
|
|
72
|
+
* dbPath?: string, dshHome?: string, dbRoot?: string,
|
|
73
|
+
* config?: any, logger?: any,
|
|
74
|
+
* sessionLock?: any, recallLog?: any[],
|
|
75
|
+
* getHostLlm?: () => any, hostLlm?: any,
|
|
76
|
+
* syncSession?: (sessionId: string) => Promise<any>,
|
|
77
|
+
* }} [opts]
|
|
78
|
+
*/
|
|
79
|
+
export function createPanelApi(opts = /** @type {any} */ ({})) {
|
|
80
|
+
const handle = opts.handle;
|
|
81
|
+
if (!handle?.db) throw new TypeError('createPanelApi: 需要 openDb() 返回的 handle');
|
|
82
|
+
|
|
83
|
+
const repo = opts.repo ?? createRepo(handle);
|
|
84
|
+
const extras = opts.extras ?? createExtras(handle);
|
|
85
|
+
const db = handle.db;
|
|
86
|
+
const dbPath = opts.dbPath ?? handle.dbPath ?? ':memory:';
|
|
87
|
+
const dshHome = opts.dshHome ?? handle.dshHome ?? process.env.DSH_HOME ?? path.join(os.homedir(), '.dsh');
|
|
88
|
+
const dbRoot = opts.dbRoot ?? (dbPath && dbPath !== ':memory:'
|
|
89
|
+
? path.dirname(dbPath)
|
|
90
|
+
: path.join(dshHome, 'verbatim'));
|
|
91
|
+
const sessionsRoot = path.join(dshHome, 'sessions');
|
|
92
|
+
const config = opts.config ?? {};
|
|
93
|
+
const logger = opts.logger ?? {};
|
|
94
|
+
const syncSession = typeof opts.syncSession === 'function' ? opts.syncSession : null;
|
|
95
|
+
const getHostLlm = typeof opts.getHostLlm === 'function'
|
|
96
|
+
? opts.getHostLlm
|
|
97
|
+
: (opts.hostLlm ? () => opts.hostLlm : () => null);
|
|
98
|
+
|
|
99
|
+
/** 预编译语句缓存(面板一次请求会查十几次,别每次都 prepare) */
|
|
100
|
+
const stmtCache = new Map();
|
|
101
|
+
const stmt = (sql) => {
|
|
102
|
+
let s = stmtCache.get(sql);
|
|
103
|
+
if (!s) {
|
|
104
|
+
s = db.prepare(sql);
|
|
105
|
+
stmtCache.set(sql, s);
|
|
106
|
+
}
|
|
107
|
+
return s;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
const {
|
|
111
|
+
getGlobal,
|
|
112
|
+
invalidateGlobal,
|
|
113
|
+
embCfg,
|
|
114
|
+
hasEmbeddingKey,
|
|
115
|
+
llmCfg,
|
|
116
|
+
hasLlmReady,
|
|
117
|
+
rerankCfg,
|
|
118
|
+
} = createConfigResolver({ config, dshHome, logger, getHostLlm });
|
|
119
|
+
|
|
120
|
+
/** note 表有没有 session_id 列(v6 起已加;保留探测以兼容未迁移的 v5 老库) */
|
|
121
|
+
let noteColsCache = null;
|
|
122
|
+
function noteHasSessionColumn() {
|
|
123
|
+
if (noteColsCache !== null) return noteColsCache;
|
|
124
|
+
try {
|
|
125
|
+
noteColsCache = db
|
|
126
|
+
.prepare('PRAGMA table_info(note)')
|
|
127
|
+
.all()
|
|
128
|
+
.some((c) => c.name === 'session_id');
|
|
129
|
+
} catch {
|
|
130
|
+
noteColsCache = false;
|
|
131
|
+
}
|
|
132
|
+
return noteColsCache;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const {
|
|
136
|
+
sessionFiles,
|
|
137
|
+
findLogFile,
|
|
138
|
+
loadLog,
|
|
139
|
+
safeLoadLog,
|
|
140
|
+
readSessionConfig,
|
|
141
|
+
sessionAggregate,
|
|
142
|
+
vectorStatus,
|
|
143
|
+
buildWarnings,
|
|
144
|
+
cachedLogs,
|
|
145
|
+
} = createPanelSessionStore({
|
|
146
|
+
handle,
|
|
147
|
+
repo,
|
|
148
|
+
extras,
|
|
149
|
+
db,
|
|
150
|
+
stmt,
|
|
151
|
+
dbRoot,
|
|
152
|
+
sessionsRoot,
|
|
153
|
+
logger,
|
|
154
|
+
embCfg,
|
|
155
|
+
hasEmbeddingKey,
|
|
156
|
+
noteHasSessionColumn,
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
const {
|
|
160
|
+
recentTasks,
|
|
161
|
+
assertSafeToReset,
|
|
162
|
+
makeEmbeddingProvider,
|
|
163
|
+
findRunningTask,
|
|
164
|
+
startRebuildTask,
|
|
165
|
+
getTask,
|
|
166
|
+
} = createRebuildManager({
|
|
167
|
+
handle,
|
|
168
|
+
repo,
|
|
169
|
+
extras,
|
|
170
|
+
dbPath,
|
|
171
|
+
embCfg,
|
|
172
|
+
llmCfg,
|
|
173
|
+
hasEmbeddingKey,
|
|
174
|
+
hasLlmReady,
|
|
175
|
+
getHostLlm,
|
|
176
|
+
noteHasSessionColumn,
|
|
177
|
+
syncSession,
|
|
178
|
+
logger,
|
|
179
|
+
PanelError,
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
/* ══════════════════════════════ 20 个 RPC ══════════════════════════════ */
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* E1:需要会话范围的方法必须带 sessionId,缺了报错 —— **绝不默认全库**。
|
|
186
|
+
* @param {string} method
|
|
187
|
+
* @param {Record<string, any>} params
|
|
188
|
+
* @returns {string}
|
|
189
|
+
*/
|
|
190
|
+
function requireSession(method, params) {
|
|
191
|
+
const raw = params?.sessionId;
|
|
192
|
+
if (typeof raw !== 'string' || !raw.trim()) {
|
|
193
|
+
throw new PanelError(
|
|
194
|
+
'SESSION_ID_REQUIRED',
|
|
195
|
+
`panel.${method} 必须带 sessionId(D-014:一个对话一个面板)。`
|
|
196
|
+
+ '不带 sessionId 会把别的会话的数据混进来 —— 这正是旧 /verbatim-api/stats 的 bug,不再允许。',
|
|
197
|
+
400,
|
|
198
|
+
);
|
|
199
|
+
}
|
|
200
|
+
try {
|
|
201
|
+
return assertSessionId(raw);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
throw new PanelError('BAD_SESSION_ID', error?.message ?? String(error), 400);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** 可选 sessionId(按 id 定位的方法用它做跨会话保护;不传 = 全库管理视角) */
|
|
208
|
+
function optionalSession(method, params) {
|
|
209
|
+
const raw = params?.sessionId;
|
|
210
|
+
if (raw === undefined || raw === null || raw === '') return null;
|
|
211
|
+
if (typeof raw !== 'string') {
|
|
212
|
+
throw new PanelError('BAD_SESSION_ID', `panel.${method} 的 sessionId 必须是非空字符串`, 400);
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
return assertSessionId(raw);
|
|
216
|
+
} catch (error) {
|
|
217
|
+
throw new PanelError('BAD_SESSION_ID', error?.message ?? String(error), 400);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* `panel.status({ sessionId })` → { enabled, stats, vector }(B3~B7)
|
|
223
|
+
*
|
|
224
|
+
* - enabled 只有 record / tools 两个开关(D-166:autoRecall 不进面板)
|
|
225
|
+
* - stats 只算**这个会话**(A2),compactedMsgs 是面板最核心的数字(B4)
|
|
226
|
+
* - rewindedMsgs 从原始日志重新数(库里是物理删除的,查不到,B5)
|
|
227
|
+
* - vector.state 明确区分 ok / degraded / disabled(B6/B7)
|
|
228
|
+
*/
|
|
229
|
+
function status(params) {
|
|
230
|
+
const sessionId = requireSession('status', params);
|
|
231
|
+
const cfg = readSessionConfig(sessionId);
|
|
232
|
+
const agg = sessionAggregate(sessionId);
|
|
233
|
+
const log = safeLoadLog(sessionId);
|
|
234
|
+
const rewindedMsgs = log ? Number(log.stats.rewoundCount ?? 0) : null;
|
|
235
|
+
const rewindedChars = log ? Number(log.stats.rewoundChars ?? 0) : null;
|
|
236
|
+
const excludedMsgs = agg.excludedMsgs;
|
|
237
|
+
const deletedNotesCount = noteHasSessionColumn()
|
|
238
|
+
? extras.note.count({ sessionId, deletedOnly: true })
|
|
239
|
+
: extras.note.count({ deletedOnly: true });
|
|
240
|
+
let scenesWithGist = 0;
|
|
241
|
+
let llmGistScenes = 0;
|
|
242
|
+
try {
|
|
243
|
+
scenesWithGist = Number(
|
|
244
|
+
stmt("SELECT COUNT(*) AS c FROM scene WHERE session_id = ? AND gist IS NOT NULL AND TRIM(gist) != ''").get(sessionId)?.c ?? 0,
|
|
245
|
+
);
|
|
246
|
+
llmGistScenes = Number(
|
|
247
|
+
stmt("SELECT COUNT(*) AS c FROM scene WHERE session_id = ? AND gist_source = 'llm'").get(sessionId)?.c ?? 0,
|
|
248
|
+
);
|
|
249
|
+
} catch {
|
|
250
|
+
scenesWithGist = 0;
|
|
251
|
+
llmGistScenes = 0;
|
|
252
|
+
}
|
|
253
|
+
const llmGistRatio = agg.sceneCount > 0 ? Math.round((llmGistScenes / agg.sceneCount) * 100) : 0;
|
|
254
|
+
const llmConf = llmCfg();
|
|
255
|
+
|
|
256
|
+
return {
|
|
257
|
+
enabled: { record: cfg.record === true, tools: cfg.tools === true },
|
|
258
|
+
excludeRanges: cfg.excludeRanges,
|
|
259
|
+
stats: {
|
|
260
|
+
totalMsgs: agg.totalMsgs,
|
|
261
|
+
totalChars: agg.totalChars,
|
|
262
|
+
startAt: agg.startAt,
|
|
263
|
+
compactedMsgs: agg.compactedMsgs,
|
|
264
|
+
compactedChars: agg.compactedChars,
|
|
265
|
+
rewindedMsgs,
|
|
266
|
+
rewindedChars,
|
|
267
|
+
excludedMsgs,
|
|
268
|
+
deletedNotesCount,
|
|
269
|
+
sceneCount: agg.sceneCount,
|
|
270
|
+
scenesWithGist,
|
|
271
|
+
llmGistScenes,
|
|
272
|
+
llmGistRatio,
|
|
273
|
+
dayCount: agg.dayCount,
|
|
274
|
+
},
|
|
275
|
+
vector: vectorStatus(sessionId, agg.totalMsgs),
|
|
276
|
+
llm: {
|
|
277
|
+
ready: hasLlmReady(),
|
|
278
|
+
enabled: llmConf.enabled,
|
|
279
|
+
mode: llmConf.mode,
|
|
280
|
+
model: llmConf.model,
|
|
281
|
+
},
|
|
282
|
+
sessionId,
|
|
283
|
+
dbPath,
|
|
284
|
+
hasVec: handle.hasVec === true,
|
|
285
|
+
warnings: buildWarnings(),
|
|
286
|
+
tasks: recentTasks(),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* `panel.timeline({ sessionId, from?, to?, limit? })`
|
|
292
|
+
* → [{ date, msgCount, sceneCount, chars, scenes: [{ id, startAt, endAt, msgCount, compacted }] }]
|
|
293
|
+
*
|
|
294
|
+
* 按天分组,默认最近 7 天(PANEL §3.4「默认展开最近 7 天」)。
|
|
295
|
+
* `limit` 是**天数**,不是消息数。
|
|
296
|
+
*/
|
|
297
|
+
function timeline(params) {
|
|
298
|
+
const sessionId = requireSession('timeline', params);
|
|
299
|
+
const limit = intParam(params.limit, 'limit', { def: 7, min: 1, max: 100 });
|
|
300
|
+
const from = instantParam(params.from, 'from', 0);
|
|
301
|
+
const to = instantParam(params.to, 'to', TIME_MAX);
|
|
302
|
+
if (to <= from) throw new PanelError('BAD_RANGE', `to(${to})必须大于 from(${from})`, 400);
|
|
303
|
+
|
|
304
|
+
const scenes = repo.scenesByTimeRange(sessionId, from, to, ALL_ROWS);
|
|
305
|
+
|
|
306
|
+
/** @type {Map<string, {date:string, msgCount:number, sceneCount:number, pendingMsgs:number, chars:number, scenes:any[]}>} */
|
|
307
|
+
const byDay = new Map();
|
|
308
|
+
const ensure = (date) => {
|
|
309
|
+
let d = byDay.get(date);
|
|
310
|
+
if (!d) {
|
|
311
|
+
d = { date, msgCount: 0, sceneCount: 0, pendingMsgs: 0, chars: 0, scenes: [] };
|
|
312
|
+
byDay.set(date, d);
|
|
313
|
+
}
|
|
314
|
+
return d;
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
for (const m of stmt(
|
|
318
|
+
'SELECT at, LENGTH(text) AS len, scene_id FROM msg WHERE session_id = ? AND at >= ? AND at < ?',
|
|
319
|
+
).iterate(sessionId, from, to)) {
|
|
320
|
+
const d = ensure(dayKeyInZone(Number(m.at)));
|
|
321
|
+
d.msgCount += 1;
|
|
322
|
+
d.chars += Number(m.len ?? 0);
|
|
323
|
+
if (m.scene_id === null || m.scene_id === undefined) {
|
|
324
|
+
d.pendingMsgs += 1;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
for (const s of scenes) {
|
|
328
|
+
// 场景归到「它在查询区间内的第一天」(不是 startAt 那天):
|
|
329
|
+
// 一场可能跨午夜(11-15 18:25 → 11-16 04:35),如果按 startAt 归组,
|
|
330
|
+
// from=11-16 时会在 11-15 凭空造出一个 msgCount=0 的天,看起来像 bug。
|
|
331
|
+
const day = dayKeyInZone(Math.max(s.startAt, from));
|
|
332
|
+
const d = ensure(day);
|
|
333
|
+
d.scenes.push({
|
|
334
|
+
id: s.id,
|
|
335
|
+
startAt: s.startAt,
|
|
336
|
+
endAt: s.endAt,
|
|
337
|
+
msgCount: s.msgCount,
|
|
338
|
+
gist: gistHeadline(s.gist, 42),
|
|
339
|
+
gistSource: s.gistSource ?? null,
|
|
340
|
+
locked: s.locked === 1,
|
|
341
|
+
// 这一场里有没有被压缩掉的(D-141:压缩的内容必须还在库里)
|
|
342
|
+
compacted: s.crossesCompaction === 1 || s.outOfSurfaceCount > 0,
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const days = [...byDay.values()]
|
|
347
|
+
.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0))
|
|
348
|
+
.slice(0, limit);
|
|
349
|
+
for (const d of days) {
|
|
350
|
+
d.scenes.sort((a, b) => a.startAt - b.startAt);
|
|
351
|
+
d.sceneCount = d.scenes.length;
|
|
352
|
+
}
|
|
353
|
+
return days;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* `panel.sceneDetail({ sceneId })`
|
|
358
|
+
* → { startAt, endAt, msgs: [{ id, at, speaker, text, inSurface }], leadIn }
|
|
359
|
+
*
|
|
360
|
+
* 按 id 定位,不需要 sessionId(E1 豁免)。
|
|
361
|
+
*/
|
|
362
|
+
function sceneDetail(params) {
|
|
363
|
+
const sceneId = intParam(params.sceneId, 'sceneId', { min: 1 });
|
|
364
|
+
const scene = repo.sceneById(sceneId);
|
|
365
|
+
if (!scene) throw new PanelError('SCENE_NOT_FOUND', `没有 id=${sceneId} 的场景`, 404);
|
|
366
|
+
|
|
367
|
+
// includeExcluded=true:核对时被排除的那段也要看得见(不然会以为"没记")
|
|
368
|
+
const rawMsgs = repo.msgsByScene(sceneId, true);
|
|
369
|
+
const mediaByMsg = extras?.media?.byMsgIds ? extras.media.byMsgIds(rawMsgs.map((m) => m.id)) : new Map();
|
|
370
|
+
const msgs = rawMsgs.map((m) => ({
|
|
371
|
+
id: m.id,
|
|
372
|
+
at: m.at,
|
|
373
|
+
speaker: m.speaker,
|
|
374
|
+
text: m.text,
|
|
375
|
+
inSurface: m.inSurface,
|
|
376
|
+
excluded: m.excluded ?? 0,
|
|
377
|
+
media: mediaByMsg.get(Number(m.id)) ?? [],
|
|
378
|
+
}));
|
|
379
|
+
|
|
380
|
+
let leadIn = null;
|
|
381
|
+
if (scene.leadIn !== null && scene.leadIn !== undefined) {
|
|
382
|
+
try {
|
|
383
|
+
leadIn = JSON.parse(scene.leadIn);
|
|
384
|
+
} catch {
|
|
385
|
+
leadIn = scene.leadIn; // 老数据可能不是 JSON,原样给出,别让面板崩
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
return {
|
|
390
|
+
sceneId: scene.id,
|
|
391
|
+
sessionId: scene.sessionId,
|
|
392
|
+
startAt: scene.startAt,
|
|
393
|
+
endAt: scene.endAt,
|
|
394
|
+
msgCount: scene.msgCount,
|
|
395
|
+
precededBy: scene.precededBy ?? null,
|
|
396
|
+
followedBy: scene.followedBy ?? null,
|
|
397
|
+
locked: scene.locked === 1,
|
|
398
|
+
gist: gistHeadline(scene.gist, 60),
|
|
399
|
+
gistSource: scene.gistSource ?? null,
|
|
400
|
+
compacted: scene.crossesCompaction === 1 || scene.outOfSurfaceCount > 0,
|
|
401
|
+
msgs,
|
|
402
|
+
leadIn,
|
|
403
|
+
};
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* `panel.notes({ sessionId, limit?, offset? })` → [{ id, content, about, at }]
|
|
408
|
+
*
|
|
409
|
+
* A2 会话隔离:`note` 表从 v6 起有 `session_id` 列,按会话过滤(TA记的是
|
|
410
|
+
* 「在这个对话里记的」,面板也是「一个对话一个面板」)。
|
|
411
|
+
* 老库(v5 及更早、还没迁移完)没有这一列时才退回全库,并在 warnings 里明说。
|
|
412
|
+
*/
|
|
413
|
+
function notes(params) {
|
|
414
|
+
const sessionId = requireSession('notes', params);
|
|
415
|
+
const limit = intParam(params.limit, 'limit', { def: 100, min: 1, max: 500 });
|
|
416
|
+
const offset = intParam(params.offset, 'offset', { def: 0, min: 0, max: 1_000_000 });
|
|
417
|
+
|
|
418
|
+
const rows = noteHasSessionColumn()
|
|
419
|
+
? extras.note.list({ sessionId, limit, offset })
|
|
420
|
+
: extras.note.list({ limit, offset });
|
|
421
|
+
return rows.map((r) => ({
|
|
422
|
+
id: r.id,
|
|
423
|
+
content: r.content,
|
|
424
|
+
about: r.about ?? null,
|
|
425
|
+
at: r.at,
|
|
426
|
+
}));
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/**
|
|
430
|
+
* `panel.deletedNotes({ sessionId, limit?, offset? })` → { items, total }
|
|
431
|
+
* 回收站:仅列该会话已被软删、仍在 30 天保留期内的笔记,并在读取前顺手清理过期条目。
|
|
432
|
+
*/
|
|
433
|
+
function deletedNotes(params) {
|
|
434
|
+
const NOTE_RETENTION_MS = 30 * 86_400_000;
|
|
435
|
+
const sessionId = requireSession('deletedNotes', params);
|
|
436
|
+
const limit = intParam(params.limit, 'limit', { def: 50, min: 1, max: 500 });
|
|
437
|
+
const offset = intParam(params.offset, 'offset', { def: 0, min: 0, max: 1_000_000 });
|
|
438
|
+
const hasSessionCol = noteHasSessionColumn();
|
|
439
|
+
|
|
440
|
+
try {
|
|
441
|
+
if (hasSessionCol) extras.note.purgeExpired(NOTE_RETENTION_MS, Date.now(), { sessionId });
|
|
442
|
+
else extras.note.purgeExpired(NOTE_RETENTION_MS, Date.now());
|
|
443
|
+
} catch {
|
|
444
|
+
// best-effort:清理失败不影响列回收站
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
const filter = hasSessionCol ? { sessionId, deletedOnly: true } : { deletedOnly: true };
|
|
448
|
+
const rows = extras.note.list({ ...filter, limit, offset });
|
|
449
|
+
const total = extras.note.count(filter);
|
|
450
|
+
return {
|
|
451
|
+
items: rows.map((r) => ({
|
|
452
|
+
id: r.id,
|
|
453
|
+
content: r.content,
|
|
454
|
+
about: r.about ?? null,
|
|
455
|
+
at: r.at,
|
|
456
|
+
deletedAt: r.deletedAt,
|
|
457
|
+
expiresAt: r.deletedAt ? r.deletedAt + NOTE_RETENTION_MS : null,
|
|
458
|
+
})),
|
|
459
|
+
total,
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* `panel.search({ sessionId, query, when?, limit?, includeExcluded? })`
|
|
465
|
+
* 面板搜索:关键词路优先;命中 < 5 条且本会话向量可用时按需补语义路(RRF 融合)。
|
|
466
|
+
*/
|
|
467
|
+
const search = createPanelSearch({
|
|
468
|
+
handle,
|
|
469
|
+
repo,
|
|
470
|
+
extras,
|
|
471
|
+
db,
|
|
472
|
+
dshHome,
|
|
473
|
+
logger,
|
|
474
|
+
requireSession,
|
|
475
|
+
vectorStatus,
|
|
476
|
+
hasEmbeddingKey,
|
|
477
|
+
makeEmbeddingProvider,
|
|
478
|
+
rerankCfg,
|
|
479
|
+
noteHasSessionColumn,
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* `panel.sample({ sessionId })` → { id, at, speaker, text, scene }
|
|
485
|
+
*
|
|
486
|
+
* 「抽一条」用于核对(C4)。该会话没有任何消息时返回 null(面板显示空态)。
|
|
487
|
+
*/
|
|
488
|
+
function sample(params) {
|
|
489
|
+
const sessionId = requireSession('sample', params);
|
|
490
|
+
const total = Number(stmt('SELECT COUNT(*) AS c FROM msg WHERE session_id = ?').get(sessionId)?.c ?? 0);
|
|
491
|
+
if (total === 0) return null;
|
|
492
|
+
|
|
493
|
+
// 均匀随机:O(1) 抽样,不把全库消息正文拉进内存
|
|
494
|
+
const offset = Math.floor(Math.random() * total);
|
|
495
|
+
const picked = stmt('SELECT id FROM msg WHERE session_id = ? ORDER BY seq LIMIT 1 OFFSET ?').get(sessionId, offset);
|
|
496
|
+
if (!picked) return null;
|
|
497
|
+
const m = repo.msgsByIds([Number(picked.id)])[0];
|
|
498
|
+
if (!m) return null;
|
|
499
|
+
const scene = m.sceneId ? repo.sceneById(m.sceneId) : null;
|
|
500
|
+
return {
|
|
501
|
+
id: m.id,
|
|
502
|
+
seq: m.seq,
|
|
503
|
+
sessionId,
|
|
504
|
+
at: m.at,
|
|
505
|
+
speaker: m.speaker,
|
|
506
|
+
text: m.text,
|
|
507
|
+
inSurface: m.inSurface,
|
|
508
|
+
scene: scene
|
|
509
|
+
? { id: scene.id, startAt: scene.startAt, endAt: scene.endAt, msgCount: scene.msgCount }
|
|
510
|
+
: null,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* `panel.verify({ msgId })` → { dbText, logText, identical }(C4 / E2,P0)
|
|
516
|
+
*
|
|
517
|
+
* 这是整个面板最重要的功能:让你亲眼确认「库里存的字」和「日志里的字」一模一样。
|
|
518
|
+
*
|
|
519
|
+
* dbText —— 库里存的(已经清洗过桥接元数据,D-216)
|
|
520
|
+
* logText —— 从原始会话日志重导出并**再清洗一次**(stripBridgeMetadata)后的正文
|
|
521
|
+
* identical —— 两者是否逐字相同
|
|
522
|
+
*/
|
|
523
|
+
function verify(params) {
|
|
524
|
+
const msgId = intParam(params.msgId, 'msgId', { min: 1 });
|
|
525
|
+
const row = repo.msgsByIds([msgId])[0];
|
|
526
|
+
if (!row) {
|
|
527
|
+
throw new PanelError(
|
|
528
|
+
'MSG_NOT_FOUND',
|
|
529
|
+
`没有 id=${msgId} 的消息。原文是唯一事实来源,查不到就是真的不在库里(可能已撤回,或 id 不属于这个库)。`,
|
|
530
|
+
404,
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const log = safeLoadLog(row.sessionId);
|
|
535
|
+
let logText = null;
|
|
536
|
+
let source = 'no-log';
|
|
537
|
+
let reason = null;
|
|
538
|
+
|
|
539
|
+
if (log) {
|
|
540
|
+
const entry = log.raw.get(row.seq);
|
|
541
|
+
if (entry) {
|
|
542
|
+
// 库里存的是清洗后的正文(D-216);比对必须用同一条清洗路径,
|
|
543
|
+
// 否则每条带 `【当前时间】…` 的消息都会假失败。
|
|
544
|
+
logText = stripBridgeMetadata(entry.raw);
|
|
545
|
+
source = 'log';
|
|
546
|
+
} else {
|
|
547
|
+
source = 'log-missing-seq';
|
|
548
|
+
reason = `日志里没有 seq=${row.seq}(可能已被撤回、或日志已轮转)`;
|
|
549
|
+
}
|
|
550
|
+
} else {
|
|
551
|
+
reason = '找不到这个会话的原始日志文件,无法比对';
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
const identical = typeof logText === 'string' && logText === row.text;
|
|
555
|
+
return {
|
|
556
|
+
dbText: row.text,
|
|
557
|
+
logText,
|
|
558
|
+
identical,
|
|
559
|
+
msgId: row.id,
|
|
560
|
+
sessionId: row.sessionId,
|
|
561
|
+
seq: row.seq,
|
|
562
|
+
at: row.at,
|
|
563
|
+
speaker: row.speaker,
|
|
564
|
+
source,
|
|
565
|
+
reason,
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* `panel.set({ sessionId, key, value })` → 落盘后的开关状态(E4:写操作必须明确返回)
|
|
571
|
+
*
|
|
572
|
+
* key: 'record' | 'tools' | 'autoRecall'
|
|
573
|
+
* 走 `setSessionFlag`(T9 的配置层),**不自己写文件**。
|
|
574
|
+
*/
|
|
575
|
+
function set(params) {
|
|
576
|
+
const sessionId = requireSession('set', params);
|
|
577
|
+
const key = String(params.key ?? '');
|
|
578
|
+
if (!['record', 'tools', 'autoRecall'].includes(key)) {
|
|
579
|
+
throw new PanelError(
|
|
580
|
+
'BAD_KEY',
|
|
581
|
+
`开关名只能是 "record" / "tools" / "autoRecall",收到 ${JSON.stringify(params.key)}`,
|
|
582
|
+
400,
|
|
583
|
+
);
|
|
584
|
+
}
|
|
585
|
+
const value = boolParam(params.value, 'value');
|
|
586
|
+
|
|
587
|
+
let cfg;
|
|
588
|
+
try {
|
|
589
|
+
cfg = setSessionFlag(sessionId, /** @type {'record'|'tools'|'autoRecall'} */ (key), value, { dbRoot });
|
|
590
|
+
} catch (error) {
|
|
591
|
+
throw new PanelError('CONFIG_WRITE_FAILED', `开关没保存上:${error?.message ?? error}`, 500);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const applies = key === 'record'
|
|
595
|
+
? '已保存。下一次同步开始按新开关执行(关掉后新消息不再入库,已有数据一条不删)。'
|
|
596
|
+
: key === 'tools'
|
|
597
|
+
? '已保存。已尝试热更新当前会话的工具注入;若对话未加载,将在下次打开时生效。'
|
|
598
|
+
: '已保存(autoRecall 是预留配置项,面板不显示开关,D-166)。';
|
|
599
|
+
|
|
600
|
+
return {
|
|
601
|
+
ok: true,
|
|
602
|
+
sessionId,
|
|
603
|
+
key,
|
|
604
|
+
value,
|
|
605
|
+
// 面板只渲染两个开关(D-166);autoRecall 保留在协议里但前端不显示
|
|
606
|
+
enabled: { record: cfg.record === true, tools: cfg.tools === true },
|
|
607
|
+
config: {
|
|
608
|
+
record: cfg.record === true,
|
|
609
|
+
tools: cfg.tools === true,
|
|
610
|
+
autoRecall: cfg.autoRecall === true,
|
|
611
|
+
excludeRanges: cfg.excludeRanges,
|
|
612
|
+
},
|
|
613
|
+
applies,
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* `panel.setExcludeRanges({ sessionId, ranges })` → { ok: true, sessionId, excludeRanges, synced }
|
|
619
|
+
* 写回排除区间配置,并立刻同步更新数据库里的 `msg.excluded` 与 `scene.excluded_count/has_excluded`。
|
|
620
|
+
*/
|
|
621
|
+
function setExcludeRanges(params) {
|
|
622
|
+
const sessionId = requireSession('setExcludeRanges', params);
|
|
623
|
+
const rawRanges = params.ranges !== undefined ? params.ranges : params.excludeRanges;
|
|
624
|
+
if (!Array.isArray(rawRanges)) {
|
|
625
|
+
throw new PanelError('BAD_EXCLUDE_RANGE', 'ranges 必须是数组', 400);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
let cfg;
|
|
629
|
+
let normalized;
|
|
630
|
+
try {
|
|
631
|
+
cfg = setSessionExcludeRanges(sessionId, rawRanges, { dbRoot });
|
|
632
|
+
normalized = normalizeRanges(cfg.excludeRanges);
|
|
633
|
+
} catch (err) {
|
|
634
|
+
if (err instanceof ConfigError || err?.name === 'ConfigError') {
|
|
635
|
+
throw new PanelError('BAD_EXCLUDE_RANGE', err.message, 400);
|
|
636
|
+
}
|
|
637
|
+
throw new PanelError('CONFIG_WRITE_FAILED', `排除区间没保存上:${err?.message ?? err}`, 500);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
const synced = extras.sceneAssign.syncExcludedForSession(sessionId, normalized);
|
|
641
|
+
return {
|
|
642
|
+
ok: true,
|
|
643
|
+
sessionId,
|
|
644
|
+
excludeRanges: cfg.excludeRanges,
|
|
645
|
+
synced,
|
|
646
|
+
};
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
/**
|
|
650
|
+
* `panel.rebuild({ sessionId, scope })` → { taskId }(然后轮询 panel.task)
|
|
651
|
+
*
|
|
652
|
+
* scope:
|
|
653
|
+
* 'scene' —— 从 msg 重建场景(切分 + 邻接),原文一条不动
|
|
654
|
+
* 'vector' —— 重建向量索引(需要 embedding key)
|
|
655
|
+
* 'derive' —— 场景 + gist(要 llm)+ 向量(要 embedding),缺什么就明确说跳过
|
|
656
|
+
*
|
|
657
|
+
* 安全闸门(E3):任何 `reset: true` 的清库意图先过 assertSafeToReset(),
|
|
658
|
+
* 真实记忆库直接 403;即使临时库也只重建派生数据,**永不删 msg**。
|
|
659
|
+
*/
|
|
660
|
+
function rebuild(params) {
|
|
661
|
+
const sessionId = requireSession('rebuild', params);
|
|
662
|
+
const scope = params.scope === undefined || params.scope === null || params.scope === ''
|
|
663
|
+
? 'derive'
|
|
664
|
+
: String(params.scope);
|
|
665
|
+
if (!['scene', 'vector', 'derive', 'incremental', 'gist'].includes(scope)) {
|
|
666
|
+
throw new PanelError(
|
|
667
|
+
'BAD_SCOPE',
|
|
668
|
+
`scope 只能是 "scene" / "vector" / "derive" / "incremental" / "gist",收到 ${JSON.stringify(params.scope)}`,
|
|
669
|
+
400,
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
if (params.reset === true) {
|
|
674
|
+
// 真实库会在这里被 403 拒绝(可复现的闸门)
|
|
675
|
+
assertSafeToReset(dbPath);
|
|
676
|
+
// 临时库也不清原文:重建只重建派生数据
|
|
677
|
+
logger.warn?.(`[verbatim] panel.rebuild reset 请求:库在临时目录下,仍只重建派生数据(不删 msg)`);
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// 向量重建依赖 embedding key:没有就**当场明确拒绝**(E4 / B7),
|
|
681
|
+
// 不要先返回 taskId 再在后台失败 —— 前端会一直以为"还在跑"。
|
|
682
|
+
if (scope === 'vector' && !hasEmbeddingKey()) {
|
|
683
|
+
throw new PanelError(
|
|
684
|
+
'NO_EMBEDDING',
|
|
685
|
+
'没有配置 embedding 的 API Key,向量索引无法重建。去设置页填一个,或把服务类型改成「本地」。'
|
|
686
|
+
+ '时间轴与关键词检索不受影响 —— 这不是失败,是「语义搜索未启用」(B7)。',
|
|
687
|
+
503,
|
|
688
|
+
);
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
if (scope === 'gist' && !hasLlmReady()) {
|
|
692
|
+
throw new PanelError(
|
|
693
|
+
'NO_LLM',
|
|
694
|
+
'尚未启用或未配好场景摘要 LLM。请先在「设置 → 逐字记忆 → 场景摘要 LLM」启用并完成配置(未启用时已自动使用零成本抽取式摘要)。',
|
|
695
|
+
503,
|
|
696
|
+
);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// 同会话已有同类(或全量)向量任务在跑时直接复用,避免连点造成并发重算
|
|
700
|
+
const active = findRunningTask(sessionId, scope);
|
|
701
|
+
if (active) {
|
|
702
|
+
return {
|
|
703
|
+
taskId: active.id,
|
|
704
|
+
scope: active.scope,
|
|
705
|
+
sessionId,
|
|
706
|
+
state: active.state,
|
|
707
|
+
progress: active.progress ?? null,
|
|
708
|
+
reused: true,
|
|
709
|
+
};
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
const useLlm = params.useLlm === false ? false : undefined;
|
|
713
|
+
const onlyUnrefined = params.onlyUnrefined === true;
|
|
714
|
+
const concurrency = Number.isFinite(Number(params.concurrency)) ? Number(params.concurrency) : undefined;
|
|
715
|
+
const task = startRebuildTask({ sessionId, scope, useLlm, onlyUnrefined, concurrency });
|
|
716
|
+
return { taskId: task.id, scope, sessionId, state: task.state, progress: task.progress ?? null };
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** `panel.task({ taskId })` → 重建任务进度(PANEL §5「然后轮询进度」的落点) */
|
|
720
|
+
function taskInfo(params) {
|
|
721
|
+
const taskId = String(params.taskId ?? '');
|
|
722
|
+
if (!taskId) throw new PanelError('BAD_ARG', '缺少 taskId', 400);
|
|
723
|
+
const t = getTask(taskId);
|
|
724
|
+
if (!t) throw new PanelError('TASK_NOT_FOUND', `没有 taskId=${taskId} 的重建任务(任务只保留最近 20 个)`, 404);
|
|
725
|
+
return {
|
|
726
|
+
taskId: t.id,
|
|
727
|
+
scope: t.scope,
|
|
728
|
+
sessionId: t.sessionId,
|
|
729
|
+
state: t.state,
|
|
730
|
+
progress: t.progress ?? null,
|
|
731
|
+
startedAt: t.startedAt,
|
|
732
|
+
finishedAt: t.finishedAt,
|
|
733
|
+
result: t.result,
|
|
734
|
+
error: t.error,
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* `panel.flag({ msgId, reason? })` → { id }
|
|
740
|
+
*
|
|
741
|
+
* 只记一笔,不删任何东西(C5 / D-167)。标记后检索照常返回该条。
|
|
742
|
+
*/
|
|
743
|
+
function flag(params) {
|
|
744
|
+
const msgId = intParam(params.msgId, 'msgId', { min: 1 });
|
|
745
|
+
const row = repo.msgsByIds([msgId])[0];
|
|
746
|
+
if (!row) throw new PanelError('MSG_NOT_FOUND', `没有 id=${msgId} 的消息,标不了`, 404);
|
|
747
|
+
const reason = params.reason === undefined || params.reason === null || params.reason === ''
|
|
748
|
+
? null
|
|
749
|
+
: String(params.reason);
|
|
750
|
+
|
|
751
|
+
let id;
|
|
752
|
+
try {
|
|
753
|
+
id = extras.flag.insert({ msgId, reason });
|
|
754
|
+
} catch (error) {
|
|
755
|
+
throw new PanelError('FLAG_FAILED', `标记没记上:${error?.message ?? error}`, 500);
|
|
756
|
+
}
|
|
757
|
+
return { id, msgId, reason, at: Date.now(), sessionId: row.sessionId };
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/**
|
|
761
|
+
* `panel.flags({ sessionId, limit? })` → [{ id, msgId, reason, at, snippet }]
|
|
762
|
+
*
|
|
763
|
+
* 只要未取消的标记(resolved_at IS NULL)。snippet 供核对页直接显示原文开头。
|
|
764
|
+
*/
|
|
765
|
+
function flags(params) {
|
|
766
|
+
const sessionId = requireSession('flags', params);
|
|
767
|
+
const limit = intParam(params.limit, 'limit', { def: 50, min: 1, max: 500 });
|
|
768
|
+
|
|
769
|
+
const rows = extras.flag.list({ sessionId, openOnly: true, limit });
|
|
770
|
+
const ids = rows.map((r) => r.msgId);
|
|
771
|
+
const byId = new Map(repo.msgsByIds(ids).map((m) => [m.id, m]));
|
|
772
|
+
|
|
773
|
+
return rows.map((r) => {
|
|
774
|
+
const msg = byId.get(r.msgId);
|
|
775
|
+
const text = msg?.text ?? '';
|
|
776
|
+
return {
|
|
777
|
+
id: r.id,
|
|
778
|
+
msgId: r.msgId,
|
|
779
|
+
reason: r.reason ?? null,
|
|
780
|
+
at: r.at,
|
|
781
|
+
snippet: text.length > 80 ? `${text.slice(0, 80)}…` : text,
|
|
782
|
+
};
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** `panel.unflag({ id })` → { ok }(只撤销标记,不碰原文) */
|
|
787
|
+
function unflag(params) {
|
|
788
|
+
const id = intParam(params.id, 'id', { min: 1 });
|
|
789
|
+
const changed = extras.flag.resolve(id);
|
|
790
|
+
return {
|
|
791
|
+
ok: changed,
|
|
792
|
+
id,
|
|
793
|
+
message: changed ? '已取消标记(这条原文没有任何变化)' : '没有可取消的标记(不存在,或已经取消过了)',
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* `panel.deleteNote({ id, sessionId?, reason? })` → { ok }(软删,30 天内可恢复)
|
|
799
|
+
*
|
|
800
|
+
* 带 sessionId 时只删该会话的笔记(A1:B 会话不能凭编号删掉 A 的);
|
|
801
|
+
* 不带 = 全库管理视角(PANEL §5 的契约只写了 id,这里向后兼容)。
|
|
802
|
+
*/
|
|
803
|
+
function deleteNote(params) {
|
|
804
|
+
const id = intParam(params.id, 'id', { min: 1 });
|
|
805
|
+
const sessionId = optionalSession('deleteNote', params);
|
|
806
|
+
const reason = params.reason === undefined || params.reason === null || params.reason === ''
|
|
807
|
+
? null
|
|
808
|
+
: String(params.reason);
|
|
809
|
+
|
|
810
|
+
const row = extras.note.byId(id, sessionId ? { sessionId } : {});
|
|
811
|
+
if (!row) {
|
|
812
|
+
throw new PanelError(
|
|
813
|
+
'NOTE_NOT_FOUND',
|
|
814
|
+
`没有 id=${id} 的笔记${sessionId ? `(会话 ${sessionId} 里没有这条)` : ''}`,
|
|
815
|
+
404,
|
|
816
|
+
);
|
|
817
|
+
}
|
|
818
|
+
if (row.deletedAt !== null) {
|
|
819
|
+
return { ok: false, id, deletedAt: row.deletedAt, message: '这条笔记之前已经删过了(30 天内可以在回收站恢复)' };
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
const deletedAt = Date.now();
|
|
823
|
+
const changed = extras.note.softDelete(id, deletedAt, sessionId ? { sessionId } : {});
|
|
824
|
+
if (changed) {
|
|
825
|
+
try {
|
|
826
|
+
if (handle.hasVec) db.prepare('DELETE FROM vec_note WHERE note_id = ?').run(BigInt(id));
|
|
827
|
+
} catch { /* ignore */ }
|
|
828
|
+
try {
|
|
829
|
+
extras.audit.insert({
|
|
830
|
+
action: 'forget',
|
|
831
|
+
target: `note:${id}`,
|
|
832
|
+
detail: { via: 'panel', reason, sessionId },
|
|
833
|
+
});
|
|
834
|
+
} catch {
|
|
835
|
+
// 审计失败不该让删除回滚:笔记已经标记删除了
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
return {
|
|
839
|
+
ok: changed,
|
|
840
|
+
id,
|
|
841
|
+
deletedAt: changed ? deletedAt : null,
|
|
842
|
+
message: changed ? '已删除(软删,30 天内可在回收站恢复)' : '删除没生效(可能刚刚被删过)',
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* `panel.restoreNote({ id, sessionId? })` → { ok }
|
|
848
|
+
*
|
|
849
|
+
* 带 sessionId 时只恢复该会话的笔记(和 deleteNote 同一套归属判断)。
|
|
850
|
+
*/
|
|
851
|
+
function restoreNote(params) {
|
|
852
|
+
const id = intParam(params.id, 'id', { min: 1 });
|
|
853
|
+
const sessionId = optionalSession('restoreNote', params);
|
|
854
|
+
const row = extras.note.byId(id, sessionId ? { sessionId } : {});
|
|
855
|
+
if (!row) {
|
|
856
|
+
throw new PanelError(
|
|
857
|
+
'NOTE_NOT_FOUND',
|
|
858
|
+
`没有 id=${id} 的笔记${sessionId ? `(会话 ${sessionId} 里没有这条)` : ''}`,
|
|
859
|
+
404,
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
if (row.deletedAt === null) {
|
|
863
|
+
return { ok: false, id, message: '这条笔记没有被删过,不需要恢复' };
|
|
864
|
+
}
|
|
865
|
+
const changed = extras.note.restore(id, sessionId ? { sessionId } : {});
|
|
866
|
+
if (changed) {
|
|
867
|
+
try {
|
|
868
|
+
extras.audit.insert({ action: 'restore', target: `note:${id}`, detail: { via: 'panel', sessionId } });
|
|
869
|
+
} catch {
|
|
870
|
+
// 同上
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
return { ok: changed, id, message: changed ? '已恢复' : '恢复没生效' };
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* `panel.addNote({ sessionId, content, about? })` → { ok, id, note }
|
|
878
|
+
* 允许用户在面板里主动补记一条笔记(与 Agent 的 memory_remember 共用 note 表,严格按会话隔离)。
|
|
879
|
+
*/
|
|
880
|
+
function addNote(params) {
|
|
881
|
+
const sessionId = requireSession('addNote', params);
|
|
882
|
+
const content = typeof params.content === 'string' ? params.content.trim() : '';
|
|
883
|
+
if (!content) throw new PanelError('BAD_ARG', '笔记内容不能为空', 400);
|
|
884
|
+
if (content.length > 2000) throw new PanelError('BAD_ARG', '单条笔记最多 2000 字', 400);
|
|
885
|
+
const rawAbout = params.about === undefined || params.about === null || params.about === ''
|
|
886
|
+
? null
|
|
887
|
+
: String(params.about).trim();
|
|
888
|
+
if (rawAbout !== null && !['me', 'him', 'us'].includes(rawAbout)) {
|
|
889
|
+
throw new PanelError('BAD_ARG', `about 只能是 me / him / us 或留空,收到 ${JSON.stringify(params.about)}`, 400);
|
|
890
|
+
}
|
|
891
|
+
const at = Date.now();
|
|
892
|
+
const id = extras.note.insert({ sessionId, content, about: rawAbout, at });
|
|
893
|
+
try {
|
|
894
|
+
extras.audit.insert({ action: 'remember', target: `note:${id}`, detail: { via: 'panel', sessionId, about: rawAbout } });
|
|
895
|
+
} catch { /* 审计失败不影响写入 */ }
|
|
896
|
+
const note = extras.note.byId(id, { sessionId }) ?? { id, sessionId, content, about: rawAbout, at, deletedAt: null };
|
|
897
|
+
return { ok: true, id, note };
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
function globalConfig(params) {
|
|
901
|
+
optionalSession('globalConfig', params);
|
|
902
|
+
const { config: loadedCfg, exists, warnings } = loadGlobalConfig({ dshHome });
|
|
903
|
+
return {
|
|
904
|
+
config: sanitizeGlobalConfig(loadedCfg),
|
|
905
|
+
path: globalConfigPath({ dshHome }),
|
|
906
|
+
exists,
|
|
907
|
+
warnings,
|
|
908
|
+
embedding: buildEmbeddingView(loadedCfg),
|
|
909
|
+
llm: buildLlmView(loadedCfg, Boolean(getHostLlm())),
|
|
910
|
+
rerank: buildRerankView(loadedCfg),
|
|
911
|
+
vecExt: buildVecExtView(handle),
|
|
912
|
+
};
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
const probeLocal = createModelProber({ embCfg, llmCfg, rerankCfg, getHostLlm });
|
|
916
|
+
|
|
917
|
+
/** 写全局配置(深合并)。白名单字段,避免前端乱写把配置搞坏。 */
|
|
918
|
+
function setGlobalConfig(params) {
|
|
919
|
+
optionalSession('setGlobalConfig', params);
|
|
920
|
+
const patch = params.patch ?? params.config;
|
|
921
|
+
if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) {
|
|
922
|
+
throw new PanelError('BAD_ARG', 'patch 必须是一个对象', 400);
|
|
923
|
+
}
|
|
924
|
+
const allowed = new Set(['defaults', 'embedding', 'llm', 'rerank', 'search', 'index']);
|
|
925
|
+
const unknown = Object.keys(patch).filter((k) => !allowed.has(k));
|
|
926
|
+
if (unknown.length) {
|
|
927
|
+
throw new PanelError(
|
|
928
|
+
'BAD_KEY',
|
|
929
|
+
`不认识的配置块:${unknown.join(', ')}。可写:${[...allowed].join(' / ')}`,
|
|
930
|
+
400,
|
|
931
|
+
);
|
|
932
|
+
}
|
|
933
|
+
// Key 直接存(作者 2026-11-18:不绕环境变量)。只是提醒一下会明文落盘。
|
|
934
|
+
const patchKey = patch?.embedding?.apiKey;
|
|
935
|
+
if (typeof patchKey === 'string' && patchKey.length > 500) {
|
|
936
|
+
throw new PanelError('BAD_ARG', 'embedding.apiKey 太长了(上限 500 字符)', 400);
|
|
937
|
+
}
|
|
938
|
+
const patchLlmKey = patch?.llm?.apiKey;
|
|
939
|
+
if (typeof patchLlmKey === 'string' && patchLlmKey.length > 500) {
|
|
940
|
+
throw new PanelError('BAD_ARG', 'llm.apiKey 太长了(上限 500 字符)', 400);
|
|
941
|
+
}
|
|
942
|
+
const patchRerankKey = patch?.rerank?.apiKey;
|
|
943
|
+
if (typeof patchRerankKey === 'string' && patchRerankKey.length > 500) {
|
|
944
|
+
throw new PanelError('BAD_ARG', 'rerank.apiKey 太长了(上限 500 字符)', 400);
|
|
945
|
+
}
|
|
946
|
+
const checkInt = (val, label, min, max) => {
|
|
947
|
+
if (val === undefined) return;
|
|
948
|
+
if (typeof val !== 'number' || !Number.isInteger(val) || val < min || val > max) {
|
|
949
|
+
throw new PanelError('BAD_ARG', `${label} 必须是 ${min}~${max} 的整数`, 400);
|
|
950
|
+
}
|
|
951
|
+
};
|
|
952
|
+
if (patch.embedding) checkInt(patch.embedding.dim, 'embedding.dim', 16, 16384);
|
|
953
|
+
if (patch.rerank) {
|
|
954
|
+
checkInt(patch.rerank.topN, 'rerank.topN', 1, 100);
|
|
955
|
+
checkInt(patch.rerank.timeoutMs, 'rerank.timeoutMs', 500, 60000);
|
|
956
|
+
}
|
|
957
|
+
if (patch.search) {
|
|
958
|
+
checkInt(patch.search.defaultLimit, 'search.defaultLimit', 1, 100);
|
|
959
|
+
checkInt(patch.search.maxLimit, 'search.maxLimit', 1, 500);
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
const next = saveGlobalConfig(patch, { dshHome });
|
|
963
|
+
invalidateGlobal(); // 设置页改完立即生效,不用重启插件
|
|
964
|
+
return {
|
|
965
|
+
ok: true,
|
|
966
|
+
config: sanitizeGlobalConfig(next),
|
|
967
|
+
path: globalConfigPath({ dshHome }),
|
|
968
|
+
embedding: buildEmbeddingView(next),
|
|
969
|
+
llm: buildLlmView(next, Boolean(getHostLlm())),
|
|
970
|
+
rerank: buildRerankView(next),
|
|
971
|
+
vecExt: buildVecExtView(handle),
|
|
972
|
+
applies: '已保存,立即生效。新会话按新默认值走;已有会话各自的开关不受影响(对话级优先)。',
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
|
|
977
|
+
/* ───────────────────────── 数据库管理台(全局 + 跨会话切换视图) ───────────────────────── */
|
|
978
|
+
|
|
979
|
+
const { dbOverview, dbRows, dbQuery, dbMaintain } = createDbAdmin({
|
|
980
|
+
handle,
|
|
981
|
+
db,
|
|
982
|
+
repo,
|
|
983
|
+
extras,
|
|
984
|
+
dbPath,
|
|
985
|
+
dbRoot,
|
|
986
|
+
stmt,
|
|
987
|
+
noteHasSessionColumn,
|
|
988
|
+
requireSession,
|
|
989
|
+
optionalSession,
|
|
990
|
+
readSessionConfig,
|
|
991
|
+
intParam,
|
|
992
|
+
PanelError,
|
|
993
|
+
logger,
|
|
994
|
+
});
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
const {
|
|
998
|
+
mergeScene,
|
|
999
|
+
splitScene,
|
|
1000
|
+
refineOneScene,
|
|
1001
|
+
setSceneGist,
|
|
1002
|
+
setMsgExcluded,
|
|
1003
|
+
updateNote,
|
|
1004
|
+
mediaPreview,
|
|
1005
|
+
setMediaCaption,
|
|
1006
|
+
findDuplicateNotes,
|
|
1007
|
+
mergeNotes,
|
|
1008
|
+
} = createSceneOps({
|
|
1009
|
+
handle,
|
|
1010
|
+
db,
|
|
1011
|
+
repo,
|
|
1012
|
+
extras,
|
|
1013
|
+
stmt,
|
|
1014
|
+
requireSession,
|
|
1015
|
+
intParam,
|
|
1016
|
+
PanelError,
|
|
1017
|
+
llmCfg,
|
|
1018
|
+
getHostLlm,
|
|
1019
|
+
hasEmbeddingKey,
|
|
1020
|
+
makeEmbeddingProvider,
|
|
1021
|
+
noteHasSessionColumn,
|
|
1022
|
+
dshHome,
|
|
1023
|
+
dbRoot,
|
|
1024
|
+
logger,
|
|
1025
|
+
});
|
|
1026
|
+
|
|
1027
|
+
const recallEntries = Array.isArray(opts.recallLog) ? opts.recallLog : [];
|
|
1028
|
+
function recallLog(params) {
|
|
1029
|
+
const sid = optionalSession('recallLog', params);
|
|
1030
|
+
const limit = intParam(params.limit, 'limit', { def: 20, min: 1, max: 50 });
|
|
1031
|
+
const list = sid ? recallEntries.filter((e) => e.sessionId === sid) : recallEntries;
|
|
1032
|
+
return { items: list.slice(0, limit), total: list.length };
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
const sessionLock = opts.sessionLock ?? createSessionLock();
|
|
1036
|
+
const lockWrite = (key, fn) => sessionLock.withLock(key, fn);
|
|
1037
|
+
|
|
1038
|
+
const methods = {
|
|
1039
|
+
status,
|
|
1040
|
+
timeline,
|
|
1041
|
+
sceneDetail,
|
|
1042
|
+
notes,
|
|
1043
|
+
deletedNotes,
|
|
1044
|
+
sample,
|
|
1045
|
+
verify,
|
|
1046
|
+
search,
|
|
1047
|
+
set,
|
|
1048
|
+
setExcludeRanges,
|
|
1049
|
+
rebuild,
|
|
1050
|
+
flag,
|
|
1051
|
+
flags,
|
|
1052
|
+
unflag,
|
|
1053
|
+
deleteNote,
|
|
1054
|
+
restoreNote,
|
|
1055
|
+
addNote,
|
|
1056
|
+
globalConfig,
|
|
1057
|
+
setGlobalConfig,
|
|
1058
|
+
probeLocal,
|
|
1059
|
+
dbOverview,
|
|
1060
|
+
dbRows,
|
|
1061
|
+
dbQuery,
|
|
1062
|
+
dbMaintain: (p) => (
|
|
1063
|
+
['clearSession', 'importSession', 'vacuum'].includes(p?.action)
|
|
1064
|
+
? lockWrite(p?.sessionId || p?.payload?.sessionId || '__global__', () => dbMaintain(p))
|
|
1065
|
+
: dbMaintain(p)
|
|
1066
|
+
),
|
|
1067
|
+
recallLog,
|
|
1068
|
+
mergeScene: (p) => lockWrite(p?.sessionId, () => mergeScene(p)),
|
|
1069
|
+
splitScene: (p) => lockWrite(p?.sessionId, () => splitScene(p)),
|
|
1070
|
+
refineOneScene: (p) => lockWrite(p?.sessionId, () => refineOneScene(p)),
|
|
1071
|
+
mediaPreview,
|
|
1072
|
+
setMediaCaption,
|
|
1073
|
+
findDuplicateNotes,
|
|
1074
|
+
mergeNotes,
|
|
1075
|
+
setSceneGist: (p) => lockWrite(p?.sessionId, () => setSceneGist(p)),
|
|
1076
|
+
setMsgExcluded: (p) => lockWrite(p?.sessionId, () => setMsgExcluded(p)),
|
|
1077
|
+
updateNote,
|
|
1078
|
+
// 补充方法:PANEL §5 的 rebuild 说「→ { taskId } 然后轮询进度」,
|
|
1079
|
+
// 没有它前端无法轮询(详见报告)。
|
|
1080
|
+
task: taskInfo,
|
|
1081
|
+
};
|
|
1082
|
+
|
|
1083
|
+
return {
|
|
1084
|
+
methods,
|
|
1085
|
+
/** 统一入口:未知方法 404,业务错误统一成 PanelError */
|
|
1086
|
+
async call(method, params) {
|
|
1087
|
+
const name = String(method ?? '');
|
|
1088
|
+
const fn = methods[name];
|
|
1089
|
+
if (typeof fn !== 'function') {
|
|
1090
|
+
throw new PanelError(
|
|
1091
|
+
'METHOD_NOT_FOUND',
|
|
1092
|
+
`没有 panel.${name} 这个方法。可用:${Object.keys(methods).map((k) => `panel.${k}`).join(', ')}`,
|
|
1093
|
+
404,
|
|
1094
|
+
);
|
|
1095
|
+
}
|
|
1096
|
+
return await fn(params ?? {});
|
|
1097
|
+
},
|
|
1098
|
+
/** 测试/诊断用:当前日志缓存状态 */
|
|
1099
|
+
debug() {
|
|
1100
|
+
return {
|
|
1101
|
+
methodNames: Object.keys(methods),
|
|
1102
|
+
cachedLogs: cachedLogs(),
|
|
1103
|
+
tasks: recentTasks(),
|
|
1104
|
+
dbRoot,
|
|
1105
|
+
dbPath,
|
|
1106
|
+
};
|
|
1107
|
+
},
|
|
1108
|
+
};
|
|
1109
|
+
}
|