@aiwayds/dsh-opentui 0.27.2 → 0.28.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.
@@ -22,7 +22,18 @@
22
22
  "command.model.discovered": "discovered {n} models: {list}",
23
23
  "command.model.discoverEmpty": "no models discovered from the endpoint",
24
24
  "command.model.discoverUnavailable": "model discovery unavailable — {reason}",
25
- "command.login.description": "log in a provider (bare opens the picker; Custom provider opens the form)",
25
+ "command.login.description": "log in (DeepSeek account / third-party / custom provider)",
26
+ "command.login.mode.title": "Sign in — choose a method",
27
+ "command.login.mode.account.title": "DeepSeek account",
28
+ "command.login.mode.account.hint": "Sign in through your DeepSeek account",
29
+ "command.login.mode.thirdParty.title": "Third-party provider",
30
+ "command.login.mode.thirdParty.hint": "Pick a known provider and enter its API key",
31
+ "command.login.mode.custom.title": "Custom provider",
32
+ "command.login.mode.custom.hint": "Route id, base URL, models and API key",
33
+ "command.login.account.title": "DeepSeek account",
34
+ "command.login.account.state": "Show account state",
35
+ "command.login.account.signin": "Sign in",
36
+ "command.login.account.signout": "Sign out",
26
37
  "command.login.routeRegistrationFailed": "{id}: route registration failed — key not stored",
27
38
  "command.login.keyStoreFailed": "{id}: key store failed — {detail}",
28
39
  "command.login.subscribed": "{name} subscribed — key stored, route registered (in /model next session)",
@@ -32,8 +43,10 @@
32
43
  "command.login.unavailable": "/login unavailable in this session",
33
44
  "command.login.directoryDegraded": "provider directory unavailable — showing the built-in provider list",
34
45
  "command.login.directoryPartial": "provider directory partly unavailable — showing the providers that responded",
46
+ "command.profile.mismatch": "Profile mismatch: profile files would go to {clientDir}, but the running dsh process reads {hostDir}. Nothing was written. Next: restart dsh-opentui so both use {hostDir} (remove any one-sided profile override), then retry.",
35
47
  "command.account.description": "show account sign-in state (signin/signout)",
36
48
  "command.account.unavailable": "/account unavailable in this session",
49
+ "command.account.signinUnavailable": "Browser sign-in is not available in this build.",
37
50
  "command.account.state": "account: status={status} phase={phase} urlReady={urlReady} links={links}",
38
51
  "command.account.failed": "account action failed: {reason}",
39
52
  "command.account.unknownAction": "unknown account action: {action} (use signin/signout)",
@@ -63,7 +76,7 @@
63
76
  "command.logout.routeFailed": "{id}: logout failed — {reason}",
64
77
  "command.logout.done": "{name} logged out — key removed (route kept)",
65
78
  "command.logout.routeRemoved": "{name} logged out — key + route removed (leaves /model next session)",
66
- "command.logout.routeRemoveFailed": "{name} logged out — key removed, route removal failed",
79
+ "command.logout.routeRemoveFailed": "{name} logged out — key removed, but the {id} route stayed: {reason}. Next: fix that settings write (retry after the host recovers) or remove the {id} route in /settings; no key is stored now.",
67
80
  "command.logout.unavailable": "/logout unavailable in this session",
68
81
  "command.logout.none": "no logged-in providers",
69
82
  "command.quit.description": "exit the app",
@@ -22,7 +22,18 @@
22
22
  "command.model.discovered": "发现 {n} 个模型:{list}",
23
23
  "command.model.discoverEmpty": "端点未返回模型",
24
24
  "command.model.discoverUnavailable": "模型发现不可用 — {reason}",
25
- "command.login.description": "登录 provider(不带参数打开选择器;Custom provider 打开表单)",
25
+ "command.login.description": "登录(DeepSeek 账号 / 第三方 / 自定义 provider)",
26
+ "command.login.mode.title": "登录 — 选择方式",
27
+ "command.login.mode.account.title": "DeepSeek 账号",
28
+ "command.login.mode.account.hint": "通过 DeepSeek 账号登录",
29
+ "command.login.mode.thirdParty.title": "第三方 provider",
30
+ "command.login.mode.thirdParty.hint": "选择已知 provider 并填写 API key",
31
+ "command.login.mode.custom.title": "自定义 provider",
32
+ "command.login.mode.custom.hint": "路由 id、base URL、模型列表与 API key",
33
+ "command.login.account.title": "DeepSeek 账号",
34
+ "command.login.account.state": "查看账号状态",
35
+ "command.login.account.signin": "登录",
36
+ "command.login.account.signout": "退出登录",
26
37
  "command.login.routeRegistrationFailed": "{id}:路由注册失败 — 密钥未保存",
27
38
  "command.login.keyStoreFailed": "{id}:密钥保存失败 — {detail}",
28
39
  "command.login.subscribed": "{name} 已订阅 — 密钥已保存,路由已注册(下次会话在 /model 中生效)",
@@ -32,8 +43,10 @@
32
43
  "command.login.unavailable": "本会话中 /login 不可用",
33
44
  "command.login.directoryDegraded": "provider 目录不可用 — 显示内置 provider 列表",
34
45
  "command.login.directoryPartial": "provider 目录部分不可用 — 显示已响应的 provider",
46
+ "command.profile.mismatch": "profile 不一致:本会写入 {clientDir},但正在运行的 dsh 进程读取 {hostDir}。未写入任何内容。下一步:重启 dsh-opentui,让两边都使用 {hostDir}(去掉只对一边生效的 profile 覆盖设置),然后重试。",
35
47
  "command.account.description": "查看账号登录态(signin/signout)",
36
48
  "command.account.unavailable": "本会话中 /account 不可用",
49
+ "command.account.signinUnavailable": "本版本暂不支持浏览器登录。",
37
50
  "command.account.state": "账号:状态={status} 阶段={phase} 链接就绪={urlReady} 链接存在={links}",
38
51
  "command.account.failed": "账号操作失败:{reason}",
39
52
  "command.account.unknownAction": "未知账号操作:{action}(用 signin/signout)",
@@ -63,7 +76,7 @@
63
76
  "command.logout.routeFailed": "{id}:登出失败 — {reason}",
64
77
  "command.logout.done": "{name} 已登出 — 密钥已删除(路由保留)",
65
78
  "command.logout.routeRemoved": "{name} 已登出 — 密钥与路由已删除(下次会话停在 /model)",
66
- "command.logout.routeRemoveFailed": "{name} 已登出 — 密钥已删除,路由删除失败",
79
+ "command.logout.routeRemoveFailed": "{name} 密钥已删除,但 {id} 路由未清除:{reason}。下一步:待宿主设置服务恢复后重试,或在 /settings 中删除 {id} 路由;当前没有保存任何密钥。",
67
80
  "command.logout.unavailable": "本会话中 /logout 不可用",
68
81
  "command.logout.none": "没有已登录的 provider",
69
82
  "command.quit.description": "退出应用",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-opentui",
3
- "version": "0.27.2",
3
+ "version": "0.28.0",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,12 +16,7 @@
16
16
  "scripts",
17
17
  "dist/client",
18
18
  "dist/bridge",
19
- "dist/scripts",
20
19
  "dist/locales",
21
- "dist/host-launch.mjs",
22
- "dist/host-launch.mjs.map",
23
- "dist/watchdog.mjs",
24
- "dist/watchdog.mjs.map",
25
20
  "README.md",
26
21
  "LICENSE",
27
22
  "NOTICE",
@@ -34,18 +29,19 @@
34
29
  },
35
30
  "dependencies": {
36
31
  "@opentui/core": "0.8.1",
37
- "@opentui/solid": "0.8.1",
38
32
  "@opentui/keymap": "0.8.1",
33
+ "@opentui/solid": "0.8.1",
39
34
  "solid-js": "1.9.17",
40
- "ws": "^8.22.1"
35
+ "ws": "^8.22.1",
36
+ "yaml": "2.9.1"
41
37
  },
42
38
  "devDependencies": {
43
- "typescript": "^5.7.0",
44
- "@types/bun": "latest",
45
39
  "@deepseek-ai/cordis": "4.1.0",
46
40
  "@deepseek-ai/dsh-llm": "0.2.2-rc.1",
47
41
  "@deepseek-ai/schemastery": "~3.19.0",
48
- "@dsh-opentui/runtime": "workspace:*"
42
+ "@dsh-opentui/runtime": "workspace:*",
43
+ "@types/bun": "latest",
44
+ "typescript": "^5.7.0"
49
45
  },
50
46
  "engines": {
51
47
  "node": ">=26.4.0",
@@ -0,0 +1,16 @@
1
+ // D2 user decision (2026-11-24): the companion IDs installed by default for
2
+ // the opentui-monday profile. IDs match `COMPANIONS[].short`; package specs and
3
+ // version guards stay in the catalog. `workflow` was explicitly dropped.
4
+ export const DEFAULT_COMPANION_IDS = [
5
+ 'registry',
6
+ 'ask-router',
7
+ 'approval-policy',
8
+ 'llm-net-retry',
9
+ 'model-sync',
10
+ 'llm-stats',
11
+ 'mcp-adapter',
12
+ 'vault',
13
+ 'web-search',
14
+ 'topics-memory',
15
+ 'cron',
16
+ ]
@@ -1,36 +1,43 @@
1
- // Pure decision table for the `opentui-inproc` profile's companion step.
1
+ // Pure decision table for the `opentui-monday` profile's companion step.
2
2
  //
3
3
  // No filesystem I/O, no process spawn and no ambient process.env reads in the
4
4
  // policy functions: every input is passed in, so the catalog, the selection and
5
5
  // the per-package install decision are unit-testable without a registry or a
6
- // real dsh profile. Only `queryDistTagLatest` performs I/O, and it takes an
7
- // injectable executor for the same reason.
6
+ // real dsh profile. Only the `queryDistTagLatest*` functions perform I/O, and
7
+ // they take injectable executors for the same reason.
8
8
  //
9
9
  // Why this table exists: the inproc profile is deliberately minimal
10
- // (dsh-base + the in-process bridge + the bridge-owned approval gate). Adding
11
- // every @aiwayds companion "just in case" would pull client UI bundles into a
12
- // headless-ish profile and create new failure modes. Each candidate below is
13
- // judged by whether the inproc assembly has a CONSUMER for it; the ones without
14
- // one are listed explicitly with `defaultOn: false` and are opt-in only.
10
+ // (dsh-base + the in-process bridge + the bridge-owned approval gate). The
11
+ // default roster is the D2 user decision recorded on 2026-11-24; package specs
12
+ // and version guards live here while the ordered default IDs live in
13
+ // companion-policy.mjs.
15
14
  //
16
15
  // Reference precedent: dsh-tui-pi 2.38.2's `bin/companion-policy.mjs` +
17
16
  // `DSH_TUI_COMPANION_LATEST`. The switch name here follows the same style with
18
17
  // the opentui prefix.
19
18
 
20
- import { execFileSync } from 'node:child_process'
19
+ import { execFile, execFileSync } from 'node:child_process'
20
+ import { promisify } from 'node:util'
21
+ import { DEFAULT_COMPANION_IDS } from './companion-policy.mjs'
22
+
23
+ // One `npm view` must never hold provisioning hostage; the batch below adds a
24
+ // second, outer bound so a slow registry cannot stretch a launch indefinitely.
25
+ export const COMPANION_QUERY_TIMEOUT_MS = 9_000
26
+ export const COMPANION_QUERY_BUDGET_MS = 20_000
27
+ export const COMPANION_QUERY_CONCURRENCY = 4
21
28
 
22
29
  /** Master kill switch. Anything other than 0/false/off (including unset) = enabled. */
23
30
  export const COMPANION_LATEST_ENV = 'DSH_OPENTUI_COMPANION_LATEST'
24
- /** Opt-in list of additional companions (comma-separated short names or full package names). */
31
+ /** Override list of companions (comma-separated catalog IDs or full package names). */
25
32
  export const COMPANIONS_ENV = 'DSH_OPENTUI_COMPANIONS'
26
33
 
27
34
  /**
28
35
  * The companion catalog.
29
36
  *
30
- * `short` is the token accepted by DSH_OPENTUI_COMPANIONS. `declaredRange` is
31
- * the caret range used ONLY as a breaking-version guard against a moved
37
+ * `short` is the catalog ID accepted by DSH_OPENTUI_COMPANIONS. `declaredRange`
38
+ * is the caret range used ONLY as a breaking-version guard against a moved
32
39
  * `latest` dist-tag (major, plus minor while still 0.x) — it is never
33
- * installed. `defaultOn` marks the minimal set.
40
+ * installed. `defaultOn` marks the D2 default roster.
34
41
  */
35
42
  export const COMPANIONS = Object.freeze([
36
43
  Object.freeze({
@@ -43,58 +50,72 @@ export const COMPANIONS = Object.freeze([
43
50
  Object.freeze({
44
51
  name: '@aiwayds/dsh-ask-router',
45
52
  short: 'ask-router',
46
- declaredRange: '^0.7.0',
47
- defaultOn: false,
48
- reason: 'inproc owns the ask surface bridge-side (ask.request frames from packages/bridge/src/ask-registry.ts); no inproc row consumes @aiwayds/dsh-ask-router.',
53
+ declaredRange: '^0.8.0',
54
+ defaultOn: true,
55
+ reason: 'retained by the D2 user decision to own the ask surface for companion UI bundles.',
49
56
  }),
50
57
  Object.freeze({
51
58
  name: '@aiwayds/dsh-approval-policy',
52
59
  short: 'approval-policy',
53
60
  declaredRange: '^0.3.0',
54
- defaultOn: false,
55
- reason: 'inproc uses its own bridge /approval-gate row plus @deepseek-ai/dsh-permission-presets; no consumer of the @aiwayds policy plugin.',
61
+ defaultOn: true,
62
+ reason: 'retained by the D2 user decision for tool-approval policy shared with shell approval cards.',
56
63
  }),
57
64
  Object.freeze({
58
65
  name: '@aiwayds/dsh-llm-net-retry',
59
66
  short: 'llm-net-retry',
60
67
  declaredRange: '^0.8.0',
61
- defaultOn: false,
62
- reason: 'dsh-base already mounts @deepseek-ai/dsh-llm-retry in the inproc assembly; a second retry layer has no consumer.',
68
+ defaultOn: true,
69
+ reason: 'retained by the D2 user decision to retry transient provider and network failures.',
63
70
  }),
64
71
  Object.freeze({
65
72
  name: '@aiwayds/dsh-model-sync',
66
73
  short: 'model-sync',
67
- declaredRange: '^0.9.0',
68
- defaultOn: false,
69
- reason: 'the inproc patch pins its own provider model list; nothing in the profile asks this plugin to sync it.',
74
+ declaredRange: '^0.10.0',
75
+ defaultOn: true,
76
+ reason: 'retained by the D2 user decision to keep the profile model list in sync with the provider catalog.',
70
77
  }),
71
78
  Object.freeze({
72
79
  name: '@aiwayds/dsh-llm-stats',
73
80
  short: 'llm-stats',
74
81
  declaredRange: '^0.9.0',
75
- defaultOn: false,
76
- reason: 'token/cost accounting behind /usage; no /usage consumer exists in the inproc client path.',
82
+ defaultOn: true,
83
+ reason: 'retained by the D2 user decision for token and cost accounting behind /usage.',
77
84
  }),
78
85
  Object.freeze({
79
86
  name: '@aiwayds/dsh-mcp-adapter',
80
87
  short: 'mcp-adapter',
81
88
  declaredRange: '^0.8.0',
82
- defaultOn: false,
83
- reason: 'the inproc patch carries a mcp-context7 client row, but no inproc row consumes the adapter\'s mcp_list/mcp_call meta-tools; opt-in only.',
89
+ defaultOn: true,
90
+ reason: 'retained by the D2 user decision for MCP catalog and dispatch meta-tools paired with the context7 server row.',
91
+ }),
92
+ Object.freeze({
93
+ name: '@aiwayds/dsh-vault',
94
+ short: 'vault',
95
+ declaredRange: '^0.8.2',
96
+ defaultOn: true,
97
+ reason: 'retained by the D2 user decision for secret storage used by companion plugins.',
84
98
  }),
85
99
  Object.freeze({
86
100
  name: '@aiwayds/dsh-web-search-anysearch',
87
101
  short: 'web-search',
88
102
  declaredRange: '^0.9.0',
89
- defaultOn: false,
90
- reason: 'tool-web is enabled in the inproc patch but no search provider is pinned; independent of delegation, opt-in only.',
103
+ defaultOn: true,
104
+ reason: 'retained by the D2 user decision for web search without a per-provider key.',
91
105
  }),
92
106
  Object.freeze({
93
- name: '@aiwayds/dsh-vault',
94
- short: 'vault',
95
- declaredRange: '^0.8.2',
96
- defaultOn: false,
97
- reason: 'secret storage; no consumer in the minimal inproc set.',
107
+ name: '@aiwayds/dsh-topics-memory',
108
+ short: 'topics-memory',
109
+ declaredRange: '^0.26.0',
110
+ defaultOn: true,
111
+ reason: 'added by the D2 user decision for cross-session topic memory.',
112
+ }),
113
+ Object.freeze({
114
+ name: '@aiwayds/dsh-cron',
115
+ short: 'cron',
116
+ declaredRange: '^0.7.0',
117
+ defaultOn: true,
118
+ reason: 'added by the D2 user decision for scheduled prompts.',
98
119
  }),
99
120
  ])
100
121
 
@@ -109,14 +130,18 @@ export function companionLatestEnabled(env = process.env) {
109
130
  * The companions this launch should satisfy.
110
131
  * - master switch off => no companions at all (non-destructive: already
111
132
  * installed packages are left in place, they are just not queried/installed)
112
- * - DSH_OPENTUI_COMPANIONS unset => the `defaultOn` set (registry only)
113
- * - explicit list => defaultOn set is replaced by the named entries;
133
+ * - DSH_OPENTUI_COMPANIONS unset => DEFAULT_COMPANION_IDS, in policy order
134
+ * - explicit list => default set is replaced by the named entries;
114
135
  * `none` means empty, `all` means the whole catalog.
115
136
  */
116
137
  export function selectCompanions(env = process.env) {
117
138
  if (!companionLatestEnabled(env)) return []
118
139
  const raw = env[COMPANIONS_ENV]
119
- if (raw === undefined || String(raw).trim() === '') return COMPANIONS.filter((entry) => entry.defaultOn)
140
+ if (raw === undefined || String(raw).trim() === '') {
141
+ return DEFAULT_COMPANION_IDS
142
+ .map((id) => COMPANIONS.find((entry) => entry.short === id))
143
+ .filter(Boolean)
144
+ }
120
145
  const tokens = String(raw).split(',').map((token) => token.trim()).filter(Boolean)
121
146
  if (tokens.includes('none')) return []
122
147
  if (tokens.includes('all')) return [...COMPANIONS]
@@ -203,7 +228,7 @@ export function queryDistTagLatest(name, { cwd, env, exec } = {}) {
203
228
  cwd,
204
229
  env,
205
230
  encoding: 'utf8',
206
- timeout: 30_000,
231
+ timeout: COMPANION_QUERY_TIMEOUT_MS,
207
232
  })
208
233
  const tags = JSON.parse(typeof out === 'string' ? out : String(out?.stdout ?? ''))
209
234
  return typeof tags?.latest === 'string' ? normalizeVersion(tags.latest) : null
@@ -211,3 +236,68 @@ export function queryDistTagLatest(name, { cwd, env, exec } = {}) {
211
236
  return null
212
237
  }
213
238
  }
239
+
240
+ const execFileAsync = promisify(execFile)
241
+
242
+ /** Async twin of `queryDistTagLatest`, used by the bounded concurrent batch. */
243
+ export async function queryDistTagLatestAsync(name, { cwd, env, exec } = {}) {
244
+ const run = exec ?? execFileAsync
245
+ try {
246
+ const out = await run('npm', ['view', name, 'dist-tags', '--json'], {
247
+ cwd,
248
+ env,
249
+ encoding: 'utf8',
250
+ timeout: COMPANION_QUERY_TIMEOUT_MS,
251
+ })
252
+ const stdout = typeof out === 'string' ? out : String(out?.stdout ?? '')
253
+ const tags = JSON.parse(stdout)
254
+ return typeof tags?.latest === 'string' ? normalizeVersion(tags.latest) : null
255
+ } catch {
256
+ return null
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Query every name with bounded concurrency and a total wall-clock budget.
262
+ *
263
+ * Results land at the INPUT index (never completion order), so callers stay
264
+ * deterministic. A per-item failure — including a thrown injected query — is
265
+ * swallowed into `null`, which is exactly the existing "unresolved" fallback;
266
+ * provisioning never aborts because one registry lookup failed or timed out.
267
+ * New lookups stop once the budget is spent; lookups already in flight still
268
+ * settle on their own shorter timeout.
269
+ */
270
+ export async function queryDistTagLatestBatch(
271
+ names,
272
+ {
273
+ cwd,
274
+ env,
275
+ query = queryDistTagLatestAsync,
276
+ concurrency = COMPANION_QUERY_CONCURRENCY,
277
+ budgetMs = COMPANION_QUERY_BUDGET_MS,
278
+ now = () => Date.now(),
279
+ } = {},
280
+ ) {
281
+ const results = new Array(names.length).fill(null)
282
+ const deadline = now() + budgetMs
283
+ let cursor = 0
284
+ const worker = async () => {
285
+ while (cursor < names.length && now() < deadline) {
286
+ const index = cursor++
287
+ try {
288
+ results[index] = await query(names[index], { cwd, env })
289
+ } catch {
290
+ results[index] = null
291
+ }
292
+ }
293
+ }
294
+ const lanes = Math.max(1, Math.min(concurrency, names.length))
295
+ await Promise.all(Array.from({ length: lanes }, worker))
296
+ return results
297
+ }
298
+
299
+ /** One summary line for skipped companions, or null when every one succeeded. */
300
+ export function formatSkippedCompanionsWarning(shortNames = []) {
301
+ if (shortNames.length === 0) return null
302
+ return `${shortNames.length} companion(s) skipped (version query failed or outside declared range): ${shortNames.join(', ')}`
303
+ }
@@ -0,0 +1,231 @@
1
+ /**
2
+ * T8b — migration I/O helper (06 §7.4/§7.5; D6 §二/§三).
3
+ *
4
+ * Split from the pure planner (`migration.mjs`): this module is the only place
5
+ * that touches the filesystem. It never reads `~/.dsh` on its own — every path
6
+ * comes from its arguments, so tests can point it at a scratch home.
7
+ *
8
+ * Contract:
9
+ * readMigrationInputs({ dshHome, profileDir, templatePatchText })
10
+ * -> { markerExists, marker, inprocPatchText, opentuiPatchText,
11
+ * opentuiConfigText, opentuiKeybindingsText, opentuiProviderKeysText }
12
+ * applyMigrationPlan({ profileDir, plan, version, now = new Date(), backupsOnly = false, skipBackups = false })
13
+ * -> { wroteConfig, wroteKeybindings, backupsWritten, markerWritten, notices }
14
+ *
15
+ * Hard rules:
16
+ * - readMigrationInputs is read-only and creates no directory;
17
+ * - marker present on entry => the legacy files are NEVER read (an EACCES /
18
+ * EISDIR artifact must not break an already-migrated machine's startup);
19
+ * - invalid config/keybindings payloads are NOT written to the active files;
20
+ * - marker is written LAST; any write failure throws before the marker;
21
+ * - backupsOnly writes ONLY backups (wroteConfig / wroteKeybindings /
22
+ * markerWritten all stay false) — used to snapshot the source before
23
+ * converge rewrites it when source B is the target profile;
24
+ * - skipBackups leaves an existing snapshot untouched on crash re-entry while
25
+ * still writing config / keybindings / marker;
26
+ * - marker present on entry => immediate no-op (no overwrite, no notice replay);
27
+ * - every write is tmp+rename in the target's own directory, mode 0600 for
28
+ * active files / marker / provider-keys backup, 0644 for other backups;
29
+ * - equal content is skipped (no mtime churn); a differing backup rotates a
30
+ * single `.bak` before being overwritten;
31
+ * - no console output — notices are returned for the caller to print. A
32
+ * "已备份" claim is dropped unless a matching backup file exists.
33
+ */
34
+ import { createHash, randomBytes } from 'node:crypto'
35
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
36
+ import { join } from 'node:path'
37
+
38
+ export const MARKER_NAME = '.migration.json'
39
+ export const BACKUP_DIR = '.migrated-from'
40
+
41
+ function markerPath(profileDir) {
42
+ return join(profileDir, MARKER_NAME)
43
+ }
44
+
45
+ /** Create the new profile lazily, only when there is a payload to write. */
46
+ function ensureProfileDir(profileDir) {
47
+ if (!existsSync(profileDir)) mkdirSync(profileDir, { recursive: true, mode: 0o700 })
48
+ }
49
+
50
+ /** Text of a file, or undefined when it does not exist. Other IO errors throw. */
51
+ function readTextIfExists(path) {
52
+ try {
53
+ return readFileSync(path, 'utf8')
54
+ } catch (error) {
55
+ if (error && error.code === 'ENOENT') return undefined
56
+ throw error
57
+ }
58
+ }
59
+
60
+ /** tmp + rename inside the target's directory; cleanup on any failure. */
61
+ function atomicWrite(target, content, mode) {
62
+ const tmp = `${target}.tmp-${process.pid}-${randomBytes(8).toString('hex')}`
63
+ try {
64
+ writeFileSync(tmp, content, { mode })
65
+ renameSync(tmp, target)
66
+ } catch (error) {
67
+ try { rmSync(tmp, { force: true }) } catch { /* best effort */ }
68
+ throw error
69
+ }
70
+ }
71
+
72
+ /** Deterministic JSON with sorted object keys (used only for the marker digest). */
73
+ function canonical(value) {
74
+ if (value === undefined || value === null) return 'null'
75
+ if (typeof value !== 'object') return JSON.stringify(value)
76
+ if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
77
+ const keys = Object.keys(value).sort()
78
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`
79
+ }
80
+
81
+ /** sha256 over { marker, backups } — at/version are deliberately excluded. */
82
+ function markerDigest(marker, backups) {
83
+ const payload = {
84
+ marker,
85
+ backups: backups.map(({ source, kind, text }) => ({ source, kind, text })),
86
+ }
87
+ return createHash('sha256').update(canonical(payload)).digest('hex')
88
+ }
89
+
90
+ /**
91
+ * A printed notice must match what is actually on disk. The planner emits an
92
+ * "已备份" claim in its invalid config/keybindings notices, but those payloads
93
+ * are never part of `plan.backups` (only patches and provider-keys are) and no
94
+ * backup file is written for them. Drop the false claim in that case; genuine
95
+ * patch / provider-keys backup notices keep their exact wording.
96
+ */
97
+ function honestBackupNotices(notices, plan, profileDir) {
98
+ const backedKinds = new Set(
99
+ (Array.isArray(plan.backups) ? plan.backups : []).map((entry) => entry && entry.kind),
100
+ )
101
+ return notices.map((notice) => {
102
+ if (typeof notice !== 'string') return notice
103
+ let text = notice
104
+ for (const name of ['config.json', 'keybindings.json']) {
105
+ if (backedKinds.has(name)) continue
106
+ if (typeof profileDir === 'string' && existsSync(join(profileDir, BACKUP_DIR, `opentui-${name}`))) continue
107
+ text = text.replace(`${name} 解析失败:已备份、`, `${name} 解析失败:`)
108
+ }
109
+ return text
110
+ })
111
+ }
112
+
113
+ /**
114
+ * Read everything the planner needs. No directory creation, no writes.
115
+ * A missing file yields `undefined` for that field; a corrupt marker still sets
116
+ * `markerExists: true` but yields `marker: undefined` (safe direction: block).
117
+ */
118
+ export function readMigrationInputs({ dshHome, profileDir, templatePatchText } = {}) {
119
+ const mp = markerPath(profileDir)
120
+ const markerExists = existsSync(mp)
121
+ let marker
122
+ if (markerExists) {
123
+ // Migration is already done: do NOT open ANY legacy file. A source that
124
+ // turned into a directory (EISDIR), lost its read bit (EACCES) or holds a
125
+ // half-written payload must never make every later start fail. A corrupt
126
+ // marker takes the same safe route (marker: undefined => planner no-op).
127
+ try {
128
+ marker = JSON.parse(readFileSync(mp, 'utf8'))
129
+ } catch {
130
+ marker = undefined
131
+ }
132
+ return {
133
+ markerExists: true,
134
+ marker,
135
+ inprocPatchText: undefined,
136
+ opentuiPatchText: undefined,
137
+ opentuiConfigText: undefined,
138
+ opentuiKeybindingsText: undefined,
139
+ opentuiProviderKeysText: undefined,
140
+ }
141
+ }
142
+ const legacy = (name) => join(dshHome, 'profiles', name)
143
+ const opentui = legacy('opentui')
144
+ const inproc = legacy('opentui-inproc')
145
+ return {
146
+ markerExists,
147
+ marker,
148
+ inprocPatchText: readTextIfExists(join(inproc, 'cordis.patch.yml')),
149
+ opentuiPatchText: readTextIfExists(join(opentui, 'cordis.patch.yml')),
150
+ opentuiConfigText: readTextIfExists(join(opentui, 'config.json')),
151
+ opentuiKeybindingsText: readTextIfExists(join(opentui, 'keybindings.json')),
152
+ opentuiProviderKeysText: readTextIfExists(join(opentui, 'provider-keys.json')),
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Apply a plan from `planMigration`. Marker is the last write, so a failure in
158
+ * config / keybindings / backups leaves no marker and the next call re-runs.
159
+ * Files already holding the exact payload are skipped (idempotent re-entry).
160
+ */
161
+ export function applyMigrationPlan({ profileDir, plan = {}, version, now = new Date(), backupsOnly = false, skipBackups = false } = {}) {
162
+ const notices = honestBackupNotices(Array.isArray(plan.notices) ? plan.notices : [], plan, profileDir)
163
+ const result = {
164
+ wroteConfig: false,
165
+ wroteKeybindings: false,
166
+ backupsWritten: [],
167
+ markerWritten: false,
168
+ notices,
169
+ }
170
+
171
+ // Marker gate: already migrated => no writes and no notice replay.
172
+ if (existsSync(markerPath(profileDir))) {
173
+ return { ...result, notices: [] }
174
+ }
175
+
176
+ // ---- active config / keybindings (invalid payloads are never activated) --
177
+ // backupsOnly snapshots the source BEFORE converge rewrites it; it must not
178
+ // activate any payload, so these flags stay false on that path.
179
+ if (!backupsOnly) {
180
+ const active = [
181
+ ['wroteConfig', plan.config, 'config.json'],
182
+ ['wroteKeybindings', plan.keybindings, 'keybindings.json'],
183
+ ]
184
+ if (active.some(([, payload]) => payload && payload.invalid !== true && typeof payload.text === 'string')) {
185
+ ensureProfileDir(profileDir)
186
+ }
187
+ for (const [flag, payload, name] of active) {
188
+ if (!payload || payload.invalid === true || typeof payload.text !== 'string') continue
189
+ const target = join(profileDir, name)
190
+ if (readTextIfExists(target) === payload.text) continue
191
+ atomicWrite(target, payload.text, 0o600)
192
+ result[flag] = true
193
+ }
194
+ }
195
+
196
+ // ---- backups (copy into the new profile; old profiles stay untouched) ----
197
+ const backups = Array.isArray(plan.backups) ? plan.backups : []
198
+ if (backups.length > 0 && !skipBackups) {
199
+ const dir = join(profileDir, BACKUP_DIR)
200
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
201
+ for (const entry of backups) {
202
+ if (!entry || !entry.source || !entry.kind || typeof entry.text !== 'string') continue
203
+ const mode = entry.kind === 'provider-keys.json' ? 0o600 : 0o644
204
+ const dest = join(dir, `${entry.source}-${entry.kind}`)
205
+ const existing = readTextIfExists(dest)
206
+ if (existing === entry.text) continue
207
+ if (existing !== undefined) atomicWrite(`${dest}.bak`, existing, mode)
208
+ atomicWrite(dest, entry.text, mode)
209
+ result.backupsWritten.push(`${BACKUP_DIR}/${entry.source}-${entry.kind}`)
210
+ }
211
+ }
212
+
213
+ // ---- marker: last write, and only when the planner allows it -------------
214
+ if (!backupsOnly && plan.marker && plan.canWriteMarker === true) {
215
+ ensureProfileDir(profileDir)
216
+ const record = {
217
+ from: plan.marker.from,
218
+ at: now.toISOString(),
219
+ version,
220
+ digest: markerDigest(plan.marker, backups),
221
+ migrated: plan.marker.migrated,
222
+ dropped: plan.marker.dropped,
223
+ }
224
+ atomicWrite(markerPath(profileDir), `${JSON.stringify(record, null, 2)}\n`, 0o600)
225
+ result.markerWritten = true
226
+ }
227
+
228
+ return result
229
+ }
230
+
231
+ export default { readMigrationInputs, applyMigrationPlan, MARKER_NAME, BACKUP_DIR }