dsh-lmw-plugin 0.0.0-stage → 1.0.4

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,1353 @@
1
+ /**
2
+ * Host half of the lmw-plugin bundle.
3
+ *
4
+ * Scans stored Sessions that no Workspace accounts for, assigns selected
5
+ * Sessions the way DSH itself would (create or reuse a Workspace over the
6
+ * Session's recorded cwd, then attach it), and reports/creates the default
7
+ * skills directory. The browser half (`client.js`) renders the dialog and the
8
+ * sidebar entry; both faces share one package.
9
+ *
10
+ * Every route sits behind the composition's `connection` trust fence, the
11
+ * same way the shipped open-in-app routes do, so only an authenticated page
12
+ * of this Host can read or change anything.
13
+ *
14
+ * @module dsh-lmw-plugin
15
+ */
16
+
17
+ import { copyFile, mkdir, open, readdir, realpath, rm, stat } from 'node:fs/promises'
18
+ import { homedir } from 'node:os'
19
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
20
+ import { zstdDecompressSync } from 'node:zlib'
21
+ import {
22
+ assignedSessionIds, collectUnassigned, normalizeRequestedIds, planAssignment, SCAN_DEFAULTS,
23
+ } from './src/scan.js'
24
+
25
+ /** Cordis function-plugin name. */
26
+ export const name = 'lmw-plugin'
27
+
28
+ /** The route carrier, the trust fence, the workspace registry, and the Session services. */
29
+ export const inject = [
30
+ 'webServer', 'connection', 'workspaceRegistry', 'sessionQuery', 'sessionPersistence', 'sessions',
31
+ ]
32
+
33
+ const STATE_PATH = '/lmw-plugin/state'
34
+ const ASSIGN_PATH = '/lmw-plugin/assign'
35
+ const SKILLS_PATH = '/lmw-plugin/skills'
36
+ const IMPORT_SCAN_PATH = '/lmw-plugin/import/scan'
37
+ const IMPORT_APPLY_PATH = '/lmw-plugin/import/apply'
38
+ const WORKSPACE_STATUS_PATH = '/lmw-plugin/workspaces/status'
39
+ const WORKSPACE_SORT_PATH = '/lmw-plugin/workspaces/sort'
40
+ const MAX_BODY_BYTES = 64 * 1024
41
+ /** One canonical DSH generation filename: `session.v4.jsonl.zstd` (or plain JSONL). */
42
+ const SESSION_FILE_NAME = /^session(?:\.v\d+)?\.jsonl(?:\.zstd)?$/
43
+ /** Current Session format version this bundle understands. */
44
+ const SESSION_FORMAT_VERSION = 4
45
+ /** Zstandard frame magic, used to locate frame boundaries without decompressing. */
46
+ const ZSTD_MAGIC = 0xfd2fb528
47
+ /** A session event line that proves the session holds a real conversation. */
48
+ const USER_MESSAGE_PREFIX = '{"type":"user/message"'
49
+ /** Compressed bytes read to look for the first user message; leftovers stay conservative. */
50
+ const EMPTY_SESSION_PROBE_BYTES = 128 * 1024
51
+ /** Emptiness cache for assignment scans: session id -> { key, empty }. */
52
+ const EMPTY_SESSION_CACHE = new Map()
53
+ const EMPTY_SESSION_CACHE_LIMIT = 5000
54
+ /** New file probes one assignment scan may run; cached ids do not count. */
55
+ const EMPTY_SESSION_CHECK_LIMIT = 500
56
+
57
+ /** Bundle defaults; a profile patch row may override any of them. */
58
+ const DEFAULTS = {
59
+ ...SCAN_DEFAULTS,
60
+ autoOpenOnStartup: true,
61
+ dshHome: undefined,
62
+ /** Warm missing projection-cache title rows for accounted Sessions. */
63
+ warmTitleCache: true,
64
+ /** Maximum Sessions warmed per scan; the rest warm on a later scan. */
65
+ warmTitleLimit: 100,
66
+ /** Skip Sessions with more events than this; their fold would stall the Host. */
67
+ warmMaxEvents: 20_000,
68
+ /** Maximum session files one import scan collects. */
69
+ importMaxFiles: 2000,
70
+ /** Refuse a source session file larger than this. */
71
+ importMaxFileBytes: 512 * 1024 * 1024,
72
+ }
73
+
74
+ /**
75
+ * Merge the row config over the bundle defaults.
76
+ * @param {Record<string, unknown> | undefined} config - the row's `config` mapping.
77
+ * @returns {typeof DEFAULTS} effective settings.
78
+ */
79
+ function resolveSettings(config) {
80
+ const merged = { ...DEFAULTS }
81
+ if (config && typeof config === 'object') {
82
+ for (const key of Object.keys(DEFAULTS)) {
83
+ if (config[key] !== undefined) merged[key] = config[key]
84
+ }
85
+ }
86
+ return merged
87
+ }
88
+
89
+ /** Expand the `~` prefixes DSH accepts for a configured home. */
90
+ function expandHomePath(path) {
91
+ if (path === '~') return homedir()
92
+ if (path.startsWith('~/') || path.startsWith('~\\')) return join(homedir(), path.slice(2))
93
+ return path
94
+ }
95
+
96
+ /**
97
+ * Resolve the DSH home exactly as `@deepseek-ai/dsh-home-paths` does: explicit
98
+ * config, then `$DSH_HOME`, then `~/.dsh`.
99
+ * @param {typeof DEFAULTS} settings - effective settings.
100
+ * @returns {string} absolute home.
101
+ */
102
+ function resolveDshHome(settings) {
103
+ const configured = typeof settings.dshHome === 'string' ? settings.dshHome.trim() : ''
104
+ if (configured.length > 0) return resolve(expandHomePath(configured))
105
+ const fromEnv = process.env.DSH_HOME
106
+ if (typeof fromEnv === 'string' && fromEnv.trim().length > 0) return resolve(expandHomePath(fromEnv))
107
+ return join(homedir(), '.dsh')
108
+ }
109
+
110
+ /** @returns {Promise<boolean>} whether the path is an existing directory. */
111
+ async function isDirectory(path) {
112
+ try {
113
+ return (await stat(path)).isDirectory()
114
+ } catch {
115
+ // Any stat failure means "not a usable directory" for this check.
116
+ return false
117
+ }
118
+ }
119
+
120
+ /** Human-facing failure text. */
121
+ function errorMessage(error) {
122
+ if (error instanceof Error && error.message.length > 0) return error.message
123
+ return String(error)
124
+ }
125
+
126
+ /** JSON response; live facts are never cached. */
127
+ function sendJson(res, status, payload) {
128
+ res.statusCode = status
129
+ res.setHeader('content-type', 'application/json; charset=utf-8')
130
+ res.setHeader('cache-control', 'no-store')
131
+ res.end(JSON.stringify(payload))
132
+ }
133
+
134
+ /** 405 with the one supported method. */
135
+ function sendMethodNotAllowed(res, allow) {
136
+ res.statusCode = 405
137
+ res.setHeader('allow', allow)
138
+ res.end()
139
+ }
140
+
141
+ /** Collect a bounded JSON body; `{ ok: false }` carries the refusal status. */
142
+ async function readJsonBody(req) {
143
+ const chunks = []
144
+ let size = 0
145
+ for await (const chunk of req) {
146
+ const part = typeof chunk === 'string' ? Buffer.from(chunk) : chunk
147
+ size += part.byteLength
148
+ if (size > MAX_BODY_BYTES) {
149
+ req.resume()
150
+ return { ok: false, status: 413 }
151
+ }
152
+ chunks.push(part)
153
+ }
154
+ const text = Buffer.concat(chunks, size).toString('utf8')
155
+ if (text.trim().length === 0) return { ok: true, value: {} }
156
+ try {
157
+ return { ok: true, value: JSON.parse(text) }
158
+ } catch {
159
+ return { ok: false, status: 400 }
160
+ }
161
+ }
162
+
163
+ /** True when the request declares exactly an `application/json` essence. */
164
+ function isJsonRequest(req) {
165
+ const essence = String(req.headers['content-type']).split(';', 1)[0]?.trim().toLowerCase()
166
+ return essence === 'application/json'
167
+ }
168
+
169
+ /**
170
+ * Headers of accounted Sessions whose title projection has no cache row yet.
171
+ * The sidebar lists cold Sessions from that cache alone, so a missing row
172
+ * shows as "untitled" until the Session is opened; these are the rows to warm.
173
+ * @param {import('@deepseek-ai/cordis').Context} ctx - Host context.
174
+ * @param {readonly { header?: Record<string, unknown>, formatStatus?: string }[]} records - session corpus rows.
175
+ * @param {ReadonlySet<string>} accounted - ids owned by some Workspace.
176
+ * @returns {Record<string, unknown>[]} headers to warm.
177
+ */
178
+ function missingTitleCacheHeaders(ctx, records, accounted) {
179
+ const cache = typeof ctx.get === 'function' ? ctx.get('sessionProjectionCache') : undefined
180
+ if (cache === undefined || typeof cache.cachedSnapshot !== 'function') return []
181
+ const headers = []
182
+ for (const record of records) {
183
+ const header = record?.header
184
+ if (!header || typeof header.id !== 'string') continue
185
+ if (!accounted.has(String(header.id))) continue
186
+ if (record.formatStatus === 'migration-required') continue
187
+ let cached
188
+ try {
189
+ cached = cache.cachedSnapshot(header, ['title'])
190
+ } catch {
191
+ cached = undefined
192
+ }
193
+ const hasTitleRow = cached !== undefined && cached.values !== undefined && cached.values.title !== undefined
194
+ if (!hasTitleRow) headers.push(header)
195
+ }
196
+ return headers
197
+ }
198
+
199
+ /**
200
+ * Fold and persist the projection cache for the listed Sessions, one at a
201
+ * time, so `session.list` can serve their titles without opening them. The
202
+ * work runs in the background after the HTTP response; per-Session failures
203
+ * are logged and never fail the scan.
204
+ * @param {import('@deepseek-ai/cordis').Context} ctx - Host context.
205
+ * @param {readonly Record<string, unknown>[]} headers - headers to warm.
206
+ * @param {typeof DEFAULTS} settings - effective settings.
207
+ */
208
+ async function warmTitleCache(ctx, headers, settings) {
209
+ const cache = typeof ctx.get === 'function' ? ctx.get('sessionProjectionCache') : undefined
210
+ if (cache === undefined || typeof cache.coldSnapshot !== 'function') return
211
+ let budget = Math.max(0, Number(settings.warmTitleLimit) || 0)
212
+ for (const header of headers) {
213
+ if (budget <= 0) return
214
+ budget -= 1
215
+ try {
216
+ const log = await ctx.sessionQuery.readSession(header.id)
217
+ const events = Array.isArray(log?.events) ? log.events : []
218
+ if (events.length <= settings.warmMaxEvents) {
219
+ cache.coldSnapshot(log.session, log.inheritedEventCount, events)
220
+ }
221
+ } catch (error) {
222
+ ctx.logger?.warn?.(`lmw-plugin: warming title cache for "${header.id}" failed: ${errorMessage(error)}`)
223
+ }
224
+ // Yield so a warm pass never monopolizes the Host event loop.
225
+ await new Promise((resolve) => setTimeout(resolve, 0))
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Build the scan response the dialog renders.
231
+ * @param {import('@deepseek-ai/cordis').Context} ctx - Host context.
232
+ * @param {typeof DEFAULTS} settings - effective settings.
233
+ * @returns {Promise<{ body: Record<string, unknown>, warm: Record<string, unknown>[] }>} response body and title-cache warm list.
234
+ */
235
+ async function buildState(ctx, settings) {
236
+ const home = resolveDshHome(settings)
237
+ const sessionsDir = join(home, 'sessions')
238
+ const skillDir = join(home, 'skills')
239
+ const [records, sessionsDirExists, skillDirExists] = await Promise.all([
240
+ ctx.sessionQuery.listSessions(),
241
+ isDirectory(sessionsDir),
242
+ isDirectory(skillDir),
243
+ ])
244
+ const workspaces = ctx.workspaceRegistry.list()
245
+ const assigned = assignedSessionIds(workspaces)
246
+ const candidates = collectUnassigned(records, assigned, settings)
247
+ const scan = withoutEmptySessions(candidates, await findEmptySessions(ctx, candidates))
248
+
249
+ const titleIds = []
250
+ for (const group of scan.groups) {
251
+ for (const session of group.sessions) {
252
+ if (titleIds.length >= settings.titleLimit) break
253
+ titleIds.push(session.id)
254
+ }
255
+ }
256
+ if (titleIds.length > 0 && typeof ctx.sessionQuery.readTitleSnapshots === 'function') {
257
+ try {
258
+ const observations = await ctx.sessionQuery.readTitleSnapshots(titleIds)
259
+ const titles = new Map()
260
+ for (const observation of observations ?? []) {
261
+ if (observation?.status !== 'fulfilled') continue
262
+ const title = observation.value?.title?.title
263
+ if (typeof title === 'string' && title.length > 0) titles.set(observation.sessionId, title)
264
+ }
265
+ for (const group of scan.groups) {
266
+ for (const session of group.sessions) {
267
+ const title = titles.get(session.id)
268
+ if (title !== undefined) session.title = title
269
+ }
270
+ }
271
+ } catch (error) {
272
+ ctx.logger?.warn?.(`lmw-plugin: reading session titles failed: ${errorMessage(error)}`)
273
+ }
274
+ }
275
+
276
+ const groups = []
277
+ for (const group of scan.groups) {
278
+ groups.push({
279
+ cwd: group.cwd,
280
+ exists: await isDirectory(group.cwd),
281
+ sessionCount: group.sessions.length,
282
+ sessions: group.sessions,
283
+ })
284
+ }
285
+
286
+ const warm = missingTitleCacheHeaders(ctx, records, assigned)
287
+
288
+ return {
289
+ body: {
290
+ ok: true,
291
+ home,
292
+ sessionsDir: { path: sessionsDir, exists: sessionsDirExists },
293
+ skillDir: { path: skillDir, exists: skillDirExists },
294
+ counts: {
295
+ workspaces: workspaces.length,
296
+ assignedSessions: assigned.size,
297
+ unassignedSessions: scan.total,
298
+ unassignedDirectories: groups.length,
299
+ },
300
+ unassignable: scan.unassignable,
301
+ groups,
302
+ titleWarm: { pending: warm.length },
303
+ config: {
304
+ autoOpenOnStartup: settings.autoOpenOnStartup !== false,
305
+ includeSubagentSessions: settings.includeSubagentSessions === true,
306
+ includeArchivedSessions: true,
307
+ },
308
+ generatedAt: new Date().toISOString(),
309
+ },
310
+ warm,
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Apply one assignment request. The client never supplies a path: the Host
316
+ * re-derives every cwd from the current session corpus, so a stale or hostile
317
+ * body can only name Session ids.
318
+ * @param {import('@deepseek-ai/cordis').Context} ctx - Host context.
319
+ * @param {typeof DEFAULTS} settings - effective settings.
320
+ * @param {unknown} body - parsed request body.
321
+ * @returns {Promise<{ status: number, payload: Record<string, unknown> }>} HTTP status and body.
322
+ */
323
+ async function applyAssignment(ctx, settings, body) {
324
+ const requested = normalizeRequestedIds(body?.sessionIds, settings.maxSessions)
325
+ if (requested.length === 0) {
326
+ return {
327
+ status: 400,
328
+ payload: { ok: false, error: { code: 'no-sessions', message: 'the request selected no sessions' } },
329
+ }
330
+ }
331
+ const records = await ctx.sessionQuery.listSessions()
332
+ const assigned = assignedSessionIds(ctx.workspaceRegistry.list())
333
+ const plan = planAssignment(records, assigned, requested, settings)
334
+
335
+ const failed = []
336
+ const skipped = plan.alreadyAssigned.map((sessionId) => ({ sessionId, code: 'already-assigned' }))
337
+ for (const sessionId of plan.unknown) {
338
+ failed.push({
339
+ sessionId,
340
+ code: 'not-assignable',
341
+ message: 'the stored session has no usable cwd, is a subagent session, or is no longer stored',
342
+ })
343
+ }
344
+
345
+ const touched = []
346
+ let attached = 0
347
+ const cwds = [...plan.byCwd.keys()].sort((left, right) => left.localeCompare(right))
348
+ for (const cwd of cwds) {
349
+ const sessionIds = plan.byCwd.get(cwd) ?? []
350
+ let canonical
351
+ try {
352
+ canonical = await realpath(cwd)
353
+ } catch (error) {
354
+ for (const sessionId of sessionIds) {
355
+ failed.push({ sessionId, code: 'cwd-unresolvable', message: errorMessage(error) })
356
+ }
357
+ continue
358
+ }
359
+ if (!(await isDirectory(canonical))) {
360
+ for (const sessionId of sessionIds) {
361
+ failed.push({ sessionId, code: 'cwd-not-directory', message: `'${cwd}' is not a directory` })
362
+ }
363
+ continue
364
+ }
365
+ let existing
366
+ try {
367
+ existing = await ctx.workspaceRegistry.resolveByPath(canonical)
368
+ } catch {
369
+ existing = undefined
370
+ }
371
+ let workspace
372
+ try {
373
+ workspace = await ctx.workspaceRegistry.create(canonical)
374
+ } catch (error) {
375
+ for (const sessionId of sessionIds) {
376
+ failed.push({ sessionId, code: 'workspace-create-failed', message: errorMessage(error) })
377
+ }
378
+ continue
379
+ }
380
+ touched.push({
381
+ workspaceId: workspace.id,
382
+ path: workspace.path,
383
+ title: workspace.title,
384
+ created: existing === undefined,
385
+ })
386
+ for (const sessionId of sessionIds) {
387
+ try {
388
+ await workspace.attachSession(sessionId)
389
+ attached += 1
390
+ } catch (error) {
391
+ failed.push({ sessionId, code: 'attach-failed', message: errorMessage(error) })
392
+ }
393
+ }
394
+ }
395
+
396
+ return {
397
+ status: 200,
398
+ payload: {
399
+ ok: true,
400
+ assigned: attached,
401
+ workspaces: touched,
402
+ skipped,
403
+ failed,
404
+ },
405
+ }
406
+ }
407
+
408
+ /* ------------------------------------------------------------------ */
409
+ /* Session import */
410
+ /* ------------------------------------------------------------------ */
411
+
412
+ /** Path-safe single segment for a Session id (mirrors the JSONL backend). */
413
+ function encodeSegment(raw) {
414
+ if (raw.length === 0) throw new Error('cannot encode an empty path segment')
415
+ if (raw === '.') return '~002E'
416
+ if (raw === '..') return '~002E~002E'
417
+ let out = ''
418
+ for (let i = 0; i < raw.length; i++) {
419
+ const code = raw.charCodeAt(i)
420
+ const ch = String.fromCharCode(code)
421
+ if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) out += ch
422
+ else out += `~${code.toString(16).toUpperCase().padStart(4, '0')}`
423
+ }
424
+ return out
425
+ }
426
+
427
+ /** Human-navigable project folder for one cwd (mirrors the JSONL backend). */
428
+ function projectKey(cwd) {
429
+ let readable = ''
430
+ let separatorRun = false
431
+ for (let i = 0; i < cwd.length; i++) {
432
+ const code = cwd.charCodeAt(i)
433
+ const ch = String.fromCharCode(code)
434
+ if (ch === '/' || ch === '\\' || ch === ':') {
435
+ if (!separatorRun) readable += '-'
436
+ separatorRun = true
437
+ } else if (ch !== '~' && /^[A-Za-z0-9._-]$/.test(ch)) {
438
+ readable += ch
439
+ separatorRun = false
440
+ } else {
441
+ readable += `~${code.toString(16).toUpperCase().padStart(4, '0')}`
442
+ separatorRun = false
443
+ }
444
+ }
445
+ const slug = readable.replace(/^-+/, '') || 'root'
446
+ return `--${slug.slice(0, 251)}--`
447
+ }
448
+
449
+ /** The canonical generation path a stored Session with this header occupies. */
450
+ function targetSessionPath(root, cwd, id, compression) {
451
+ const project = cwd === undefined ? '_no-cwd' : projectKey(cwd)
452
+ const suffix = compression === 'zstd' ? '.jsonl.zstd' : '.jsonl'
453
+ return join(root, project, encodeSegment(id), `session.v${SESSION_FORMAT_VERSION}${suffix}`)
454
+ }
455
+
456
+ /** Parse and validate one DSH session header line (the first JSONL record). */
457
+ function parseSessionHeaderLine(text) {
458
+ const line = text.split('\n', 1)[0]
459
+ let header
460
+ try {
461
+ header = JSON.parse(line)
462
+ } catch {
463
+ throw new Error('会话文件首行不是合法的 JSON 头')
464
+ }
465
+ if (header === null || typeof header !== 'object' || Array.isArray(header)) {
466
+ throw new Error('会话文件首行不是会话头')
467
+ }
468
+ if (header.type !== 'session') throw new Error('会话文件首行缺少 type: session')
469
+ if (header.version !== SESSION_FORMAT_VERSION) {
470
+ throw new Error(`不支持的会话格式版本 v${String(header.version)}(需要 v${SESSION_FORMAT_VERSION})`)
471
+ }
472
+ if (typeof header.id !== 'string' || header.id.length === 0) throw new Error('会话头缺少 id')
473
+ if (typeof header.createdAt !== 'number') throw new Error('会话头缺少 createdAt')
474
+ if (header.cwd !== undefined && (typeof header.cwd !== 'string' || !isAbsolute(header.cwd))) {
475
+ throw new Error('会话头的 cwd 不是绝对路径')
476
+ }
477
+ return header
478
+ }
479
+
480
+ /** Read one session file's header without decoding its event body. */
481
+ async function readSessionHeaderFromFile(file) {
482
+ const info = await stat(file)
483
+ if (info.size === 0) throw new Error('会话文件为空')
484
+ if (!file.endsWith('.zstd')) {
485
+ const handle = await open(file, 'r')
486
+ try {
487
+ const buffer = Buffer.alloc(Math.min(info.size, 64 * 1024))
488
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0)
489
+ return parseSessionHeaderLine(buffer.subarray(0, bytesRead).toString('utf8'))
490
+ } finally {
491
+ await handle.close()
492
+ }
493
+ }
494
+ let length = Math.min(info.size, 64 * 1024)
495
+ for (;;) {
496
+ const handle = await open(file, 'r')
497
+ try {
498
+ const buffer = Buffer.alloc(length)
499
+ const { bytesRead } = await handle.read(buffer, 0, length, 0)
500
+ try {
501
+ return parseSessionHeaderLine(zstdDecompressSync(buffer.subarray(0, bytesRead)).toString('utf8'))
502
+ } catch (error) {
503
+ if (length >= info.size) throw error
504
+ }
505
+ } finally {
506
+ await handle.close()
507
+ }
508
+ length = Math.min(info.size, length * 8)
509
+ }
510
+ }
511
+
512
+ /**
513
+ * Locate complete Zstandard frames in a concatenated session container without
514
+ * decompressing their blocks. Mirrors the persistence backend's frame scan so a
515
+ * bounded prefix can be decoded frame by frame.
516
+ * @param {Buffer} buffer - bytes read from the session file.
517
+ * @returns {{ frames: { start: number, end: number }[], tornStart?: number }} frame ranges.
518
+ */
519
+ function scanZstdFrameRanges(buffer) {
520
+ const frames = []
521
+ let offset = 0
522
+ while (offset < buffer.length) {
523
+ const start = offset
524
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
525
+ if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) throw new Error('会话文件包含损坏的 zstd 帧')
526
+ offset += 4
527
+ if (offset === buffer.length) return { frames, tornStart: start }
528
+ const descriptor = buffer.readUInt8(offset)
529
+ offset += 1
530
+ if ((descriptor & 0x18) !== 0) throw new Error('会话文件包含保留位的 zstd 帧')
531
+ const contentSizeFlag = descriptor >>> 6
532
+ const singleSegment = (descriptor & 0x20) !== 0
533
+ const checksum = (descriptor & 0x04) !== 0
534
+ const dictionaryFlag = descriptor & 0x03
535
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
536
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
537
+ offset += (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
538
+ if (offset > buffer.length) return { frames, tornStart: start }
539
+ for (;;) {
540
+ if (buffer.length - offset < 3) return { frames, tornStart: start }
541
+ const blockHeader = buffer.readUIntLE(offset, 3)
542
+ offset += 3
543
+ const lastBlock = (blockHeader & 1) !== 0
544
+ const blockType = (blockHeader >>> 1) & 0x03
545
+ if (blockType === 0x03) throw new Error('会话文件包含保留类型的 zstd 块')
546
+ const payloadBytes = blockType === 0x01 ? 1 : blockHeader >>> 3
547
+ if (buffer.length - offset < payloadBytes) return { frames, tornStart: start }
548
+ offset += payloadBytes
549
+ if (lastBlock) break
550
+ }
551
+ if (checksum) {
552
+ if (buffer.length - offset < 4) return { frames, tornStart: start }
553
+ offset += 4
554
+ }
555
+ frames.push({ start, end: offset })
556
+ }
557
+ return { frames }
558
+ }
559
+
560
+ /** @returns {boolean} whether decoded JSONL text holds a user message. */
561
+ function textHasUserMessage(text) {
562
+ for (const line of text.split('\n')) {
563
+ if (line.startsWith(USER_MESSAGE_PREFIX)) return true
564
+ }
565
+ return false
566
+ }
567
+
568
+ /**
569
+ * Whether a session file holds at least one user message. Sessions created but
570
+ * never used store only setup events (permission/sandbox/approval) and DSH shows
571
+ * them as untitled ("未命名"); importing them adds nothing. A file larger than
572
+ * the probe window, a torn frame, a corrupt frame, or a seeded header is treated
573
+ * as non-empty so a real session is never excluded by mistake.
574
+ * @param {string} file - absolute session file path.
575
+ * @param {number} size - file size in bytes.
576
+ * @returns {Promise<boolean>} true when the session has conversation content.
577
+ */
578
+ async function sessionHasUserMessage(file, size) {
579
+ if (size <= 0) return false
580
+ const limit = Math.min(size, EMPTY_SESSION_PROBE_BYTES)
581
+ const handle = await open(file, 'r')
582
+ let buffer
583
+ try {
584
+ buffer = Buffer.alloc(limit)
585
+ const { bytesRead } = await handle.read(buffer, 0, limit, 0)
586
+ buffer = buffer.subarray(0, bytesRead)
587
+ } finally {
588
+ await handle.close()
589
+ }
590
+ if (!file.endsWith('.zstd')) {
591
+ if (textHasUserMessage(buffer.toString('utf8'))) return true
592
+ return buffer.length < size
593
+ }
594
+ let scan
595
+ try {
596
+ scan = scanZstdFrameRanges(buffer)
597
+ } catch {
598
+ return true
599
+ }
600
+ for (const range of scan.frames) {
601
+ let text
602
+ try {
603
+ text = zstdDecompressSync(buffer.subarray(range.start, range.end)).toString('utf8')
604
+ } catch {
605
+ return true
606
+ }
607
+ if (textHasUserMessage(text)) return true
608
+ }
609
+ if (buffer.length < size || scan.tornStart !== undefined) return true
610
+ return false
611
+ }
612
+
613
+ /**
614
+ * Locate the scan's Sessions that hold no user message: created but never
615
+ * used, shown by DSH as untitled. Assigning them would add a Workspace whose
616
+ * only members are blank, so the assignment dialog hides them. Snapshots come
617
+ * from the persistence index; the probe is bounded and cached by size+mtime.
618
+ * @returns {Promise<Set<string>>} ids of empty Sessions.
619
+ */
620
+ async function findEmptySessions(ctx, scan) {
621
+ const empty = new Set()
622
+ let snapshots
623
+ try {
624
+ snapshots = await ctx.sessionPersistence.list()
625
+ } catch {
626
+ return empty
627
+ }
628
+ const byId = new Map()
629
+ for (const snapshot of snapshots) byId.set(String(snapshot.header.id), snapshot)
630
+ let probes = 0
631
+ for (const group of scan.groups) {
632
+ for (const session of group.sessions) {
633
+ const snapshot = byId.get(session.id)
634
+ const path = snapshot?.location?.path
635
+ if (typeof path !== 'string') continue
636
+ let info
637
+ try {
638
+ info = await stat(path)
639
+ } catch {
640
+ continue
641
+ }
642
+ const key = `${info.size}:${info.mtimeMs}`
643
+ const cached = EMPTY_SESSION_CACHE.get(session.id)
644
+ if (cached !== undefined && cached.key === key) {
645
+ if (cached.empty) empty.add(session.id)
646
+ continue
647
+ }
648
+ if (probes >= EMPTY_SESSION_CHECK_LIMIT) continue
649
+ probes += 1
650
+ let hasMessage = true
651
+ try {
652
+ hasMessage = await sessionHasUserMessage(path, info.size)
653
+ } catch {
654
+ hasMessage = true
655
+ }
656
+ if (EMPTY_SESSION_CACHE.size >= EMPTY_SESSION_CACHE_LIMIT) EMPTY_SESSION_CACHE.clear()
657
+ EMPTY_SESSION_CACHE.set(session.id, { key, empty: !hasMessage })
658
+ if (!hasMessage) empty.add(session.id)
659
+ }
660
+ }
661
+ return empty
662
+ }
663
+
664
+ /** Drop empty Sessions from a scan and report how many were hidden. */
665
+ function withoutEmptySessions(scan, emptyIds) {
666
+ if (emptyIds.size === 0) return scan
667
+ const groups = []
668
+ let total = 0
669
+ for (const group of scan.groups) {
670
+ const sessions = group.sessions.filter((session) => !emptyIds.has(session.id))
671
+ if (sessions.length === 0) continue
672
+ groups.push({ cwd: group.cwd, sessions })
673
+ total += sessions.length
674
+ }
675
+ return { groups, total, unassignable: { ...scan.unassignable, empty: emptyIds.size } }
676
+ }
677
+
678
+ /** Collect canonical session files under a user-selected directory (bounded). */async function collectSessionFiles(dir, limit, depth = 0) {
679
+ if (limit <= 0 || depth > 3) return []
680
+ let entries
681
+ try {
682
+ entries = await readdir(dir, { withFileTypes: true })
683
+ } catch {
684
+ return []
685
+ }
686
+ const files = []
687
+ for (const entry of entries) {
688
+ if (files.length >= limit) return files
689
+ const path = join(dir, entry.name)
690
+ if (entry.isDirectory()) {
691
+ files.push(...await collectSessionFiles(path, limit - files.length, depth + 1))
692
+ } else if (entry.isFile() && SESSION_FILE_NAME.test(entry.name)) {
693
+ files.push(path)
694
+ }
695
+ }
696
+ return files
697
+ }
698
+
699
+ /** The artifact encoding in use, inferred from the stored sessions. */
700
+ function targetCompression(snapshots) {
701
+ for (const snapshot of snapshots) {
702
+ const path = snapshot.location?.path
703
+ if (typeof path !== 'string') continue
704
+ if (path.endsWith('.jsonl.zstd')) return 'zstd'
705
+ if (path.endsWith('.jsonl')) return 'none'
706
+ }
707
+ return 'zstd'
708
+ }
709
+
710
+ /**
711
+ * Scan an import source and classify every session against the stored corpus.
712
+ * @returns {{ status: number, payload: Record<string, unknown> }} HTTP status and body.
713
+ */
714
+ async function scanImportSource(ctx, settings, rawPath) {
715
+ const source = typeof rawPath === 'string' ? rawPath.trim() : ''
716
+ if (source.length === 0) {
717
+ return { status: 400, payload: { ok: false, error: { code: 'no-path', message: '请填写要导入的目录' } } }
718
+ }
719
+ if (!isAbsolute(source)) {
720
+ return { status: 400, payload: { ok: false, error: { code: 'relative-path', message: '目录必须是绝对路径' } } }
721
+ }
722
+ let info
723
+ try {
724
+ info = await stat(source)
725
+ } catch {
726
+ return { status: 400, payload: { ok: false, error: { code: 'missing-dir', message: `目录不存在或无法访问:${source}` } } }
727
+ }
728
+ if (!info.isDirectory()) {
729
+ return { status: 400, payload: { ok: false, error: { code: 'not-dir', message: '目标不是目录' } } }
730
+ }
731
+ const root = join(resolveDshHome(settings), 'sessions')
732
+ const snapshots = await ctx.sessionPersistence.list()
733
+ const existing = new Map()
734
+ for (const snapshot of snapshots) existing.set(String(snapshot.header.id), snapshot)
735
+ const compression = targetCompression(snapshots)
736
+ const files = await collectSessionFiles(source, settings.importMaxFiles)
737
+ if (files.length === 0) {
738
+ return {
739
+ status: 422,
740
+ payload: {
741
+ ok: false,
742
+ error: { code: 'no-sessions', message: '目录下没有找到 DSH 会话文件(session.v4.jsonl.zstd)' },
743
+ source,
744
+ },
745
+ }
746
+ }
747
+
748
+ const entries = []
749
+ const seen = new Map()
750
+ let skippedSubagent = 0
751
+ let skippedLarge = 0
752
+ for (const file of files) {
753
+ let header
754
+ let size = 0
755
+ let mtime = 0
756
+ try {
757
+ const fileStat = await stat(file)
758
+ size = fileStat.size
759
+ mtime = fileStat.mtimeMs
760
+ if (size > settings.importMaxFileBytes) {
761
+ skippedLarge += 1
762
+ continue
763
+ }
764
+ header = await readSessionHeaderFromFile(file)
765
+ } catch (error) {
766
+ entries.push({
767
+ id: file,
768
+ cwd: undefined,
769
+ createdAt: 0,
770
+ status: 'invalid',
771
+ warning: null,
772
+ reason: errorMessage(error),
773
+ sourceFile: file,
774
+ sourceBytes: size,
775
+ sourceMtime: mtime,
776
+ })
777
+ continue
778
+ }
779
+ if (header.origin === 'subagent') {
780
+ skippedSubagent += 1
781
+ continue
782
+ }
783
+ const sourceIsZstd = file.endsWith('.zstd')
784
+ if (sourceIsZstd !== (compression === 'zstd')) {
785
+ entries.push({
786
+ id: String(header.id),
787
+ cwd: header.cwd,
788
+ createdAt: header.createdAt,
789
+ status: 'invalid',
790
+ warning: null,
791
+ reason: `会话文件的压缩格式(${sourceIsZstd ? 'zstd' : 'plain'})与当前会话目录(${compression})不一致`,
792
+ sourceFile: file,
793
+ sourceBytes: size,
794
+ sourceMtime: mtime,
795
+ })
796
+ continue
797
+ }
798
+ const id = String(header.id)
799
+ // A session created but never used stores only setup events and renders as
800
+ // "未命名" in DSH; it carries nothing worth importing, so it is never
801
+ // addable. Seeded logs inherit a predecessor's content and are exempt.
802
+ if (header.isSeeded !== true) {
803
+ let hasConversation = true
804
+ try {
805
+ hasConversation = await sessionHasUserMessage(file, size)
806
+ } catch {
807
+ hasConversation = true
808
+ }
809
+ if (!hasConversation) {
810
+ entries.push({
811
+ id,
812
+ cwd: header.cwd,
813
+ createdAt: header.createdAt,
814
+ status: 'empty',
815
+ warning: null,
816
+ reason: '空会话:没有任何对话消息,DSH 中显示为「未命名」',
817
+ sourceFile: file,
818
+ sourceBytes: size,
819
+ sourceMtime: mtime,
820
+ })
821
+ continue
822
+ }
823
+ }
824
+ if (seen.has(id)) {
825
+ entries.push({
826
+ id,
827
+ cwd: header.cwd,
828
+ createdAt: header.createdAt,
829
+ status: 'duplicate',
830
+ warning: null,
831
+ reason: '同一会话在该目录中出现了多次,已跳过后续副本',
832
+ sourceFile: file,
833
+ sourceBytes: size,
834
+ sourceMtime: mtime,
835
+ })
836
+ continue
837
+ }
838
+ seen.set(id, file)
839
+ const snapshot = existing.get(id)
840
+ const entry = {
841
+ id,
842
+ cwd: header.cwd,
843
+ createdAt: header.createdAt,
844
+ sourceFile: file,
845
+ sourceBytes: size,
846
+ sourceMtime: mtime,
847
+ existingBytes: snapshot?.sizeBytes,
848
+ existingMtime: undefined,
849
+ existingPath: snapshot?.location?.path,
850
+ status: 'new',
851
+ warning: null,
852
+ reason: undefined,
853
+ }
854
+ if (snapshot === undefined) {
855
+ entries.push(entry)
856
+ continue
857
+ }
858
+ const live = typeof ctx.sessions?.get === 'function' ? ctx.sessions.get(id) : undefined
859
+ if (live !== undefined) {
860
+ entry.status = 'live'
861
+ entry.reason = '该会话正在 DSH 中打开,不能替换'
862
+ entries.push(entry)
863
+ continue
864
+ }
865
+ if ((snapshot.header.cwd ?? '') !== (header.cwd ?? '')) {
866
+ entry.status = 'conflict'
867
+ entry.reason = '同一会话 ID 的工作区不一致,不能替换'
868
+ entries.push(entry)
869
+ continue
870
+ }
871
+ if (typeof snapshot.location?.path === 'string') {
872
+ try {
873
+ entry.existingMtime = (await stat(snapshot.location.path)).mtimeMs
874
+ } catch {
875
+ entry.existingMtime = undefined
876
+ }
877
+ }
878
+ const larger = size > (snapshot.sizeBytes ?? 0)
879
+ const newer = entry.existingMtime !== undefined && mtime > entry.existingMtime
880
+ if (!larger && !newer) {
881
+ entry.status = 'unchanged'
882
+ entry.reason = '目录内副本不比现有会话更大或更新'
883
+ entries.push(entry)
884
+ continue
885
+ }
886
+ entry.status = 'replace'
887
+ entry.warning = larger && newer ? null : (larger ? 'larger-only' : 'newer-only')
888
+ entries.push(entry)
889
+ }
890
+
891
+ const addable = entries.filter((entry) => entry.status === 'new' || entry.status === 'replace')
892
+ return {
893
+ status: 200,
894
+ payload: {
895
+ ok: true,
896
+ source,
897
+ root,
898
+ compression,
899
+ entries,
900
+ scannedFiles: files.length,
901
+ counts: {
902
+ total: entries.length,
903
+ addable: addable.length,
904
+ new: entries.filter((entry) => entry.status === 'new').length,
905
+ replace: entries.filter((entry) => entry.status === 'replace').length,
906
+ unchanged: entries.filter((entry) => entry.status === 'unchanged').length,
907
+ empty: entries.filter((entry) => entry.status === 'empty').length,
908
+ blocked: entries.filter((entry) => entry.status === 'live' || entry.status === 'conflict'
909
+ || entry.status === 'empty').length,
910
+ invalid: entries.filter((entry) => entry.status === 'invalid' || entry.status === 'duplicate').length,
911
+ skippedSubagent,
912
+ skippedLarge,
913
+ },
914
+ generatedAt: new Date().toISOString(),
915
+ },
916
+ }
917
+ }
918
+
919
+ /** Report each Workspace's directory state; sessions of a missing directory are offline. */
920
+ async function collectWorkspaceStatus(ctx) {
921
+ const rows = []
922
+ for (const workspace of ctx.workspaceRegistry.list()) {
923
+ let missing = false
924
+ try {
925
+ missing = typeof workspace.status === 'function'
926
+ ? (await workspace.status()) === 'missing-dir'
927
+ : !(await isDirectory(workspace.path))
928
+ } catch {
929
+ missing = !(await isDirectory(workspace.path))
930
+ }
931
+ rows.push({
932
+ id: String(workspace.id),
933
+ path: workspace.path,
934
+ title: workspace.title,
935
+ missing,
936
+ sessionIds: (workspace.sessionIds ?? []).map(String),
937
+ })
938
+ }
939
+ return rows
940
+ }
941
+
942
+ /** Latest Session-log activity per Workspace, used by the activity sort. */
943
+ async function workspaceActivity(ctx) {
944
+ let snapshots = []
945
+ try {
946
+ snapshots = await ctx.sessionPersistence.list()
947
+ } catch {
948
+ return new Map()
949
+ }
950
+ const sessionTime = new Map()
951
+ for (const snapshot of snapshots) {
952
+ const id = String(snapshot.header.id)
953
+ let time = typeof snapshot.header.createdAt === 'number' ? snapshot.header.createdAt : 0
954
+ const path = snapshot.location?.path
955
+ if (typeof path === 'string') {
956
+ try {
957
+ time = Math.max(time, (await stat(path)).mtimeMs)
958
+ } catch {
959
+ // A missing log keeps its header time.
960
+ }
961
+ }
962
+ sessionTime.set(id, time)
963
+ }
964
+ const activity = new Map()
965
+ for (const workspace of ctx.workspaceRegistry.list()) {
966
+ let latest = 0
967
+ for (const id of workspace.sessionIds ?? []) latest = Math.max(latest, sessionTime.get(String(id)) ?? 0)
968
+ if (latest === 0) {
969
+ const updated = Date.parse(workspace.updatedAt ?? '')
970
+ if (Number.isFinite(updated)) latest = updated
971
+ }
972
+ activity.set(String(workspace.id), latest)
973
+ }
974
+ return activity
975
+ }
976
+
977
+ /** Order workspaces by path, title, or latest session activity, then persist via insertBefore. */
978
+ async function sortWorkspaceOrder(ctx, mode) {
979
+ const workspaces = ctx.workspaceRegistry.list()
980
+ const activity = mode === 'activity' ? await workspaceActivity(ctx) : undefined
981
+ const compare = (left, right) => {
982
+ if (mode === 'activity') {
983
+ const a = activity?.get(String(left.id)) ?? 0
984
+ const b = activity?.get(String(right.id)) ?? 0
985
+ if (a !== b) return b - a
986
+ return left.path.localeCompare(right.path)
987
+ }
988
+ if (mode === 'title') {
989
+ const a = (left.title ?? '').toLowerCase()
990
+ const b = (right.title ?? '').toLowerCase()
991
+ if (a !== b) return a < b ? -1 : 1
992
+ }
993
+ return left.path.localeCompare(right.path)
994
+ }
995
+ const ordered = [...workspaces].sort(compare)
996
+ let anchor
997
+ for (let index = ordered.length - 1; index >= 0; index -= 1) {
998
+ const id = ordered[index].id
999
+ await ctx.workspaceRegistry.insertBefore(id, anchor)
1000
+ anchor = id
1001
+ }
1002
+ return ordered.map((workspace) => ({ id: String(workspace.id), path: workspace.path, title: workspace.title }))
1003
+ }
1004
+
1005
+ /** Fold and persist one session's projection cache (fail-soft). */
1006
+ async function warmOneSession(ctx, id, settings) {
1007
+ const cache = typeof ctx.get === 'function' ? ctx.get('sessionProjectionCache') : undefined
1008
+ if (cache === undefined || typeof cache.coldSnapshot !== 'function') return
1009
+ try {
1010
+ const log = await ctx.sessionQuery.readSession(id)
1011
+ const events = Array.isArray(log?.events) ? log.events : []
1012
+ if (events.length <= settings.warmMaxEvents) {
1013
+ cache.coldSnapshot(log.session, log.inheritedEventCount, events)
1014
+ }
1015
+ } catch (error) {
1016
+ ctx.logger?.warn?.(`lmw-plugin: warming title cache for "${id}" failed: ${errorMessage(error)}`)
1017
+ }
1018
+ }
1019
+
1020
+ /**
1021
+ * Copy the selected sessions into the DSH session root, replacing identical
1022
+ * ones (guarded by a backup) and assigning new ones through the workspace
1023
+ * registry, then warm their titles.
1024
+ * @returns {{ status: number, payload: Record<string, unknown> }} HTTP status and body.
1025
+ */
1026
+ async function applyImportSelection(ctx, settings, rawPath, requestedIds) {
1027
+ const ids = normalizeRequestedIds(requestedIds, settings.importMaxFiles)
1028
+ if (ids.length === 0) {
1029
+ return { status: 400, payload: { ok: false, error: { code: 'no-sessions', message: '未选择要添加的会话' } } }
1030
+ }
1031
+ const scan = await scanImportSource(ctx, settings, rawPath)
1032
+ if (scan.status !== 200) return scan
1033
+ const root = scan.payload.root
1034
+ const compression = scan.payload.compression
1035
+ const byId = new Map()
1036
+ for (const entry of scan.payload.entries) {
1037
+ if (entry.id !== entry.sourceFile) byId.set(entry.id, entry)
1038
+ }
1039
+
1040
+ const results = []
1041
+ let added = 0
1042
+ let replaced = 0
1043
+ let failed = 0
1044
+ let skipped = 0
1045
+ for (const id of ids) {
1046
+ const entry = byId.get(id)
1047
+ if (entry === undefined) {
1048
+ results.push({ sessionId: id, action: 'failed', message: '该会话不在本次识别结果中' })
1049
+ failed += 1
1050
+ continue
1051
+ }
1052
+ if (entry.status === 'new') {
1053
+ try {
1054
+ const target = targetSessionPath(root, entry.cwd, id, compression)
1055
+ await mkdir(dirname(target), { recursive: true })
1056
+ await copyFile(entry.sourceFile, target)
1057
+ let workspace
1058
+ if (typeof entry.cwd === 'string' && entry.cwd.length > 0) {
1059
+ try {
1060
+ const canonical = await realpath(entry.cwd)
1061
+ if (await isDirectory(canonical)) {
1062
+ workspace = await ctx.workspaceRegistry.create(canonical)
1063
+ await workspace.attachSession(id)
1064
+ }
1065
+ } catch (error) {
1066
+ ctx.logger?.warn?.(`lmw-plugin: assigning imported session "${id}" failed: ${errorMessage(error)}`)
1067
+ }
1068
+ }
1069
+ await warmOneSession(ctx, id, settings)
1070
+ results.push({
1071
+ sessionId: id,
1072
+ action: 'added',
1073
+ cwd: entry.cwd,
1074
+ workspace: workspace === undefined
1075
+ ? undefined
1076
+ : { workspaceId: workspace.id, path: workspace.path, title: workspace.title },
1077
+ })
1078
+ added += 1
1079
+ } catch (error) {
1080
+ results.push({ sessionId: id, action: 'failed', message: errorMessage(error) })
1081
+ failed += 1
1082
+ }
1083
+ continue
1084
+ }
1085
+ if (entry.status === 'replace') {
1086
+ const live = typeof ctx.sessions?.get === 'function' ? ctx.sessions.get(id) : undefined
1087
+ if (live !== undefined || typeof entry.existingPath !== 'string') {
1088
+ results.push({ sessionId: id, action: 'skipped', message: live !== undefined ? '该会话正在使用中' : '找不到现有会话文件' })
1089
+ skipped += 1
1090
+ continue
1091
+ }
1092
+ const backup = `${entry.existingPath}.lmw-bak`
1093
+ try {
1094
+ await copyFile(entry.existingPath, backup)
1095
+ try {
1096
+ await copyFile(entry.sourceFile, entry.existingPath)
1097
+ } catch (error) {
1098
+ try {
1099
+ await copyFile(backup, entry.existingPath)
1100
+ } catch {
1101
+ // The backup file remains for manual recovery.
1102
+ }
1103
+ throw error
1104
+ }
1105
+ await warmOneSession(ctx, id, settings)
1106
+ results.push({ sessionId: id, action: 'replaced', cwd: entry.cwd })
1107
+ replaced += 1
1108
+ } catch (error) {
1109
+ results.push({ sessionId: id, action: 'failed', message: errorMessage(error) })
1110
+ failed += 1
1111
+ } finally {
1112
+ await rm(backup, { force: true }).catch(() => {})
1113
+ }
1114
+ continue
1115
+ }
1116
+ results.push({ sessionId: id, action: 'skipped', message: entry.reason ?? entry.status })
1117
+ skipped += 1
1118
+ }
1119
+
1120
+ return {
1121
+ status: 200,
1122
+ payload: {
1123
+ ok: true,
1124
+ source: scan.payload.source,
1125
+ results,
1126
+ counts: { added, replaced, failed, skipped },
1127
+ generatedAt: new Date().toISOString(),
1128
+ },
1129
+ }
1130
+ }
1131
+
1132
+ /**
1133
+ * Register the three routes on the composition's web server.
1134
+ * @param {import('@deepseek-ai/cordis').Context} ctx - Host context.
1135
+ * @param {typeof DEFAULTS} settings - effective settings.
1136
+ */
1137
+ export function apply(ctx, config) {
1138
+ const settings = resolveSettings(config)
1139
+ const connection = Reflect.get(ctx, 'connection')
1140
+ const rejected = (req, res) => {
1141
+ let rejection
1142
+ try {
1143
+ rejection = connection?.requestRejection?.(req)
1144
+ } catch {
1145
+ rejection = 403
1146
+ }
1147
+ if (rejection === undefined) return false
1148
+ res.statusCode = rejection
1149
+ res.end()
1150
+ return true
1151
+ }
1152
+ const internalFailure = (res, error, label) => {
1153
+ ctx.logger?.warn?.(`lmw-plugin: ${label} failed: ${errorMessage(error)}`)
1154
+ sendJson(res, 500, { ok: false, error: { code: 'internal', message: errorMessage(error) } })
1155
+ }
1156
+
1157
+ // One background warm pass at a time; a later scan picks up whatever it missed.
1158
+ let warming = false
1159
+ const startWarm = (headers) => {
1160
+ if (warming || headers.length === 0) return
1161
+ warming = true
1162
+ void warmTitleCache(ctx, headers, settings)
1163
+ .catch((error) => {
1164
+ ctx.logger?.warn?.(`lmw-plugin: title warm pass failed: ${errorMessage(error)}`)
1165
+ })
1166
+ .finally(() => {
1167
+ warming = false
1168
+ })
1169
+ }
1170
+
1171
+ ctx.effect(() => ctx.webServer.register({
1172
+ kind: 'exact',
1173
+ path: STATE_PATH,
1174
+ handler: async (req, res) => {
1175
+ if (rejected(req, res)) return
1176
+ if (req.method !== 'GET') {
1177
+ sendMethodNotAllowed(res, 'GET')
1178
+ return
1179
+ }
1180
+ try {
1181
+ const { body, warm } = await buildState(ctx, settings)
1182
+ sendJson(res, 200, body)
1183
+ if (settings.warmTitleCache !== false) startWarm(warm)
1184
+ } catch (error) {
1185
+ internalFailure(res, error, 'state scan')
1186
+ }
1187
+ },
1188
+ }), `lmw-plugin: GET ${STATE_PATH}`)
1189
+
1190
+ ctx.effect(() => ctx.webServer.register({
1191
+ kind: 'exact',
1192
+ path: ASSIGN_PATH,
1193
+ handler: async (req, res) => {
1194
+ if (rejected(req, res)) return
1195
+ if (req.method !== 'POST') {
1196
+ sendMethodNotAllowed(res, 'POST')
1197
+ return
1198
+ }
1199
+ if (!isJsonRequest(req)) {
1200
+ sendJson(res, 415, { ok: false, error: { code: 'unsupported-media-type', message: 'content-type must be application/json' } })
1201
+ return
1202
+ }
1203
+ const body = await readJsonBody(req)
1204
+ if (!body.ok) {
1205
+ sendJson(res, body.status, { ok: false, error: { code: 'bad-body', message: 'the request body was rejected' } })
1206
+ return
1207
+ }
1208
+ try {
1209
+ const result = await applyAssignment(ctx, settings, body.value)
1210
+ sendJson(res, result.status, result.payload)
1211
+ } catch (error) {
1212
+ internalFailure(res, error, 'assignment')
1213
+ }
1214
+ },
1215
+ }), `lmw-plugin: POST ${ASSIGN_PATH}`)
1216
+
1217
+ ctx.effect(() => ctx.webServer.register({
1218
+ kind: 'exact',
1219
+ path: SKILLS_PATH,
1220
+ handler: async (req, res) => {
1221
+ if (rejected(req, res)) return
1222
+ if (req.method !== 'POST') {
1223
+ sendMethodNotAllowed(res, 'POST')
1224
+ return
1225
+ }
1226
+ if (!isJsonRequest(req)) {
1227
+ sendJson(res, 415, { ok: false, error: { code: 'unsupported-media-type', message: 'content-type must be application/json' } })
1228
+ return
1229
+ }
1230
+ const body = await readJsonBody(req)
1231
+ if (!body.ok) {
1232
+ sendJson(res, body.status, { ok: false, error: { code: 'bad-body', message: 'the request body was rejected' } })
1233
+ return
1234
+ }
1235
+ if (body.value?.action !== 'create') {
1236
+ sendJson(res, 400, { ok: false, error: { code: 'unsupported-action', message: 'action must be "create"' } })
1237
+ return
1238
+ }
1239
+ const skillDir = join(resolveDshHome(settings), 'skills')
1240
+ try {
1241
+ const existed = await isDirectory(skillDir)
1242
+ if (!existed) await mkdir(skillDir, { recursive: true })
1243
+ sendJson(res, 200, { ok: true, path: skillDir, exists: true, created: !existed })
1244
+ } catch (error) {
1245
+ internalFailure(res, error, 'skills directory creation')
1246
+ }
1247
+ },
1248
+ }), `lmw-plugin: POST ${SKILLS_PATH}`)
1249
+
1250
+ ctx.effect(() => ctx.webServer.register({
1251
+ kind: 'exact',
1252
+ path: IMPORT_SCAN_PATH,
1253
+ handler: async (req, res) => {
1254
+ if (rejected(req, res)) return
1255
+ if (req.method !== 'POST') {
1256
+ sendMethodNotAllowed(res, 'POST')
1257
+ return
1258
+ }
1259
+ if (!isJsonRequest(req)) {
1260
+ sendJson(res, 415, { ok: false, error: { code: 'unsupported-media-type', message: 'content-type must be application/json' } })
1261
+ return
1262
+ }
1263
+ const body = await readJsonBody(req)
1264
+ if (!body.ok) {
1265
+ sendJson(res, body.status, { ok: false, error: { code: 'bad-body', message: 'the request body was rejected' } })
1266
+ return
1267
+ }
1268
+ try {
1269
+ const result = await scanImportSource(ctx, settings, body.value?.path)
1270
+ sendJson(res, result.status, result.payload)
1271
+ } catch (error) {
1272
+ internalFailure(res, error, 'import scan')
1273
+ }
1274
+ },
1275
+ }), `lmw-plugin: POST ${IMPORT_SCAN_PATH}`)
1276
+
1277
+ ctx.effect(() => ctx.webServer.register({
1278
+ kind: 'exact',
1279
+ path: IMPORT_APPLY_PATH,
1280
+ handler: async (req, res) => {
1281
+ if (rejected(req, res)) return
1282
+ if (req.method !== 'POST') {
1283
+ sendMethodNotAllowed(res, 'POST')
1284
+ return
1285
+ }
1286
+ if (!isJsonRequest(req)) {
1287
+ sendJson(res, 415, { ok: false, error: { code: 'unsupported-media-type', message: 'content-type must be application/json' } })
1288
+ return
1289
+ }
1290
+ const body = await readJsonBody(req)
1291
+ if (!body.ok) {
1292
+ sendJson(res, body.status, { ok: false, error: { code: 'bad-body', message: 'the request body was rejected' } })
1293
+ return
1294
+ }
1295
+ try {
1296
+ const result = await applyImportSelection(ctx, settings, body.value?.path, body.value?.sessionIds)
1297
+ sendJson(res, result.status, result.payload)
1298
+ } catch (error) {
1299
+ internalFailure(res, error, 'import apply')
1300
+ }
1301
+ },
1302
+ }), `lmw-plugin: POST ${IMPORT_APPLY_PATH}`)
1303
+
1304
+ ctx.effect(() => ctx.webServer.register({
1305
+ kind: 'exact',
1306
+ path: WORKSPACE_STATUS_PATH,
1307
+ handler: async (req, res) => {
1308
+ if (rejected(req, res)) return
1309
+ if (req.method !== 'GET') {
1310
+ sendMethodNotAllowed(res, 'GET')
1311
+ return
1312
+ }
1313
+ try {
1314
+ const workspaces = await collectWorkspaceStatus(ctx)
1315
+ sendJson(res, 200, { ok: true, workspaces, generatedAt: new Date().toISOString() })
1316
+ } catch (error) {
1317
+ internalFailure(res, error, 'workspace status')
1318
+ }
1319
+ },
1320
+ }), `lmw-plugin: GET ${WORKSPACE_STATUS_PATH}`)
1321
+
1322
+ ctx.effect(() => ctx.webServer.register({
1323
+ kind: 'exact',
1324
+ path: WORKSPACE_SORT_PATH,
1325
+ handler: async (req, res) => {
1326
+ if (rejected(req, res)) return
1327
+ if (req.method !== 'POST') {
1328
+ sendMethodNotAllowed(res, 'POST')
1329
+ return
1330
+ }
1331
+ if (!isJsonRequest(req)) {
1332
+ sendJson(res, 415, { ok: false, error: { code: 'unsupported-media-type', message: 'content-type must be application/json' } })
1333
+ return
1334
+ }
1335
+ const body = await readJsonBody(req)
1336
+ if (!body.ok) {
1337
+ sendJson(res, body.status, { ok: false, error: { code: 'bad-body', message: 'the request body was rejected' } })
1338
+ return
1339
+ }
1340
+ const mode = body.value?.mode
1341
+ if (mode !== 'path' && mode !== 'title' && mode !== 'activity') {
1342
+ sendJson(res, 400, { ok: false, error: { code: 'unsupported-mode', message: 'mode must be path, title, or activity' } })
1343
+ return
1344
+ }
1345
+ try {
1346
+ const order = await sortWorkspaceOrder(ctx, mode)
1347
+ sendJson(res, 200, { ok: true, mode, order })
1348
+ } catch (error) {
1349
+ internalFailure(res, error, 'workspace sort')
1350
+ }
1351
+ },
1352
+ }), `lmw-plugin: POST ${WORKSPACE_SORT_PATH}`)
1353
+ }