@wangnanshan/dsh-nanshan-session-manager 0.0.0-stage → 1.1.7

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/index.js ADDED
@@ -0,0 +1,1440 @@
1
+ /**
2
+ * Host half of 【南山】会话管理.
3
+ *
4
+ * DSH deliberately has no session-deletion surface: session logs are an
5
+ * append-only archive, and the shipped sidebar only archives them. This plugin
6
+ * adds a local, explicitly destructive management surface on top of the same
7
+ * on-disk layout:
8
+ *
9
+ * $DSH_HOME/sessions/<project-key>/<encoded-session-id>/session.v4.jsonl.zstd
10
+ * $DSH_HOME/storages/session_projcache/sessions/<session-id>.json
11
+ *
12
+ * The JSON API is intentionally small and only listens on the authenticated
13
+ * local Web server. Reads use ctx.sessionQuery when it is available; the
14
+ * fallback scans the JSONL layout so the page still works in a minimal
15
+ * composition.
16
+ */
17
+ import { createHash, randomUUID } from 'node:crypto'
18
+ import { constants } from 'node:fs'
19
+ import { copyFile, mkdir, open, readFile, readdir, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises'
20
+ import { homedir } from 'node:os'
21
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
22
+ import { zstdDecompressSync } from 'node:zlib'
23
+
24
+ export const inject = ['webServer']
25
+
26
+ const API = '/api/nanshan-session-manager'
27
+ const SESSION_FORMAT = 4
28
+ const SAFE_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
29
+ const LOG_NAME = /^session\.v(\d+)\.jsonl(\.zstd)?$/
30
+ const MAX_BODY_BYTES = 512 * 1024 * 1024
31
+ const MAX_SESSION_BYTES = 256 * 1024 * 1024
32
+ const MAX_IMPORT_SESSIONS = 500
33
+ const MAX_DELETE_SESSIONS = 500
34
+ const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
35
+
36
+ export function apply(ctx) {
37
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
38
+ const sessionsRoot = join(home, 'sessions')
39
+ const cacheRoot = join(home, 'storages', 'session_projcache', 'sessions')
40
+ const dataRoot = join(home, 'nanshan-session-manager')
41
+ const titlesPath = join(dataRoot, 'titles.json')
42
+ const trashRoot = join(dataRoot, 'trash')
43
+
44
+ let titlesCache = null
45
+ let mutationChain = Promise.resolve()
46
+ let cachedCompression = null
47
+
48
+ function service(name) {
49
+ try {
50
+ return ctx.get(name)
51
+ } catch {
52
+ return undefined
53
+ }
54
+ }
55
+
56
+ function exclusive(task) {
57
+ const next = mutationChain.then(task, task)
58
+ mutationChain = next.then(
59
+ () => undefined,
60
+ () => undefined,
61
+ )
62
+ return next
63
+ }
64
+
65
+ async function loadTitles() {
66
+ if (titlesCache !== null) return titlesCache
67
+ let parsed
68
+ try {
69
+ parsed = JSON.parse(await readFile(titlesPath, 'utf8'))
70
+ } catch (error) {
71
+ titlesCache = {}
72
+ return titlesCache
73
+ }
74
+ const source = parsed && typeof parsed === 'object' && parsed.titles && typeof parsed.titles === 'object' ? parsed.titles : {}
75
+ const result = {}
76
+ for (const [id, value] of Object.entries(source)) {
77
+ if (!SAFE_ID.test(id) || !value || typeof value !== 'object') continue
78
+ if (typeof value.title !== 'string' || value.title.trim() === '') continue
79
+ result[id] = {
80
+ title: value.title.trim().slice(0, 300),
81
+ at: Number.isFinite(value.at) ? value.at : 0,
82
+ }
83
+ }
84
+ titlesCache = result
85
+ return titlesCache
86
+ }
87
+
88
+ async function saveTitles() {
89
+ if (titlesCache === null) return
90
+ await mkdir(dataRoot, { recursive: true })
91
+ const temporary = `${titlesPath}.${process.pid}.${Date.now()}.tmp`
92
+ const payload = { version: 1, titles: titlesCache }
93
+ await writeFile(temporary, `${JSON.stringify(payload, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
94
+ await rename(temporary, titlesPath)
95
+ }
96
+
97
+ async function compression() {
98
+ if (cachedCompression !== null) return cachedCompression
99
+ let sawZstd = false
100
+ let sawPlain = false
101
+ try {
102
+ const projects = await readdir(sessionsRoot, { withFileTypes: true })
103
+ for (const project of projects) {
104
+ if (!project.isDirectory()) continue
105
+ let sessions
106
+ try {
107
+ sessions = await readdir(join(sessionsRoot, project.name), { withFileTypes: true })
108
+ } catch {
109
+ continue
110
+ }
111
+ for (const session of sessions) {
112
+ if (!session.isDirectory()) continue
113
+ let files
114
+ try {
115
+ files = await readdir(join(sessionsRoot, project.name, session.name), { withFileTypes: true })
116
+ } catch {
117
+ continue
118
+ }
119
+ for (const file of files) {
120
+ if (!file.isFile()) continue
121
+ const match = LOG_NAME.exec(file.name)
122
+ if (match === null) continue
123
+ if (match[2] === '.zstd') sawZstd = true
124
+ else sawPlain = true
125
+ }
126
+ }
127
+ }
128
+ } catch {
129
+ // A missing root is an empty store; zstd is the shipped default.
130
+ }
131
+ cachedCompression = sawPlain && !sawZstd ? 'none' : 'zstd'
132
+ return cachedCompression
133
+ }
134
+
135
+ async function buildList() {
136
+ const records = await listRecords()
137
+ const cache = await readProjectionCache()
138
+ const titles = await loadTitles()
139
+ const registry = service('workspaceRegistry')
140
+ const workspaces = typeof registry?.list === 'function' ? registry.list() : []
141
+ const workspaceByPath = new Map()
142
+ for (const workspace of workspaces) {
143
+ if (workspace && typeof workspace.path === 'string') workspaceByPath.set(normalizePath(workspace.path), workspace)
144
+ }
145
+ const archived = new Set(Array.isArray(registry?.archivedSessionIds) ? registry.archivedSessionIds : [])
146
+ const pinned = new Set(Array.isArray(registry?.pinnedSessionIds) ? registry.pinnedSessionIds : [])
147
+ const stored = service('sessions')
148
+ const agents = service('agents')
149
+ const live = new Set()
150
+ if (stored && typeof stored.list === 'function') {
151
+ for (const session of stored.list()) live.add(session.id)
152
+ }
153
+ await exclusive(() => settlePendingTrash())
154
+ const trash = await listTrash()
155
+ const trashedIds = new Set(trash.map((entry) => entry.id))
156
+
157
+ const rows = []
158
+ for (const record of records) {
159
+ const header = record && record.header
160
+ if (!header || typeof header.id !== 'string' || !SAFE_ID.test(header.id)) continue
161
+ const id = header.id
162
+ if (trashedIds.has(id)) continue
163
+ const artifact = await resolveArtifact(record)
164
+ let sizeBytes = 0
165
+ let mtimeMs = 0
166
+ let exists = false
167
+ if (artifact !== null) {
168
+ try {
169
+ const info = await stat(artifact)
170
+ sizeBytes = info.size
171
+ mtimeMs = info.mtimeMs
172
+ exists = true
173
+ } catch {
174
+ exists = false
175
+ }
176
+ }
177
+ const cached = cache.get(id) || null
178
+ const sidecar = titles[id] || null
179
+ const title = firstText(cached?.title, sidecar?.title)
180
+ const cwd = typeof header.cwd === 'string' && isAbsolute(header.cwd) ? header.cwd : null
181
+ const workspace = cwd === null ? null : workspaceByPath.get(normalizePath(cwd)) || null
182
+ const group = workspace
183
+ ? {
184
+ kind: 'workspace',
185
+ id: workspace.id,
186
+ title: workspace.title || basename(workspace.path),
187
+ path: workspace.path,
188
+ }
189
+ : cwd === null
190
+ ? { kind: 'none', id: 'ungrouped', title: '', path: null }
191
+ : { kind: 'cwd', id: `cwd:${cwd}`, title: basename(cwd) || cwd, path: cwd }
192
+ const updatedAt = Math.max(
193
+ Number.isFinite(cached?.lastPromptAt) ? cached.lastPromptAt : 0,
194
+ Number.isFinite(mtimeMs) ? mtimeMs : 0,
195
+ Number.isFinite(header.createdAt) ? header.createdAt : 0,
196
+ )
197
+ rows.push({
198
+ id,
199
+ title,
200
+ cwd,
201
+ createdAt: Number.isFinite(header.createdAt) ? header.createdAt : 0,
202
+ updatedAt,
203
+ sizeBytes,
204
+ exists,
205
+ live: live.has(id) || record.live === true,
206
+ running: Boolean(agents && typeof agents.get === 'function' && agents.get(id)?.status === 'running'),
207
+ archived: archived.has(id),
208
+ pinned: pinned.has(id),
209
+ origin: header.origin === 'subagent' ? 'subagent' : 'user',
210
+ parentSessionId: typeof header.parentSession === 'string' ? header.parentSession : null,
211
+ agentPreset: typeof header.agentPreset === 'string' ? header.agentPreset : null,
212
+ formatStatus: record.formatStatus === 'migration-required' ? 'migration-required' : 'current',
213
+ workspace: workspace
214
+ ? { id: workspace.id, title: workspace.title || basename(workspace.path), path: workspace.path }
215
+ : null,
216
+ group,
217
+ path: artifact,
218
+ turns: Number.isFinite(cached?.turns) ? cached.turns : 0,
219
+ steps: Number.isFinite(cached?.steps) ? cached.steps : 0,
220
+ })
221
+ }
222
+
223
+ rows.sort((left, right) => right.updatedAt - left.updatedAt || right.createdAt - left.createdAt)
224
+ const groups = new Map()
225
+ let totalBytes = 0
226
+ let liveCount = 0
227
+ let archivedCount = 0
228
+ for (const row of rows) {
229
+ totalBytes += row.sizeBytes
230
+ if (row.live) liveCount += 1
231
+ if (row.archived) archivedCount += 1
232
+ const existing = groups.get(row.group.id)
233
+ if (existing === undefined) {
234
+ groups.set(row.group.id, { ...row.group, count: 1, bytes: row.sizeBytes })
235
+ } else {
236
+ existing.count += 1
237
+ existing.bytes += row.sizeBytes
238
+ }
239
+ }
240
+
241
+ return {
242
+ ok: true,
243
+ generatedAt: Date.now(),
244
+ sessionRoot: sessionsRoot,
245
+ sessions: rows,
246
+ trash,
247
+ workspaces: [...groups.values()].sort((left, right) => {
248
+ if (left.kind === 'none') return 1
249
+ if (right.kind === 'none') return -1
250
+ return left.title.localeCompare(right.title)
251
+ }),
252
+ stats: {
253
+ total: rows.length,
254
+ groups: groups.size,
255
+ live: liveCount,
256
+ archived: archivedCount,
257
+ trash: trash.length,
258
+ bytes: totalBytes,
259
+ },
260
+ }
261
+ }
262
+
263
+ async function listRecords() {
264
+ const query = service('sessionQuery')
265
+ if (query && typeof query.listSessions === 'function') {
266
+ try {
267
+ const result = await query.listSessions()
268
+ if (Array.isArray(result) && result.length > 0) return result
269
+ } catch (error) {
270
+ ctx.logger?.warn?.(`nanshan-session-manager: sessionQuery.listSessions failed: ${String(error)}`)
271
+ }
272
+ }
273
+ const persistence = service('sessionPersistence')
274
+ if (persistence && typeof persistence.list === 'function') {
275
+ try {
276
+ const result = await persistence.list()
277
+ if (Array.isArray(result) && result.length > 0) return result
278
+ } catch (error) {
279
+ ctx.logger?.warn?.(`nanshan-session-manager: sessionPersistence.list failed: ${String(error)}`)
280
+ }
281
+ }
282
+ return scanStoredRecords()
283
+ }
284
+
285
+ async function readProjectionCache() {
286
+ const result = new Map()
287
+ let names
288
+ try {
289
+ names = await readdir(cacheRoot)
290
+ } catch {
291
+ return result
292
+ }
293
+ for (const name of names) {
294
+ if (!name.endsWith('.json') || name.includes('.bak.')) continue
295
+ const id = name.slice(0, -5)
296
+ if (!SAFE_ID.test(id)) continue
297
+ try {
298
+ const parsed = JSON.parse(await readFile(join(cacheRoot, name), 'utf8'))
299
+ const rows = parsed?.record?.rows
300
+ const title = typeof rows?.title?.val === 'string' ? rows.title.val.trim() : ''
301
+ const metadata = rows?.sessionListMetadata?.val
302
+ const stats = rows?.sessionStats?.val
303
+ result.set(id, {
304
+ title,
305
+ lastPromptAt: Number.isFinite(metadata?.lastPromptAt) ? metadata.lastPromptAt : 0,
306
+ turns: Number.isFinite(stats?.turns) ? stats.turns : 0,
307
+ steps: Number.isFinite(stats?.steps) ? stats.steps : 0,
308
+ })
309
+ } catch {
310
+ // A cache record is a shortcut, never the authority. Ignore bad rows.
311
+ }
312
+ }
313
+ return result
314
+ }
315
+
316
+ async function scanStoredRecords() {
317
+ const records = []
318
+ let projects
319
+ try {
320
+ projects = await readdir(sessionsRoot, { withFileTypes: true })
321
+ } catch {
322
+ return records
323
+ }
324
+ for (const project of projects) {
325
+ if (!project.isDirectory()) continue
326
+ let sessions
327
+ try {
328
+ sessions = await readdir(join(sessionsRoot, project.name), { withFileTypes: true })
329
+ } catch {
330
+ continue
331
+ }
332
+ for (const session of sessions) {
333
+ if (!session.isDirectory()) continue
334
+ const artifacts = await listArtifacts(join(sessionsRoot, project.name, session.name))
335
+ if (artifacts.length === 0) continue
336
+ const chosen = artifacts[0]
337
+ try {
338
+ const header = await readHeader(chosen.path)
339
+ if (header === null) continue
340
+ records.push({
341
+ header,
342
+ live: false,
343
+ persisted: true,
344
+ formatStatus: chosen.version === SESSION_FORMAT ? 'current' : 'migration-required',
345
+ location: { kind: 'jsonl', path: chosen.path },
346
+ })
347
+ } catch {
348
+ // Unreadable logs are intentionally not advertised as sessions.
349
+ }
350
+ }
351
+ }
352
+ return records
353
+ }
354
+
355
+ async function resolveArtifact(record) {
356
+ const header = record?.header
357
+ if (!header || typeof header.id !== 'string') return null
358
+ const location = record?.location
359
+ if (location && typeof location.path === 'string' && await fileExists(location.path)) return location.path
360
+ if (typeof header.cwd === 'string' && isAbsolute(header.cwd)) {
361
+ const candidate = logPathFor(sessionsRoot, header.cwd, header.id, await compression())
362
+ if (await fileExists(candidate)) return candidate
363
+ }
364
+ const found = await findArtifact(header.id)
365
+ return found === null ? null : found.path
366
+ }
367
+
368
+ async function findArtifact(id) {
369
+ if (!SAFE_ID.test(id)) return null
370
+ const encoded = encodeSegment(id)
371
+ let projects
372
+ try {
373
+ projects = await readdir(sessionsRoot, { withFileTypes: true })
374
+ } catch {
375
+ return null
376
+ }
377
+ for (const project of projects) {
378
+ if (!project.isDirectory()) continue
379
+ const directory = join(sessionsRoot, project.name, encoded)
380
+ const artifacts = await listArtifacts(directory)
381
+ if (artifacts.length > 0) return artifacts[0]
382
+ }
383
+ return null
384
+ }
385
+
386
+ async function buildBundle(ids) {
387
+ const records = await listRecords()
388
+ const byId = new Map()
389
+ for (const record of records) {
390
+ const id = record?.header?.id
391
+ if (typeof id !== 'string' || !SAFE_ID.test(id)) continue
392
+ byId.set(id, record)
393
+ }
394
+ const trashedIds = new Set((await listTrash()).map((entry) => entry.id))
395
+ const requested = Array.isArray(ids) && ids.length > 0 ? [...new Set(ids)] : [...byId.keys()].filter((id) => !trashedIds.has(id))
396
+ const cache = await readProjectionCache()
397
+ const titles = await loadTitles()
398
+ const stored = service('sessions')
399
+ const items = []
400
+ const skipped = []
401
+ for (const id of requested) {
402
+ if (!SAFE_ID.test(id)) {
403
+ skipped.push({ id, reason: 'invalid' })
404
+ continue
405
+ }
406
+ if (trashedIds.has(id)) {
407
+ skipped.push({ id, reason: 'trashed' })
408
+ continue
409
+ }
410
+ const record = byId.get(id)
411
+ if (record === undefined) {
412
+ skipped.push({ id, reason: 'missing' })
413
+ continue
414
+ }
415
+ const artifact = await resolveArtifact(record)
416
+ if (artifact === null) {
417
+ skipped.push({ id, reason: 'missing' })
418
+ continue
419
+ }
420
+ const live = stored && typeof stored.get === 'function' ? stored.get(id) : undefined
421
+ if (live !== undefined && typeof stored.flush === 'function') {
422
+ try {
423
+ await stored.flush(live)
424
+ } catch (error) {
425
+ ctx.logger?.warn?.(`nanshan-session-manager: flush before export failed for ${id}: ${String(error)}`)
426
+ }
427
+ }
428
+ let bytes
429
+ try {
430
+ bytes = await readFile(artifact)
431
+ } catch (error) {
432
+ skipped.push({ id, reason: 'unreadable' })
433
+ continue
434
+ }
435
+ if (bytes.length > MAX_SESSION_BYTES) {
436
+ skipped.push({ id, reason: 'too-large' })
437
+ continue
438
+ }
439
+ const header = record.header
440
+ const cached = cache.get(id) || null
441
+ const sidecar = titles[id] || null
442
+ const title = firstText(cached?.title, sidecar?.title)
443
+ items.push({
444
+ id,
445
+ title,
446
+ cwd: typeof header.cwd === 'string' ? header.cwd : null,
447
+ createdAt: Number.isFinite(header.createdAt) ? header.createdAt : 0,
448
+ encoding: artifact.endsWith('.zstd') ? 'zstd' : 'none',
449
+ sha256: createHash('sha256').update(bytes).digest('hex'),
450
+ bytes: bytes.length,
451
+ data: bytes.toString('base64'),
452
+ })
453
+ }
454
+ if (items.length === 0) {
455
+ const error = new Error('没有可导出的会话。')
456
+ error.status = 404
457
+ error.skipped = skipped
458
+ throw error
459
+ }
460
+ return {
461
+ format: 'dsh-nanshan-session-bundle',
462
+ version: 1,
463
+ exportedAt: new Date().toISOString(),
464
+ source: { home, sessionFormat: SESSION_FORMAT },
465
+ sessions: items,
466
+ skipped,
467
+ }
468
+ }
469
+
470
+ async function importBundle(bundle) {
471
+ if (!bundle || typeof bundle !== 'object' || bundle.format !== 'dsh-nanshan-session-bundle') {
472
+ throw httpError(400, '这不是【南山】会话管理导出的备份文件。')
473
+ }
474
+ if (bundle.version !== 1) throw httpError(400, `不支持的备份版本:${String(bundle.version)}`)
475
+ if (!Array.isArray(bundle.sessions)) throw httpError(400, '备份文件缺少 sessions 数组。')
476
+ if (bundle.sessions.length > MAX_IMPORT_SESSIONS) throw httpError(413, `一次最多导入 ${MAX_IMPORT_SESSIONS} 个会话。`)
477
+
478
+ const encoding = await compression()
479
+ const registry = service('workspaceRegistry')
480
+ const stored = service('sessions')
481
+ const trashedIds = new Set((await listTrash()).map((entry) => entry.id))
482
+ const imported = []
483
+ const skipped = []
484
+ const errors = []
485
+ let totalBytes = 0
486
+
487
+ for (const item of bundle.sessions) {
488
+ const id = item && typeof item.id === 'string' ? item.id : ''
489
+ if (!SAFE_ID.test(id)) {
490
+ skipped.push({ id, reason: 'invalid-id' })
491
+ continue
492
+ }
493
+ if (trashedIds.has(id)) {
494
+ skipped.push({ id, reason: 'trashed' })
495
+ continue
496
+ }
497
+ if (stored && typeof stored.get === 'function' && stored.get(id) !== undefined) {
498
+ skipped.push({ id, reason: 'live' })
499
+ continue
500
+ }
501
+ if (await findArtifact(id) !== null) {
502
+ skipped.push({ id, reason: 'exists' })
503
+ continue
504
+ }
505
+ if (typeof item.data !== 'string' || item.data.length === 0) {
506
+ skipped.push({ id, reason: 'invalid-data' })
507
+ continue
508
+ }
509
+ const itemEncoding = item.encoding === 'none' ? 'none' : 'zstd'
510
+ if (itemEncoding !== encoding) {
511
+ skipped.push({ id, reason: 'encoding-mismatch' })
512
+ continue
513
+ }
514
+ let bytes
515
+ try {
516
+ bytes = Buffer.from(item.data, 'base64')
517
+ } catch {
518
+ skipped.push({ id, reason: 'invalid-data' })
519
+ continue
520
+ }
521
+ if (bytes.length === 0) {
522
+ skipped.push({ id, reason: 'invalid-data' })
523
+ continue
524
+ }
525
+ if (bytes.length > MAX_SESSION_BYTES) {
526
+ skipped.push({ id, reason: 'too-large' })
527
+ continue
528
+ }
529
+ if (typeof item.sha256 === 'string' && item.sha256 !== '') {
530
+ const digest = createHash('sha256').update(bytes).digest('hex')
531
+ if (digest !== item.sha256) {
532
+ skipped.push({ id, reason: 'checksum' })
533
+ continue
534
+ }
535
+ }
536
+ let header
537
+ try {
538
+ header = parseHeaderBytes(bytes, itemEncoding === 'zstd')
539
+ } catch {
540
+ skipped.push({ id, reason: 'invalid-log' })
541
+ continue
542
+ }
543
+ if (header === null || header.id !== id || header.version !== SESSION_FORMAT) {
544
+ skipped.push({ id, reason: 'invalid-log' })
545
+ continue
546
+ }
547
+ if (header.cwd !== undefined && (typeof header.cwd !== 'string' || !isAbsolute(header.cwd))) {
548
+ skipped.push({ id, reason: 'invalid-cwd' })
549
+ continue
550
+ }
551
+ const cwd = header.cwd
552
+ const directory = sessionDirFor(sessionsRoot, cwd, id)
553
+ const target = join(directory, `session.v${SESSION_FORMAT}.jsonl${itemEncoding === 'zstd' ? '.zstd' : ''}`)
554
+ try {
555
+ await mkdir(directory, { recursive: true })
556
+ await writeFile(target, bytes, { flag: 'wx', mode: 0o600 })
557
+ totalBytes += bytes.length
558
+ imported.push({ id, title: typeof item.title === 'string' ? item.title : '' })
559
+ await removeCacheFile(id)
560
+ if (typeof item.title === 'string' && item.title.trim() !== '') {
561
+ const titles = await loadTitles()
562
+ titles[id] = { title: item.title.trim().slice(0, 300), at: Date.now() }
563
+ }
564
+ if (registry) {
565
+ try {
566
+ if (typeof registry.unarchiveSession === 'function') await registry.unarchiveSession(id)
567
+ if (typeof registry.unpinSession === 'function') await registry.unpinSession(id)
568
+ } catch {
569
+ // Archive/pin cleanup is best effort; the log import already succeeded.
570
+ }
571
+ if (cwd !== undefined && typeof registry.list === 'function') {
572
+ const workspace = registry.list().find((candidate) => candidate && typeof candidate.path === 'string' && normalizePath(candidate.path) === normalizePath(cwd))
573
+ if (workspace && typeof workspace.attachSession === 'function') {
574
+ try {
575
+ await workspace.attachSession(id)
576
+ } catch (error) {
577
+ ctx.logger?.warn?.(`nanshan-session-manager: attach imported session ${id} failed: ${String(error)}`)
578
+ }
579
+ }
580
+ }
581
+ }
582
+ } catch (error) {
583
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined)
584
+ errors.push({ id, message: error && error.message ? String(error.message) : '写入失败' })
585
+ }
586
+ }
587
+
588
+ await saveTitles()
589
+ return {
590
+ imported: imported.length,
591
+ bytes: totalBytes,
592
+ sessions: imported,
593
+ skipped,
594
+ errors,
595
+ }
596
+ }
597
+
598
+ async function deleteSessions(ids, options = {}) {
599
+ const stopActive = options.stopActive === true
600
+ const registry = service('workspaceRegistry')
601
+ const stored = service('sessions')
602
+ const agents = service('agents')
603
+ const records = await listRecords()
604
+ const byId = new Map()
605
+ for (const record of records) {
606
+ const id = record?.header?.id
607
+ if (typeof id === 'string') byId.set(id, record)
608
+ }
609
+ const cache = await readProjectionCache()
610
+ const titles = await loadTitles()
611
+ const alreadyTrashed = new Set((await listTrash()).map((entry) => entry.id))
612
+ const archived = new Set(Array.isArray(registry?.archivedSessionIds) ? registry.archivedSessionIds : [])
613
+ const pinned = new Set(Array.isArray(registry?.pinnedSessionIds) ? registry.pinnedSessionIds : [])
614
+ const deleted = []
615
+ const trashIds = []
616
+ const pending = []
617
+ const skipped = []
618
+ const errors = []
619
+ let bytes = 0
620
+
621
+ for (const rawId of ids) {
622
+ const id = typeof rawId === 'string' ? rawId : ''
623
+ if (!SAFE_ID.test(id)) {
624
+ skipped.push({ id, reason: 'invalid-id' })
625
+ continue
626
+ }
627
+ if (alreadyTrashed.has(id)) {
628
+ skipped.push({ id, reason: 'trashed' })
629
+ continue
630
+ }
631
+ let artifact = await findArtifact(id)
632
+ if (artifact === null) {
633
+ skipped.push({ id, reason: 'missing' })
634
+ continue
635
+ }
636
+ const record = byId.get(id)
637
+ let header = record && record.header ? record.header : null
638
+ if (header === null) {
639
+ try {
640
+ header = await readHeader(artifact.path)
641
+ } catch {
642
+ header = null
643
+ }
644
+ }
645
+ if (header === null) {
646
+ skipped.push({ id, reason: 'invalid-log' })
647
+ continue
648
+ }
649
+ const agent = agents && typeof agents.get === 'function' ? agents.get(id) : undefined
650
+ const wasRunning = Boolean(agent && agent.status === 'running')
651
+ const wasLive = Boolean(stored && typeof stored.get === 'function' && stored.get(id) !== undefined)
652
+ const wasArchived = archived.has(id)
653
+ const wasPinned = pinned.has(id)
654
+ let info
655
+ try {
656
+ info = await stat(artifact.path)
657
+ } catch (error) {
658
+ errors.push({ id, message: error && error.message ? String(error.message) : '读取日志失败' })
659
+ continue
660
+ }
661
+ const cached = cache.get(id) || null
662
+ const title = firstText(cached?.title, titles[id]?.title)
663
+ const updatedAt = Math.max(
664
+ Number.isFinite(cached?.lastPromptAt) ? cached.lastPromptAt : 0,
665
+ Number.isFinite(info.mtimeMs) ? info.mtimeMs : 0,
666
+ Number.isFinite(header.createdAt) ? header.createdAt : 0,
667
+ )
668
+ const shared = {
669
+ id,
670
+ artifact: artifact.path,
671
+ title,
672
+ cwd: typeof header.cwd === 'string' ? header.cwd : null,
673
+ createdAt: Number.isFinite(header.createdAt) ? header.createdAt : 0,
674
+ updatedAt,
675
+ sizeBytes: info.size,
676
+ origin: header.origin === 'subagent' ? 'subagent' : 'user',
677
+ agentPreset: typeof header.agentPreset === 'string' ? header.agentPreset : null,
678
+ wasArchived,
679
+ wasPinned,
680
+ wasRunning,
681
+ }
682
+
683
+ if (wasLive) {
684
+ if (!stopActive) {
685
+ skipped.push({ id, reason: 'live', message: '会话正在使用中;请选择停止并删除。' })
686
+ continue
687
+ }
688
+ let staged
689
+ try {
690
+ staged = await stagePendingTrash(shared)
691
+ } catch (error) {
692
+ errors.push({ id, message: error && error.message ? String(error.message) : '写入回收站失败' })
693
+ continue
694
+ }
695
+ const archivedResult = await archiveSessionForDeletion(id)
696
+ if (!archivedResult.ok) {
697
+ await rm(staged.directory, { recursive: true, force: true }).catch(() => undefined)
698
+ skipped.push({ id, reason: archivedResult.reason, message: archivedResult.message })
699
+ continue
700
+ }
701
+ deleted.push(id)
702
+ trashIds.push(staged.trashId)
703
+ pending.push(id)
704
+ continue
705
+ }
706
+
707
+ let staged
708
+ try {
709
+ staged = await stageTrash(shared)
710
+ } catch (error) {
711
+ errors.push({ id, message: error && error.message ? String(error.message) : '写入回收站失败' })
712
+ continue
713
+ }
714
+ const removal = await removeSessionArtifact(id)
715
+ if (!removal.ok) {
716
+ await rm(staged.directory, { recursive: true, force: true }).catch(() => undefined)
717
+ skipped.push({ id, reason: removal.reason, message: removal.message })
718
+ continue
719
+ }
720
+ deleted.push(id)
721
+ trashIds.push(staged.trashId)
722
+ bytes += removal.bytes
723
+ }
724
+
725
+ await saveTitles().catch((error) => {
726
+ ctx.logger?.warn?.(`nanshan-session-manager: save titles failed: ${String(error)}`)
727
+ })
728
+ return { deleted, trashIds, pending, bytes, skipped, errors }
729
+ }
730
+
731
+ async function listTrash() {
732
+ const entries = []
733
+ let directories
734
+ try {
735
+ directories = await readdir(trashRoot, { withFileTypes: true })
736
+ } catch {
737
+ return entries
738
+ }
739
+ for (const directory of directories) {
740
+ if (!directory.isDirectory()) continue
741
+ let manifest
742
+ try {
743
+ manifest = JSON.parse(await readFile(join(trashRoot, directory.name, 'manifest.json'), 'utf8'))
744
+ } catch {
745
+ continue
746
+ }
747
+ const entry = normalizeTrashEntry(manifest, directory.name)
748
+ if (entry !== null) entries.push(entry)
749
+ }
750
+ entries.sort((left, right) => right.deletedAt - left.deletedAt)
751
+ return entries
752
+ }
753
+
754
+ function normalizeTrashEntry(manifest, directoryName) {
755
+ if (!manifest || manifest.version !== 1) return null
756
+ if (typeof manifest.trashId !== 'string' || manifest.trashId !== directoryName || !SAFE_ID.test(manifest.trashId)) return null
757
+ if (typeof manifest.id !== 'string' || !SAFE_ID.test(manifest.id)) return null
758
+ const relativePath = typeof manifest.relativePath === 'string' ? manifest.relativePath : ''
759
+ if (relativePath === '' || isAbsolute(relativePath)) return null
760
+ const segments = relativePath.split(/[\\/]/)
761
+ if (segments.includes('..') || segments.some((segment) => segment === '')) return null
762
+ const logName = typeof manifest.logName === 'string' ? manifest.logName : ''
763
+ if (logName === '' || basename(logName) !== logName || LOG_NAME.exec(logName) === null) return null
764
+ const pending = manifest.pending === true
765
+ const logFile = typeof manifest.logFile === 'string' ? manifest.logFile : ''
766
+ if (logFile !== '' && basename(logFile) !== logFile) return null
767
+ if (!pending && logFile === '') return null
768
+ if (!Number.isFinite(manifest.deletedAt) || manifest.deletedAt < 0) return null
769
+ return {
770
+ trashId: manifest.trashId,
771
+ id: manifest.id,
772
+ title: typeof manifest.title === 'string' ? manifest.title.trim().slice(0, 300) : '',
773
+ cwd: typeof manifest.cwd === 'string' ? manifest.cwd : null,
774
+ createdAt: Number.isFinite(manifest.createdAt) ? manifest.createdAt : 0,
775
+ updatedAt: Number.isFinite(manifest.updatedAt) ? manifest.updatedAt : 0,
776
+ deletedAt: manifest.deletedAt,
777
+ sizeBytes: Number.isFinite(manifest.sizeBytes) ? manifest.sizeBytes : 0,
778
+ origin: manifest.origin === 'subagent' ? 'subagent' : 'user',
779
+ agentPreset: typeof manifest.agentPreset === 'string' ? manifest.agentPreset : null,
780
+ wasLive: manifest.wasLive === true,
781
+ wasRunning: manifest.wasRunning === true,
782
+ wasArchived: manifest.wasArchived === true,
783
+ wasPinned: manifest.wasPinned === true,
784
+ pending,
785
+ relativePath,
786
+ logName,
787
+ logFile,
788
+ }
789
+ }
790
+
791
+ async function stageTrash(input) {
792
+ const trashId = randomUUID()
793
+ const directory = join(trashRoot, trashId)
794
+ const logFile = 'session.log'
795
+ const directoryRelative = relative(sessionsRoot, dirname(input.artifact))
796
+ if (!isInside(sessionsRoot, dirname(input.artifact))) throw new Error('会话目录不在会话根目录内。')
797
+ try {
798
+ await mkdir(directory, { recursive: true })
799
+ await copyFile(input.artifact, join(directory, logFile), constants.COPYFILE_EXCL)
800
+ const manifest = {
801
+ version: 1,
802
+ trashId,
803
+ id: input.id,
804
+ title: typeof input.title === 'string' ? input.title.trim().slice(0, 300) : '',
805
+ cwd: typeof input.cwd === 'string' ? input.cwd : null,
806
+ createdAt: Number.isFinite(input.createdAt) ? input.createdAt : 0,
807
+ updatedAt: Number.isFinite(input.updatedAt) ? input.updatedAt : 0,
808
+ deletedAt: Date.now(),
809
+ sizeBytes: Number.isFinite(input.sizeBytes) ? input.sizeBytes : 0,
810
+ origin: input.origin === 'subagent' ? 'subagent' : 'user',
811
+ agentPreset: typeof input.agentPreset === 'string' ? input.agentPreset : null,
812
+ wasLive: input.wasLive === true,
813
+ wasRunning: input.wasRunning === true,
814
+ wasArchived: input.wasArchived === true,
815
+ wasPinned: input.wasPinned === true,
816
+ pending: false,
817
+ relativePath: directoryRelative.split('\\').join('/'),
818
+ logName: basename(input.artifact),
819
+ logFile,
820
+ }
821
+ await writeFile(join(directory, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
822
+ return { trashId, directory, manifest }
823
+ } catch (error) {
824
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined)
825
+ throw error
826
+ }
827
+ }
828
+
829
+ async function archiveSessionForDeletion(id) {
830
+ const registry = service('workspaceRegistry')
831
+ if (!registry || typeof registry.archiveSession !== 'function') return { ok: false, reason: 'no-archive' }
832
+ try {
833
+ await registry.archiveSession(id, { stopActivity: true })
834
+ return { ok: true }
835
+ } catch (error) {
836
+ return { ok: false, reason: 'archive-failed', message: error && error.message ? String(error.message) : '归档并停止会话失败' }
837
+ }
838
+ }
839
+
840
+ async function stagePendingTrash(input) {
841
+ const trashId = randomUUID()
842
+ const directory = join(trashRoot, trashId)
843
+ const directoryRelative = relative(sessionsRoot, dirname(input.artifact))
844
+ if (!isInside(sessionsRoot, dirname(input.artifact))) throw new Error('会话目录不在会话根目录内。')
845
+ try {
846
+ await mkdir(directory, { recursive: true })
847
+ const manifest = {
848
+ version: 1,
849
+ trashId,
850
+ id: input.id,
851
+ title: typeof input.title === 'string' ? input.title.trim().slice(0, 300) : '',
852
+ cwd: typeof input.cwd === 'string' ? input.cwd : null,
853
+ createdAt: Number.isFinite(input.createdAt) ? input.createdAt : 0,
854
+ updatedAt: Number.isFinite(input.updatedAt) ? input.updatedAt : 0,
855
+ deletedAt: Date.now(),
856
+ sizeBytes: Number.isFinite(input.sizeBytes) ? input.sizeBytes : 0,
857
+ origin: input.origin === 'subagent' ? 'subagent' : 'user',
858
+ agentPreset: typeof input.agentPreset === 'string' ? input.agentPreset : null,
859
+ wasLive: true,
860
+ wasRunning: input.wasRunning === true,
861
+ wasArchived: input.wasArchived === true,
862
+ wasPinned: input.wasPinned === true,
863
+ pending: true,
864
+ relativePath: directoryRelative.split('\\').join('/'),
865
+ logName: basename(input.artifact),
866
+ logFile: '',
867
+ }
868
+ await writeFile(join(directory, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
869
+ return { trashId, directory, manifest }
870
+ } catch (error) {
871
+ await rm(directory, { recursive: true, force: true }).catch(() => undefined)
872
+ throw error
873
+ }
874
+ }
875
+
876
+ async function removeSessionArtifact(id) {
877
+ const stored = service('sessions')
878
+ if (stored && typeof stored.get === 'function' && stored.get(id) !== undefined) return { ok: false, reason: 'live' }
879
+ const artifact = await findArtifact(id)
880
+ if (artifact === null) return { ok: true, bytes: 0 }
881
+ const directory = dirname(artifact.path)
882
+ if (!isInside(sessionsRoot, directory) || basename(directory) !== encodeSegment(id)) return { ok: false, reason: 'unsafe-path' }
883
+ let bytes = 0
884
+ try {
885
+ bytes = (await stat(artifact.path)).size
886
+ } catch {
887
+ // Size is informational.
888
+ }
889
+ const registry = service('workspaceRegistry')
890
+ if (registry) {
891
+ try {
892
+ if (typeof registry.list === 'function') {
893
+ for (const workspace of registry.list()) {
894
+ if (!workspace || !Array.isArray(workspace.sessionIds)) continue
895
+ if (!workspace.sessionIds.includes(id)) continue
896
+ if (typeof workspace.detachSession === 'function') await workspace.detachSession(id)
897
+ break
898
+ }
899
+ }
900
+ if (typeof registry.unarchiveSession === 'function') await registry.unarchiveSession(id)
901
+ if (typeof registry.unpinSession === 'function') await registry.unpinSession(id)
902
+ } catch (error) {
903
+ ctx.logger?.warn?.(`nanshan-session-manager: workspace cleanup failed for ${id}: ${String(error)}`)
904
+ }
905
+ }
906
+ try {
907
+ const project = dirname(directory)
908
+ await rm(directory, { recursive: true, force: true })
909
+ await rmdir(project).catch(() => undefined)
910
+ await removeCacheFile(id)
911
+ const titles = await loadTitles()
912
+ delete titles[id]
913
+ try {
914
+ ctx.emit?.('api-session/removed', id)
915
+ } catch {
916
+ // The Client refreshes explicitly after a successful delete.
917
+ }
918
+ return { ok: true, bytes }
919
+ } catch (error) {
920
+ return { ok: false, reason: 'delete-failed', message: error && error.message ? String(error.message) : '删除失败' }
921
+ }
922
+ }
923
+
924
+ async function settlePendingTrash() {
925
+ const entries = await listTrash()
926
+ let changed = false
927
+ for (const entry of entries) {
928
+ if (!entry.pending) continue
929
+ const stored = service('sessions')
930
+ if (stored && typeof stored.get === 'function' && stored.get(entry.id) !== undefined) continue
931
+ const sourceDirectory = join(trashRoot, entry.trashId)
932
+ if (!isInside(trashRoot, sourceDirectory)) continue
933
+ const artifact = await findArtifact(entry.id)
934
+ if (artifact === null) {
935
+ const copied = join(sourceDirectory, 'session.log')
936
+ if (await fileExists(copied)) {
937
+ try {
938
+ const manifestPath = join(sourceDirectory, 'manifest.json')
939
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
940
+ manifest.pending = false
941
+ manifest.logFile = 'session.log'
942
+ manifest.settledAt = Date.now()
943
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
944
+ changed = true
945
+ } catch (error) {
946
+ ctx.logger?.warn?.(`nanshan-session-manager: settle trash ${entry.trashId} failed: ${String(error)}`)
947
+ }
948
+ } else {
949
+ await rm(sourceDirectory, { recursive: true, force: true }).catch(() => undefined)
950
+ changed = true
951
+ }
952
+ continue
953
+ }
954
+ try {
955
+ await rm(join(sourceDirectory, 'session.log'), { force: true })
956
+ await copyFile(artifact.path, join(sourceDirectory, 'session.log'), constants.COPYFILE_EXCL)
957
+ } catch (error) {
958
+ ctx.logger?.warn?.(`nanshan-session-manager: copy pending trash ${entry.id} failed: ${String(error)}`)
959
+ continue
960
+ }
961
+ const removal = await removeSessionArtifact(entry.id)
962
+ if (!removal.ok) {
963
+ await rm(join(sourceDirectory, 'session.log'), { force: true }).catch(() => undefined)
964
+ continue
965
+ }
966
+ try {
967
+ const manifestPath = join(sourceDirectory, 'manifest.json')
968
+ const manifest = JSON.parse(await readFile(manifestPath, 'utf8'))
969
+ manifest.pending = false
970
+ manifest.logFile = 'session.log'
971
+ manifest.settledAt = Date.now()
972
+ manifest.sizeBytes = removal.bytes
973
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
974
+ changed = true
975
+ } catch (error) {
976
+ ctx.logger?.warn?.(`nanshan-session-manager: finalize trash ${entry.trashId} failed: ${String(error)}`)
977
+ }
978
+ }
979
+ if (changed) await saveTitles().catch(() => undefined)
980
+ }
981
+
982
+ async function restoreTrash(trashIds) {
983
+ const entries = await listTrash()
984
+ const byId = new Map(entries.map((entry) => [entry.trashId, entry]))
985
+ const registry = service('workspaceRegistry')
986
+ const stored = service('sessions')
987
+ const restored = []
988
+ const skipped = []
989
+ const errors = []
990
+
991
+ async function restoreArchiveState(entry) {
992
+ if (!registry) return
993
+ try {
994
+ if (entry.wasArchived === true) {
995
+ if (typeof registry.archiveSession === 'function') await registry.archiveSession(entry.id)
996
+ return
997
+ }
998
+ if (typeof registry.unarchiveSession === 'function') await registry.unarchiveSession(entry.id)
999
+ if (entry.wasPinned === true && typeof registry.pinSession === 'function') await registry.pinSession(entry.id)
1000
+ } catch (error) {
1001
+ ctx.logger?.warn?.(`nanshan-session-manager: restore workspace state ${entry.id} failed: ${String(error)}`)
1002
+ }
1003
+ }
1004
+
1005
+ for (const rawTrashId of trashIds) {
1006
+ const trashId = typeof rawTrashId === 'string' ? rawTrashId : ''
1007
+ const entry = byId.get(trashId)
1008
+ if (entry === undefined) {
1009
+ skipped.push({ trashId, reason: 'missing' })
1010
+ continue
1011
+ }
1012
+ const sourceDirectory = join(trashRoot, entry.trashId)
1013
+ if (!isInside(trashRoot, sourceDirectory)) {
1014
+ skipped.push({ trashId, id: entry.id, reason: 'unsafe-path' })
1015
+ continue
1016
+ }
1017
+ const original = await findArtifact(entry.id)
1018
+ if (entry.pending && original !== null) {
1019
+ try {
1020
+ await restoreArchiveState(entry)
1021
+ await rm(sourceDirectory, { recursive: true, force: true })
1022
+ restored.push(entry.id)
1023
+ } catch (error) {
1024
+ errors.push({ trashId, id: entry.id, message: error && error.message ? String(error.message) : '恢复失败' })
1025
+ }
1026
+ continue
1027
+ }
1028
+ if (original !== null) {
1029
+ skipped.push({ trashId, id: entry.id, reason: 'exists' })
1030
+ continue
1031
+ }
1032
+ if (stored && typeof stored.get === 'function' && stored.get(entry.id) !== undefined) {
1033
+ skipped.push({ trashId, id: entry.id, reason: 'live' })
1034
+ continue
1035
+ }
1036
+ const targetDirectory = join(sessionsRoot, entry.relativePath)
1037
+ if (!isInside(sessionsRoot, targetDirectory) || basename(targetDirectory) !== encodeSegment(entry.id)) {
1038
+ skipped.push({ trashId, id: entry.id, reason: 'unsafe-path' })
1039
+ continue
1040
+ }
1041
+ const logFile = entry.logFile !== '' ? entry.logFile : 'session.log'
1042
+ const sourceLog = join(sourceDirectory, logFile)
1043
+ if (logFile === '' || !(await fileExists(sourceLog))) {
1044
+ skipped.push({ trashId, id: entry.id, reason: 'missing-log' })
1045
+ continue
1046
+ }
1047
+ try {
1048
+ await mkdir(targetDirectory, { recursive: true })
1049
+ await copyFile(sourceLog, join(targetDirectory, entry.logName), constants.COPYFILE_EXCL)
1050
+ await removeCacheFile(entry.id)
1051
+ if (entry.title !== '') {
1052
+ const titles = await loadTitles()
1053
+ titles[entry.id] = { title: entry.title, at: Date.now() }
1054
+ }
1055
+ if (registry) {
1056
+ await restoreArchiveState(entry)
1057
+ if (entry.cwd !== null && typeof registry.list === 'function') {
1058
+ const workspace = registry.list().find((candidate) => candidate && typeof candidate.path === 'string' && normalizePath(candidate.path) === normalizePath(entry.cwd))
1059
+ if (workspace && typeof workspace.attachSession === 'function') {
1060
+ try {
1061
+ await workspace.attachSession(entry.id)
1062
+ } catch (error) {
1063
+ ctx.logger?.warn?.(`nanshan-session-manager: attach restored session ${entry.id} failed: ${String(error)}`)
1064
+ }
1065
+ }
1066
+ }
1067
+ }
1068
+ await rm(sourceDirectory, { recursive: true, force: true })
1069
+ restored.push(entry.id)
1070
+ } catch (error) {
1071
+ errors.push({ trashId, id: entry.id, message: error && error.message ? String(error.message) : '恢复失败' })
1072
+ }
1073
+ }
1074
+
1075
+ await saveTitles().catch(() => undefined)
1076
+ return { restored, skipped, errors }
1077
+ }
1078
+
1079
+ async function purgeTrash(trashIds) {
1080
+ const entries = await listTrash()
1081
+ const byId = new Map(entries.map((entry) => [entry.trashId, entry]))
1082
+ const purged = []
1083
+ const skipped = []
1084
+ const errors = []
1085
+ for (const rawTrashId of trashIds) {
1086
+ const trashId = typeof rawTrashId === 'string' ? rawTrashId : ''
1087
+ const entry = byId.get(trashId)
1088
+ if (entry === undefined) {
1089
+ skipped.push({ trashId, reason: 'missing' })
1090
+ continue
1091
+ }
1092
+ const directory = join(trashRoot, entry.trashId)
1093
+ if (!isInside(trashRoot, directory)) {
1094
+ skipped.push({ trashId, reason: 'unsafe-path' })
1095
+ continue
1096
+ }
1097
+ if (entry.pending) {
1098
+ const stored = service('sessions')
1099
+ if (stored && typeof stored.get === 'function' && stored.get(entry.id) !== undefined) {
1100
+ skipped.push({ trashId, id: entry.id, reason: 'pending-live', message: '会话仍在使用中;重启 DSH 后可彻底删除。' })
1101
+ continue
1102
+ }
1103
+ const removal = await removeSessionArtifact(entry.id)
1104
+ if (!removal.ok) {
1105
+ skipped.push({ trashId, id: entry.id, reason: removal.reason, message: removal.message })
1106
+ continue
1107
+ }
1108
+ }
1109
+ try {
1110
+ await rm(directory, { recursive: true, force: true })
1111
+ purged.push(entry.id)
1112
+ } catch (error) {
1113
+ errors.push({ trashId, message: error && error.message ? String(error.message) : '彻底删除失败' })
1114
+ }
1115
+ }
1116
+ await saveTitles().catch(() => undefined)
1117
+ return { purged, skipped, errors }
1118
+ }
1119
+
1120
+ async function removeCacheFile(id) {
1121
+ try {
1122
+ await rm(join(cacheRoot, `${id}.json`), { force: true })
1123
+ } catch {
1124
+ // Cache cleanup is best effort; the projection cache never owns the log.
1125
+ }
1126
+ }
1127
+
1128
+ async function handler(request, response) {
1129
+ let url
1130
+ try {
1131
+ url = new URL(request.url || API, 'http://localhost')
1132
+ } catch {
1133
+ return sendJson(response, 400, { ok: false, error: 'bad-url', message: '无法解析请求地址。' })
1134
+ }
1135
+ const pathname = url.pathname
1136
+ try {
1137
+ // The Web server may be configured to listen beyond loopback. This
1138
+ // destructive surface is deliberately local-only even then.
1139
+ if (!isLoopbackRequest(request)) {
1140
+ return sendJson(response, 403, { ok: false, error: 'local-only', message: '会话管理接口只接受本机请求。' })
1141
+ }
1142
+ if (request.method === 'GET' || request.method === 'HEAD') {
1143
+ if (pathname === API) {
1144
+ if (request.method === 'HEAD') {
1145
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
1146
+ response.end()
1147
+ return
1148
+ }
1149
+ return sendJson(response, 200, await buildList())
1150
+ }
1151
+ if (pathname === `${API}/export`) {
1152
+ if (request.method === 'HEAD') {
1153
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
1154
+ response.end()
1155
+ return
1156
+ }
1157
+ const ids = readIds(url)
1158
+ const bundle = await buildBundle(ids)
1159
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
1160
+ return sendDownload(response, `nanshan-sessions-${stamp}.json`, bundle)
1161
+ }
1162
+ return sendJson(response, 404, { ok: false, error: 'not-found', message: '未知的会话管理接口。' })
1163
+ }
1164
+
1165
+ if (request.method !== 'POST') {
1166
+ response.setHeader('allow', 'GET, HEAD, POST')
1167
+ return sendJson(response, 405, { ok: false, error: 'method', message: '请使用 GET 或 POST。' })
1168
+ }
1169
+ if (!sameOrigin(request)) {
1170
+ return sendJson(response, 403, { ok: false, error: 'origin', message: '拒绝跨站写入会话管理数据。' })
1171
+ }
1172
+ const body = await readJson(request)
1173
+ if (pathname === `${API}/import`) {
1174
+ const result = await exclusive(() => importBundle(body))
1175
+ return sendJson(response, 200, { ok: true, ...result })
1176
+ }
1177
+ if (pathname === `${API}/delete`) {
1178
+ const ids = Array.isArray(body?.ids) ? body.ids.slice(0, MAX_DELETE_SESSIONS) : []
1179
+ if (ids.length === 0) return sendJson(response, 400, { ok: false, error: 'ids', message: '请选择要删除的会话。' })
1180
+ const result = await exclusive(() => deleteSessions(ids, { stopActive: body?.stopActive === true }))
1181
+ return sendJson(response, 200, { ok: true, ...result })
1182
+ }
1183
+ if (pathname === `${API}/restore`) {
1184
+ const trashIds = Array.isArray(body?.trashIds) ? body.trashIds.slice(0, MAX_DELETE_SESSIONS) : []
1185
+ if (trashIds.length === 0) return sendJson(response, 400, { ok: false, error: 'trashIds', message: '请选择要恢复的会话。' })
1186
+ const result = await exclusive(() => restoreTrash(trashIds))
1187
+ return sendJson(response, 200, { ok: true, ...result })
1188
+ }
1189
+ if (pathname === `${API}/purge`) {
1190
+ const trashIds = Array.isArray(body?.trashIds) ? body.trashIds.slice(0, MAX_DELETE_SESSIONS) : []
1191
+ if (trashIds.length === 0) return sendJson(response, 400, { ok: false, error: 'trashIds', message: '请选择要彻底删除的会话。' })
1192
+ const result = await exclusive(() => purgeTrash(trashIds))
1193
+ return sendJson(response, 200, { ok: true, ...result })
1194
+ }
1195
+ return sendJson(response, 404, { ok: false, error: 'not-found', message: '未知的会话管理接口。' })
1196
+ } catch (error) {
1197
+ const status = error && Number.isInteger(error.status) ? error.status : 500
1198
+ if (status >= 500) ctx.logger?.warn?.(`nanshan-session-manager: ${error && error.stack ? error.stack : String(error)}`)
1199
+ return sendJson(response, status, {
1200
+ ok: false,
1201
+ error: status === 500 ? 'internal' : 'request',
1202
+ message: error && error.message ? String(error.message) : '会话管理请求失败。',
1203
+ ...(Array.isArray(error?.skipped) ? { skipped: error.skipped } : {}),
1204
+ })
1205
+ }
1206
+ }
1207
+
1208
+ ctx.effect(
1209
+ () => ctx.webServer.register({ kind: 'prefix', path: API, handler }),
1210
+ 'nanshan-session-manager: session management api',
1211
+ )
1212
+ }
1213
+
1214
+ function httpError(status, message) {
1215
+ const error = new Error(message)
1216
+ error.status = status
1217
+ return error
1218
+ }
1219
+
1220
+ function sendJson(response, status, payload) {
1221
+ const body = Buffer.from(JSON.stringify(payload), 'utf8')
1222
+ response.writeHead(status, {
1223
+ 'content-type': 'application/json; charset=utf-8',
1224
+ 'content-length': String(body.length),
1225
+ 'cache-control': 'no-store',
1226
+ })
1227
+ response.end(body)
1228
+ }
1229
+
1230
+ function sendDownload(response, filename, payload) {
1231
+ const body = Buffer.from(JSON.stringify(payload), 'utf8')
1232
+ response.writeHead(200, {
1233
+ 'content-type': 'application/json; charset=utf-8',
1234
+ 'content-length': String(body.length),
1235
+ 'content-disposition': `attachment; filename="${filename}"`,
1236
+ 'cache-control': 'no-store',
1237
+ })
1238
+ response.end(body)
1239
+ }
1240
+
1241
+ function readIds(url) {
1242
+ const values = url.searchParams.getAll('ids')
1243
+ const ids = []
1244
+ for (const value of values) {
1245
+ for (const part of value.split(',')) {
1246
+ const id = part.trim()
1247
+ if (id !== '' && !ids.includes(id)) ids.push(id)
1248
+ }
1249
+ }
1250
+ return ids
1251
+ }
1252
+
1253
+ function isLoopbackRequest(request) {
1254
+ const address = request.socket && request.socket.remoteAddress
1255
+ if (typeof address !== 'string' || address === '') return true
1256
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
1257
+ }
1258
+
1259
+ function sameOrigin(request) {
1260
+ const origin = request.headers.origin
1261
+ if (typeof origin !== 'string' || origin === '') return true
1262
+ try {
1263
+ return new URL(origin).host === request.headers.host
1264
+ } catch {
1265
+ return false
1266
+ }
1267
+ }
1268
+
1269
+ function readJson(request) {
1270
+ return new Promise((resolveBody, reject) => {
1271
+ const declared = Number(request.headers['content-length'])
1272
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
1273
+ reject(httpError(413, '请求内容过大。'))
1274
+ request.destroy()
1275
+ return
1276
+ }
1277
+ let size = 0
1278
+ const chunks = []
1279
+ request.on('data', (chunk) => {
1280
+ size += chunk.length
1281
+ if (size > MAX_BODY_BYTES) {
1282
+ reject(httpError(413, '请求内容过大。'))
1283
+ request.destroy()
1284
+ return
1285
+ }
1286
+ chunks.push(chunk)
1287
+ })
1288
+ request.on('end', () => {
1289
+ try {
1290
+ const text = Buffer.concat(chunks).toString('utf8')
1291
+ if (text.trim() === '') return resolveBody(null)
1292
+ resolveBody(JSON.parse(text))
1293
+ } catch {
1294
+ reject(httpError(400, '请求内容不是有效的 JSON。'))
1295
+ }
1296
+ })
1297
+ request.on('error', reject)
1298
+ })
1299
+ }
1300
+
1301
+ function firstText(...values) {
1302
+ for (const value of values) {
1303
+ if (typeof value === 'string' && value.trim() !== '') return value.trim()
1304
+ }
1305
+ return ''
1306
+ }
1307
+
1308
+ function delay(ms) {
1309
+ return new Promise((resolveDelay) => setTimeout(resolveDelay, ms))
1310
+ }
1311
+
1312
+ function normalizePath(value) {
1313
+ if (typeof value !== 'string' || value === '') return ''
1314
+ return value.length > 1 ? value.replace(/[\\/]+$/, '') : value
1315
+ }
1316
+
1317
+ async function fileExists(path) {
1318
+ try {
1319
+ return (await stat(path)).isFile()
1320
+ } catch {
1321
+ return false
1322
+ }
1323
+ }
1324
+
1325
+ function isInside(root, candidate) {
1326
+ const resolvedRoot = resolve(root)
1327
+ const resolvedCandidate = resolve(candidate)
1328
+ const relation = relative(resolvedRoot, resolvedCandidate)
1329
+ return relation !== '' && !relation.startsWith('..') && !isAbsolute(relation)
1330
+ }
1331
+
1332
+ async function listArtifacts(directory) {
1333
+ let files
1334
+ try {
1335
+ files = await readdir(directory, { withFileTypes: true })
1336
+ } catch {
1337
+ return []
1338
+ }
1339
+ const artifacts = []
1340
+ for (const file of files) {
1341
+ if (!file.isFile()) continue
1342
+ const match = LOG_NAME.exec(file.name)
1343
+ if (match === null) continue
1344
+ const version = Number(match[1])
1345
+ if (!Number.isSafeInteger(version) || version < 0) continue
1346
+ artifacts.push({ path: join(directory, file.name), version })
1347
+ }
1348
+ artifacts.sort((left, right) => right.version - left.version || Number(right.path.endsWith('.zstd')) - Number(left.path.endsWith('.zstd')))
1349
+ return artifacts
1350
+ }
1351
+
1352
+ async function readHeader(path) {
1353
+ let handle
1354
+ try {
1355
+ handle = await open(path, 'r')
1356
+ const buffer = Buffer.alloc(64 * 1024)
1357
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0)
1358
+ if (bytesRead === 0) return null
1359
+ try {
1360
+ return parseHeaderBytes(buffer.subarray(0, bytesRead), path.endsWith('.zstd'))
1361
+ } catch {
1362
+ // The first Zstd frame may carry the header together with a large first
1363
+ // batch. Fall back to a full read rather than dropping the session.
1364
+ const info = await stat(path)
1365
+ if (info.size > 256 * 1024 * 1024) return null
1366
+ return parseHeaderBytes(await readFile(path), path.endsWith('.zstd'))
1367
+ }
1368
+ } finally {
1369
+ if (handle !== undefined) await handle.close().catch(() => undefined)
1370
+ }
1371
+ }
1372
+
1373
+ function parseHeaderBytes(bytes, compressed) {
1374
+ let text
1375
+ if (compressed || (bytes.length >= 4 && bytes.subarray(0, 4).equals(ZSTD_MAGIC))) {
1376
+ text = zstdDecompressSync(bytes).toString('utf8')
1377
+ } else {
1378
+ text = bytes.toString('utf8')
1379
+ }
1380
+ const line = text.split('\n', 1)[0].trim()
1381
+ if (line === '') return null
1382
+ let header
1383
+ try {
1384
+ header = JSON.parse(line)
1385
+ } catch {
1386
+ return null
1387
+ }
1388
+ if (!header || typeof header !== 'object' || Array.isArray(header)) return null
1389
+ if (header.type !== 'session' || header.version !== SESSION_FORMAT) return null
1390
+ if (typeof header.id !== 'string' || header.id === '') return null
1391
+ if (!Number.isSafeInteger(header.createdAt) || header.createdAt < 0) return null
1392
+ if (typeof header.isSeeded !== 'boolean') return null
1393
+ if (header.cwd !== undefined && typeof header.cwd !== 'string') return null
1394
+ return header
1395
+ }
1396
+
1397
+ function encodeSegment(raw) {
1398
+ if (raw.length === 0) throw new Error('cannot encode an empty path segment')
1399
+ if (raw === '.') return '~002E'
1400
+ if (raw === '..') return '~002E~002E'
1401
+ let out = ''
1402
+ for (let index = 0; index < raw.length; index += 1) {
1403
+ const code = raw.charCodeAt(index)
1404
+ const character = String.fromCharCode(code)
1405
+ if (character !== '~' && /^[A-Za-z0-9._-]$/.test(character)) out += character
1406
+ else out += `~${code.toString(16).toUpperCase().padStart(4, '0')}`
1407
+ }
1408
+ return out
1409
+ }
1410
+
1411
+ function projectKey(cwd) {
1412
+ if (cwd.length === 0) throw new Error('cannot encode an empty project path')
1413
+ let readable = ''
1414
+ let separatorRun = false
1415
+ for (let index = 0; index < cwd.length; index += 1) {
1416
+ const code = cwd.charCodeAt(index)
1417
+ const character = String.fromCharCode(code)
1418
+ if (character === '/' || character === '\\' || character === ':') {
1419
+ if (!separatorRun) readable += '-'
1420
+ separatorRun = true
1421
+ } else if (character !== '~' && /^[A-Za-z0-9._-]$/.test(character)) {
1422
+ readable += character
1423
+ separatorRun = false
1424
+ } else {
1425
+ readable += `~${code.toString(16).toUpperCase().padStart(4, '0')}`
1426
+ separatorRun = false
1427
+ }
1428
+ }
1429
+ return `--${(readable.replace(/^-+/, '') || 'root').slice(0, 251)}--`
1430
+ }
1431
+
1432
+ function sessionDirFor(root, cwd, id) {
1433
+ const project = cwd === undefined ? join(root, '_no-cwd') : join(root, projectKey(cwd))
1434
+ return join(project, encodeSegment(id))
1435
+ }
1436
+
1437
+ function logPathFor(root, cwd, id, compression) {
1438
+ const suffix = compression === 'none' ? '' : '.zstd'
1439
+ return join(sessionDirFor(root, cwd, id), `session.v${SESSION_FORMAT}.jsonl${suffix}`)
1440
+ }