dsh-profile-config-sync 0.6.47 → 0.7.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.
@@ -10,7 +10,8 @@
10
10
  // 2. 任何探测失败都返回空/默认值,**绝不抛**:调用方拿到的永远是可用值。
11
11
  // 3. 平台差异只允许出现在本文件。业务代码里出现 process.platform 就是漏了这层。
12
12
 
13
- import { existsSync, statSync } from 'node:fs'
13
+ import { spawnSync } from 'node:child_process'
14
+ import { closeSync, existsSync, openSync, readFileSync as require$readFileSync, readSync, statSync } from 'node:fs'
14
15
  import { homedir } from 'node:os'
15
16
  import { delimiter, join, sep } from 'node:path'
16
17
 
@@ -85,12 +86,18 @@ export function pathExists(path) {
85
86
  * 两个判据都必须接受「asar 是目录」这一形态 —— 打包版 Electron 里
86
87
  * statSync('app.asar').isDirectory() 才是 true,只写 isFile() 会让
87
88
  * 真实客户端永远认不出自己的根。
89
+ *
90
+ * 0.6.49:判据本身只认「Windows 形状」(<root>/resources/...),但 macOS 的
91
+ * .app bundle 是 <root>/Contents/Resources/... —— 所以这里先把 .app 归一成
92
+ * Windows 形状再判(normalizeAppRoot)。少了这一步,macOS 上**所有**候选都判 false,
93
+ * resolveAppRoot 返回空串,面板直接报「定位不到客户端根目录」、三份脚本生成不了。
88
94
  */
89
95
  export function isAppRoot(path) {
90
96
  if (!path) return false
91
- const asar = join(path, 'resources', 'app.asar')
92
- if (pathExists(asar)) return true
93
- return isFile(join(path, 'resources', 'app', 'package.json'))
97
+ const layout = appRootLayout(path)
98
+ if (!layout.resources) return false
99
+ if (pathExists(join(layout.resources, 'app.asar'))) return true
100
+ return isFile(join(layout.resources, 'app', 'package.json'))
94
101
  }
95
102
 
96
103
  /**
@@ -137,6 +144,10 @@ export function appRootCandidates() {
137
144
  * macOS 上 Electron 应用的 resources 目录在 `Xxx.app/Contents/Resources`,
138
145
  * 而插件被部署在 `<AppRoot>` 的上一级。这里把 .app 内的 Resources 归一成
139
146
  * 与 Windows 一致的形状,让上层逻辑(readAppMeta / hostDshNodeModules)不用改。
147
+ *
148
+ * 0.6.49:只在真的认出 Contents/Resources 时才归一 —— 原来无条件返回内层路径,
149
+ * 于是一个**不是** .app bundle 的目录(例如用户把 appRoot 填成 .../Contents/Resources)
150
+ * 会被反复套娃。现在认不出就原样返回。
140
151
  */
141
152
  export function normalizeAppRoot(path) {
142
153
  if (!path || !isDir(path)) return path
@@ -152,10 +163,12 @@ export function normalizeAppRoot(path) {
152
163
  *
153
164
  * Windows:就是 AppRoot 本身。
154
165
  * macOS:.app bundle → Contents/MacOS(可执行)与 Contents/Resources(资源)。
166
+ * 非 .app 的 macOS 安装(解包目录)退回 <root>/resources。
167
+ * 0.6.49:原来 macOS 分支只认 .app,解包版会被算成 macos=<root>/resources(错)。
155
168
  */
156
169
  export function appRootLayout(appRoot) {
157
170
  if (!appRoot) return { root: appRoot, resources: '', macos: '' }
158
- if (IS_MAC && appRoot.endsWith('.app')) {
171
+ if (IS_MAC && appRoot.endsWith('.app') && isDir(join(appRoot, 'Contents', 'Resources'))) {
159
172
  return {
160
173
  root: appRoot,
161
174
  resources: join(appRoot, 'Contents', 'Resources'),
@@ -165,6 +178,139 @@ export function appRootLayout(appRoot) {
165
178
  return { root: appRoot, resources: join(appRoot, 'resources'), macos: appRoot }
166
179
  }
167
180
 
181
+ /**
182
+ * 客户端 resources 目录下 app.asar 的路径(不存在也返回路径)。
183
+ * 0.6.49:macOS 上 asar 在 <root>/Contents/Resources/app.asar,原来各处直接
184
+ * join(appRoot,'resources','app.asar') 在 macOS 上必定读不到 → 版本、bundle 清单全空。
185
+ */
186
+ export function asarPath(appRoot) {
187
+ const res = appRootLayout(appRoot).resources
188
+ return res ? join(res, 'app.asar') : ''
189
+ }
190
+
191
+ /**
192
+ * 读 asar 里的一个 JSON 文件。两种读法都试:
193
+ * 1) Electron 主进程把 asar 当目录挂载 → 直接按路径读(普通 node 读不到,返回 null 即可);
194
+ * 2) 不依赖挂载 → 自己解析 asar 头(Header 里的 files 树 + offset)。
195
+ * 读不到返回 null(调用方据此降级,不报错)。
196
+ */
197
+ export function readAsarJson(appRoot, relPath = 'dsh/package.json') {
198
+ const asar = asarPath(appRoot)
199
+ if (!asar) return null
200
+ const viaMount = (() => {
201
+ try { return JSON.parse(require$readFileSync(join(asar, relPath), 'utf8')) } catch { return null }
202
+ })()
203
+ if (viaMount) return viaMount
204
+ if (!isFile(asar)) return null
205
+ try {
206
+ const fd = openSync(asar, 'r')
207
+ try {
208
+ const head = Buffer.alloc(16)
209
+ readSync(fd, head, 0, 16, 0)
210
+ const headerSize = head.readUInt32LE(4)
211
+ const jsonLen = head.readUInt32LE(12)
212
+ if (jsonLen < 2 || jsonLen > 64 * 1024 * 1024) return null
213
+ const json = Buffer.alloc(jsonLen)
214
+ readSync(fd, json, 0, jsonLen, 16)
215
+ const header = JSON.parse(json.toString('utf8'))
216
+ let node = header
217
+ for (const seg of String(relPath).split('/').filter(Boolean)) node = node && node.files ? node.files[seg] : null
218
+ const entry = node
219
+ if (!entry || entry.size == null || entry.offset == null) return null
220
+ const body = Buffer.alloc(Number(entry.size))
221
+ readSync(fd, body, 0, Number(entry.size), 8 + headerSize + Number(entry.offset))
222
+ return JSON.parse(body.toString('utf8'))
223
+ } finally { closeSync(fd) }
224
+ } catch { return null }
225
+ }
226
+
227
+ /**
228
+ * 客户端 app 版本(面板「本机 / 契约」那一格)。
229
+ * 解包版读 resources/app/package.json;打包版读 asar 里的 dsh/package.json。
230
+ * 0.6.49:路径统一走 asarPath → macOS 上也读得到(原来 macOS 恒为空)。
231
+ */
232
+ export function readAppVersion(appRoot) {
233
+ if (!appRoot) return ''
234
+ const res = appRootLayout(appRoot).resources
235
+ if (!res) return ''
236
+ const plain = (() => {
237
+ try { return JSON.parse(require$readFileSync(join(res, 'app', 'package.json'), 'utf8')) } catch { return null }
238
+ })()
239
+ if (plain && plain.version) return String(plain.version)
240
+ const pkg = readAsarJson(appRoot, 'dsh/package.json')
241
+ if (pkg && pkg.version) return String(pkg.version)
242
+ return ''
243
+ }
244
+
245
+ /**
246
+ * Electron 版本(面板元信息行 "app 0.2.2-rc.5 / Electron 44.7.0")。
247
+ *
248
+ * 三个来源,按可信度:
249
+ * 1) Windows:<root>/version(Electron 自己写的版本文件);
250
+ * 2) 宿主进程内:process.versions.electron(插件就跑在 Electron 主进程里,最准);
251
+ * 3) macOS:.app 里 Electron Framework 的 Info.plist(XML,取 CFBundleVersion)。
252
+ * 读不到返回空串 —— 调用方显示 '?',不假装知道。
253
+ */
254
+ let electronVersionCache = null
255
+ export function readElectronVersion(appRoot) {
256
+ if (electronVersionCache !== null) return electronVersionCache
257
+ electronVersionCache = ''
258
+ if (appRoot) {
259
+ try {
260
+ const v = require$readFileSync(join(appRoot, 'version'), 'utf8').trim()
261
+ if (v) { electronVersionCache = v; return electronVersionCache }
262
+ } catch { /* 没有这个文件是常态(macOS / Linux) */ }
263
+ }
264
+ const inProcess = (() => { try { return String(process.versions.electron || '') } catch { return '' } })()
265
+ if (inProcess) { electronVersionCache = inProcess; return electronVersionCache }
266
+ if (IS_MAC && appRoot && appRoot.endsWith('.app')) {
267
+ const plist = join(appRoot, 'Contents', 'Frameworks', 'Electron Framework.framework',
268
+ 'Versions', 'A', 'Resources', 'Info.plist')
269
+ try {
270
+ const xml = require$readFileSync(plist, 'utf8')
271
+ const m = /<key>CFBundleVersion<\/key>\s*<string>([^<]+)<\/string>/.exec(xml)
272
+ if (m) electronVersionCache = m[1].trim()
273
+ } catch { /* 读不到就空 */ }
274
+ }
275
+ return electronVersionCache
276
+ }
277
+
278
+ /**
279
+ * 本机默认的同步仓库目录(面板输入框的占位符、自动探测的候选都用它)。
280
+ * 0.6.49 之前只有 Windows 语义(D:\dsh-config),macOS 用户看到占位符是盘符路径。
281
+ */
282
+ export function defaultRepoPath() {
283
+ return IS_WIN ? 'D:\\dsh-config' : join(homedir(), 'dsh-config')
284
+ }
285
+
286
+ /**
287
+ * 仓库路径的合法性(按平台分档)。
288
+ *
289
+ * 为什么必须分档:macOS / Linux 上把 `D:\dsh-config` 当相对路径处理,
290
+ * mkdirSync 会在当前工作目录里真的建出一个名为 `D:\dsh-config` 的目录
291
+ * (0.6.47 实测:在项目根留下一个这样的空目录)。反过来 Windows 上
292
+ * 也不该接受 `/Users/x/dsh-config`。返回 { ok, reason },调用方整批报错。
293
+ */
294
+ export function repoPathProblem(p) {
295
+ const s = String(p == null ? '' : p).trim()
296
+ if (!s) return { ok: false, reason: 'empty' }
297
+ if (IS_WIN) {
298
+ const ok = /^[A-Za-z]:[\\/]/.test(s) || s.startsWith('\\\\')
299
+ return ok ? { ok: true, reason: '' } : { ok: false, reason: 'windows-absolute' }
300
+ }
301
+ if (/^[A-Za-z]:[\\/]/.test(s) || s.startsWith('\\\\')) return { ok: false, reason: 'windows-shape' }
302
+ if (!s.startsWith('/')) return { ok: false, reason: 'posix-absolute' }
303
+ return { ok: true, reason: '' }
304
+ }
305
+
306
+ /**
307
+ * 自动化开关 / 退出后执行的执行体在哪个平台上有实现。
308
+ * Windows 走 PowerShell 脚本;macOS / Linux 走 Node 脚本(post-exit.mjs)。
309
+ */
310
+ export function postExitScriptName() {
311
+ return IS_WIN ? 'post-exit.ps1' : 'post-exit.mjs'
312
+ }
313
+
168
314
  /**
169
315
  * 客户端可执行文件(用于「DSH 是否还在运行」判断与重启)。
170
316
  * Windows: <root>\DeepSeek Harness.exe
@@ -199,6 +345,53 @@ export function clientProcessNames() {
199
345
  return ['dsh', 'deepseek-harness', 'DeepSeek Harness']
200
346
  }
201
347
 
348
+ /**
349
+ * 这行 `ps` 输出是不是「客户端本体」进程。
350
+ *
351
+ * 为什么不能按进程名模糊匹配(0.6.49 实测踩到):powershell/pgrep 用
352
+ * `-f "DeepSeek Harness"` 去匹配整条命令行时,**我们自己的等待进程**命令行里就带着
353
+ * `/Applications/DeepSeek Harness.app/Contents/Resources/runtime/.../node post-exit.mjs` ——
354
+ * 于是它永远认为自己要等的客户端还在跑,等到超时也不会动手;`pkill -f` 更糟,会把自己杀掉。
355
+ *
356
+ * 判据因此收紧到「客户端可执行文件本身的路径」:.app 里是 Contents/MacOS/<name>,
357
+ * 而 Node 运行时在 Contents/Resources 下,两者不会互相误伤。
358
+ */
359
+ export function looksLikeClientProcess(cmdline, appRoot, selfPid = 0) {
360
+ const cmd = String(cmdline || '')
361
+ if (!cmd) return false
362
+ const exe = clientExecutable(appRoot)
363
+ if (exe && cmd.includes(exe)) return true
364
+ if (exe) return false
365
+ // 拿不到可执行文件(appRoot 没定位到)时退回保守判据:带客户端名,但排除我们自己的
366
+ // Node 执行体(post-exit / install-plugin / 宿主 runtime 里的 node)
367
+ if (!/DeepSeek Harness/.test(cmd)) return false
368
+ if (/post-exit\.mjs|install-plugin\.mjs|\/Resources\/runtime\//.test(cmd)) return false
369
+ void selfPid
370
+ return true
371
+ }
372
+
373
+ /** 用 `ps` 列出当前匹配到的客户端进程 pid(不含自己)。找不到 ps 时返回 null。 */
374
+ export function listClientProcesses(appRoot, selfPid = 0) {
375
+ const r = spawnSync('ps', ['-Ao', 'pid=,command='], { encoding: 'utf8', timeout: 8000 })
376
+ if (r.error || typeof r.stdout !== 'string') return null
377
+ const out = []
378
+ for (const line of r.stdout.split(/\r?\n/)) {
379
+ const m = /^\s*(\d+)\s+(.*)$/.exec(line)
380
+ if (!m) continue
381
+ const pid = Number(m[1])
382
+ if (!pid || pid === selfPid) continue
383
+ if (looksLikeClientProcess(m[2], appRoot, selfPid)) out.push(pid)
384
+ }
385
+ return out
386
+ }
387
+
388
+ /** 命令行匹配用的客户端模式(给 .sh 脚本里的 pgrep 用,避开我们自己的 Node 进程)。 */
389
+ export function clientProcessPattern(appRoot) {
390
+ const exe = clientExecutable(appRoot)
391
+ if (exe) return exe.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
392
+ return 'DeepSeek Harness\\.app/Contents/MacOS'
393
+ }
394
+
202
395
  /** 宿主自带 bundle 的落点(解包版 / 打包版)。 */
203
396
  export function hostDshNodeModules(appRoot) {
204
397
  const layout = appRootLayout(appRoot)
@@ -0,0 +1,319 @@
1
+ /**
2
+ * 跨平台移植:把另一套系统上传的配置改成本机能用的样子。
3
+ *
4
+ * 为什么需要这一层:0.6.49 之前只有 Windows 版,"换机还原"默认两边都是 Windows。
5
+ * 现在 macOS 也能同步,云端的 `profile/package.json` 里就会出现
6
+ *
7
+ * "@local/dsh-personal": "link:{{ROOT:userHome}}/AppData/Local/dsh-personal"
8
+ *
9
+ * 这类依赖 —— 在 macOS 上展开成 `/Users/xxx/AppData/Local/dsh-personal`,目录不存在,
10
+ * pnpm 解不出 link 依赖,profile 起不来。`cordis.patch.yml`、`settings/dsh-workspaces.json`、
11
+ * `prompt/AGENTS.md` 里同理全是 `D:\project\...` 之类的路径。
12
+ *
13
+ * 这一层的态度:**能翻的翻,翻了不可用的直接丢掉并写清楚原因**,绝不原样铺过去。
14
+ * 翻译规则按「最像的对应物」排优先级,全部以本机文件系统是否存在为准:
15
+ *
16
+ * ① 用户在 `config-sync-port.json` 里写死的映射(最长前缀优先);
17
+ * ② `%USERPROFILE%` / `%LOCALAPPDATA%` / `%APPDATA%` 这类环境变量;
18
+ * ③ WSL 的 `/mnt/c/Users/<U>/...`;
19
+ * ④ `C:\Users\<U>\<rest>` → `<userHome>/<rest>`;
20
+ * ⑤ `D:\<...>\<leaf>` → 本机同名工作区(按标题 / 目录名匹配)→ `<userHome>/projects/<leaf>`
21
+ * → `<userHome>/<leaf>` → `<userHome>/Documents/<leaf>`,取第一个真实存在的。
22
+ *
23
+ * 一条都命中不了就返回 null,调用方据此跳过该项(而不是写一个不存在的路径)。
24
+ */
25
+
26
+ import { existsSync, readFileSync } from 'node:fs'
27
+ import { constants as fsConstants } from 'node:fs'
28
+ import { accessSync } from 'node:fs'
29
+ import { basename, join } from 'node:path'
30
+
31
+ export const PORT_CONFIG_NAME = 'config-sync-port.json'
32
+
33
+ /** 读用户写的映射表。格式:{ "paths": { "D:\\c": "{{ROOT:userHome}}/dsh-personal" }, "extra": ["D:\\data"] } */
34
+ export function readPortConfig(dshHome) {
35
+ const out = { paths: [], ok: true, note: '' }
36
+ const p = join(dshHome, PORT_CONFIG_NAME)
37
+ if (!existsSync(p)) return out
38
+ let doc = null
39
+ try {
40
+ doc = JSON.parse(readFileSync(p, 'utf8').replace(/^\uFEFF/, ''))
41
+ } catch (e) {
42
+ return { paths: [], ok: false, note: `${PORT_CONFIG_NAME} 不是合法 JSON:${e && e.message ? e.message : e}` }
43
+ }
44
+ const map = doc && typeof doc.paths === 'object' && doc.paths ? doc.paths : {}
45
+ for (const [from, to] of Object.entries(map)) {
46
+ if (!from || typeof to !== 'string' || !to) continue
47
+ out.paths.push({ from: String(from), to })
48
+ }
49
+ // 长前缀优先,避免 D:\c 抢走 D:\c\dsh-personal 的匹配
50
+ out.paths.sort((a, b) => b.from.length - a.from.length)
51
+ return out
52
+ }
53
+
54
+ /** 本机上下文:家目录、工作区清单、根占位符表。 */
55
+ export function portContext({ userHome, roots = {}, localWorkspaces = [], portConfig = { paths: [] }, expand = null } = {}) {
56
+ return {
57
+ userHome,
58
+ roots,
59
+ localWorkspaces: Array.isArray(localWorkspaces) ? localWorkspaces : [],
60
+ rules: Array.isArray(portConfig.paths) ? portConfig.paths : [],
61
+ // 可选:把 {{ROOT:x}} / {{DSH_HOME}} 这类占位符展开成真实路径(由调用方注入,避免两个模块互相依赖)
62
+ expand: typeof expand === 'function' ? expand : null,
63
+ exists: (p) => {
64
+ try {
65
+ accessSync(p, fsConstants.F_OK)
66
+ return true
67
+ } catch {
68
+ return false
69
+ }
70
+ },
71
+ }
72
+ }
73
+
74
+ /** 把 {{ROOT:x}} 占位符展开成真实路径(会用 ctx.roots,缺的返回 null 交给调用方判空)。 */
75
+ function expandPlaceholders(text, ctx) {
76
+ return String(text).replace(/\{\{ROOT:([A-Za-z0-9_.-]+)\}\}/g, (m, name) => {
77
+ const v = ctx.roots[name]
78
+ return typeof v === 'string' && v ? v : m
79
+ })
80
+ }
81
+
82
+ /** 是否像一条 Windows 绝对路径。 */
83
+ export function looksWindowsPath(p) {
84
+ const s = String(p || '')
85
+ return /^[A-Za-z]:[\\/]/.test(s) || /^\\\\/.test(s) || /^%[A-Za-z0-9_()]+%/.test(s) || /^\/mnt\/[a-z]\//i.test(s)
86
+ }
87
+
88
+ /** 统一成反斜杠形态便于比较(只用于匹配,不用于输出)。 */
89
+ function winish(p) {
90
+ return String(p).replace(/\//g, '\\').replace(/\\+$/, '')
91
+ }
92
+
93
+ /** Windows 路径 → 本机 POSIX 路径。返回 { to, how } 或 null。 */
94
+ export function translateWinPath(input, ctx) {
95
+ const raw = String(input || '').trim()
96
+ if (!raw) return null
97
+ if (raw.startsWith('/') && !/^\/mnt\/[a-z]\//i.test(raw)) {
98
+ // 已经是 POSIX 路径:只做占位符展开,存在就用
99
+ const expanded = expandPlaceholders(raw, ctx)
100
+ return ctx.exists(expanded) ? { to: expanded, how: '本机路径' } : null
101
+ }
102
+ // ① 用户写死的映射(最长前缀)
103
+ const w = winish(raw)
104
+ for (const rule of ctx.rules) {
105
+ const from = winish(rule.from)
106
+ if (w === from || w.toLowerCase().startsWith(from.toLowerCase() + '\\')) {
107
+ const rest = w.slice(from.length).replace(/^\\+/, '')
108
+ const to = expandPlaceholders(rule.to, ctx) + (rest ? '/' + rest.replace(/\\/g, '/') : '')
109
+ return { to, how: `映射表 ${rule.from} → ${rule.to}` }
110
+ }
111
+ }
112
+ // ② 环境变量
113
+ let envHit = null
114
+ const envMap = {
115
+ '%USERPROFILE%': ctx.userHome,
116
+ '%HOME%': ctx.userHome,
117
+ '%APPDATA%': join(ctx.userHome, 'AppData', 'Roaming'),
118
+ '%LOCALAPPDATA%': join(ctx.userHome, 'AppData', 'Local'),
119
+ }
120
+ const envMatch = w.match(/^(%[A-Za-z0-9_()]+%)\\?(.*)$/)
121
+ if (envMatch) {
122
+ const value = envMap[envMatch[1].toUpperCase()]
123
+ const rest = envMatch[2] || ''
124
+ if (value) {
125
+ const to = value + (rest ? '/' + rest.replace(/\\/g, '/') : '')
126
+ if (ctx.exists(to)) envHit = { to, how: `环境变量 ${envMatch[1]}` }
127
+ }
128
+ }
129
+ if (envHit) return envHit
130
+ // ③ WSL:/mnt/c/Users/<U>/rest
131
+ const wsl = raw.match(/^\/mnt\/([a-z])\/(.*)$/i)
132
+ if (wsl) {
133
+ const tail = wsl[2]
134
+ const users = tail.match(/^Users\/([^/]+)\/?(.*)$/i)
135
+ const rest = users ? users[2] : tail
136
+ const to = ctx.userHome + (rest ? '/' + rest : '')
137
+ return ctx.exists(to) ? { to, how: 'WSL /mnt 路径' } : null
138
+ }
139
+ // ④ C:\Users\<U>\<rest> → <userHome>/<rest>
140
+ const drive = raw.match(/^([A-Za-z]):[\\/](.*)$/)
141
+ if (!drive) return null
142
+ const restRaw = drive[2]
143
+ const userProfile = restRaw.match(/^Users[\\/]([^\\/]+)[\\/]?(.*)$/i)
144
+ if (userProfile) {
145
+ const to = ctx.userHome + (userProfile[2] ? '/' + userProfile[2].replace(/\\/g, '/') : '')
146
+ if (ctx.exists(to)) return { to, how: 'C:\\Users → 本机家目录' }
147
+ }
148
+ // ⑤ 按「同名工作区 / 常见位置」找对应物
149
+ const leaf = basename(winish(restRaw).replace(/\\/g, '/'))
150
+ if (!leaf) return null
151
+ const tries = []
152
+ for (const ws of ctx.localWorkspaces) {
153
+ if (!ws || !ws.path) continue
154
+ const wsLeaf = basename(String(ws.path))
155
+ if (String(ws.title || '') === leaf || wsLeaf === leaf) tries.push({ to: ws.path, how: `同名工作区「${ws.title || wsLeaf}」` })
156
+ }
157
+ tries.push({ to: join(ctx.userHome, 'projects', leaf), how: '~/projects/<同名>' })
158
+ tries.push({ to: join(ctx.userHome, leaf), how: '~/<同名>' })
159
+ tries.push({ to: join(ctx.userHome, 'Documents', leaf), how: '~/Documents/<同名>' })
160
+ for (const t of tries) if (ctx.exists(t.to)) return t
161
+ return null
162
+ }
163
+
164
+ /** 文本里的 Windows 路径统一翻译(用于 cordis.patch.yml / AGENTS.md)。 */
165
+ export function translatePortableText(text, ctx) {
166
+ const hits = []
167
+ const misses = []
168
+ const out = String(text || '')
169
+ .replace(/(?:[A-Za-z]:[\\/]|\/mnt\/[a-z]\/|%[A-Za-z0-9_]+%[\\/])[^\s"'`,。;))】]*/g, (m) => {
170
+ const cleaned = m.replace(/[.,;:]+$/, '')
171
+ const trailing = m.slice(cleaned.length)
172
+ const t = translateWinPath(cleaned, ctx)
173
+ if (t) {
174
+ if (hits.length < 40) hits.push({ from: cleaned, to: t.to, how: t.how })
175
+ return t.to + trailing
176
+ }
177
+ if (misses.length < 40) misses.push(cleaned)
178
+ return m
179
+ })
180
+ return { text: out, hits, misses }
181
+ }
182
+
183
+ /**
184
+ * 合并两个 profile 的 package.json。
185
+ *
186
+ * 本机那份是**权威**:name / private / 已有依赖的版本号都用本机的。
187
+ * 云端的贡献:本机没有的依赖(link: 先翻译,翻不出来的丢掉)、只增不减的 bundles。
188
+ */
189
+ export function portPackageJson({ localPkg, cloudPkg, ctx }) {
190
+ const notes = []
191
+ const dropped = []
192
+ const local = localPkg && typeof localPkg === 'object' ? localPkg : null
193
+ const cloud = cloudPkg && typeof cloudPkg === 'object' ? cloudPkg : null
194
+ if (!cloud) return { pkg: null, notes: ['云端没有 package.json'], dropped }
195
+ if (!local) return { pkg: null, notes: ['本机没有 package.json(新机器?先用 pull 之外的路径建一份)'], dropped }
196
+ const deps = { ...(local.dependencies || {}) }
197
+ for (const [name, specRaw] of Object.entries(cloud.dependencies || {})) {
198
+ const spec = String(specRaw)
199
+ if (deps[name]) {
200
+ if (deps[name] !== spec) notes.push(`${name}: 本机 ${deps[name]} 优先于云端 ${spec}`)
201
+ continue
202
+ }
203
+ if (/^link:/i.test(spec)) {
204
+ const t = translateWinPath(spec.slice(5), ctx)
205
+ if (!t) {
206
+ dropped.push(`${name}: link:${spec.slice(5)} 在本机找不到对应目录`)
207
+ continue
208
+ }
209
+ if (!ctx.exists(join(t.to, 'package.json'))) {
210
+ dropped.push(`${name}: ${t.to} 里没有 package.json`)
211
+ continue
212
+ }
213
+ deps[name] = 'link:' + t.to
214
+ notes.push(`${name}: link 改写到 ${t.to}(${t.how})`)
215
+ continue
216
+ }
217
+ if (/^file:/i.test(spec)) {
218
+ dropped.push(`${name}: ${spec} 指向的 tgz 不在云端仓库里,本机装不上`)
219
+ continue
220
+ }
221
+ deps[name] = spec
222
+ notes.push(`${name}: 新增 ${spec}`)
223
+ }
224
+ const bundles = [...((local.dsh && local.dsh.profile && local.dsh.profile.bundles) || [])]
225
+ for (const b of (cloud.dsh && cloud.dsh.profile && cloud.dsh.profile.bundles) || []) {
226
+ if (bundles.includes(b)) continue
227
+ const isBuiltin = /^@deepseek-ai\//.test(b)
228
+ if (isBuiltin || deps[b]) {
229
+ bundles.push(b)
230
+ notes.push(`bundle 新增:${b}`)
231
+ } else {
232
+ dropped.push(`bundle ${b}: 对应依赖既不在本机也不在云端可移植项里`)
233
+ }
234
+ }
235
+ const pkg = {
236
+ ...local,
237
+ dependencies: deps,
238
+ dsh: {
239
+ ...(local.dsh || {}),
240
+ profile: { ...((local.dsh && local.dsh.profile) || {}), bundles },
241
+ },
242
+ }
243
+ return { pkg, notes, dropped }
244
+ }
245
+
246
+ /**
247
+ * 合并工作区登记表:云端条目先翻译路径,翻不出来就跳过;本机已有的同 id / 同名条目一律优先。
248
+ * 返回 { registry, notes, skipped } —— registry 是合并后的完整 storages/workspace.json 结构。
249
+ */
250
+ export function portWorkspaceRegistry({ localReg, cloudReg, ctx }) {
251
+ const notes = []
252
+ const skipped = []
253
+ const base = localReg && typeof localReg === 'object' ? JSON.parse(JSON.stringify(localReg)) : { version: 1, tables: { workspaces: {} }, global: {} }
254
+ base.tables = base.tables && typeof base.tables === 'object' ? base.tables : {}
255
+ base.tables.workspaces = base.tables.workspaces && typeof base.tables.workspaces === 'object' ? base.tables.workspaces : {}
256
+ base.global = base.global && typeof base.global === 'object' ? base.global : {}
257
+ const localByTitle = new Map()
258
+ for (const [id, w] of Object.entries(base.tables.workspaces)) {
259
+ if (w && w.title) localByTitle.set(String(w.title), { id, path: w.path })
260
+ }
261
+ // 两种形状都要认:仓库里的 workspace-registry.json 是 { workspaces: [] },
262
+ // settings 组那份整份快照是 DSH 自己的 { tables: { workspaces: { id: {...} } } }。
263
+ let cloudList = Array.isArray(cloudReg && cloudReg.workspaces) ? cloudReg.workspaces : []
264
+ const cloudTable = cloudReg && cloudReg.tables && cloudReg.tables.workspaces
265
+ if (!cloudList.length && cloudTable && typeof cloudTable === 'object') {
266
+ cloudList = Object.entries(cloudTable).map(([id, w]) => ({ id, ...(w || {}) }))
267
+ }
268
+ for (const w of cloudList) {
269
+ if (!w || !w.id) continue
270
+ if (base.tables.workspaces[w.id]) continue
271
+ const title = w.title || w.id
272
+ const already = localByTitle.get(String(title))
273
+ if (already) {
274
+ skipped.push(`${title}: 本机已有同名工作区(${already.path}),不重复登记`)
275
+ continue
276
+ }
277
+ // 先展开 {{ROOT:userHome}} / {{DSH_HOME}} 这类占位符,再按 Windows 规则翻译
278
+ const rawPath = ctx.expand ? ctx.expand(String(w.path || '')) : String(w.path || '')
279
+ const t = translateWinPath(rawPath, ctx)
280
+ if (!t) {
281
+ skipped.push(`${title}: 云端路径 ${w.path} 在本机找不到对应目录`)
282
+ continue
283
+ }
284
+ // 映射到「家目录本身」没有意义(那是 Windows 的 C:\Users\<U>,不是项目目录),只会给面板添乱
285
+ if (t.to === ctx.userHome || t.to === '/') {
286
+ skipped.push(`${title}: 云端路径 ${w.path} 只对应到本机家目录,不作为工作区`)
287
+ continue
288
+ }
289
+ base.tables.workspaces[w.id] = {
290
+ title,
291
+ path: t.to,
292
+ sessionIds: Array.isArray(w.sessionIds) ? w.sessionIds : [],
293
+ archivedSessionIds: Array.isArray(w.archivedSessionIds) ? w.archivedSessionIds : [],
294
+ pinnedSessionIds: Array.isArray(w.pinnedSessionIds) ? w.pinnedSessionIds : [],
295
+ createdAt: w.createdAt || '',
296
+ updatedAt: w.updatedAt || '',
297
+ }
298
+ notes.push(`${title}: ${w.path} → ${t.to}(${t.how})`)
299
+ }
300
+ return { registry: base, notes, skipped }
301
+ }
302
+
303
+ /** 全局提示(AGENTS.md):只翻路径,不动内容结构,开头加一句来源说明。 */
304
+ export function portAgentsMd(text, ctx) {
305
+ const r = translatePortableText(text, ctx)
306
+ const header = `<!-- 本文件由 dsh-profile-config-sync 从另一套系统的仓库移植:路径已按本机实际情况改写${r.misses.length ? `;${r.misses.length} 处路径在本机找不到对应物,保持原样` : ''} -->\n`
307
+ return { text: header + r.text, hits: r.hits, misses: r.misses }
308
+ }
309
+
310
+ /** 报告用:把翻译结果压成几行给面板看。 */
311
+ export function summarizePort({ hits = [], misses = [], dropped = [], notes = [], skipped = [] } = {}) {
312
+ const lines = []
313
+ if (hits.length) lines.push(`翻译路径 ${hits.length} 处`)
314
+ if (notes.length) lines.push(`依赖/条目调整 ${notes.length} 处`)
315
+ if (dropped.length) lines.push(`丢弃 ${dropped.length} 项(本机不可用)`)
316
+ if (skipped.length) lines.push(`跳过 ${skipped.length} 项(找不到对应物)`)
317
+ if (misses.length) lines.push(`未翻译 ${misses.length} 处`)
318
+ return lines.join(',')
319
+ }