dsh-topic-split 0.0.0-stage → 0.12.0

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.
@@ -0,0 +1,219 @@
1
+ /** 会话登记与归档:优先走 DSH 的 workspaceRegistry 服务,文件写入仅作兜底。
2
+ *
3
+ * 背景:直接改写 `workspace.json` 会与 DSH 内存中的注册表快照竞争,
4
+ * 导致插件创建的会话被覆盖、侧边栏条目消失。服务 API 才是正确路径。
5
+ *
6
+ * 归档同样如此:DSH 的归档语义是「把 id 记进 `global.archivedSessionIds`」,
7
+ * 会话目录必须保持 `session-<id>` 不动。历史版本用「重命名目录」实现归档,
8
+ * 那会让 DSH 的会话列表读取整份失败(侧边栏会话列表消失),已废弃。
9
+ */
10
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
11
+
12
+ import { ERR, SessionSplitError } from './errors.js'
13
+ import { atomicWrite, readRegistry, registryPath, writeRegistry } from './store.js'
14
+
15
+ /**
16
+ * 解析 workspaceRegistry 服务:优先取动态注入的实例,其次属性/ctx.get。
17
+ * @param {any} ctx cordis 上下文
18
+ * @param {() => any} [getService] 动态注入回调提供的实例
19
+ */
20
+ function resolveRegistry(ctx, getService) {
21
+ try {
22
+ const injected = typeof getService === 'function' ? getService() : null
23
+ if (injected && typeof injected.resolveByPath === 'function') return injected
24
+ } catch {
25
+ /* 忽略 */
26
+ }
27
+ if (!ctx) return null
28
+ try {
29
+ const direct = ctx.workspaceRegistry
30
+ if (direct && typeof direct.resolveByPath === 'function') return direct
31
+ } catch {
32
+ /* 服务未注入时会抛错,继续尝试 ctx.get */
33
+ }
34
+ try {
35
+ const got = typeof ctx.get === 'function' ? ctx.get('workspaceRegistry') : null
36
+ if (got && typeof got.resolveByPath === 'function') return got
37
+ } catch {
38
+ /* 忽略 */
39
+ }
40
+ return null
41
+ }
42
+
43
+ function findWorkspace(registry, cwd) {
44
+ const workspaces = registry?.tables?.workspaces ?? {}
45
+ return Object.values(workspaces).find(
46
+ (w) => String(w?.path ?? '').toLowerCase() === String(cwd ?? '').toLowerCase(),
47
+ )
48
+ }
49
+
50
+ /** 兜底:文件读-改-写,带备份与回读校验;只增删目标 id。 */
51
+ function fileAdd(cwd, sessionId) {
52
+ const file = registryPath()
53
+ const backup = `${file}.bak-registry-${Date.now()}`
54
+ if (existsSync(file)) {
55
+ writeFileSync(backup, readFileSync(file))
56
+ }
57
+ const reg = readRegistry()
58
+ reg.tables ??= { workspaces: {} }
59
+ reg.tables.workspaces ??= {}
60
+ let target = findWorkspace(reg, cwd)
61
+ if (!target) {
62
+ target = {
63
+ path: cwd,
64
+ title: String(cwd).split(/[\\/]/).pop() || cwd,
65
+ sessionIds: [],
66
+ updatedAt: new Date().toISOString(),
67
+ }
68
+ reg.tables.workspaces[`fallback-${Date.now()}`] = target
69
+ }
70
+ target.sessionIds = [sessionId, ...(target.sessionIds ?? []).filter((id) => id !== sessionId)]
71
+ target.updatedAt = new Date().toISOString()
72
+ writeRegistry(reg)
73
+ const check = readRegistry()
74
+ const ok = (findWorkspace(check, cwd)?.sessionIds ?? []).includes(sessionId)
75
+ if (!ok) {
76
+ if (existsSync(backup)) {
77
+ try {
78
+ atomicWrite(file, readFileSync(backup))
79
+ } catch {
80
+ /* 尽力回滚 */
81
+ }
82
+ }
83
+ throw new SessionSplitError(ERR.IO_FAILED, '会话登记写入校验失败,已回滚')
84
+ }
85
+ }
86
+
87
+ /** 兜底:文件移除目标 id(不触碰其它条目)。 */
88
+ function fileRemove(cwd, sessionId) {
89
+ const file = registryPath()
90
+ const backup = `${file}.bak-registry-${Date.now()}`
91
+ if (existsSync(file)) writeFileSync(backup, readFileSync(file))
92
+ const reg = readRegistry()
93
+ const target = findWorkspace(reg, cwd)
94
+ if (!target) return
95
+ target.sessionIds = (target.sessionIds ?? []).filter((id) => id !== sessionId)
96
+ target.updatedAt = new Date().toISOString()
97
+ writeRegistry(reg)
98
+ const check = readRegistry()
99
+ const still = (findWorkspace(check, cwd)?.sessionIds ?? []).includes(sessionId)
100
+ if (still) {
101
+ if (existsSync(backup)) {
102
+ try {
103
+ atomicWrite(file, readFileSync(backup))
104
+ } catch {
105
+ /* 尽力回滚 */
106
+ }
107
+ }
108
+ throw new SessionSplitError(ERR.IO_FAILED, '会话注销校验失败,已回滚')
109
+ }
110
+ }
111
+
112
+ /**
113
+ * 兜底:把 id 写进 `global.archivedSessionIds`(只增,不碰会话目录)。
114
+ * @param {string} sessionId 要归档的会话 id
115
+ */
116
+ function fileArchive(sessionId) {
117
+ const file = registryPath()
118
+ const backup = `${file}.bak-archive-${Date.now()}`
119
+ if (existsSync(file)) writeFileSync(backup, readFileSync(file))
120
+ const reg = readRegistry()
121
+ reg.global ??= {}
122
+ const current = Array.isArray(reg.global.archivedSessionIds) ? reg.global.archivedSessionIds : []
123
+ if (!current.includes(sessionId)) reg.global.archivedSessionIds = [...current, sessionId]
124
+ writeRegistry(reg)
125
+ const check = readRegistry()
126
+ const ok = (check.global?.archivedSessionIds ?? []).includes(sessionId)
127
+ if (!ok) {
128
+ if (existsSync(backup)) {
129
+ try {
130
+ atomicWrite(file, readFileSync(backup))
131
+ } catch {
132
+ /* 尽力回滚 */
133
+ }
134
+ }
135
+ throw new SessionSplitError(ERR.IO_FAILED, '会话归档写入校验失败,已回滚')
136
+ }
137
+ }
138
+
139
+ /**
140
+ * 创建登记器。
141
+ * @param {{ctx?: any, log?: {warn: Function}, getService?: () => any}} input
142
+ */
143
+ export function createRegistrar({ ctx, log, getService } = {}) {
144
+ let announced = false
145
+ const announce = (service) => {
146
+ if (announced) return
147
+ announced = true
148
+ log?.info?.(`会话登记方式:${service ? 'workspaceRegistry 服务' : '文件兜底'}`)
149
+ }
150
+ return {
151
+ get mode() {
152
+ return resolveRegistry(ctx, getService) ? 'service' : 'file'
153
+ },
154
+ /**
155
+ * 登记一个刚创建的会话。
156
+ * @param {string} cwd 工作目录
157
+ * @param {string} sessionId 会话 id
158
+ */
159
+ async register(cwd, sessionId) {
160
+ const service = resolveRegistry(ctx, getService)
161
+ announce(service)
162
+ if (!service) return fileAdd(cwd, sessionId)
163
+ try {
164
+ const ws = await service.resolveByPath(cwd)
165
+ await ws.attachSession(sessionId)
166
+ return
167
+ } catch (err) {
168
+ log?.warn('workspaceRegistry.attachSession 失败,回退文件登记:', err?.message ?? err)
169
+ return fileAdd(cwd, sessionId)
170
+ }
171
+ },
172
+ /**
173
+ * 注销一个会话:只从 workspace 的 `sessionIds` 里摘掉,不归档、不碰目录。
174
+ * @param {string} cwd 工作目录
175
+ * @param {string} sessionId 会话 id
176
+ */
177
+ async unregister(cwd, sessionId) {
178
+ const service = resolveRegistry(ctx, getService)
179
+ announce(service)
180
+ if (!service) return fileRemove(cwd, sessionId)
181
+ try {
182
+ const ws = await service.resolveByPath(cwd)
183
+ await ws.detachSession(sessionId)
184
+ return
185
+ } catch (err) {
186
+ log?.warn('workspaceRegistry.detachSession 失败,回退文件注销:', err?.message ?? err)
187
+ return fileRemove(cwd, sessionId)
188
+ }
189
+ },
190
+ /**
191
+ * 归档一个会话:只改注册表的归档集合,绝不重命名会话目录。
192
+ * 服务可用时必须走服务(DSH 会校验会话是否仍在跑,并即时广播给客户端)。
193
+ * @param {string} cwd 工作目录(服务路径下只用于诊断)
194
+ * @param {string} sessionId 会话 id
195
+ * @returns {Promise<'service'|'file'>} 实际使用的归档方式
196
+ */
197
+ async archive(cwd, sessionId) {
198
+ const service = resolveRegistry(ctx, getService)
199
+ announce(service)
200
+ if (!service || typeof service.archiveSession !== 'function') {
201
+ fileArchive(sessionId)
202
+ return 'file'
203
+ }
204
+ try {
205
+ await service.archiveSession(sessionId)
206
+ return 'service'
207
+ } catch (err) {
208
+ // 归档被 DSH 拒绝(例如会话正在跑、或会话不被持久化层认识)时不能退回改名,
209
+ // 也不能退回写文件:那样要么破坏会话列表,要么绕过「活跃会话不可归档」的保护。
210
+ const reason = err?.message ? err.message : String(err)
211
+ throw new SessionSplitError(
212
+ ERR.IO_FAILED,
213
+ `DSH 拒绝归档会话 ${sessionId}(${reason});会话目录未改动`,
214
+ { sessionId, cwd: String(cwd ?? '') },
215
+ )
216
+ }
217
+ },
218
+ }
219
+ }
package/src/repair.js ADDED
@@ -0,0 +1,75 @@
1
+ /** 启动自愈:把历史版本留下的 `.archived-session-*` 目录改回 `session-*`。
2
+ *
3
+ * 为什么必须修:DSH 读取会话列表时,会用每个会话文件头里的 `id` 与 `cwd` 重新
4
+ * 推导它应该所在的路径,并要求与实际路径一致(`corrupt session log ... header id
5
+ * and cwd identify ...`)。目录一旦被改名成 `.archived-session-<id>-<时间戳>`,
6
+ * 这条校验就失败,**整份** `session/list` 直接报错,侧边栏的会话列表整块消失;
7
+ * 因为坏的是磁盘状态,重启也不会好,只有修复目录名才能恢复。
8
+ *
9
+ * 0.9.1 之前的版本正用「重命名目录」实现归档,所以这里在插件启动时顺手修一遍。
10
+ */
11
+ import { existsSync, readdirSync, renameSync, statSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+
14
+ import { sessionsRoot } from './store.js'
15
+
16
+ /** `.archived-session-<uuid>-<时间戳>` / `.archived-session-<uuid>-<时间戳>-<n>` */
17
+ const ARCHIVED_DIR_RE =
18
+ /^\.archived-(session-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-/i
19
+
20
+ /**
21
+ * 找出所有被改名的归档会话目录(只读,不改动)。
22
+ * @returns {Array<{workspace: string, name: string, id: string, path: string, target: string}>}
23
+ */
24
+ export function listArchivedDirs() {
25
+ const found = []
26
+ const root = sessionsRoot()
27
+ if (!existsSync(root)) return found
28
+ for (const workspace of readdirSync(root)) {
29
+ const workspaceDir = join(root, workspace)
30
+ let entries
31
+ try {
32
+ if (!statSync(workspaceDir).isDirectory()) continue
33
+ entries = readdirSync(workspaceDir)
34
+ } catch {
35
+ continue
36
+ }
37
+ for (const name of entries) {
38
+ const match = ARCHIVED_DIR_RE.exec(name)
39
+ if (!match) continue
40
+ found.push({
41
+ workspace,
42
+ name,
43
+ id: match[1],
44
+ path: join(workspaceDir, name),
45
+ target: join(workspaceDir, match[1]),
46
+ })
47
+ }
48
+ }
49
+ return found
50
+ }
51
+
52
+ /**
53
+ * 扫描会话根目录,把被改名的归档目录恢复成 `session-<id>`。
54
+ *
55
+ * 只处理能唯一还原目标名字的条目;目标已存在时跳过并告警,绝不覆盖。
56
+ * @param {{log?: {warn?: Function}}} [input]
57
+ * @returns {Array<{id: string, path: string}>} 已修复的条目
58
+ */
59
+ export function repairArchivedDirs({ log } = {}) {
60
+ const repaired = []
61
+ for (const entry of listArchivedDirs()) {
62
+ if (existsSync(entry.target)) {
63
+ log?.warn?.(`归档目录自愈跳过(目标已存在):${entry.name}`)
64
+ continue
65
+ }
66
+ try {
67
+ renameSync(entry.path, entry.target)
68
+ repaired.push({ id: entry.id, path: entry.target })
69
+ log?.warn?.(`归档目录自愈:${entry.name} → ${entry.id}(目录名被改过会让 DSH 整份会话列表读不出来)`)
70
+ } catch (err) {
71
+ log?.warn?.(`归档目录自愈失败:${entry.name}:${err && err.message ? err.message : err}`)
72
+ }
73
+ }
74
+ return repaired
75
+ }
package/src/routes.js ADDED
@@ -0,0 +1,349 @@
1
+ /**
2
+ * HTTP 路由:让客户端面板能真正触发分段与导出(而不是只靠对话调工具)。
3
+ *
4
+ * GET /dsh-topic-split/sessions 会话列表(id + 标题 + 轮次)
5
+ * GET /dsh-topic-split/topics?sessionId=..&mode=auto|model|keyword
6
+ * POST /dsh-topic-split/preview { sessionId, groups: [{title, ranges}] }
7
+ * POST /dsh-topic-split/export { sessionId, groups: [{title, ranges}], dryRun? }
8
+ * GET /dsh-topic-split/diag
9
+ *
10
+ * 安全(v0.6):
11
+ * - 默认关闭(httpRoutes: 'off'),只注册工具,不暴露任何 HTTP 接口;
12
+ * - 开启后要求令牌(配置/环境变量,或进程内随机并注入页面 meta);
13
+ * - 校验 Host / Origin,只允许本机来源,防 DNS rebinding 与跨站请求;
14
+ * - 限流:普通请求与导出请求分档;
15
+ * - 会话标题默认隐藏,诊断信息默认脱敏;
16
+ * - 只读源会话;导出走 store 的原子写;参数全部白名单校验。
17
+ */
18
+ import { buildDiagnostics } from './diagnostics.js'
19
+ import { ERR, SessionSplitError } from './errors.js'
20
+ import { createSession } from './exporter.js'
21
+ import { createHttpGuard, tokenMetaTag } from './http-auth.js'
22
+ import { listSessions, resolveSession } from './store.js'
23
+ import { selectionFromArgs } from './selection.js'
24
+ import { coverage, extractTurns } from './topics.js'
25
+ import { createResolveTopics } from './tools.js'
26
+
27
+ const PREFIX = '/dsh-topic-split'
28
+ const MAX_GROUPS = 10
29
+
30
+ function json(res, payload, status = 200) {
31
+ const body = JSON.stringify(payload)
32
+ res.writeHead(status, {
33
+ 'content-type': 'application/json; charset=utf-8',
34
+ 'content-length': Buffer.byteLength(body),
35
+ 'cache-control': 'no-store',
36
+ 'x-content-type-options': 'nosniff',
37
+ })
38
+ res.end(body)
39
+ }
40
+
41
+ function fail(res, err, status = 400) {
42
+ const split =
43
+ err instanceof SessionSplitError
44
+ ? err
45
+ : new SessionSplitError(ERR.IO_FAILED, String(err?.message ?? err))
46
+ json(res, { ok: false, error: split.message, code: split.code }, status)
47
+ }
48
+
49
+ /** 从请求体读取 JSON(带大小上限)。 */
50
+ async function readBody(req, limit = 256 * 1024) {
51
+ const chunks = []
52
+ let size = 0
53
+ for await (const chunk of req) {
54
+ size += chunk.length
55
+ if (size > limit) throw new SessionSplitError(ERR.RANGE_INVALID, '请求体过大')
56
+ chunks.push(chunk)
57
+ }
58
+ if (chunks.length === 0) return {}
59
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))
60
+ }
61
+
62
+ /** 会话标题(优先 session/title 事件)。 */
63
+ function titleOf(events, fallback) {
64
+ const hit = events.find((e) => e.type === 'session/title')
65
+ return hit?.data?.title ?? fallback
66
+ }
67
+
68
+ /** 解析 webServer 服务:属性直取与 ctx.get 双路径。 */
69
+ function resolveWebServer(ctx) {
70
+ if (!ctx) return null
71
+ try {
72
+ const direct = ctx.webServer
73
+ if (direct && typeof direct.register === 'function') return direct
74
+ } catch {
75
+ /* 未注入时可能抛错,继续尝试 ctx.get */
76
+ }
77
+ try {
78
+ const got = typeof ctx.get === 'function' ? ctx.get('webServer') : null
79
+ if (got && typeof got.register === 'function') return got
80
+ } catch {
81
+ /* 忽略 */
82
+ }
83
+ return null
84
+ }
85
+
86
+ /**
87
+ * 注册路由(默认关闭)。
88
+ * @param {any} ctx cordis 上下文
89
+ * @param {object} deps 依赖(cfg / readSession / log / getToolNames / judge / registrar)
90
+ * @returns {boolean} 是否注册成功
91
+ */
92
+ export function registerRoutes(ctx, deps) {
93
+ const { cfg, readSession, log, getToolNames, judge, registrar } = deps
94
+ if (cfg.httpRoutes !== 'token') {
95
+ log.info('HTTP 面板路由已关闭(httpRoutes=off);工具仍可用')
96
+ return null
97
+ }
98
+ const webserver = resolveWebServer(ctx)
99
+ if (!webserver) {
100
+ log.warn('没有 webServer 服务,跳过 HTTP 路由(工具仍可用)')
101
+ return null
102
+ }
103
+
104
+ const resolveTopics = createResolveTopics({ cfg, log, judge })
105
+ const guard = createHttpGuard({ cfg, log })
106
+ /** 收集路由与页面注入的释放函数,插件卸载时统一清理。 */
107
+ const disposers = []
108
+
109
+ const routeDisposer = webserver.register({
110
+ kind: 'prefix',
111
+ path: PREFIX,
112
+ handler: async (req, res) => {
113
+ const url = new URL(req.url ?? '/', 'http://localhost')
114
+ const path = url.pathname
115
+ const kind = path === `${PREFIX}/export` ? 'export' : 'general'
116
+ const verdict = guard.check(req, kind)
117
+ if (!verdict.ok) {
118
+ json(res, { ok: false, error: verdict.message, code: verdict.code }, verdict.status)
119
+ return
120
+ }
121
+ try {
122
+ if (req.method === 'GET' && (path === `${PREFIX}/sessions` || path === `${PREFIX}/sessions/`)) {
123
+ const rows = listSessions()
124
+ .slice(0, 50)
125
+ .map((s) => {
126
+ let turns = -1
127
+ let title = s.dirName
128
+ try {
129
+ const parsed = readSession(s.file)
130
+ turns = extractTurns(parsed.events).length
131
+ title = titleOf(parsed.events, title)
132
+ } catch {
133
+ turns = -1
134
+ }
135
+ const row = { id: s.dirName, turns, size: s.size, mtime: s.mtime }
136
+ if (cfg.exposeTitles) row.title = title
137
+ return row
138
+ })
139
+ json(res, { ok: true, value: rows })
140
+ return
141
+ }
142
+
143
+ if (req.method === 'GET' && path.startsWith(`${PREFIX}/topics`)) {
144
+ const sessionId = url.searchParams.get('sessionId') ?? ''
145
+ const mode = url.searchParams.get('mode') ?? 'auto'
146
+ const session = resolveSession(sessionId)
147
+ const { events } = readSession(session.file)
148
+ const items = extractTurns(events)
149
+ const { segs, note } = await resolveTopics(items, mode, undefined)
150
+ const cov = coverage(items, segs)
151
+ json(res, {
152
+ ok: true,
153
+ value: {
154
+ sessionId: session.dirName,
155
+ turns: items.length,
156
+ segments: segs.map((s) => ({ label: s.label, from: s.from, to: s.to, chars: s.chars })),
157
+ coverage: cov,
158
+ note: note ?? null,
159
+ },
160
+ })
161
+ return
162
+ }
163
+
164
+ if (req.method === 'POST' && path === `${PREFIX}/preview`) {
165
+ const body = await readBody(req)
166
+ json(res, { ok: true, value: preview(cfg, readSession, body) })
167
+ return
168
+ }
169
+
170
+ if (req.method === 'POST' && path === `${PREFIX}/export`) {
171
+ const body = await readBody(req)
172
+ const plan = preview(cfg, readSession, body)
173
+ if (body.dryRun === true) {
174
+ json(res, { ok: true, value: { dryRun: true, plan } })
175
+ return
176
+ }
177
+ const session = resolveSession(body.sessionId)
178
+ const { header, events } = readSession(session.file)
179
+ const items = extractTurns(events)
180
+ const cwd = header.cwd ?? process.cwd()
181
+ const made = []
182
+ const union = new Set()
183
+ for (const [index, group] of plan.groups.entries()) {
184
+ const selection = groupSelection(cfg, items, body.groups[index])
185
+ for (const i of selection.indices) union.add(i)
186
+ const pairs = selection.indices.map((i) => [items[i].user, items[i].assistant])
187
+ const created = createSession({ cwd, pairs, title: group.title })
188
+ if (registrar) await registrar.register(cwd, created.id)
189
+ made.push(created.id)
190
+ }
191
+ let main = null
192
+ let archived = null
193
+ if (body.cut === true) {
194
+ const keep = []
195
+ items.forEach((item, i) => {
196
+ if (!union.has(i)) keep.push([item.user, item.assistant])
197
+ })
198
+ if (keep.length === 0) {
199
+ throw new SessionSplitError(ERR.EMPTY_RESULT, '剪除后主会话为空,已拒绝执行')
200
+ }
201
+ const createdMain = createSession({
202
+ cwd,
203
+ pairs: keep,
204
+ title: `${body.title ?? '主会话'}(已剪除独立段)`,
205
+ })
206
+ if (registrar) await registrar.register(cwd, createdMain.id)
207
+ main = createdMain.id
208
+ if (registrar) {
209
+ try {
210
+ await registrar.archive(cwd, session.dirName)
211
+ archived = true
212
+ } catch (err) {
213
+ archived = false
214
+ log.warn('归档原会话失败:', err?.message ?? err)
215
+ }
216
+ }
217
+ }
218
+ log.info('HTTP 导出完成', {
219
+ from: session.dirName,
220
+ count: made.length,
221
+ cut: body.cut === true,
222
+ })
223
+ json(res, { ok: true, value: { created: made, main, archived } })
224
+ return
225
+ }
226
+
227
+ if (req.method === 'GET' && path === `${PREFIX}/diag`) {
228
+ json(res, {
229
+ ok: true,
230
+ value: {
231
+ text: buildDiagnostics({
232
+ cfg,
233
+ readerStats: () => readSession.stats?.(),
234
+ toolNames: getToolNames ? getToolNames() : [],
235
+ redact: true,
236
+ }),
237
+ judge: judge ? judge.describe?.() ?? judge.kind ?? 'unknown' : '不可用',
238
+ http: guard.describe(),
239
+ },
240
+ })
241
+ return
242
+ }
243
+
244
+ fail(res, new SessionSplitError(ERR.RANGE_INVALID, '未知路由: ' + path), 404)
245
+ } catch (err) {
246
+ fail(res, err)
247
+ }
248
+ },
249
+ })
250
+ if (typeof routeDisposer === 'function') disposers.push(routeDisposer)
251
+
252
+ // 把令牌注入 index.html:页面只能在通过宿主鉴权后拿到,客户端自动读取
253
+ try {
254
+ if (typeof webserver.tapIndex === 'function') {
255
+ const tapDisposer = webserver.tapIndex((html) =>
256
+ String(html).includes(`name="dsh-split-token"`)
257
+ ? html
258
+ : String(html).replace('</head>', `${tokenMetaTag(guard.token)}</head>`),
259
+ )
260
+ if (typeof tapDisposer === 'function') disposers.push(tapDisposer)
261
+ log.info('访问令牌已注入页面 meta(客户端自动使用)')
262
+ } else {
263
+ log.warn('webServer 不支持 tapIndex:客户端需手动在 localStorage 设置 dsh-split-token')
264
+ }
265
+ } catch (err) {
266
+ log.warn('令牌注入失败:', err && err.message ? err.message : err)
267
+ }
268
+
269
+ log.info('HTTP 路由已注册(需令牌): ' + PREFIX)
270
+ return () => {
271
+ for (const dispose of disposers.splice(0)) {
272
+ try {
273
+ dispose()
274
+ } catch {
275
+ /* 释放失败不影响卸载流程 */
276
+ }
277
+ }
278
+ }
279
+ }
280
+
281
+ /** 单组轮次选择:ranges 或 turns 二选一。 */
282
+ function groupSelection(cfg, items, group) {
283
+ const selection = selectionFromArgs(
284
+ { ranges: group?.ranges, turns: group?.turns },
285
+ items.length,
286
+ cfg,
287
+ )
288
+ if (!selection) {
289
+ throw new SessionSplitError(ERR.RANGE_INVALID, '每个导出组需要 ranges 或 turns')
290
+ }
291
+ return selection
292
+ }
293
+
294
+ /** 统计一组选中轮次的字数。 */
295
+ function charsOf(items, indices) {
296
+ let chars = 0
297
+ for (const i of indices) chars += items[i].user.length + items[i].assistant.length
298
+ return chars
299
+ }
300
+
301
+ /** 校验并展开分组计划(供 preview 与 export 共用)。 */
302
+ function preview(cfg, readSession, body) {
303
+ const session = resolveSession(body.sessionId)
304
+ const { events } = readSession(session.file)
305
+ const items = extractTurns(events)
306
+ const groups = Array.isArray(body.groups) ? body.groups : []
307
+ if (groups.length === 0) throw new SessionSplitError(ERR.RANGE_INVALID, '至少需要一个导出组')
308
+ if (groups.length > MAX_GROUPS) throw new SessionSplitError(ERR.RANGE_TOO_MANY, `最多 ${MAX_GROUPS} 组`)
309
+ const out = []
310
+ const union = new Set()
311
+ let duplicateTurns = 0
312
+ for (const [index, group] of groups.entries()) {
313
+ const selection = groupSelection(cfg, items, group)
314
+ for (const i of selection.indices) {
315
+ if (union.has(i)) duplicateTurns += 1
316
+ union.add(i)
317
+ }
318
+ out.push({
319
+ title: String(group.title ?? `独立会话 ${index + 1}`),
320
+ source: selection.source,
321
+ ranges: selection.runs,
322
+ turns: selection.indices.length,
323
+ chars: charsOf(items, selection.indices),
324
+ })
325
+ }
326
+ const cutInfo =
327
+ body.cut === true
328
+ ? {
329
+ remainingTurns: items.length - union.size,
330
+ remainingChars: items.reduce(
331
+ (sum, item, i) => (union.has(i) ? sum : sum + item.user.length + item.assistant.length),
332
+ 0,
333
+ ),
334
+ archive: true,
335
+ }
336
+ : null
337
+ return {
338
+ sessionId: session.dirName,
339
+ totalTurns: items.length,
340
+ groups: out,
341
+ coverage: {
342
+ coveredTurns: union.size,
343
+ totalTurns: items.length,
344
+ complete: union.size === items.length,
345
+ duplicateTurns,
346
+ },
347
+ cut: cutInfo,
348
+ }
349
+ }