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