dsh-pack-and-go 0.2.1 → 0.2.3

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.md CHANGED
@@ -36,7 +36,7 @@
36
36
  |---|---|
37
37
  | Windows 10/11 | ✅ 已完成全链路验证(导入/导出/CDP UI) |
38
38
  | macOS | ✅ 2026-11-12 全量 220 项通过(P-04b/P-05a/P-05c/P-05d/P-06b/P-09) |
39
- | Linux(含服务器) | 🧪 代码与测试就绪,CLI 可用,CI 待跑 |
39
+ | Linux(含服务器) | ✅ 2026-11-12 全量 203 项通过(Ubuntu 24.04 / Node 24) |
40
40
  | WSL / Termux | 🧪 按 Node 运行环境支持(未单独验证) |
41
41
 
42
42
  要求:**Node.js ≥ 22.15**、装有 DSH 的任意 profile。
@@ -56,7 +56,7 @@ dsh plugin --profile desktop add github:VermilionPasvikin/dsh-pack-and-go
56
56
 
57
57
  重启 DSH 后,侧边栏出现「**迁移对话或工作区**」入口。
58
58
 
59
- **npm(发布后)**
59
+ **npm(已发布 0.2.1)**
60
60
 
61
61
  ```bash
62
62
  dsh plugin --profile desktop add dsh-pack-and-go
@@ -78,7 +78,7 @@ dsh plugin --profile <profile> add ./dsh-pack-and-go-0.2.1.tgz
78
78
 
79
79
  也可以在 DSH 插件管理页添加本地路径,或直接输入 npm / GitHub 坐标。安装后侧边栏出现「**迁移对话或工作区**」入口。
80
80
 
81
- > 兼容性:DSH `>=0.2.0 <0.3.0`(当前 0.2.2-rc.2 已验证);Node.js ≥ 22.15。
81
+ > 兼容性:DSH `>=0.2.0 <0.3.0`(当前 0.2.2-rc.5 已验证,2026-11-23 检出报告见 `docs/compat/reports/detect-0.2.2-rc.5.md`);Node.js ≥ 22.15。
82
82
 
83
83
  ### 使用(Web UI)
84
84
 
@@ -199,13 +199,13 @@ flowchart LR
199
199
  node --test "tests/unit/**/*.test.mjs" "tests/e2e/**/*.test.mjs"
200
200
  ```
201
201
 
202
- 当前 **220 项测试**:macOS 2026-11-12 全量 220 通过;Windows 199 通过 + 9 个 POSIX 权限用例预期跳过;Linux 203 为 B1 时点,B2 新增 5 项待 Linux CI 复核。另有 CDP 无头浏览器用例覆盖真实 UI 路径(导出/导入/冲突/迁移提示/仅工作区)。
202
+ 当前 **220 项测试**:macOS 2026-11-12 全量 220 通过;Windows 199 通过 + 9 个 POSIX 权限用例预期跳过;Linux 203 为 B1 时点,B2 新增 5 项待 Linux 复跑。另有 CDP 无头浏览器用例覆盖真实 UI 路径(导出/导入/冲突/迁移提示/仅工作区)。
203
203
 
204
204
  ---
205
205
 
206
206
  ## 🗺️ 状态与限制
207
207
 
208
- - 版本 `0.2.1`(SPEC v1.5);发布渠道:GitHub(可用)→ npm(发布后)→ dsh-market(收录后);发布步骤见 [docs/RELEASE.md](docs/RELEASE.md);
208
+ - 版本 `0.2.1`(SPEC v1.5);发布渠道:npm(`0.2.1` 已发布,`dsh plugin add dsh-pack-and-go`)/ GitHub(可用)→ dsh-market(收录审核中);发布步骤见 [docs/RELEASE.md](docs/RELEASE.md);
209
209
  - 取消功能与精确进度按用户决定不做(沿用转圈 + 阶段文案);
210
210
  - macOS 平台专项已完成(2026-11-12,220 项全通过);Linux 已完成符号链接/权限位/大小写/权限保真验证;
211
211
  - 已打开会话的回滚/迁移位置显示需要重启 DSH(DSH 未提供会话 reload API)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-pack-and-go",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "type": "module",
5
5
  "description": "Cross-platform migration for DSH conversations and workspaces",
6
6
  "license": "MIT",
package/src/cli/index.js CHANGED
@@ -11,6 +11,7 @@
11
11
  */
12
12
 
13
13
  import { randomUUID } from 'node:crypto'
14
+ import { existsSync } from 'node:fs'
14
15
  import { access, copyFile, mkdir, readFile, readdir, realpath, stat, writeFile } from 'node:fs/promises'
15
16
  import { join } from 'node:path'
16
17
  import { parseArgs } from 'node:util'
@@ -24,6 +25,9 @@ import {
24
25
  parseManifest,
25
26
  planExport,
26
27
  readZip,
28
+ normalizeSessionAgentState,
29
+ readSessionHeaderFromBuffer,
30
+ repairSessionFileReferences,
27
31
  restoreAttachments,
28
32
  restoreWorkspaceFiles,
29
33
  safeDirName,
@@ -36,6 +40,7 @@ const USAGE = `dsh-pack-and-go <命令> [选项]
36
40
  命令:
37
41
  export 导出对话
38
42
  import 导入迁移包
43
+ repair 修复已导入会话中失效的绝对文件路径
39
44
 
40
45
  选项:
41
46
  --home <目录> DSH_HOME(必填)
@@ -43,6 +48,8 @@ const USAGE = `dsh-pack-and-go <命令> [选项]
43
48
  --pack <文件> import 的迁移包(必填)
44
49
  --target <目录> import 的目标目录(必填,不会回退默认目录)
45
50
  --sessions <ids> export 只导出指定会话(逗号分隔)
51
+ --session <id> repair 只修复指定会话(可选)
52
+ --dry-run repair 只报告不写入
46
53
  -h, --help 显示帮助
47
54
  `
48
55
 
@@ -362,6 +369,86 @@ async function cmdImport(options) {
362
369
  )
363
370
  }
364
371
 
372
+ /**
373
+ * 修复已导入会话中失效的绝对路径(ADR-0017 补充)。
374
+ * @param {{ home?: string, session?: string, dryRun?: boolean }} options
375
+ */
376
+ async function cmdRepair(options) {
377
+ if (!options.home) fail('缺少 --home')
378
+ const sessionsRoot = join(options.home, 'sessions')
379
+ const projects = await readdir(sessionsRoot, { withFileTypes: true }).catch(() => [])
380
+ const wanted = typeof options.session === 'string' ? options.session.trim() : ''
381
+ let scanned = 0
382
+ let changedSessions = 0
383
+ let repaired = 0
384
+ let failed = 0
385
+
386
+ for (const project of projects.filter((entry) => entry.isDirectory())) {
387
+ const projectDir = join(sessionsRoot, project.name)
388
+ const dirs = await readdir(projectDir, { withFileTypes: true }).catch(() => [])
389
+ for (const dir of dirs.filter((entry) => entry.isDirectory())) {
390
+ const sessionDir = join(projectDir, dir.name)
391
+ const files = await readdir(sessionDir).catch(() => [])
392
+ const log = files.find((name) => /^session\.v\d+\.jsonl\.zstd$/.test(name))
393
+ if (!log) continue
394
+ const file = join(sessionDir, log)
395
+ let buffer
396
+ try {
397
+ buffer = await readFile(file)
398
+ } catch {
399
+ failed += 1
400
+ continue
401
+ }
402
+ let header
403
+ try {
404
+ header = readSessionHeaderFromBuffer(buffer)
405
+ } catch {
406
+ failed += 1
407
+ continue
408
+ }
409
+ const id = typeof header.id === 'string' ? header.id : dir.name
410
+ if (wanted && !dir.name.includes(wanted) && id !== wanted) continue
411
+ scanned += 1
412
+ const cwd = typeof header.cwd === 'string' ? header.cwd : ''
413
+ if (cwd.length === 0) continue
414
+ const exists = (relative) => existsSync(join(cwd, relative))
415
+ let result
416
+ try {
417
+ result = repairSessionFileReferences(buffer, { sessionCwd: cwd, exists })
418
+ } catch {
419
+ failed += 1
420
+ continue
421
+ }
422
+ let normalized
423
+ try {
424
+ normalized = normalizeSessionAgentState(result.buffer)
425
+ } catch {
426
+ failed += 1
427
+ continue
428
+ }
429
+ const rewritten = result.rewritten + normalized.rewritten
430
+ if (rewritten === 0) continue
431
+ changedSessions += 1
432
+ repaired += rewritten
433
+ result = { buffer: normalized.buffer, rewritten }
434
+ if (options['dry-run'] === true) {
435
+ console.log(`[dry-run] ${id}: 将改写 ${result.rewritten} 处(${file})`)
436
+ continue
437
+ }
438
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
439
+ const backup = `${file}.bak-${stamp}`
440
+ await copyFile(file, backup)
441
+ await writeFile(file, result.buffer)
442
+ console.log(`修复 ${id}: 改写 ${result.rewritten} 处,备份 ${backup}`)
443
+ }
444
+ }
445
+ console.log(
446
+ `完成:扫描 ${scanned} 个会话,修复 ${changedSessions} 个(${repaired} 处)${
447
+ failed > 0 ? `,失败 ${failed} 个` : ''
448
+ }。`,
449
+ )
450
+ }
451
+
365
452
  async function main() {
366
453
  let parsed
367
454
  try {
@@ -374,6 +461,8 @@ async function main() {
374
461
  pack: { type: 'string' },
375
462
  target: { type: 'string' },
376
463
  sessions: { type: 'string' },
464
+ session: { type: 'string' },
465
+ 'dry-run': { type: 'boolean' },
377
466
  workspace: { type: 'string', multiple: true },
378
467
  overwrite: { type: 'boolean' },
379
468
  help: { type: 'boolean', short: 'h' },
@@ -390,6 +479,7 @@ async function main() {
390
479
  }
391
480
  if (command === 'export') return cmdExport(parsed.values)
392
481
  if (command === 'import') return cmdImport(parsed.values)
482
+ if (command === 'repair') return cmdRepair(parsed.values)
393
483
  fail(`未知命令:${command}`)
394
484
  }
395
485
 
@@ -21,7 +21,12 @@ import { ERROR_CODES, MoverError } from './errors.js'
21
21
  import { parseManifest } from './manifest-io.js'
22
22
  import { sessionDir } from './paths.js'
23
23
  import { planImport } from './plan-import.js'
24
- import { rewriteSessionHeader, rewriteSessionWorkingDirectories } from './session-rewrite.js'
24
+ import {
25
+ normalizeSessionAgentState,
26
+ rewriteSessionFileReferences,
27
+ rewriteSessionHeader,
28
+ rewriteSessionWorkingDirectories,
29
+ } from './session-rewrite.js'
25
30
  import { readZip } from './zip-reader.js'
26
31
 
27
32
  /**
@@ -179,6 +184,30 @@ export async function importSessionsToDisk(input) {
179
184
  cwdEventsRewritten = result.rewritten
180
185
  }
181
186
 
187
+ // 重定位导入时 deliverables/presented 的绝对路径与 tool meta.cwd 仍指向源机器;
188
+ // DSH 的「在工作区中查看」会按新 cwd 解析这些路径,必须改成目标端可解析的形式
189
+ // (ADR-0017 补充,2026-11-18)。
190
+ let fileRefsRewritten = 0
191
+ if (session.targetCwd !== undefined && source.cwd !== session.targetCwd) {
192
+ const refs = rewriteSessionFileReferences(finalData, {
193
+ fromCwd: source.cwd,
194
+ toCwd: session.targetCwd,
195
+ sourcePlatform: manifest.source.platform,
196
+ targetPlatform,
197
+ })
198
+ finalData = refs.buffer
199
+ fileRefsRewritten = refs.rewritten
200
+ }
201
+
202
+ // 源机器的 auto 权限预设可能在目标 profile 不存在(DSH 恢复时报
203
+ // "cannot restore preset auto"),跨平台导入时归一化为 workspace-write(ADR-0017 补充二)。
204
+ let agentStateRewritten = 0
205
+ if (manifest.source.platform !== targetPlatform) {
206
+ const normalized = normalizeSessionAgentState(finalData)
207
+ finalData = normalized.buffer
208
+ agentStateRewritten = normalized.rewritten
209
+ }
210
+
182
211
  let backupPath
183
212
  if (session.action === 'overwrite' && backupDir) {
184
213
  backupPath = await backupExisting(file, backupDir)
@@ -212,6 +241,8 @@ export async function importSessionsToDisk(input) {
212
241
  ...(session.migrateFrom !== undefined ? { migrateFrom: session.migrateFrom } : {}),
213
242
  ...(backupPath !== undefined ? { backupPath } : {}),
214
243
  ...(cwdEventsRewritten > 0 ? { cwdEventsRewritten } : {}),
244
+ ...(fileRefsRewritten > 0 ? { fileRefsRewritten } : {}),
245
+ ...(agentStateRewritten > 0 ? { agentStateRewritten } : {}),
215
246
  })
216
247
  }
217
248
 
@@ -380,6 +380,354 @@ export function rewriteSessionWorkingDirectories(buffer, input = {}) {
380
380
  }
381
381
  }
382
382
 
383
+ /**
384
+ * 判断值是否为该平台的绝对路径。
385
+ * @param {string} value
386
+ * @param {string} platform
387
+ * @returns {boolean}
388
+ */
389
+ function isAbsolutePath(value, platform) {
390
+ if (typeof value !== 'string' || value.length === 0) return false
391
+ if (platform === 'win32') {
392
+ return /^[A-Za-z]:[\\/]/.test(value) || /^\\\\[^\\]/.test(value)
393
+ }
394
+ return value.startsWith('/')
395
+ }
396
+
397
+ /**
398
+ * 返回绝对路径相对 root 的 POSIX 相对路径;不在 root 下返回 undefined。
399
+ * @param {string} value
400
+ * @param {string} root
401
+ * @param {string} platform
402
+ * @returns {string|undefined}
403
+ */
404
+ function relativeUnderRoot(value, root, platform) {
405
+ const separator = separatorFor(platform)
406
+ const normalizedRoot = normalizeCwd(root, platform)
407
+ const normalizedValue = normalizeCwd(value, platform)
408
+ if (normalizedRoot.length === 0) return undefined
409
+ const foldedRoot = foldCwd(normalizedRoot, platform)
410
+ const foldedValue = foldCwd(normalizedValue, platform)
411
+ if (foldedValue === foldedRoot) return ''
412
+ const prefix = foldedRoot.endsWith(separator) ? foldedRoot : foldedRoot + separator
413
+ if (!foldedValue.startsWith(prefix)) return undefined
414
+ const start = normalizedRoot.length + (normalizedRoot.endsWith(separator) ? 0 : 1)
415
+ return normalizedValue.slice(start).split(separator).join('/')
416
+ }
417
+
418
+ /**
419
+ * 统一的事件行重写:首帧原样保留,事件帧按行解压/变换/重压。
420
+ * @param {Buffer} buffer
421
+ * @param {(event: Record<string, any>) => boolean} transform 返回 true 表示事件被改写
422
+ * @param {number} [chunkBytes]
423
+ * @returns {{ buffer: Buffer, rewritten: number }}
424
+ */
425
+ function rewriteEventLines(buffer, transform, chunkBytes = EVENT_FRAME_BYTES) {
426
+ if (!Buffer.isBuffer(buffer)) {
427
+ throw headerError('会话改写需要 Buffer 输入', { reason: 'not-buffer' })
428
+ }
429
+ if (!Number.isSafeInteger(chunkBytes) || chunkBytes <= 0) {
430
+ throw headerError('chunkBytes 必须是正整数', { reason: 'invalid-chunk-size' })
431
+ }
432
+ const { frames, first, header } = decodeSessionHeader(buffer)
433
+ assertCurrentVersion(header)
434
+ if (frames.length === 1) return { buffer, rewritten: 0 }
435
+
436
+ const eventFrames = frames.slice(1)
437
+ const decoded = []
438
+ for (const frame of eventFrames) {
439
+ try {
440
+ decoded.push(zlib.zstdDecompressSync(buffer.subarray(frame.start, frame.end)))
441
+ } catch (error) {
442
+ throw frameError('事件帧解压失败', {
443
+ reason: 'decompress-failed',
444
+ offset: frame.start,
445
+ cause: error instanceof Error ? error.message : String(error),
446
+ })
447
+ }
448
+ }
449
+
450
+ const text = Buffer.concat(decoded).toString('utf8')
451
+ const trailingNewline = text.endsWith('\n')
452
+ const lines = text.split('\n')
453
+ if (trailingNewline) lines.pop()
454
+
455
+ let rewritten = 0
456
+ const nextLines = lines.map((line) => {
457
+ if (line.length === 0) return line
458
+ let event
459
+ try {
460
+ event = JSON.parse(line)
461
+ } catch {
462
+ return line
463
+ }
464
+ if (event === null || typeof event !== 'object') return line
465
+ if (transform(event) !== true) return line
466
+ rewritten += 1
467
+ return JSON.stringify(event)
468
+ })
469
+
470
+ if (rewritten === 0) return { buffer, rewritten: 0 }
471
+ const eventFramesOut = packEventFrames(
472
+ nextLines,
473
+ trailingNewline,
474
+ chunkBytes,
475
+ eventFrames[0].checksum,
476
+ )
477
+ return {
478
+ buffer: Buffer.concat([buffer.subarray(first.start, first.end), ...eventFramesOut]),
479
+ rewritten,
480
+ }
481
+ }
482
+
483
+ /**
484
+ * 跨平台/重定位导入时改写结构化文件引用路径(ADR-0017 补充):
485
+ *
486
+ * - `deliverables/presented` 的 `data.files[].path`:源根下绝对路径 → 工作区相对 POSIX 路径,
487
+ * 保证 DSH 的 `/api/present.open` 在新 cwd 下仍可解析;
488
+ * - `tool/result`/`tool/call` 的 `data.meta.cwd`:源根 cwd → 目标 cwd;
489
+ * - 历史消息正文里的路径文本不改(沿用 ADR-0001 Q4)。
490
+ *
491
+ * @param {Buffer} buffer
492
+ * @param {{
493
+ * fromCwd?: string,
494
+ * toCwd: string,
495
+ * sourcePlatform: 'win32'|'darwin'|'linux',
496
+ * targetPlatform: 'win32'|'darwin'|'linux',
497
+ * chunkBytes?: number
498
+ * }} input
499
+ * @returns {{ buffer: Buffer, rewritten: number }}
500
+ */
501
+ export function rewriteSessionFileReferences(buffer, input = {}) {
502
+ const { fromCwd, toCwd, sourcePlatform, targetPlatform } = input
503
+ if (typeof toCwd !== 'string' || toCwd.length === 0) {
504
+ throw headerError('toCwd 必须是非空字符串', { reason: 'invalid-cwd' })
505
+ }
506
+ separatorFor(sourcePlatform)
507
+ separatorFor(targetPlatform)
508
+ const target = normalizeCwd(toCwd, targetPlatform)
509
+
510
+ return rewriteEventLines(
511
+ buffer,
512
+ (event) => {
513
+ let changed = false
514
+
515
+ if (event.type === 'deliverables/presented') {
516
+ const files = event.data?.files
517
+ if (Array.isArray(files)) {
518
+ for (const file of files) {
519
+ if (!file || typeof file.path !== 'string' || file.path.length === 0) continue
520
+ const path = file.path
521
+ let relative
522
+ if (isAbsolutePath(path, sourcePlatform)) {
523
+ relative = relativeUnderRoot(path, fromCwd ?? '', sourcePlatform)
524
+ }
525
+ if (
526
+ (relative === undefined || relative.length === 0) &&
527
+ isAbsolutePath(path, targetPlatform)
528
+ ) {
529
+ relative = relativeUnderRoot(path, target, targetPlatform)
530
+ }
531
+ if (relative !== undefined && relative.length > 0 && relative !== path) {
532
+ file.path = relative
533
+ changed = true
534
+ }
535
+ }
536
+ }
537
+ } else if (event.type === 'tool/result' || event.type === 'tool/call') {
538
+ const meta = event.data?.meta
539
+ if (meta && typeof meta.cwd === 'string' && meta.cwd.length > 0) {
540
+ const mapped = mapSessionCwd(meta.cwd, {
541
+ fromCwd,
542
+ toCwd,
543
+ sourcePlatform,
544
+ targetPlatform,
545
+ })
546
+ if (mapped !== meta.cwd) {
547
+ meta.cwd = mapped
548
+ changed = true
549
+ }
550
+ }
551
+ }
552
+
553
+ return changed
554
+ },
555
+ input.chunkBytes ?? EVENT_FRAME_BYTES,
556
+ )
557
+ }
558
+
559
+ /**
560
+ * 跨平台导入时归一化会话的权限状态(ADR-0017 补充二):
561
+ *
562
+ * 源机器可能启用目标 profile 不存在的 `auto` 权限预设;DSH 恢复会话时
563
+ * `cannot restore preset "auto" without its active integration`,会话不可用。
564
+ * 仅当会话里出现 `permission/preset = auto` 时:
565
+ * - `permission/preset` 的 auto → `workspace-write`;
566
+ * - `sandbox/mode` 的 danger-full-access → `workspace-write`;
567
+ * - `approval/policy` 的 never → `ask`。
568
+ *
569
+ * @param {Buffer} buffer
570
+ * @param {{ preset?: string, sandbox?: string, chunkBytes?: number }} [input]
571
+ * @returns {{ buffer: Buffer, rewritten: number }}
572
+ */
573
+ export function normalizeSessionAgentState(buffer, input = {}) {
574
+ const preset =
575
+ typeof input.preset === 'string' && input.preset.length > 0 ? input.preset : 'workspace-write'
576
+ const sandbox =
577
+ typeof input.sandbox === 'string' && input.sandbox.length > 0
578
+ ? input.sandbox
579
+ : 'workspace-write'
580
+
581
+ // 先判断是否存在 auto 预设;没有时不触碰任何事件字节(同平台/普通会话零改动)。
582
+ if (!Buffer.isBuffer(buffer)) {
583
+ throw headerError('会话改写需要 Buffer 输入', { reason: 'not-buffer' })
584
+ }
585
+ const frames = scanFrames(buffer)
586
+ let hasAuto = false
587
+ for (const frame of frames.slice(1)) {
588
+ let text
589
+ try {
590
+ text = zlib.zstdDecompressSync(buffer.subarray(frame.start, frame.end)).toString('utf8')
591
+ } catch {
592
+ continue
593
+ }
594
+ for (const line of text.split('\n')) {
595
+ if (line.length === 0) continue
596
+ try {
597
+ const event = JSON.parse(line)
598
+ if (event?.type === 'permission/preset' && event.data?.preset === 'auto') {
599
+ hasAuto = true
600
+ break
601
+ }
602
+ } catch {
603
+ // 非 JSON 行忽略
604
+ }
605
+ }
606
+ if (hasAuto) break
607
+ }
608
+ if (!hasAuto) return { buffer, rewritten: 0 }
609
+
610
+ return rewriteEventLines(
611
+ buffer,
612
+ (event) => {
613
+ let changed = false
614
+ if (event.type === 'permission/preset' && event.data?.preset === 'auto') {
615
+ event.data.preset = preset
616
+ changed = true
617
+ }
618
+ if (event.type === 'sandbox/mode' && event.data?.mode === 'danger-full-access') {
619
+ event.data.mode = sandbox
620
+ changed = true
621
+ }
622
+ if (event.type === 'approval/policy' && event.data?.policy === 'never') {
623
+ event.data.policy = 'ask'
624
+ changed = true
625
+ }
626
+ return changed
627
+ },
628
+ input.chunkBytes ?? EVENT_FRAME_BYTES,
629
+ )
630
+ }
631
+
632
+ /**
633
+ * 修复已导入会话中的失效绝对路径(ADR-0017 补充,repair 命令使用):
634
+ *
635
+ * - `deliverables/presented`:绝对且目标端不存在的路径,按最长后缀在 `sessionCwd`
636
+ * 下查找真实文件,命中后写成工作区相对 POSIX 路径;
637
+ * - `tool/result`/`tool/call` 的 `meta.cwd` 与 `working-directory/change` 的 `cwd`:
638
+ * 绝对且不等于 `sessionCwd` 时改为 `sessionCwd`。
639
+ *
640
+ * @param {Buffer} buffer
641
+ * @param {{
642
+ * sessionCwd: string,
643
+ * exists?: (relativePosix: string) => boolean,
644
+ * chunkBytes?: number
645
+ * }} input
646
+ * @returns {{ buffer: Buffer, rewritten: number }}
647
+ */
648
+ export function repairSessionFileReferences(buffer, input = {}) {
649
+ const sessionCwd = typeof input.sessionCwd === 'string' ? input.sessionCwd : ''
650
+ if (sessionCwd.length === 0) {
651
+ throw headerError('sessionCwd 必须是非空字符串', { reason: 'invalid-cwd' })
652
+ }
653
+ const exists = typeof input.exists === 'function' ? input.exists : undefined
654
+
655
+ return rewriteEventLines(
656
+ buffer,
657
+ (event) => {
658
+ let changed = false
659
+
660
+ if (event.type === 'deliverables/presented' && exists !== undefined) {
661
+ const files = event.data?.files
662
+ if (Array.isArray(files)) {
663
+ for (const file of files) {
664
+ if (!file || typeof file.path !== 'string' || file.path.length === 0) continue
665
+ const path = file.path
666
+ if (!isAbsolutePath(path, 'win32') && !isAbsolutePath(path, 'linux')) continue
667
+ const segments = path
668
+ .replace(/\\/g, '/')
669
+ .split('/')
670
+ .filter((segment) => segment.length > 0)
671
+ let start = 0
672
+ if (segments.length > 0 && /^[A-Za-z]:$/.test(segments[0])) start = 1
673
+ let relative
674
+ for (let index = start; index < segments.length; index += 1) {
675
+ const candidate = segments.slice(index).join('/')
676
+ if (exists(candidate)) {
677
+ relative = candidate
678
+ break
679
+ }
680
+ }
681
+ if (relative !== undefined && relative !== path) {
682
+ file.path = relative
683
+ changed = true
684
+ }
685
+ }
686
+ }
687
+ }
688
+
689
+ if (event.type === 'working-directory/change') {
690
+ const cwd = event.data?.cwd
691
+ if (
692
+ typeof cwd === 'string' &&
693
+ cwd.length > 0 &&
694
+ cwd !== sessionCwd &&
695
+ (isAbsolutePath(cwd, 'win32') || isAbsolutePath(cwd, 'linux'))
696
+ ) {
697
+ event.data.cwd = sessionCwd
698
+ changed = true
699
+ }
700
+ }
701
+
702
+ if (event.type === 'tool/result' || event.type === 'tool/call') {
703
+ const meta = event.data?.meta
704
+ if (
705
+ meta &&
706
+ typeof meta.cwd === 'string' &&
707
+ meta.cwd.length > 0 &&
708
+ meta.cwd !== sessionCwd &&
709
+ (isAbsolutePath(meta.cwd, 'win32') || isAbsolutePath(meta.cwd, 'linux'))
710
+ ) {
711
+ meta.cwd = sessionCwd
712
+ changed = true
713
+ }
714
+ }
715
+
716
+ return changed
717
+ },
718
+ input.chunkBytes ?? EVENT_FRAME_BYTES,
719
+ )
720
+ }
721
+
722
+ /**
723
+ * 读取会话首帧 header(repair 等诊断用途)。
724
+ * @param {Buffer} buffer
725
+ * @returns {Record<string, any>}
726
+ */
727
+ export function readSessionHeaderFromBuffer(buffer) {
728
+ return decodeSessionHeader(buffer).header
729
+ }
730
+
383
731
  /**
384
732
  * 读取会话文件、改写 cwd、写入目标文件。
385
733
  * @param {string} sourcePath