dsh-pdf-workbench 1.3.3 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +225 -199
  3. package/assets/screenshot-attachments.jpg +0 -0
  4. package/assets/screenshot-canvas.jpg +0 -0
  5. package/assets/screenshot-questions.jpg +0 -0
  6. package/assets/screenshot-settings-data.jpg +0 -0
  7. package/assets/screenshot-settings-mode.jpg +0 -0
  8. package/assets/screenshot-settings-reading.jpg +0 -0
  9. package/client.js +5700 -849
  10. package/docs/DETAIL.md +1 -69
  11. package/docs/RELEASE.md +119 -119
  12. package/docs/SIDE-PREVIEW.md +5 -1
  13. package/docs/preview.svg +86 -0
  14. package/icon.svg +7 -6
  15. package/index.js +18 -2
  16. package/locale/en.json +1 -1
  17. package/locale/zh.json +1 -1
  18. package/package.json +1 -1
  19. package/screenshots.json +13 -8
  20. package/src/client/host-ui-entry.js +11 -11
  21. package/src/client/react-jsx-runtime.cjs +21 -21
  22. package/src/client/viewer.js +80 -80
  23. package/src/host/artifacts.js +31 -3
  24. package/src/host/attachments.js +159 -0
  25. package/src/host/backup.js +457 -0
  26. package/src/host/base-session.js +146 -0
  27. package/src/host/book-import.js +98 -0
  28. package/src/host/chapter-sessions.js +154 -0
  29. package/src/host/chapter-text.js +91 -0
  30. package/src/host/fonts.js +190 -0
  31. package/src/host/pdf-stream.js +168 -0
  32. package/src/host/ppt.js +153 -0
  33. package/src/host/print.js +191 -0
  34. package/src/host/questions.js +186 -0
  35. package/src/host/routes.js +671 -25
  36. package/src/host/state.js +1 -1
  37. package/src/host/zip.js +186 -0
  38. package/tools/AGENTS.md +33 -33
  39. package/tools/README.md +138 -138
  40. package/tools/auto_chapters.py +122 -122
  41. package/tools/dsfile.mjs +198 -198
  42. package/tools/export_chapter.py +108 -108
  43. package/tools/export_page.py +91 -91
  44. package/tools/md2overlay.py +200 -200
  45. package/tools/md2tex.py +422 -422
  46. package/tools/pdf_blocks.py +110 -110
  47. package/tools/pdf_fontsize.py +20 -20
  48. package/tools/pdf_merge.py +15 -15
  49. package/tools/pdf_pagesizes.py +8 -8
  50. package/tools/pdf_raster.py +21 -21
  51. package/tools/pdf_text.py +34 -0
  52. package/tools/pdfkit.py +896 -896
  53. package/tools/realign_overlay.py +248 -248
  54. package/tools/rebuild_overlay.py +55 -55
  55. package/tools/rename_chapters.py +93 -93
  56. package/tools//350/247/204/350/214/203/00_/345/205/261/345/220/214/347/272/246/345/256/232.md +142 -142
  57. package/tools//350/247/204/350/214/203/01_/346/226/207/346/234/254/346/217/220/345/217/226.md +204 -204
  58. package/tools//350/247/204/350/214/203/02_/347/255/224/347/226/221.md +61 -61
  59. package/tools//350/247/204/350/214/203/03_/344/271/240/351/242/230/350/247/243/347/255/224.md +77 -77
  60. package/tools//350/247/204/350/214/203/api/346/217/220/347/244/272/350/257/215_/346/217/220/345/217/226.md +11 -11
  61. package/vendor/cmaps/LICENSE.txt +36 -36
  62. package/vendor/fonts/excalifont/OFL.txt +98 -98
  63. package/vendor/fonts/zhhand/OFL.txt +99 -99
  64. package/vendor/host-ui.cjs +1719 -1719
  65. package/vendor/host-ui.css +799 -799
  66. package/vendor/pdf.min.mjs +28 -28
  67. package/vendor/pdf.worker.min.mjs +28 -28
  68. package/vendor/pdfjs-LICENSE.txt +177 -177
  69. package/vendor/rough/LICENSE +21 -21
  70. package/vendor/rough/rough.mjs +1 -1
  71. package/vendor/wasm/LICENSE_JBIG2 +196 -196
  72. package/vendor/wasm/LICENSE_OPENJPEG +39 -39
  73. package/vendor/wasm/LICENSE_PDFJS_JBIG2 +13 -13
  74. package/vendor/wasm/LICENSE_PDFJS_OPENJPEG +22 -22
  75. package/vendor/wasm/LICENSE_PDFJS_QCMS +19 -19
  76. package/vendor/wasm/LICENSE_QCMS +21 -21
  77. package/vendor/wasm/jbig2_nowasm_fallback.js +15 -15
  78. package/vendor/wasm/openjpeg_nowasm_fallback.js +17 -17
  79. package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +1 -1
  80. package/tools/node.cmd +0 -3
  81. package/tools/py.cmd +0 -3
  82. package/vendor/fonts/zhhand/Xiaolai-Regular.ttf +0 -0
@@ -0,0 +1,457 @@
1
+ /**
2
+ * Data-migration backup: collect a staging tree, describe it in `manifest.json`
3
+ * with checksums, and pack/unpack it as a ZIP. The archive never contains book
4
+ * PDFs or credentials; the caller decides which sources are copied in.
5
+ * @module dsh-pdf-workbench/backup
6
+ */
7
+
8
+ import { execFile } from 'node:child_process'
9
+ import { createHash, randomUUID } from 'node:crypto'
10
+ import { promisify } from 'node:util'
11
+ import { cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
12
+ import { dirname, join } from 'node:path'
13
+
14
+ import { readZip, safeZipName, writeZip } from './zip.js'
15
+
16
+ /** Version of the manifest schema. */
17
+ export const BACKUP_FORMAT = 1
18
+
19
+ /** Plugin-state files that travel with a backup (never credentials). */
20
+ export const PLUGIN_STATE_FILES = ['libraries.json', 'state.json', 'pending.json', 'links.json', 'pressure.json', 'shelves.json', 'qa-persona.md']
21
+
22
+ /**
23
+ * Copy one path when it exists.
24
+ * @param {string} source - file or directory.
25
+ * @param {string} target - destination.
26
+ * @returns {Promise<boolean>} whether anything was copied.
27
+ */
28
+ async function copyIfExists(source, target) {
29
+ const info = await stat(source).catch(() => null)
30
+ if (info === null) return false
31
+ await mkdir(dirname(target), { recursive: true })
32
+ await cp(source, target, { recursive: info.isDirectory() })
33
+ return true
34
+ }
35
+
36
+ /**
37
+ * Copy the selected sources into a staging tree.
38
+ * @param {{ dataDir: string, dshHome?: string, libraries?: object[], include?: object, root?: string }} options - source locations and selection.
39
+ * @returns {Promise<{ root: string, copied: string[], included: object }>} the staging tree.
40
+ */
41
+ export async function collectBackup(options) {
42
+ const dataDir = options.dataDir
43
+ const home = typeof options.dshHome === 'string' && options.dshHome !== '' ? options.dshHome : dirname(dataDir)
44
+ const include = options.include !== null && typeof options.include === 'object' ? options.include : {}
45
+ const root = typeof options.root === 'string' && options.root !== '' ? options.root : join(dataDir, 'backup', `staging-${randomUUID()}`)
46
+ await rm(root, { recursive: true, force: true })
47
+ await mkdir(root, { recursive: true })
48
+ const copied = []
49
+ const included = {
50
+ sessions: false,
51
+ workspace: false,
52
+ pluginState: false,
53
+ libraryData: [],
54
+ settings: false,
55
+ fonts: false,
56
+ projcache: false,
57
+ }
58
+ if (include.sessions !== false) {
59
+ included.sessions = await copyIfExists(join(home, 'sessions'), join(root, 'sessions'))
60
+ if (included.sessions) copied.push('sessions')
61
+ }
62
+ if (include.workspace !== false) {
63
+ included.workspace = await copyIfExists(join(home, 'storages', 'workspace.json'), join(root, 'storages', 'workspace.json'))
64
+ if (included.workspace) copied.push('storages/workspace.json')
65
+ }
66
+ if (include.pluginState !== false) {
67
+ let any = false
68
+ for (const name of PLUGIN_STATE_FILES) {
69
+ if (await copyIfExists(join(dataDir, name), join(root, 'plugin-state', name))) any = true
70
+ }
71
+ included.pluginState = any
72
+ if (any) copied.push('plugin-state')
73
+ }
74
+ if (include.libraryData !== false) {
75
+ const libraries = Array.isArray(options.libraries) ? options.libraries : []
76
+ for (const library of libraries) {
77
+ if (library === null || typeof library !== 'object' || typeof library.libraryDir !== 'string') continue
78
+ const id = safeZipName(String(library.id ?? 'library'))
79
+ const ok = await copyIfExists(join(library.libraryDir, '.pdfdesk'), join(root, 'libraries', id, '.pdfdesk'))
80
+ if (ok) {
81
+ included.libraryData.push(id)
82
+ copied.push(`libraries/${id}/.pdfdesk`)
83
+ }
84
+ }
85
+ }
86
+ if (include.fonts === true) {
87
+ included.fonts = await copyIfExists(join(dataDir, 'fonts'), join(root, 'fonts'))
88
+ if (included.fonts) copied.push('fonts')
89
+ }
90
+ if (include.settings === true && options.settings !== null && typeof options.settings === 'object') {
91
+ await writeFile(join(root, 'settings.json'), `${JSON.stringify(options.settings, null, 2)}\n`, 'utf8')
92
+ included.settings = true
93
+ copied.push('settings.json')
94
+ }
95
+ if (include.projcache === true) {
96
+ included.projcache = await copyIfExists(join(home, 'storages', 'session_projcache'), join(root, 'projcache'))
97
+ if (included.projcache) copied.push('projcache')
98
+ }
99
+ return { root, copied, included }
100
+ }
101
+
102
+ /**
103
+ * Build, pack and clean up a full backup archive.
104
+ * @param {{ dataDir: string, dshHome?: string, libraries?: object[], include?: object,
105
+ * outDir?: string, pluginVersion?: string, machine?: object }} options - sources, selection and metadata.
106
+ * @returns {Promise<{ outPath: string, name: string, bytes: number, files: number, manifest: object }>} the archive and its manifest.
107
+ */
108
+ export async function createBackup(options) {
109
+ const dataDir = options.dataDir
110
+ const staging = await collectBackup(options)
111
+ try {
112
+ const stamp = new Date().toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15)
113
+ const name = `dsh-workbench-backup-${stamp}.zip`
114
+ const outDir = typeof options.outDir === 'string' && options.outDir !== '' ? options.outDir : join(dataDir, 'backup')
115
+ const outPath = join(outDir, name)
116
+ const meta = {
117
+ plugin: { name: 'dsh-pdf-workbench', version: typeof options.pluginVersion === 'string' ? options.pluginVersion : '' },
118
+ machine: options.machine !== null && typeof options.machine === 'object' ? options.machine : {},
119
+ included: staging.included,
120
+ paths: {
121
+ libraries: Object.fromEntries((Array.isArray(options.libraries) ? options.libraries : [])
122
+ .filter(library => library !== null && typeof library === 'object' && typeof library.libraryDir === 'string')
123
+ .map(library => [safeZipName(String(library.id ?? 'library')), { name: String(library.name ?? ''), old: library.libraryDir }])),
124
+ },
125
+ }
126
+ const packed = await packDirectory({ root: staging.root, outPath, meta })
127
+ const manifest = JSON.parse(await readFile(join(staging.root, 'manifest.json'), 'utf8'))
128
+ return { outPath, name, bytes: packed.bytes, files: packed.files, manifest }
129
+ } finally {
130
+ await rm(staging.root, { recursive: true, force: true })
131
+ }
132
+ }
133
+
134
+ /**
135
+ * @param {Buffer} bytes - content.
136
+ * @returns {string} hex sha256.
137
+ */
138
+ export function sha256(bytes) {
139
+ return createHash('sha256').update(bytes).digest('hex')
140
+ }
141
+
142
+ /**
143
+ * List every regular file under a directory, relative with forward slashes.
144
+ * @param {string} root - directory.
145
+ * @param {string} [base] - internal prefix.
146
+ * @returns {Promise<string[]>} relative names in a stable order.
147
+ */
148
+ export async function walkFiles(root, base = '') {
149
+ const entries = await readdir(base === '' ? root : join(root, base), { withFileTypes: true }).catch(() => [])
150
+ const files = []
151
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
152
+ const relative = base === '' ? entry.name : `${base}/${entry.name}`
153
+ if (entry.isDirectory()) {
154
+ files.push(...await walkFiles(root, relative))
155
+ continue
156
+ }
157
+ if (entry.isFile()) files.push(relative)
158
+ }
159
+ return files
160
+ }
161
+
162
+ /**
163
+ * Write `manifest.json` for a staging tree and return it.
164
+ * @param {{ root: string, meta?: object }} options - staging root and extra fields (plugin version, machine, included items).
165
+ * @returns {Promise<object>} the manifest.
166
+ */
167
+ export async function buildManifest(options) {
168
+ const files = []
169
+ for (const name of await walkFiles(options.root)) {
170
+ if (name === 'manifest.json') continue
171
+ const bytes = await readFile(join(options.root, name))
172
+ files.push({ path: name, bytes: bytes.length, sha256: sha256(bytes) })
173
+ }
174
+ const manifest = {
175
+ format: BACKUP_FORMAT,
176
+ createdAt: Date.now(),
177
+ ...(options.meta === undefined ? {} : options.meta),
178
+ files,
179
+ }
180
+ await mkdir(options.root, { recursive: true })
181
+ await writeFile(join(options.root, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
182
+ return manifest
183
+ }
184
+
185
+ const PYTHON_ZIP = `import os, sys, zipfile
186
+ root, out, mode = sys.argv[1], sys.argv[2], sys.argv[3]
187
+ compression = zipfile.ZIP_STORED if mode == 'store' else zipfile.ZIP_DEFLATED
188
+ with zipfile.ZipFile(out, 'w', compression) as archive:
189
+ for base, dirs, files in os.walk(root):
190
+ dirs.sort()
191
+ for name in sorted(files):
192
+ path = os.path.join(base, name)
193
+ relative = os.path.relpath(path, root).replace(os.sep, '/')
194
+ archive.write(path, relative)
195
+ `
196
+
197
+ /**
198
+ * Pack with Python's zipfile when an interpreter is available; Node's writer
199
+ * stays the fallback so a machine without Python (or a blocked spawn) still
200
+ * produces a valid archive.
201
+ * @param {{ root: string, outPath: string, compress?: boolean }} options - tree and destination.
202
+ * @returns {Promise<{ bytes: number } | null>} the packed size, or null when unavailable.
203
+ */
204
+ async function packWithPython(options) {
205
+ const temporary = `${options.outPath}.${process.pid}.pyzip`
206
+ const script = `${temporary}.py`
207
+ await mkdir(dirname(options.outPath), { recursive: true })
208
+ await writeFile(script, PYTHON_ZIP, 'utf8')
209
+ const candidates = process.platform === 'win32'
210
+ ? [['py', ['-3', script, options.root, temporary, options.compress === false ? 'store' : 'deflate']], ['python', [script, options.root, temporary, options.compress === false ? 'store' : 'deflate']]]
211
+ : [['python3', [script, options.root, temporary, options.compress === false ? 'store' : 'deflate']], ['python', [script, options.root, temporary, options.compress === false ? 'store' : 'deflate']]]
212
+ try {
213
+ for (const [command, args] of candidates) {
214
+ try {
215
+ await promisify(execFile)(command, args, { windowsHide: true, timeout: 120000 })
216
+ const info = await stat(temporary)
217
+ if (info.isFile() === true && info.size > 0) {
218
+ await rename(temporary, options.outPath)
219
+ return { bytes: info.size }
220
+ }
221
+ } catch {
222
+ // Try the next interpreter name.
223
+ }
224
+ }
225
+ return null
226
+ } finally {
227
+ await rm(script, { force: true })
228
+ await rm(temporary, { force: true })
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Pack a staging tree into a ZIP, manifest first.
234
+ * @param {{ root: string, outPath: string, compress?: boolean, meta?: object }} options - source tree and destination.
235
+ * @returns {Promise<{ outPath: string, bytes: number, files: number }>} the archive.
236
+ */
237
+ export async function packDirectory(options) {
238
+ const manifest = await buildManifest({ root: options.root, meta: options.meta })
239
+ const entries = [{ name: 'manifest.json', data: Buffer.from(`${JSON.stringify(manifest, null, 2)}\n`, 'utf8') }]
240
+ for (const file of manifest.files) {
241
+ entries.push({ name: file.path, data: await readFile(join(options.root, file.path)) })
242
+ }
243
+ const python = await packWithPython({ root: options.root, outPath: options.outPath, compress: options.compress })
244
+ if (python !== null) return { outPath: options.outPath, bytes: python.bytes, files: entries.length }
245
+ const bytes = writeZip({ entries, compress: options.compress !== false })
246
+ await mkdir(dirname(options.outPath), { recursive: true })
247
+ const temporary = `${options.outPath}.${process.pid}.tmp`
248
+ await writeFile(temporary, bytes)
249
+ await rename(temporary, options.outPath)
250
+ return { outPath: options.outPath, bytes: bytes.length, files: entries.length }
251
+ }
252
+
253
+ /**
254
+ * Read a backup archive and verify every checksum before the caller touches it.
255
+ * @param {string} archivePath - zip path.
256
+ * @returns {Promise<{ manifest: object, entries: Map<string, Buffer> }>} verified content.
257
+ */
258
+ export async function readBackup(archivePath) {
259
+ const bytes = await readFile(archivePath)
260
+ const entries = readZip(bytes)
261
+ const manifestBytes = entries.get('manifest.json')
262
+ if (manifestBytes === undefined) throw new Error('迁移包缺少 manifest.json')
263
+ let manifest
264
+ try {
265
+ manifest = JSON.parse(manifestBytes.toString('utf8'))
266
+ } catch {
267
+ throw new Error('迁移包的 manifest.json 不是有效 JSON')
268
+ }
269
+ if (manifest === null || typeof manifest !== 'object' || manifest.format !== BACKUP_FORMAT) {
270
+ throw new Error(`不支持的迁移包版本:${manifest === null ? '?' : manifest.format}`)
271
+ }
272
+ if (!Array.isArray(manifest.files)) throw new Error('迁移包 manifest 缺少文件清单')
273
+ const problems = []
274
+ for (const file of manifest.files) {
275
+ const name = safeZipName(file.path)
276
+ const data = entries.get(name)
277
+ if (data === undefined) {
278
+ problems.push(`缺少文件:${name}`)
279
+ continue
280
+ }
281
+ const actual = sha256(data)
282
+ if (file.sha256 !== undefined && actual !== file.sha256) problems.push(`校验失败:${name}`)
283
+ if (file.bytes !== undefined && data.length !== file.bytes) problems.push(`大小不符:${name}`)
284
+ }
285
+ if (problems.length > 0) throw new Error(`迁移包校验失败:${problems.slice(0, 5).join(';')}`)
286
+ return { manifest, entries }
287
+ }
288
+
289
+ /**
290
+ * Extract a verified archive into a fresh directory (caller owns cleanup).
291
+ * @param {{ manifest: object, entries: Map<string, Buffer>, outDir: string }} options - verified content and destination.
292
+ * @returns {Promise<{ files: number }>} extraction summary.
293
+ */
294
+ export async function extractBackup(options) {
295
+ await mkdir(options.outDir, { recursive: true })
296
+ let files = 0
297
+ for (const name of options.entries.keys()) {
298
+ if (name === 'manifest.json') continue
299
+ const target = join(options.outDir, safeZipName(name))
300
+ await mkdir(dirname(target), { recursive: true })
301
+ await writeFile(target, options.entries.get(name))
302
+ files += 1
303
+ }
304
+ return { files }
305
+ }
306
+
307
+ /**
308
+ * Map one archive entry to its destination on this machine.
309
+ * @param {string} name - manifest entry path.
310
+ * @param {{ dataDir: string, dshHome: string, libraryRoots: Record<string, string> }} roots - destinations.
311
+ * @returns {string|null} absolute target, or null when the entry has no place here.
312
+ */
313
+ export function destinationOf(name, roots) {
314
+ if (name.startsWith('sessions/')) return join(roots.dshHome, 'sessions', name.slice('sessions/'.length))
315
+ if (name === 'storages/workspace.json') return join(roots.dshHome, 'storages', 'workspace.json')
316
+ if (name.startsWith('plugin-state/')) return join(roots.dataDir, name.slice('plugin-state/'.length))
317
+ if (name.startsWith('fonts/')) return join(roots.dataDir, 'fonts', name.slice('fonts/'.length))
318
+ if (name.startsWith('projcache/')) return join(roots.dshHome, 'storages', 'session_projcache', name.slice('projcache/'.length))
319
+ if (name === 'settings.json') return join(roots.dataDir, 'backup', 'imported-settings.json')
320
+ if (name.startsWith('libraries/')) {
321
+ const parts = name.split('/')
322
+ const id = parts[1]
323
+ const rest = parts.slice(2)
324
+ if (id === undefined || rest[0] !== '.pdfdesk') return null
325
+ const root = roots.libraryRoots[id]
326
+ if (typeof root !== 'string' || root === '') return null
327
+ return join(root, ...rest)
328
+ }
329
+ return null
330
+ }
331
+
332
+ /**
333
+ * Rewrite `libraries.json` roots using the manifest's recorded old paths.
334
+ * @param {{ dataDir: string, manifest: object, libraryRoots: Record<string, string> }} options - current state and mapping.
335
+ * @returns {Promise<{ rewritten: string[], missing: boolean }>} what changed.
336
+ */
337
+ export async function rewriteLibraryRoots(options) {
338
+ const path = join(options.dataDir, 'libraries.json')
339
+ const raw = await readFile(path, 'utf8').catch(() => null)
340
+ if (raw === null) return { rewritten: [], missing: true }
341
+ let parsed
342
+ try {
343
+ parsed = JSON.parse(raw)
344
+ } catch {
345
+ return { rewritten: [], missing: true }
346
+ }
347
+ if (parsed === null || typeof parsed !== 'object' || !Array.isArray(parsed.items)) return { rewritten: [], missing: true }
348
+ const recorded = options.manifest.paths !== null && typeof options.manifest.paths === 'object' && options.manifest.paths.libraries !== null
349
+ ? options.manifest.paths.libraries
350
+ : {}
351
+ const rewritten = []
352
+ for (const item of parsed.items) {
353
+ if (item === null || typeof item !== 'object') continue
354
+ const id = String(item.id ?? '')
355
+ const nextRoot = options.libraryRoots[id]
356
+ const oldRoot = recorded[id] !== undefined && recorded[id] !== null ? recorded[id].old : undefined
357
+ if (typeof nextRoot !== 'string' || nextRoot === '') continue
358
+ if (typeof oldRoot === 'string' && oldRoot !== '' && typeof item.libraryDir === 'string') {
359
+ const prefix = oldRoot.replace(/[\\/]+$/, '')
360
+ for (const field of ['libraryDir', 'fragmentDir', 'artifactDir', 'coverDir', 'indexPath']) {
361
+ if (typeof item[field] === 'string' && item[field].startsWith(prefix)) {
362
+ item[field] = `${nextRoot}${item[field].slice(prefix.length)}`
363
+ }
364
+ }
365
+ } else if (typeof item.libraryDir !== 'string' || item.libraryDir === '') {
366
+ item.libraryDir = nextRoot
367
+ }
368
+ rewritten.push(id)
369
+ }
370
+ if (rewritten.length > 0) {
371
+ const temporary = `${path}.${process.pid}.tmp`
372
+ await writeFile(temporary, `${JSON.stringify(parsed, null, 2)}\n`, 'utf8')
373
+ await rename(temporary, path)
374
+ }
375
+ return { rewritten, missing: false }
376
+ }
377
+
378
+ /**
379
+ * Keep only the newest pre-import snapshots.
380
+ * @param {string} backupDir - the plugin backup folder.
381
+ * @param {number} [keep] - how many to keep.
382
+ * @returns {Promise<void>} completion.
383
+ */
384
+ async function prunePreImports(backupDir, keep = 3) {
385
+ const names = (await readdir(backupDir).catch(() => []))
386
+ .filter(name => name.startsWith('pre-import-'))
387
+ .sort()
388
+ for (const name of names.slice(0, Math.max(0, names.length - keep))) {
389
+ await rm(join(backupDir, name), { recursive: true, force: true })
390
+ }
391
+ }
392
+
393
+ /**
394
+ * Import a verified archive with explicit conflict strategies. `merge` never
395
+ * overwrites: an existing file keeps its place and the imported copy becomes
396
+ * `<name>.imported-<ts>`. `overwrite` replaces after a pre-import snapshot.
397
+ * @param {{ archivePath: string, dataDir: string, dshHome?: string,
398
+ * libraryRoots?: Record<string, string>, strategy?: 'merge'|'overwrite'|'skip' }} options - archive and destinations.
399
+ * @returns {Promise<object>} the import report.
400
+ */
401
+ export async function importBackup(options) {
402
+ const { manifest, entries } = await readBackup(options.archivePath)
403
+ const dataDir = options.dataDir
404
+ const dshHome = typeof options.dshHome === 'string' && options.dshHome !== '' ? options.dshHome : dirname(dataDir)
405
+ const libraryRoots = options.libraryRoots !== null && typeof options.libraryRoots === 'object' ? options.libraryRoots : {}
406
+ const strategy = options.strategy === 'overwrite' || options.strategy === 'skip' ? options.strategy : 'merge'
407
+ const stamp = Date.now()
408
+ const backupDir = join(dataDir, 'backup')
409
+ const preImport = join(backupDir, `pre-import-${stamp}`)
410
+ const report = {
411
+ format: manifest.format,
412
+ createdAt: manifest.createdAt,
413
+ strategy,
414
+ imported: [],
415
+ renamed: [],
416
+ skipped: [],
417
+ warnings: [],
418
+ rewrittenLibraries: [],
419
+ }
420
+ await mkdir(backupDir, { recursive: true })
421
+ const snapshot = async target => {
422
+ const relative = target.replace(/[\\/]/g, '/').split('/').slice(-3).join('/')
423
+ const copy = join(preImport, String(report.imported.length + report.renamed.length), relative)
424
+ await mkdir(dirname(copy), { recursive: true })
425
+ await cp(target, copy, { recursive: true }).catch(() => {})
426
+ }
427
+ for (const [name, bytes] of entries) {
428
+ if (name === 'manifest.json') continue
429
+ const target = destinationOf(name, { dataDir, dshHome, libraryRoots })
430
+ if (target === null) {
431
+ report.warnings.push(`未映射:${name}`)
432
+ continue
433
+ }
434
+ const exists = await stat(target).catch(() => null)
435
+ if (exists !== null && strategy === 'skip') {
436
+ report.skipped.push(name)
437
+ continue
438
+ }
439
+ if (exists !== null && strategy === 'merge') {
440
+ const alternative = `${target}.imported-${stamp}`
441
+ await mkdir(dirname(alternative), { recursive: true })
442
+ await writeFile(alternative, bytes)
443
+ report.renamed.push(`${name} → ${alternative}`)
444
+ continue
445
+ }
446
+ if (exists !== null && strategy === 'overwrite') await snapshot(target)
447
+ await mkdir(dirname(target), { recursive: true })
448
+ await writeFile(target, bytes)
449
+ report.imported.push(name)
450
+ }
451
+ const rewritten = await rewriteLibraryRoots({ dataDir, manifest, libraryRoots })
452
+ report.rewrittenLibraries = rewritten.rewritten
453
+ report.libraryStateMissing = rewritten.missing
454
+ await writeFile(join(backupDir, 'last-import.json'), `${JSON.stringify(report, null, 2)}\n`, 'utf8')
455
+ await prunePreImports(backupDir, 3)
456
+ return report
457
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Orchestration for the chapter's shared-prefix sessions: prepare one hidden
3
+ * base session that reads the chapter text once, then fork one independent
4
+ * branch per conversation mode.
5
+ *
6
+ * A branch is created the way DSH requires: read the base session's raw log up
7
+ * to the recorded turn boundary and hand that prefix to `ctx.agents.create`
8
+ * with `meta.isSeeded` — only agent-loop-published sessions persist and get a
9
+ * driver. The services are injected so the policy is unit-tested.
10
+ * @module dsh-pdf-workbench/base-session
11
+ */
12
+
13
+ import { chapterTextPath } from './chapter-text.js'
14
+ import {
15
+ SESSION_MODES,
16
+ branchSessionId,
17
+ chapterSessionsStale,
18
+ readChapterSessions,
19
+ staleChapterSessions,
20
+ withBaseSession,
21
+ withBranchSession,
22
+ writeChapterSessions,
23
+ } from './chapter-sessions.js'
24
+
25
+ /** What the base session is told to do; it must not answer anything yet. */
26
+ export const BASE_READY_PROMPT = '通读本章全文,只回复 READY,不要回答问题,不要输出摘要。'
27
+
28
+ /**
29
+ * The seq a branch may fork at: the end boundary of the last completed turn.
30
+ * The running version returns `{ openTurnStartSeq, lastStepStartSeq,
31
+ * lastStepBoundary: { kind: 'end', seq }, lastTurn }`; an open turn has no end
32
+ * boundary and must not be forked mid-turn.
33
+ * @param {object} boundary - the value of `ctx.agents.turnBoundaryOf(session)`.
34
+ * @returns {number} the inclusive event seq, or 0 when the turn is still open.
35
+ */
36
+ export function boundarySeq(boundary) {
37
+ if (boundary === null || typeof boundary !== 'object') return 0
38
+ if (boundary.openTurnStartSeq !== null && boundary.openTurnStartSeq !== undefined) return 0
39
+ const last = boundary.lastStepBoundary
40
+ if (last === null || last === undefined || last.kind !== 'end') return 0
41
+ return Number.isFinite(last.seq) && last.seq > 0 ? last.seq : 0
42
+ }
43
+
44
+ /**
45
+ * The prompt for the hidden base session: read the extracted file, nothing else.
46
+ * @param {{ textPath: string, bookTitle?: string, chapterTitle?: string }} input - the chapter and its text file.
47
+ * @returns {string} the prompt.
48
+ */
49
+ export function baseReadPrompt(input) {
50
+ const title = [input.bookTitle, input.chapterTitle].filter(part => typeof part === 'string' && part !== '').join(' · ')
51
+ const head = title === '' ? '请' : `请先读《${title}》的章节全文文件:${input.textPath}。`
52
+ return `${head}\n${BASE_READY_PROMPT}`
53
+ }
54
+
55
+ /**
56
+ * Prepare (or reuse) the hidden base session of one chapter.
57
+ * @param {{
58
+ * agents: object, workspace?: object, libraryDir: string, book: string, code: string,
59
+ * cwd: string, pdf: { size: number, mtimeMs: number }, textPath: string,
60
+ * createMessage: (text: string) => object, newId: () => string,
61
+ * archive?: (id: string) => Promise<void>, bookTitle?: string, chapterTitle?: string,
62
+ * }} options - the services and the chapter identity.
63
+ * @returns {Promise<{ manifest: object, created: boolean, sessionId: string }>} the map and the base id.
64
+ */
65
+ export async function ensureBaseSession(options) {
66
+ const { agents, libraryDir, book, code, pdf } = options
67
+ const existing = await readChapterSessions(libraryDir, book, code)
68
+ if (existing !== null && !chapterSessionsStale(existing, pdf)) {
69
+ return { manifest: existing, created: false, sessionId: existing.base.id }
70
+ }
71
+ if (existing !== null) await staleChapterSessions(libraryDir, book, code)
72
+ const id = options.newId()
73
+ const handle = await agents.create({ sessionId: id, meta: { cwd: options.cwd } })
74
+ const agent = handle !== null && handle !== undefined && handle.agent !== undefined ? handle.agent : handle
75
+ const prompt = baseReadPrompt({ textPath: options.textPath ?? chapterTextPath(libraryDir, book, code), bookTitle: options.bookTitle, chapterTitle: options.chapterTitle })
76
+ agent.followup(options.createMessage(prompt))
77
+ await agent.whenIdle()
78
+ const boundary = agents.turnBoundaryOf(agent.session ?? agent)
79
+ let atSeq = options.atSeqOf(boundary)
80
+ // `lastStepBoundary` can end a step rather than the turn; a branch may only
81
+ // fork at a closed turn, so prefer the log's last `turn/end` when readable.
82
+ if (options.sessionQuery !== undefined && typeof options.sessionQuery.readSession === 'function') {
83
+ try {
84
+ const snapshot = await options.sessionQuery.readSession(id)
85
+ const ends = Array.isArray(snapshot.events) ? snapshot.events.filter(event => event.type === 'turn/end' && Number.isFinite(event.seq)) : []
86
+ if (ends.length > 0) atSeq = Math.max(...ends.map(event => Number(event.seq)))
87
+ } catch {
88
+ // Keep the boundary value; the branch step will reject an open turn.
89
+ }
90
+ }
91
+ if (!Number.isFinite(atSeq) || atSeq < 1) throw Object.assign(new Error('基础会话没有可用的轮次边界'), { code: 'no-boundary' })
92
+ const manifest = withBaseSession(null, { id, atSeq }, pdf)
93
+ await writeChapterSessions(libraryDir, book, code, manifest)
94
+ const archive = typeof options.archive === 'function'
95
+ ? options.archive
96
+ : options.workspace !== undefined && typeof options.workspace.archiveSession === 'function'
97
+ ? (sessionId) => options.workspace.archiveSession(sessionId, { stopActivity: true })
98
+ : null
99
+ if (archive !== null) await archive(id)
100
+ // The agent is idle and archived; disposing it leaves the persisted log
101
+ // readable for forks. The base is never handed to the UI.
102
+ if (handle !== null && handle !== undefined && typeof handle.dispose === 'function') await handle.dispose()
103
+ return { manifest, created: true, sessionId: id }
104
+ }
105
+
106
+ /**
107
+ * The session one mode should talk in: its existing branch, or a fresh seeded
108
+ * fork of the base at the recorded boundary.
109
+ * @param {{ agents: object, sessionQuery: object, libraryDir: string, book: string, code: string,
110
+ * cwd: string, manifest: object, mode: string, newId: () => string }} options - the services and the chapter map.
111
+ * @returns {Promise<{ manifest: object, sessionId: string, created: boolean }>} the selected branch.
112
+ */
113
+ export async function ensureBranchSession(options) {
114
+ const { agents, sessionQuery, libraryDir, book, code, manifest, mode } = options
115
+ if (!SESSION_MODES.includes(mode)) throw Object.assign(new Error(`未知模式:${mode}`), { code: 'bad-mode' })
116
+ if (manifest === null || typeof manifest !== 'object' || typeof manifest.base !== 'object' || manifest.base === null) {
117
+ throw Object.assign(new Error('本章还没有基础会话'), { code: 'no-base' })
118
+ }
119
+ const existing = branchSessionId(manifest, mode)
120
+ if (existing !== '') return { manifest, sessionId: existing, created: false }
121
+ const snapshot = await sessionQuery.readSession(manifest.base.id)
122
+ // Fork through the base's last completed turn, never a step boundary.
123
+ const events = Array.isArray(snapshot.events) ? snapshot.events : []
124
+ const ends = events.filter(event => event.type === 'turn/end' && Number.isFinite(event.seq))
125
+ const boundary = ends.length === 0 ? manifest.base.atSeq : Math.max(...ends.map(event => Number(event.seq)))
126
+ const prefix = events.filter(event => Number(event.seq) <= boundary)
127
+ if (prefix.length === 0) throw Object.assign(new Error('基础会话日志为空'), { code: 'no-seed' })
128
+ const sessionId = options.newId()
129
+ await agents.create({
130
+ sessionId,
131
+ seed: prefix,
132
+ inheritedEventCount: prefix.length,
133
+ meta: { cwd: options.cwd, isSeeded: true },
134
+ })
135
+ const next = withBranchSession(manifest, mode, sessionId)
136
+ await writeChapterSessions(libraryDir, book, code, next)
137
+ return { manifest: next, sessionId, created: true }
138
+ }
139
+
140
+ /**
141
+ * The modes a branch can be asked for.
142
+ * @returns {string[]} the mode names.
143
+ */
144
+ export function branchModes() {
145
+ return [...SESSION_MODES]
146
+ }