dsh-seal-scripts 0.5.2 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +220 -167
- package/README.md +214 -186
- package/lib/client.js +322 -17
- package/lib/core/index.js +11 -1
- package/lib/host/capabilities.js +4 -0
- package/lib/host/compact-delete.js +188 -24
- package/lib/host/delete.js +32 -4
- package/lib/host/import-session.js +498 -0
- package/lib/host/routes/sessions.js +47 -1
- package/package.json +4 -3
|
@@ -0,0 +1,498 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会话导入(0.6.1):把 DSH 导出的 dsh-session-<id>.zip 装进本机,
|
|
3
|
+
* 不重启,会话立刻可开,图片与文件都能显示。
|
|
4
|
+
*
|
|
5
|
+
* 格式来源(实测):导出包是**未压缩的 JSONL**(session.v4.jsonl,第一行是户口本),
|
|
6
|
+
* 落盘要转成 zstd:**首帧只装户口本一行**(DSH 有硬断言),正文一帧,两帧都在行边界结束。
|
|
7
|
+
* 图片在包里叫 media/sha256:<哈希>.<后缀>,要落两处:
|
|
8
|
+
* sessions/<格子>/<id>/media/sha256_<哈希>.<后缀> (会话自己的 media)
|
|
9
|
+
* attachments/v1/objects/<前2>/<哈希> (全局附件库,纯哈希)
|
|
10
|
+
* 文件在包里叫 files/<前2>/<哈希>/<原名>,落到 attachments/v1/files/<前2>/<哈希>/<原名>
|
|
11
|
+
* 与 file-objects/<前2>/<哈希>(附件库的规范对象)。
|
|
12
|
+
*
|
|
13
|
+
* 撞号两条(交接文件实测):同一 id 出现在两个格子、或户口本 cwd 与格子不符,
|
|
14
|
+
* 都会让会话列表整份 500。所以同 id 在别的 cwd 时一律换新 id,绝不覆盖别人的会话。
|
|
15
|
+
*
|
|
16
|
+
* 只依赖 node 内置模块与仓库里的 zip / projectKey。
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs'
|
|
20
|
+
import fsp from 'node:fs/promises'
|
|
21
|
+
import path from 'node:path'
|
|
22
|
+
import readline from 'node:readline'
|
|
23
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
24
|
+
import zlib from 'node:zlib'
|
|
25
|
+
import { projectKey } from '../core/project-key.js'
|
|
26
|
+
import { forEachZipEntry, readZipCentralFromFile } from '../core/zip.js'
|
|
27
|
+
|
|
28
|
+
export const SESSION_LOG_NAME = 'session.v4.jsonl.zstd'
|
|
29
|
+
|
|
30
|
+
/** 宿主能不能写 zstd(Node 22.15+)。导入必须能写,否则拒绝并说清楚。 */
|
|
31
|
+
export function canWriteZstd() {
|
|
32
|
+
return typeof zlib.zstdCompressSync === 'function' && typeof zlib.createZstdCompress === 'function'
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const ROOT_LOG = /^session(?:\.v[1-9][0-9]*)?\.jsonl$/
|
|
36
|
+
const SUB_LOG = /^subagents\/([^/]+)\/session(?:\.v[1-9][0-9]*)?\.jsonl$/
|
|
37
|
+
const MEDIA_NAME = /^media\/sha256:([a-f0-9]{64})\.([A-Za-z0-9]+)$/
|
|
38
|
+
const FILE_NAME = /^files\/([0-9a-f]{2})\/([a-f0-9]{64})\/(.+)$/
|
|
39
|
+
|
|
40
|
+
const message = (e) => (e instanceof Error ? e.message : String(e))
|
|
41
|
+
|
|
42
|
+
function stamp() {
|
|
43
|
+
const d = new Date()
|
|
44
|
+
const p = (n) => String(n).padStart(2, '0')
|
|
45
|
+
return d.getFullYear() + p(d.getMonth() + 1) + p(d.getDate()) + '-' + p(d.getHours()) + p(d.getMinutes()) + p(d.getSeconds())
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 一条 zip 条目的内容向量:只流一次,边写边算 sha256。 */
|
|
49
|
+
async function streamEntryToFile(entry, file) {
|
|
50
|
+
const handle = await fsp.open(file, 'w')
|
|
51
|
+
const digest = createHash('sha256')
|
|
52
|
+
let bytes = 0
|
|
53
|
+
try {
|
|
54
|
+
for await (const chunk of entry.read()) {
|
|
55
|
+
const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
56
|
+
digest.update(buf)
|
|
57
|
+
await handle.write(buf)
|
|
58
|
+
bytes += buf.length
|
|
59
|
+
}
|
|
60
|
+
} finally {
|
|
61
|
+
await handle.close().catch(() => {})
|
|
62
|
+
}
|
|
63
|
+
return { bytes, sha256: digest.digest('hex') }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** 读一个文件的前一行(以 \n 结尾);包里的户口本就这一行。 */
|
|
67
|
+
async function firstLineOf(file, limit = 4 * 1024 * 1024) {
|
|
68
|
+
const handle = await fsp.open(file, 'r')
|
|
69
|
+
try {
|
|
70
|
+
const chunks = []
|
|
71
|
+
let total = 0
|
|
72
|
+
while (total < limit) {
|
|
73
|
+
const buf = Buffer.allocUnsafe(64 * 1024)
|
|
74
|
+
const { bytesRead } = await handle.read(buf, 0, buf.length, total)
|
|
75
|
+
if (bytesRead <= 0) break
|
|
76
|
+
const hit = buf.subarray(0, bytesRead).indexOf(0x0a)
|
|
77
|
+
if (hit >= 0) { chunks.push(buf.subarray(0, hit + 1)); return Buffer.concat(chunks) }
|
|
78
|
+
chunks.push(buf.subarray(0, bytesRead))
|
|
79
|
+
total += bytesRead
|
|
80
|
+
}
|
|
81
|
+
throw new Error('the exported log has no complete header line')
|
|
82
|
+
} finally {
|
|
83
|
+
await handle.close().catch(() => {})
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 把一份 JSONL 文本文件压成 DSH 认的 zstd 日志:首帧恰好一行,正文第二帧。
|
|
89
|
+
* 走流式:日志多大都不把整份读进内存。
|
|
90
|
+
*/
|
|
91
|
+
async function packLog(srcFile, destFile) {
|
|
92
|
+
const head = await firstLineOf(srcFile)
|
|
93
|
+
if (head.length < 2 || head[head.length - 1] !== 0x0a) throw new Error('the exported log header line is malformed')
|
|
94
|
+
const opts = { params: { [zlib.constants.ZSTD_c_checksumFlag]: 1 } }
|
|
95
|
+
const out = await fsp.open(destFile, 'w')
|
|
96
|
+
try {
|
|
97
|
+
await out.write(zlib.zstdCompressSync(head, opts))
|
|
98
|
+
// 正文帧:从户口本之后的位置开始流式压。空正文也给一帧(合法空帧)。
|
|
99
|
+
const rest = fs.createReadStream(srcFile, { start: head.length, highWaterMark: 1 << 20 })
|
|
100
|
+
const zs = zlib.createZstdCompress(opts)
|
|
101
|
+
rest.pipe(zs)
|
|
102
|
+
for await (const chunk of zs) await out.write(chunk)
|
|
103
|
+
} finally {
|
|
104
|
+
await out.close().catch(() => {})
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 前端左侧列表的条目形状(照 dsh-api-session-controller 的 summarizeCold)。
|
|
110
|
+
* 导入只落盘、不建 Session 对象,拿不到 live summary,就按冷会话如实拼一份。
|
|
111
|
+
*/
|
|
112
|
+
function coldSummary(header) {
|
|
113
|
+
return {
|
|
114
|
+
sessionId: header.id,
|
|
115
|
+
updatedAt: Math.max(Number(header.createdAt) || 0, 0),
|
|
116
|
+
agentAvailable: false,
|
|
117
|
+
formatStatus: 'current',
|
|
118
|
+
running: false,
|
|
119
|
+
blank: false,
|
|
120
|
+
...(header.parentSession === void 0 ? {} : { parentSessionId: header.parentSession }),
|
|
121
|
+
...(header.origin === void 0 ? {} : { origin: header.origin }),
|
|
122
|
+
...(header.cwd === void 0 ? {} : { cwd: header.cwd })
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* 种子会话的继承切点:事件流里最后一个 session/end-seed(data.inherited === true)的 seq。
|
|
128
|
+
* DSH 校验要求 seeded 会话的这个值与标记位置严格相等,否则整条会话打不开。
|
|
129
|
+
* @returns 切点 seq;不是种子会话时返回 -1。
|
|
130
|
+
*/
|
|
131
|
+
async function scanInheritedCut(file) {
|
|
132
|
+
const rl = readline.createInterface({ input: fs.createReadStream(file), crlfDelay: Infinity })
|
|
133
|
+
let last = -1
|
|
134
|
+
let index = -1
|
|
135
|
+
try {
|
|
136
|
+
for await (const line of rl) {
|
|
137
|
+
index += 1
|
|
138
|
+
if (index === 0) continue // 第一行是户口本
|
|
139
|
+
if (line.indexOf('"session/end-seed"') < 0) continue
|
|
140
|
+
let event
|
|
141
|
+
try { event = JSON.parse(line) } catch { continue }
|
|
142
|
+
if (event?.type === 'session/end-seed' && event.data?.inherited === true) {
|
|
143
|
+
last = typeof event.seq === 'number' ? event.seq : index - 1
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
} finally {
|
|
147
|
+
rl.close()
|
|
148
|
+
}
|
|
149
|
+
return last
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function isFile(file) {
|
|
153
|
+
try { return fs.statSync(file).isFile() } catch { return false }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function existsDir(dir) {
|
|
157
|
+
try { return (await fsp.stat(dir)).isDirectory() } catch { return false }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 落一个图片:先写到会话 media 下的临时名,验过哈希再搬两处。 */
|
|
161
|
+
async function saveMedia(entry, { hash, ext, sessionDir, attachRoot }) {
|
|
162
|
+
const mediaDir = path.join(sessionDir, 'media')
|
|
163
|
+
await fsp.mkdir(mediaDir, { recursive: true })
|
|
164
|
+
const tmp = path.join(mediaDir, 'import-' + hash.slice(0, 12) + '-' + process.pid + '.tmp')
|
|
165
|
+
const stored = await streamEntryToFile(entry, tmp)
|
|
166
|
+
if (stored.sha256 !== hash) {
|
|
167
|
+
await fsp.rm(tmp, { force: true }).catch(() => {})
|
|
168
|
+
throw new Error('media ' + hash + ' does not match its sha256 (the package is corrupt)')
|
|
169
|
+
}
|
|
170
|
+
const alias = path.join(mediaDir, 'sha256_' + hash + '.' + ext)
|
|
171
|
+
await fsp.rename(tmp, alias)
|
|
172
|
+
const objDir = path.join(attachRoot, 'objects', hash.slice(0, 2))
|
|
173
|
+
const obj = path.join(objDir, hash)
|
|
174
|
+
if (!isFile(obj)) {
|
|
175
|
+
await fsp.mkdir(objDir, { recursive: true })
|
|
176
|
+
await fsp.copyFile(alias, obj + '.tmp-' + process.pid)
|
|
177
|
+
await fsp.rename(obj + '.tmp-' + process.pid, obj)
|
|
178
|
+
}
|
|
179
|
+
return stored.bytes
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** 落一个文件附件:files/<前2>/<哈希>/<原名>,另存一份 file-objects 规范对象。 */
|
|
183
|
+
async function saveFile(entry, { hash, prefix, name, attachRoot }) {
|
|
184
|
+
const safeName = path.basename(name)
|
|
185
|
+
if (safeName === '' || safeName === '.' || safeName === '..') throw new Error('the package has an unsafe file name: ' + name)
|
|
186
|
+
const dir = path.join(attachRoot, 'files', prefix, hash)
|
|
187
|
+
await fsp.mkdir(dir, { recursive: true })
|
|
188
|
+
const tmp = path.join(dir, '.import-' + process.pid + '.tmp')
|
|
189
|
+
const stored = await streamEntryToFile(entry, tmp)
|
|
190
|
+
if (stored.sha256 !== hash) {
|
|
191
|
+
await fsp.rm(tmp, { force: true }).catch(() => {})
|
|
192
|
+
throw new Error('file ' + name + ' does not match its sha256 (the package is corrupt)')
|
|
193
|
+
}
|
|
194
|
+
const dst = path.join(dir, safeName)
|
|
195
|
+
await fsp.rename(tmp, dst)
|
|
196
|
+
const objDir = path.join(attachRoot, 'file-objects', prefix)
|
|
197
|
+
const obj = path.join(objDir, hash)
|
|
198
|
+
if (!isFile(obj)) {
|
|
199
|
+
await fsp.mkdir(objDir, { recursive: true })
|
|
200
|
+
await fsp.copyFile(dst, obj + '.tmp-' + process.pid)
|
|
201
|
+
await fsp.rename(obj + '.tmp-' + process.pid, obj)
|
|
202
|
+
}
|
|
203
|
+
return stored.bytes
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** 只读第一帧的户口本(dryRun 与真导入都用它)。 */
|
|
207
|
+
async function readHeader(file) {
|
|
208
|
+
let text = ''
|
|
209
|
+
let done = false
|
|
210
|
+
await forEachZipEntry(file, async (entry) => {
|
|
211
|
+
if (done || entry.isDir || !ROOT_LOG.test(entry.name)) return
|
|
212
|
+
for await (const chunk of entry.read()) {
|
|
213
|
+
text += chunk.toString('utf8')
|
|
214
|
+
if (text.indexOf('\n') >= 0) { done = true; break }
|
|
215
|
+
if (text.length > 4 * 1024 * 1024) throw new Error('the exported log header line is too long')
|
|
216
|
+
}
|
|
217
|
+
})
|
|
218
|
+
if (!done) throw new Error('this zip has no session.v4.jsonl at its root; it is not a session package')
|
|
219
|
+
const line = text.slice(0, text.indexOf('\n'))
|
|
220
|
+
let header
|
|
221
|
+
try { header = JSON.parse(line) } catch { throw new Error('the first line of session.v4.jsonl is not JSON') }
|
|
222
|
+
if (header === null || typeof header !== 'object' || header.type !== 'session') {
|
|
223
|
+
throw new Error('the first line of session.v4.jsonl is not a session header')
|
|
224
|
+
}
|
|
225
|
+
if (typeof header.id !== 'string' || header.id === '') throw new Error('the session header carries no id')
|
|
226
|
+
return header
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** 目标工作区:按 id 找(客户端传 id,不传路径)。 */
|
|
230
|
+
function findWorkspace(deps, workspaceId) {
|
|
231
|
+
const list = deps.workspaceRegistry?.list?.()
|
|
232
|
+
if (!Array.isArray(list) || list.length === 0) throw new Error('this host has no workspace registry; open the app once so a workspace exists')
|
|
233
|
+
const hit = list.find((w) => w.id === workspaceId) ?? (workspaceId === '' || workspaceId === undefined ? list[0] : undefined)
|
|
234
|
+
if (hit === undefined) throw new Error('no workspace with id ' + workspaceId)
|
|
235
|
+
if (typeof hit.path !== 'string' || hit.path === '') throw new Error('workspace ' + hit.id + ' has no path')
|
|
236
|
+
return hit
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
async function findGrid(root, id) {
|
|
240
|
+
let grids = []
|
|
241
|
+
try { grids = await fsp.readdir(root, { withFileTypes: true }) } catch { return null }
|
|
242
|
+
for (const g of grids) {
|
|
243
|
+
if (!g.isDirectory()) continue
|
|
244
|
+
if (await existsDir(path.join(root, g.name, id))) return g.name
|
|
245
|
+
}
|
|
246
|
+
return null
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async function safeRealpath(p) {
|
|
250
|
+
try { return await fsp.realpath(p) } catch { return '' }
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 撞号检查:同一个 id 在本机现在是什么状态。
|
|
255
|
+
* 命中一律换新 id:同工作区再挂成原会话的分支,别的工作区只换号。
|
|
256
|
+
*/
|
|
257
|
+
async function inspectExisting(deps, dshHome, id, root) {
|
|
258
|
+
const grid = await findGrid(root, id)
|
|
259
|
+
let header = null
|
|
260
|
+
try {
|
|
261
|
+
const rows = await deps.persistence.list()
|
|
262
|
+
header = (rows.map((row) => row.header ?? row).find((h) => h.id === id)) ?? null
|
|
263
|
+
} catch { header = null }
|
|
264
|
+
const projcache = path.join(dshHome, 'storages', 'session_projcache', 'sessions', id + '.json')
|
|
265
|
+
return { grid, header, hasProjcache: isFile(projcache) }
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** 只改日志的第一行(户口本);正文原样。 */
|
|
269
|
+
function replaceFirstLine(file, line) {
|
|
270
|
+
const buf = fs.readFileSync(file)
|
|
271
|
+
const nl = buf.indexOf(0x0a)
|
|
272
|
+
if (nl < 0) return false
|
|
273
|
+
fs.writeFileSync(file, Buffer.concat([Buffer.from(line, 'utf8'), buf.subarray(nl + 1)]))
|
|
274
|
+
return true
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 只改第一行的 cwd(子代理日志用:换 cwd 不换 id)。 */
|
|
278
|
+
async function rewriteHeaderCwd(file, cwd) {
|
|
279
|
+
const head = (await firstLineOf(file)).toString('utf8').replace(/\n$/, '')
|
|
280
|
+
const parsed = JSON.parse(head)
|
|
281
|
+
parsed.cwd = cwd
|
|
282
|
+
replaceFirstLine(file, JSON.stringify(parsed) + '\n')
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* 导入一个会话包。
|
|
287
|
+
* @param {object} opts
|
|
288
|
+
* @param {object} opts.deps 宿主依赖(persistence / sessions / agents / workspaceRegistry)
|
|
289
|
+
* @param {string} opts.dshHome
|
|
290
|
+
* @param {string} opts.file 已落盘的 zip
|
|
291
|
+
* @param {string} opts.workspaceId 目标工作区 id
|
|
292
|
+
* @param {boolean} [opts.dryRun]
|
|
293
|
+
*/
|
|
294
|
+
export async function importSession({ deps, dshHome, file, workspaceId, dryRun = false }) {
|
|
295
|
+
if (!canWriteZstd()) throw new Error('this host runs a Node without zstdCompress; session import needs Node 22.15+')
|
|
296
|
+
const root = deps.persistence?.config?.root
|
|
297
|
+
if (typeof root !== 'string' || root === '') throw new Error('session persistence has no storage root')
|
|
298
|
+
const workspace = findWorkspace(deps, workspaceId)
|
|
299
|
+
let workspacePath
|
|
300
|
+
try { workspacePath = await fsp.realpath(workspace.path) } catch (error) { throw new Error('the target workspace path does not resolve: ' + message(error)) }
|
|
301
|
+
if (!(await existsDir(workspacePath))) throw new Error('the target workspace path is not a directory: ' + workspacePath)
|
|
302
|
+
|
|
303
|
+
const header = await readHeader(file)
|
|
304
|
+
const originalId = header.id
|
|
305
|
+
const existing = await inspectExisting(deps, dshHome, originalId, root)
|
|
306
|
+
const targetGrid = projectKey(workspacePath)
|
|
307
|
+
const sameCwd = existing.header !== null && typeof existing.header.cwd === 'string' &&
|
|
308
|
+
(existing.header.cwd === workspacePath || (await safeRealpath(existing.header.cwd)) === workspacePath)
|
|
309
|
+
// 户口本读不出来时以格子为准(格子名就是 cwd 算出来的):同格子才算同一个工作区。
|
|
310
|
+
// 判错的代价是两条同 id 会话落在两个格子 → 会话列表整份 500,所以宁可换号。
|
|
311
|
+
const sameGrid = existing.grid !== null && (existing.header !== null ? sameCwd : existing.grid === targetGrid)
|
|
312
|
+
// 撞号一律换新 id,绝不原地覆盖:覆盖不会在列表里多出条目,用户看到的是「没刷新」。
|
|
313
|
+
// 同工作区的撞号同时挂成原会话的分支(parentSession);别的工作区只换号,不跨区挂父子。
|
|
314
|
+
// seeded 会话的继承前缀另有语义,只换号不挂分支。
|
|
315
|
+
const willRename = existing.grid !== null
|
|
316
|
+
const willBranch = sameGrid
|
|
317
|
+
|
|
318
|
+
const entries = await readZipCentralFromFile(file)
|
|
319
|
+
const mediaCount = entries.filter((e) => !e.isDir && MEDIA_NAME.test(e.name)).length
|
|
320
|
+
const fileCount = entries.filter((e) => !e.isDir && FILE_NAME.test(e.name)).length
|
|
321
|
+
const subCount = entries.filter((e) => !e.isDir && SUB_LOG.test(e.name)).length
|
|
322
|
+
|
|
323
|
+
const plan = {
|
|
324
|
+
session: {
|
|
325
|
+
id: willRename ? null : originalId,
|
|
326
|
+
originalId,
|
|
327
|
+
willRename,
|
|
328
|
+
willBranch,
|
|
329
|
+
cwd: workspacePath
|
|
330
|
+
},
|
|
331
|
+
workspace: { id: workspace.id, path: workspacePath, title: workspace.title ?? '' },
|
|
332
|
+
counts: { media: mediaCount, files: fileCount, subagents: subCount },
|
|
333
|
+
warnings: []
|
|
334
|
+
}
|
|
335
|
+
if (dryRun) return { ok: true, dryRun: true, ...plan }
|
|
336
|
+
|
|
337
|
+
const attachRoot = path.join(dshHome, 'attachments', 'v1')
|
|
338
|
+
const id = willRename ? 'session-' + randomUUID() : originalId
|
|
339
|
+
const gridKey = targetGrid
|
|
340
|
+
const sessionDir = path.join(root, gridKey, id)
|
|
341
|
+
const storages = path.join(dshHome, 'storages')
|
|
342
|
+
const backupDir = path.join(workspacePath, '会话导入备份-' + stamp())
|
|
343
|
+
|
|
344
|
+
// 写盘前先备份:workspace.json + 目录册(会话目录不再被覆盖,无需备份)。
|
|
345
|
+
let backup = ''
|
|
346
|
+
try {
|
|
347
|
+
await fsp.mkdir(backupDir, { recursive: true })
|
|
348
|
+
if (isFile(path.join(storages, 'workspace.json'))) {
|
|
349
|
+
await fsp.copyFile(path.join(storages, 'workspace.json'), path.join(backupDir, 'workspace.json'))
|
|
350
|
+
}
|
|
351
|
+
const pcs = path.join(storages, 'session_projcache', 'sessions')
|
|
352
|
+
if (isFile(path.join(pcs, originalId + '.json'))) {
|
|
353
|
+
await fsp.mkdir(path.join(backupDir, 'projcache'), { recursive: true })
|
|
354
|
+
await fsp.copyFile(path.join(pcs, originalId + '.json'), path.join(backupDir, 'projcache', originalId + '.json'))
|
|
355
|
+
}
|
|
356
|
+
await fsp.writeFile(path.join(backupDir, 'import.json'), JSON.stringify({
|
|
357
|
+
at: new Date().toISOString(), package: path.basename(file), workspace: plan.workspace, id, originalId, willBranch
|
|
358
|
+
}, null, 2) + '\n')
|
|
359
|
+
backup = backupDir
|
|
360
|
+
} catch (error) {
|
|
361
|
+
throw new Error('cannot write the pre-import backup into the workspace: ' + message(error))
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const tmpLog = path.join(sessionDir, '.import-' + process.pid + '.jsonl')
|
|
365
|
+
const written = []
|
|
366
|
+
let mediaSaved = 0
|
|
367
|
+
let subSaved = 0
|
|
368
|
+
try {
|
|
369
|
+
await fsp.mkdir(path.join(sessionDir, 'media'), { recursive: true })
|
|
370
|
+
|
|
371
|
+
let rootWritten = false
|
|
372
|
+
const subDirs = []
|
|
373
|
+
await forEachZipEntry(file, async (entry) => {
|
|
374
|
+
if (entry.isDir) return
|
|
375
|
+
const media = MEDIA_NAME.exec(entry.name)
|
|
376
|
+
if (media !== null) {
|
|
377
|
+
await saveMedia(entry, { hash: media[1].toLowerCase(), ext: media[2], sessionDir, attachRoot })
|
|
378
|
+
mediaSaved += 1
|
|
379
|
+
return
|
|
380
|
+
}
|
|
381
|
+
const fileHit = FILE_NAME.exec(entry.name)
|
|
382
|
+
if (fileHit !== null) {
|
|
383
|
+
await saveFile(entry, { hash: fileHit[2].toLowerCase(), prefix: fileHit[2].toLowerCase().slice(0, 2), name: fileHit[3], attachRoot })
|
|
384
|
+
return
|
|
385
|
+
}
|
|
386
|
+
const sub = SUB_LOG.exec(entry.name)
|
|
387
|
+
if (sub !== null) {
|
|
388
|
+
const subId = sub[1]
|
|
389
|
+
const subDir = path.join(root, gridKey, subId)
|
|
390
|
+
if (await existsDir(subDir)) {
|
|
391
|
+
plan.warnings.push('subagent session ' + subId + ' already exists; skipped')
|
|
392
|
+
return
|
|
393
|
+
}
|
|
394
|
+
await fsp.mkdir(subDir, { recursive: true })
|
|
395
|
+
written.push(subDir)
|
|
396
|
+
const tmp = path.join(subDir, '.import-' + process.pid + '.jsonl')
|
|
397
|
+
await streamEntryToFile(entry, tmp)
|
|
398
|
+
// 子代理的 cwd 也指向目标工作区,但 id / parentSession / delegationDepth 原样。
|
|
399
|
+
await rewriteHeaderCwd(tmp, workspacePath)
|
|
400
|
+
await packLog(tmp, path.join(subDir, SESSION_LOG_NAME))
|
|
401
|
+
await fsp.rm(tmp, { force: true }).catch(() => {})
|
|
402
|
+
subDirs.push(subId)
|
|
403
|
+
subSaved += 1
|
|
404
|
+
return
|
|
405
|
+
}
|
|
406
|
+
if (ROOT_LOG.test(entry.name) && !rootWritten) {
|
|
407
|
+
rootWritten = true
|
|
408
|
+
await streamEntryToFile(entry, tmpLog)
|
|
409
|
+
}
|
|
410
|
+
})
|
|
411
|
+
if (!rootWritten) throw new Error('this zip has no session.v4.jsonl at its root; it is not a session package')
|
|
412
|
+
|
|
413
|
+
// 户口本:改 cwd(换号时连 id 一起改)。其余字段一个都不动。
|
|
414
|
+
const headText = (await firstLineOf(tmpLog)).toString('utf8').replace(/\n$/, '')
|
|
415
|
+
const head = JSON.parse(headText)
|
|
416
|
+
// 种子会话的继承切点必须原样写进目录册;写错 DSH 就打不开("seeded header disagrees")。
|
|
417
|
+
// 顺带把自相矛盾的包挡在写盘之前:说是种子却没有标记,或不是种子却带标记。
|
|
418
|
+
const inheritedCut = await scanInheritedCut(tmpLog)
|
|
419
|
+
if (head.isSeeded === true && inheritedCut < 0) {
|
|
420
|
+
throw new Error('this package is marked isSeeded but its log has no inherited end-seed marker')
|
|
421
|
+
}
|
|
422
|
+
if (head.isSeeded !== true && inheritedCut >= 0) {
|
|
423
|
+
throw new Error('this package is not seeded but its log carries an inherited end-seed marker')
|
|
424
|
+
}
|
|
425
|
+
const inheritedEventCount = head.isSeeded === true ? inheritedCut : 0
|
|
426
|
+
head.cwd = workspacePath
|
|
427
|
+
if (willRename) head.id = id
|
|
428
|
+
// 挂分支:新会话登记为原同 id 会话的子会话(parentSession),历史仍独立。
|
|
429
|
+
// 包里本来就带父会话的(自己就是别人的分支)保留原值,不覆盖。
|
|
430
|
+
if (willBranch && head.parentSession === void 0) head.parentSession = originalId
|
|
431
|
+
if (!replaceFirstLine(tmpLog, JSON.stringify(head) + '\n')) throw new Error('cannot rewrite the session header')
|
|
432
|
+
await packLog(tmpLog, path.join(sessionDir, SESSION_LOG_NAME))
|
|
433
|
+
await fsp.rm(tmpLog, { force: true }).catch(() => {})
|
|
434
|
+
written.push(sessionDir)
|
|
435
|
+
|
|
436
|
+
// 目录册:没有就建最小结构,有就只改 identity.cwd。
|
|
437
|
+
const pcDir = path.join(storages, 'session_projcache', 'sessions')
|
|
438
|
+
await fsp.mkdir(pcDir, { recursive: true })
|
|
439
|
+
const pcFile = path.join(pcDir, id + '.json')
|
|
440
|
+
let cache = null
|
|
441
|
+
if (isFile(pcFile)) {
|
|
442
|
+
try { cache = JSON.parse(await fsp.readFile(pcFile, 'utf8')) } catch { cache = null }
|
|
443
|
+
}
|
|
444
|
+
if (cache === null) {
|
|
445
|
+
cache = { version: 7, record: { identity: { formatVersion: 4, createdAt: head.createdAt, cwd: workspacePath, isSeeded: head.isSeeded === true, inheritedEventCount }, rows: {} } }
|
|
446
|
+
} else {
|
|
447
|
+
cache.record = cache.record ?? { identity: {}, rows: {} }
|
|
448
|
+
cache.record.identity = cache.record.identity ?? {}
|
|
449
|
+
cache.record.identity.cwd = workspacePath
|
|
450
|
+
}
|
|
451
|
+
await fsp.writeFile(pcFile + '.tmp-import', JSON.stringify(cache, null, 2) + '\n')
|
|
452
|
+
await fsp.rename(pcFile + '.tmp-import', pcFile)
|
|
453
|
+
|
|
454
|
+
// 刷新:照删除那边的写法——在动作这一刻重新 list() 取实时工作区对象再调用,
|
|
455
|
+
// 不拿函数开头那份早已过期的快照(过期对象的 mutate 只写表、不发列表变更事件)。
|
|
456
|
+
// attachSession 会校验 cwd == workspace.path,并持久化、发变更事件。
|
|
457
|
+
let liveWorkspace = workspace
|
|
458
|
+
try {
|
|
459
|
+
const freshList = deps.workspaceRegistry?.list?.()
|
|
460
|
+
const fresh = Array.isArray(freshList) ? freshList.find((row) => row?.id === workspace.id) : undefined
|
|
461
|
+
if (fresh !== undefined) liveWorkspace = fresh
|
|
462
|
+
} catch (error) {
|
|
463
|
+
plan.warnings.push('cannot refresh the workspace handle: ' + message(error))
|
|
464
|
+
}
|
|
465
|
+
// 这一步失败就把刚写的东西撤掉,别留一条没有工作区认领的孤儿。
|
|
466
|
+
try {
|
|
467
|
+
await liveWorkspace.attachSession(id)
|
|
468
|
+
for (const subId of subDirs) {
|
|
469
|
+
try { await liveWorkspace.attachSession(subId) } catch (error) {
|
|
470
|
+
plan.warnings.push('subagent session ' + subId + ' was written but not attached: ' + message(error))
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
} catch (error) {
|
|
474
|
+
for (const dir of written) await fsp.rm(dir, { recursive: true, force: true }).catch(() => {})
|
|
475
|
+
await fsp.rm(pcFile, { force: true }).catch(() => {})
|
|
476
|
+
throw new Error('the session files were written but the workspace refused to attach the session: ' + message(error))
|
|
477
|
+
}
|
|
478
|
+
// 通知前端左侧列表:导入的会话没有 session/created,宿主的 api-session/added 不会自己发。
|
|
479
|
+
try {
|
|
480
|
+
deps.notifySessionAdded?.(coldSummary(head))
|
|
481
|
+
} catch (error) {
|
|
482
|
+
plan.warnings.push('the session was imported but the list notification failed: ' + message(error))
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
return {
|
|
486
|
+
ok: true,
|
|
487
|
+
dryRun: false,
|
|
488
|
+
session: { id, originalId, willRename, willBranch, renamed: id !== originalId, cwd: workspacePath, isSeeded: head.isSeeded === true, inheritedEventCount },
|
|
489
|
+
workspace: plan.workspace,
|
|
490
|
+
counts: { media: mediaSaved, files: fileCount, subagents: subSaved },
|
|
491
|
+
backup,
|
|
492
|
+
warnings: plan.warnings
|
|
493
|
+
}
|
|
494
|
+
} catch (error) {
|
|
495
|
+
await fsp.rm(tmpLog, { force: true }).catch(() => {})
|
|
496
|
+
throw error
|
|
497
|
+
}
|
|
498
|
+
}
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* 装配 /state 的那一套也在这里(它是这份列表唯一的读者)。
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
+
import fsp from 'node:fs/promises'
|
|
6
7
|
import { join } from 'node:path'
|
|
7
8
|
import { stat } from 'node:fs/promises'
|
|
8
9
|
import { memoryDir, readAssembly } from '../../core/store.js'
|
|
@@ -13,7 +14,9 @@ import { readOptionsSync, REMINDER_SYSTEM } from '../../core/settings.js'
|
|
|
13
14
|
import { deleteSessionPermanently, sessionDirOf } from '../delete.js'
|
|
14
15
|
import { readDigest } from '../summary.js'
|
|
15
16
|
import { compactThenDelete } from '../compact-delete.js'
|
|
16
|
-
import { respond, readBody } from '../http-util.js'
|
|
17
|
+
import { respond, readBody, readBodyToFile } from '../http-util.js'
|
|
18
|
+
import { runsDir } from '../../core/schema.js'
|
|
19
|
+
import { importSession, canWriteZstd } from '../import-session.js'
|
|
17
20
|
|
|
18
21
|
const PREFIX = '/api/session-seal-scripts.'
|
|
19
22
|
const digestCache = new Map()
|
|
@@ -116,8 +119,17 @@ export async function buildState(deps, dshHome, snapshot = null) {
|
|
|
116
119
|
workspaces.push({ cwd, sessions, memories, health })
|
|
117
120
|
}
|
|
118
121
|
workspaces.sort((a, b) => a.cwd.localeCompare(b.cwd))
|
|
122
|
+
// 导入的目标工作区(0.6.1):空工作区不会出现在上面那份按 cwd 分组的列表里,
|
|
123
|
+
// 所以单独给一份名册,界面用 id 选、服务端只信 id。
|
|
124
|
+
let targets = []
|
|
125
|
+
try {
|
|
126
|
+
targets = (deps.workspaceRegistry?.list?.() ?? [])
|
|
127
|
+
.filter((w) => typeof w.id === 'string' && typeof w.path === 'string')
|
|
128
|
+
.map((w) => ({ id: w.id, path: w.path, title: typeof w.title === 'string' ? w.title : '' }))
|
|
129
|
+
} catch { targets = [] }
|
|
119
130
|
return {
|
|
120
131
|
workspaces,
|
|
132
|
+
targets,
|
|
121
133
|
options,
|
|
122
134
|
// 失败与降级只有一个入口:缺什么能力、本机能力表、宿主层面最近一次失败。
|
|
123
135
|
// 拆回顾失败按工作区记在 workspaces[].health 里,这里只放宿主自己的那条。
|
|
@@ -177,6 +189,40 @@ export function routesSessions(route, { dshHome, getDeps, waitForSplit, canLifec
|
|
|
177
189
|
respond(res, 200, describeLoad(dshHome, body.cwd, now, options, reminder))
|
|
178
190
|
})
|
|
179
191
|
|
|
192
|
+
/**
|
|
193
|
+
* 会话导入(0.6.1):把 dsh-session-<id>.zip 装进指定工作区。
|
|
194
|
+
*
|
|
195
|
+
* POST 体就是 zip 原始字节(和「自创工具」的导入同一条路:先流到 _runs/,不吃内存);
|
|
196
|
+
* ?workspaceId=<id>&dryRun=1 走预演,只报会碰到谁、要不要换 id,不写盘。
|
|
197
|
+
*
|
|
198
|
+
* 写盘前先备份到 <工作区>/会话导入备份-<时间>/;刷新用 workspace.attachSession(id),
|
|
199
|
+
* 它会校验 cwd == workspace.path、持久化并发出变更事件,所以不用重启。
|
|
200
|
+
*/
|
|
201
|
+
route(PREFIX + 'session-import', async (req, res) => {
|
|
202
|
+
if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
|
|
203
|
+
if (!canWriteZstd()) {
|
|
204
|
+
respond(res, 503, { error: { code: 'host-capability', message: 'this host runs a Node without zstdCompress; session import needs Node 22.15+' } })
|
|
205
|
+
return
|
|
206
|
+
}
|
|
207
|
+
let query
|
|
208
|
+
try { query = new URL(req.url ?? '/', 'http://placeholder').searchParams } catch { query = new URLSearchParams() }
|
|
209
|
+
const dryRun = query.get('dryRun') === '1'
|
|
210
|
+
const workspaceId = query.get('workspaceId') || ''
|
|
211
|
+
const dir = runsDir(dshHome)
|
|
212
|
+
await fsp.mkdir(dir, { recursive: true })
|
|
213
|
+
const tmp = join(dir, 'session-import-' + Date.now() + '-' + process.pid + '.zip')
|
|
214
|
+
try {
|
|
215
|
+
const written = await readBodyToFile(req, tmp)
|
|
216
|
+
if (written.bytes === 0) { respond(res, 400, { error: { code: 'empty-file', message: 'the package is empty' } }); return }
|
|
217
|
+
const result = await importSession({ deps: getDeps(), dshHome, file: tmp, workspaceId, dryRun })
|
|
218
|
+
respond(res, 200, result)
|
|
219
|
+
} catch (error) {
|
|
220
|
+
respond(res, 400, { error: { code: 'import-failed', message: error?.message ?? String(error) } })
|
|
221
|
+
} finally {
|
|
222
|
+
await fsp.rm(tmp, { force: true }).catch(() => {})
|
|
223
|
+
}
|
|
224
|
+
})
|
|
225
|
+
|
|
180
226
|
route(PREFIX + 'compact-delete', async (req, res) => {
|
|
181
227
|
if (req.method !== 'POST') { respond(res, 405, { error: { code: 'method-not-allowed', message: 'POST' } }); return }
|
|
182
228
|
const body = JSON.parse(await readBody(req) || '{}')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-seal-scripts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
@@ -16,10 +16,11 @@
|
|
|
16
16
|
"cordis.patch.yml",
|
|
17
17
|
"lib",
|
|
18
18
|
"README.md",
|
|
19
|
-
"LICENSE"
|
|
19
|
+
"LICENSE",
|
|
20
|
+
"README.en.md"
|
|
20
21
|
],
|
|
21
22
|
"peerDependencies": {
|
|
22
|
-
"@deepseek-ai/dsh": ">=0.2.
|
|
23
|
+
"@deepseek-ai/dsh": ">=0.2.2-rc.1 <1.0.0"
|
|
23
24
|
},
|
|
24
25
|
"peerDependenciesMeta": {
|
|
25
26
|
"@deepseek-ai/dsh": {
|