@aiwayds/dsh-opentui 0.28.0 → 0.28.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-opentui",
3
- "version": "0.28.0",
3
+ "version": "0.28.2",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -71,7 +71,7 @@ export const COMPANIONS = Object.freeze([
71
71
  Object.freeze({
72
72
  name: '@aiwayds/dsh-model-sync',
73
73
  short: 'model-sync',
74
- declaredRange: '^0.10.0',
74
+ declaredRange: '^0.11.0',
75
75
  defaultOn: true,
76
76
  reason: 'retained by the D2 user decision to keep the profile model list in sync with the provider catalog.',
77
77
  }),
@@ -839,6 +839,35 @@ const desiredManifest = (existing) => ({
839
839
  },
840
840
  })
841
841
 
842
+ /**
843
+ * A real `dsh plugin add` lets pnpm write `dependencies` in sorted key order
844
+ * and dsh appends the newly installed companions to `dsh.profile.bundles` in
845
+ * that same order (see dsh-plugin-manager `reconcile()`), which differs from
846
+ * `managedBundles()`' catalog order. Bundle order is not semantic — dsh reads
847
+ * the array as a set — so a replay after a successful install must not rewrite
848
+ * (and back up) an otherwise-converged manifest. Compare bundle membership
849
+ * order-insensitively; keep every other field byte-exact so genuine drift
850
+ * (missing/extra bundle, malformed array, or any other content change) still
851
+ * goes through the backup + rewrite fail-fast path.
852
+ */
853
+ function manifestAlreadyConverged(existing, desired) {
854
+ if (existing === undefined || desired === undefined) return false
855
+ const current = existing?.dsh?.profile?.bundles
856
+ const wanted = desired?.dsh?.profile?.bundles
857
+ if (!Array.isArray(current) || !Array.isArray(wanted) || current.length !== wanted.length) return false
858
+ const currentSet = new Set(current)
859
+ if (currentSet.size !== wanted.length || !wanted.every((name) => currentSet.has(name))) return false
860
+ // desiredManifest() copies every non-bundle field verbatim. Assert that
861
+ // explicitly so a future widening of desiredManifest cannot silently disable
862
+ // convergence of those fields.
863
+ const stripBundles = (manifest) => {
864
+ const profile = { ...(manifest?.dsh?.profile ?? {}) }
865
+ delete profile.bundles
866
+ return JSON.stringify({ ...manifest, dsh: { ...(manifest?.dsh ?? {}), profile } })
867
+ }
868
+ return stripBundles(existing) === stripBundles(desired)
869
+ }
870
+
842
871
  /** Version actually mounted in the profile node_modules, or undefined. */
843
872
  function installedCompanionVersion(name) {
844
873
  try {
@@ -1519,7 +1548,11 @@ function provisionProfileFiles({ externalCarry, repair } = {}) {
1519
1548
  fail(`${manifestPath} is not a valid JSON object manifest — leaving it untouched`)
1520
1549
  }
1521
1550
  const desired = desiredManifest(existing ?? { name: `dsh-profile-${activeProfile()}`, private: true })
1522
- if (existing !== undefined && JSON.stringify(existing) === JSON.stringify(desired)) {
1551
+ // A real dsh plugin add writes bundles in pnpm's sorted key order, not the
1552
+ // catalog order managedBundles() produces. Treat a converged set in any
1553
+ // order as already correct; every other difference still takes the
1554
+ // backup + rewrite path (see manifestAlreadyConverged).
1555
+ if (manifestAlreadyConverged(existing, desired)) {
1523
1556
  say(2, 'manifest', 'already correct, skipping')
1524
1557
  } else {
1525
1558
  mkdirSync(profileDir, { recursive: true })
@@ -0,0 +1,484 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Minimal `dsh-opentui upgrade` — upgrade the launcher package itself, nothing
4
+ * else. No companions, no $DSH_HOME, no provisioning, no migration: those are
5
+ * the next launch's job. The only npm commands are `npm view`, `npm prefix -g`,
6
+ * `npm i -g` and (after install) the version re-check under the global prefix.
7
+ *
8
+ * WHY A SEPARATE MODULE: the bin is a top-level script (importing it would RUN
9
+ * it). Everything decision-making here is exported as a pure function over
10
+ * plain data; the process-touching parts (npm exec, package.json reads, logs,
11
+ * exit codes) are injected through `runUpgrade`'s context so tests never
12
+ * install anything.
13
+ *
14
+ * Registry contract (deliberately does NOT parse .npmrc): npm is trusted with
15
+ * its own configuration. `DSH_UPGRADE_REGISTRY` is the one explicit override —
16
+ * when set it is appended as `--registry <value>` to BOTH `npm view` and
17
+ * `npm i -g`, so resolution and installation cannot drift apart.
18
+ */
19
+ import { spawnSync } from 'node:child_process'
20
+ import { lstatSync, realpathSync } from 'node:fs'
21
+ import { dirname, join, resolve } from 'node:path'
22
+ import { fileURLToPath } from 'node:url'
23
+ import { readLauncherVersion } from '../bin/lib/launcher.mjs'
24
+ import { compareVersions, isExactVersion } from './lib/host-compat.mjs'
25
+
26
+ export { compareVersions } from './lib/host-compat.mjs'
27
+
28
+ export const PACKAGE_NAME = '@aiwayds/dsh-opentui'
29
+ export const DEFAULT_TAG = 'latest'
30
+ export const REGISTRY_ENV = 'DSH_UPGRADE_REGISTRY'
31
+ const VIEW_TIMEOUT_MS = 15_000
32
+ const PREFIX_TIMEOUT_MS = 10_000
33
+
34
+ /**
35
+ * Last-resort scrub for third-party text (npm's own error strings) that may
36
+ * embed a credential-bearing URL. Removes the userinfo segment only.
37
+ */
38
+ function redactSecrets(text) {
39
+ return String(text).replace(/\b(https?:\/\/)[^/@\s]+@/gi, (_match, scheme) => scheme)
40
+ }
41
+
42
+ /**
43
+ * Safe rendering of a registry URL for ANY user-visible output (commands we
44
+ * print, manual instructions, dry-run, error details). Credentials embedded in
45
+ * `https://user:token@host/` must never reach a terminal or CI log. The value
46
+ * passed to `npm` is always the ORIGINAL string — only display goes through
47
+ * here. Unparseable input is replaced, never echoed verbatim.
48
+ */
49
+ export function displayRegistry(url) {
50
+ if (typeof url !== 'string' || url.trim() === '') return '<invalid registry>'
51
+ try {
52
+ const parsed = new URL(url)
53
+ if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || !parsed.host) {
54
+ return '<invalid registry>'
55
+ }
56
+ parsed.username = ''
57
+ parsed.password = ''
58
+ return parsed.toString()
59
+ } catch {
60
+ return '<invalid registry>'
61
+ }
62
+ }
63
+
64
+ // --- argv -------------------------------------------------------------------
65
+
66
+ /** Pure parse of the subcommand's own argv. No process access, no logging. */
67
+ export function parseUpgradeArgs(argv = []) {
68
+ const args = Array.isArray(argv) ? argv : []
69
+ let tag = DEFAULT_TAG
70
+ let tagSeen = false
71
+ let dryRun = false
72
+ let help = false
73
+ const rest = []
74
+ for (let i = 0; i < args.length; i++) {
75
+ const arg = args[i]
76
+ if (arg === '--help' || arg === '-h') {
77
+ help = true
78
+ continue
79
+ }
80
+ if (arg === '--dry-run') {
81
+ dryRun = true
82
+ continue
83
+ }
84
+ if (arg === '--tag') {
85
+ const value = args[i + 1]
86
+ if (value === undefined || value === '' || value.startsWith('-')) {
87
+ return { tag, dryRun, help, rest, error: 'missing-value', errorFlag: '--tag' }
88
+ }
89
+ if (tagSeen) {
90
+ return { tag, dryRun, help, rest, error: 'duplicate-tag', errorValue: value, errorPrevious: tag }
91
+ }
92
+ tag = value
93
+ tagSeen = true
94
+ i++
95
+ continue
96
+ }
97
+ if (arg.startsWith('--tag=')) {
98
+ const value = arg.slice('--tag='.length)
99
+ if (value === '') return { tag, dryRun, help, rest, error: 'missing-value', errorFlag: '--tag' }
100
+ if (tagSeen) {
101
+ return { tag, dryRun, help, rest, error: 'duplicate-tag', errorValue: value, errorPrevious: tag }
102
+ }
103
+ tag = value
104
+ tagSeen = true
105
+ continue
106
+ }
107
+ rest.push(arg)
108
+ }
109
+ if (!help && rest.length > 0) {
110
+ return { tag, dryRun, help, rest, error: 'unknown', errorValue: rest[0] }
111
+ }
112
+ if (!help && !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(tag)) {
113
+ return { tag, dryRun, help, rest, error: 'invalid-tag', errorValue: tag }
114
+ }
115
+ return { tag, dryRun, help, rest, error: null }
116
+ }
117
+
118
+ /** Dedicated subcommand help (also used by `node scripts/upgrade.mjs --help`). */
119
+ export function formatUpgradeUsage() {
120
+ return [
121
+ 'Usage: dsh-opentui upgrade [--tag <dist-tag>] [--dry-run]',
122
+ '',
123
+ 'Upgrade the launcher package (@aiwayds/dsh-opentui) itself. Profiles,',
124
+ 'companions and migrations are left to the next launch.',
125
+ '',
126
+ ' --tag <dist-tag> npm dist-tag to resolve (default: latest)',
127
+ ' letters/digits first, then letters, digits, . _ - only',
128
+ ' --dry-run resolve and print the command, do not install',
129
+ ' (no command is printed when the target is equal/older)',
130
+ ' -h, --help print this help and exit',
131
+ '',
132
+ `Requires an npm global install (--dry-run is exempt); otherwise use npm i -g ${PACKAGE_NAME}.`,
133
+ `Set ${REGISTRY_ENV} to pass --registry <url> to both npm view and npm i -g.`,
134
+ 'The tag is only a key into npm view\'s dist-tags JSON; it never enters npm argv.',
135
+ ].join('\n')
136
+ }
137
+
138
+ // --- npm helpers (all process access goes through the injected exec) --------
139
+
140
+ const defaultExec = (cmd, args, opts) => spawnSync(cmd, args, opts)
141
+
142
+ /** `npm view @aiwayds/dsh-opentui dist-tags --json` (+ optional --registry). */
143
+ export function npmViewArgs({ registry } = {}) {
144
+ const args = ['view', PACKAGE_NAME, 'dist-tags', '--json']
145
+ if (registry) args.push('--registry', registry)
146
+ return args
147
+ }
148
+
149
+ /** The exact install command we would run (argv form, executable first). */
150
+ export function npmInstallCommand({ targetVersion, registry } = {}) {
151
+ const spec = registry
152
+ ? ['i', '-g', `${PACKAGE_NAME}@${targetVersion}`, '--registry', registry]
153
+ : ['i', '-g', `${PACKAGE_NAME}@${targetVersion}`]
154
+ return ['npm', ...spec]
155
+ }
156
+
157
+ function registryFailureDetail(registry) {
158
+ if (registry) return displayRegistry(registry)
159
+ // Do not name a hardcoded public URL here: with no override npm uses its own
160
+ // configured registry, which may be a private mirror.
161
+ return `npm 自身配置的 registry(可用 ${REGISTRY_ENV} 指定)`
162
+ }
163
+
164
+ /** Display-only rendering of an argv command: scrub --registry credentials. */
165
+ function formatCommand(command) {
166
+ return command
167
+ .map((arg, i) => (i > 0 && command[i - 1] === '--registry' ? displayRegistry(arg) : arg))
168
+ .join(' ')
169
+ }
170
+
171
+ const stripV = (value) => String(value).trim().replace(/^v/, '')
172
+
173
+ /**
174
+ * Resolve a dist-tag through npm. Injected `exec` keeps this testable; a failed
175
+ * / malformed / tagless registry query throws with the registry URL in the
176
+ * message so the user can tell where the lookup went.
177
+ *
178
+ * `tag` is only used as a key into the returned dist-tags JSON — it is NEVER
179
+ * appended to the npm argv, so no user-supplied string can reach npm as a flag.
180
+ */
181
+ export function resolveTargetVersion({ tag = DEFAULT_TAG, registry, exec = defaultExec } = {}) {
182
+ const args = npmViewArgs({ registry })
183
+ let result
184
+ try {
185
+ result = exec('npm', args, { encoding: 'utf8', timeout: VIEW_TIMEOUT_MS })
186
+ } catch (error) {
187
+ throw new Error(
188
+ `无法从 npm registry 读取 ${PACKAGE_NAME} 的 dist-tag '${tag}';registry: ${registryFailureDetail(registry)}(${error?.message ?? error})`,
189
+ )
190
+ }
191
+ if (result?.error !== undefined) {
192
+ throw new Error(
193
+ `无法从 npm registry 读取 ${PACKAGE_NAME} 的 dist-tag '${tag}';registry: ${registryFailureDetail(registry)}(${result.error.message ?? result.error})`,
194
+ )
195
+ }
196
+ if (result?.status !== 0) {
197
+ throw new Error(
198
+ `无法从 npm registry 读取 ${PACKAGE_NAME} 的 dist-tag '${tag}'(npm view 退出 ${result?.status});registry: ${registryFailureDetail(registry)}`,
199
+ )
200
+ }
201
+ let tags
202
+ try {
203
+ tags = JSON.parse(String(result?.stdout ?? ''))
204
+ } catch {
205
+ throw new Error(
206
+ `npm view 返回的 dist-tags 不是合法 JSON;registry: ${registryFailureDetail(registry)}`,
207
+ )
208
+ }
209
+ const raw = tags?.[tag]
210
+ if (typeof raw !== 'string' || raw.trim() === '') {
211
+ throw new Error(
212
+ `${PACKAGE_NAME} 没有 '${tag}' dist-tag;registry: ${registryFailureDetail(registry)}`,
213
+ )
214
+ }
215
+ const version = stripV(raw)
216
+ if (!isExactVersion(version)) {
217
+ throw new Error(`dist-tag '${tag}' 的版本 ${JSON.stringify(raw)} 不是精确 semver;registry: ${registryFailureDetail(registry)}`)
218
+ }
219
+ return version
220
+ }
221
+
222
+ /**
223
+ * `npm prefix -g` through the injected executor. By default returns undefined
224
+ * on any failure (used by the post-install re-check, where a missing prefix is
225
+ * just one of the reasons verification can fail). With `strict: true` it throws
226
+ * a descriptive error instead: the pre-install guard must not confuse "npm is
227
+ * unavailable / the query failed" with "this is a source-tree checkout".
228
+ */
229
+ export function captureGlobalPrefix(exec = defaultExec, { strict = false } = {}) {
230
+ let result
231
+ try {
232
+ result = exec('npm', ['prefix', '-g'], { encoding: 'utf8', timeout: PREFIX_TIMEOUT_MS })
233
+ } catch (error) {
234
+ if (strict) throw new Error(`无法确定 npm 全局前缀(npm prefix -g 调用失败:${error?.message ?? error})`)
235
+ return undefined
236
+ }
237
+ if (result?.error !== undefined) {
238
+ if (strict) throw new Error(`无法确定 npm 全局前缀(npm prefix -g 失败:${result.error.message ?? result.error})`)
239
+ return undefined
240
+ }
241
+ if (result?.status !== 0) {
242
+ if (strict) throw new Error(`无法确定 npm 全局前缀(npm prefix -g 退出 ${result?.status})`)
243
+ return undefined
244
+ }
245
+ const prefix = String(result?.stdout ?? '').trim()
246
+ if (!prefix) {
247
+ if (strict) throw new Error('无法确定 npm 全局前缀(npm prefix -g 未返回路径)')
248
+ return undefined
249
+ }
250
+ return prefix
251
+ }
252
+
253
+ /**
254
+ * A global package dir that is a symlink is an `npm link` development install,
255
+ * not a package npm can upgrade in place. Detect it BEFORE installing so we
256
+ * never mutate the link target (the source tree).
257
+ */
258
+ export function findLinkedGlobalInstall(prefix) {
259
+ if (!prefix) return undefined
260
+ for (const candidate of globalPackagePaths(prefix)) {
261
+ try {
262
+ if (lstatSync(candidate).isSymbolicLink()) return candidate
263
+ } catch {
264
+ /* not present — keep looking */
265
+ }
266
+ }
267
+ return undefined
268
+ }
269
+
270
+ /** Where a global install of this package lives under an npm prefix. */
271
+ export function globalPackagePaths(prefix) {
272
+ if (!prefix) return []
273
+ return [
274
+ join(prefix, 'lib', 'node_modules', PACKAGE_NAME),
275
+ join(prefix, 'node_modules', PACKAGE_NAME),
276
+ ]
277
+ }
278
+
279
+ function normalizePath(path) {
280
+ try {
281
+ return realpathSync(resolve(path))
282
+ } catch {
283
+ return resolve(path)
284
+ }
285
+ }
286
+
287
+ /**
288
+ * Whether the RUNNING copy is the npm-global install of this package. A source
289
+ * tree / pnpm store / custom prefix is not: upgrading it in place would leave
290
+ * the actual global copy untouched. Both values can be injected (pure); with
291
+ * only `exec` injected the prefix is read via `npm prefix -g`.
292
+ */
293
+ export function isGlobalInstall({ globalPrefix, runningRoot, exec = defaultExec } = {}) {
294
+ const prefix = globalPrefix ?? captureGlobalPrefix(exec)
295
+ if (!prefix || !runningRoot) return false
296
+ const root = normalizePath(runningRoot)
297
+ // Only the package paths under the global prefix count. The prefix itself
298
+ // being the running root is not a global package install.
299
+ return globalPackagePaths(prefix).some((candidate) => normalizePath(candidate) === root)
300
+ }
301
+
302
+ // --- pure decision ----------------------------------------------------------
303
+
304
+ /**
305
+ * Decide what to do. Pure: no exec, no fs, no process. `cmp` is -1 / 0 / 1 for
306
+ * target vs current. Dry-run reports the command but never installs, so it
307
+ * deliberately skips the global-install guard.
308
+ */
309
+ export function planUpgrade({ targetVersion, currentVersion, dryRun = false, registry, isGlobal = false } = {}) {
310
+ const cmp = compareVersions(targetVersion, currentVersion)
311
+ const command = npmInstallCommand({ targetVersion, registry })
312
+ if (dryRun) return { action: 'dry-run', cmp, command, targetVersion, currentVersion }
313
+ if (cmp === 0) return { action: 'up-to-date', cmp, command: null, targetVersion, currentVersion }
314
+ if (cmp < 0) return { action: 'downgrade', cmp, command: null, targetVersion, currentVersion }
315
+ if (!isGlobal) return { action: 'not-global', cmp, command, targetVersion, currentVersion }
316
+ return { action: 'install', cmp, command, targetVersion, currentVersion }
317
+ }
318
+
319
+ /** After a successful install, re-read the version under `npm prefix -g`. */
320
+ export function verifyInstalledVersion({ targetVersion, exec = defaultExec, readVersion = readLauncherVersion } = {}) {
321
+ const prefix = captureGlobalPrefix(exec)
322
+ for (const candidate of globalPackagePaths(prefix)) {
323
+ try {
324
+ if (readVersion(candidate) === targetVersion) return { ok: true, path: candidate, version: targetVersion }
325
+ } catch {
326
+ /* try the next candidate */
327
+ }
328
+ }
329
+ return { ok: false, prefix, version: undefined }
330
+ }
331
+
332
+ // --- process-facing entry ---------------------------------------------------
333
+
334
+ /** Run the subcommand; returns an exit code (never calls process.exit itself). */
335
+ export async function runUpgrade(argv = [], ctx = {}) {
336
+ const {
337
+ env = process.env,
338
+ exec = defaultExec,
339
+ pkgRoot = dirname(dirname(fileURLToPath(import.meta.url))),
340
+ readVersion = readLauncherVersion,
341
+ out: rawOut = (line) => console.log(line),
342
+ err: rawErr = (line) => console.error(line),
343
+ } = ctx
344
+ // Every line this command emits passes through the redactor: a registry URL
345
+ // (or an npm error quoting one) must never leak credentials into a terminal
346
+ // or CI log. Arguments handed to `exec` are untouched.
347
+ const out = (line) => rawOut(redactSecrets(line))
348
+ const err = (line) => rawErr(redactSecrets(line))
349
+
350
+ const parsed = parseUpgradeArgs(argv)
351
+ if (parsed.help) {
352
+ out(formatUpgradeUsage())
353
+ return 0
354
+ }
355
+ if (parsed.error === 'missing-value') {
356
+ err(`dsh-opentui upgrade: option '--tag' requires a value`)
357
+ err(formatUpgradeUsage())
358
+ return 2
359
+ }
360
+ if (parsed.error === 'duplicate-tag') {
361
+ err(`dsh-opentui upgrade: option '--tag' given more than once: '${parsed.errorPrevious}' and '${parsed.errorValue}'`)
362
+ err(formatUpgradeUsage())
363
+ return 2
364
+ }
365
+ if (parsed.error === 'invalid-tag') {
366
+ err(`dsh-opentui upgrade: invalid dist-tag '${parsed.errorValue}';只允许字母/数字开头,其后为字母、数字、. _ -(不含空白或 URL 元字符)`)
367
+ err(formatUpgradeUsage())
368
+ return 2
369
+ }
370
+ if (parsed.error) {
371
+ err(`dsh-opentui upgrade: unknown argument '${parsed.errorValue}'`)
372
+ err(formatUpgradeUsage())
373
+ return 2
374
+ }
375
+
376
+ // An explicit override must be a real http(s) URL. A typo must fail loudly
377
+ // instead of silently falling back to whatever registry npm has configured.
378
+ const rawRegistry = typeof env?.[REGISTRY_ENV] === 'string' ? env[REGISTRY_ENV].trim() : ''
379
+ let registry
380
+ if (rawRegistry !== '') {
381
+ if (!/^https?:\/\//i.test(rawRegistry)) {
382
+ err(`dsh-opentui upgrade: ${REGISTRY_ENV} 必须以 http:// 或 https:// 开头(合法 URL),收到 ${JSON.stringify(displayRegistry(rawRegistry))};已中止。`)
383
+ return 1
384
+ }
385
+ registry = rawRegistry
386
+ }
387
+
388
+ let targetVersion
389
+ try {
390
+ targetVersion = resolveTargetVersion({ tag: parsed.tag, registry, exec })
391
+ } catch (error) {
392
+ err(`dsh-opentui upgrade: ${error?.message ?? error}`)
393
+ return 1
394
+ }
395
+
396
+ const currentVersion = readVersion(pkgRoot)
397
+ if (!currentVersion) {
398
+ err(`dsh-opentui upgrade: 无法从 ${join(pkgRoot, 'package.json')} 读取当前版本,已中止。`)
399
+ return 1
400
+ }
401
+
402
+ let cmp
403
+ try {
404
+ cmp = compareVersions(targetVersion, currentVersion)
405
+ } catch (error) {
406
+ err(`dsh-opentui upgrade: 版本比较失败(当前 ${JSON.stringify(currentVersion)},目标 ${JSON.stringify(targetVersion)}):${error?.message ?? error}`)
407
+ return 1
408
+ }
409
+
410
+ let isGlobal = false
411
+ if (!parsed.dryRun && cmp > 0) {
412
+ // Resolve the global prefix strictly: a failed `npm prefix -g` is NOT the
413
+ // same as "running from a source tree", and must never end in an install.
414
+ let prefix
415
+ try {
416
+ prefix = captureGlobalPrefix(exec, { strict: true })
417
+ } catch (error) {
418
+ err(`dsh-opentui upgrade: ${error?.message ?? error};未执行安装。`)
419
+ return 1
420
+ }
421
+ const linked = findLinkedGlobalInstall(prefix)
422
+ if (linked) {
423
+ err(`dsh-opentui upgrade: ${linked} 是 npm link 的符号链接(linked development install),不是 npm 全局安装;升级已中止。请在源码目录更新后重新 link,或重新执行 npm i -g ${PACKAGE_NAME}。`)
424
+ return 1
425
+ }
426
+ isGlobal = isGlobalInstall({ globalPrefix: prefix, runningRoot: pkgRoot })
427
+ }
428
+ const plan = planUpgrade({
429
+ targetVersion,
430
+ currentVersion,
431
+ dryRun: parsed.dryRun,
432
+ registry,
433
+ isGlobal,
434
+ })
435
+
436
+ if (plan.action === 'dry-run') {
437
+ out(`dsh-opentui upgrade: 当前 ${currentVersion},目标(${parsed.tag})${targetVersion}(${plan.cmp > 0 ? '有可用升级' : plan.cmp === 0 ? '已是最新' : '目标版本更旧'})。`)
438
+ out(`dsh-opentui upgrade: --dry-run,不会执行安装。`)
439
+ if (plan.cmp > 0) out(`dsh-opentui upgrade: 将执行: ${formatCommand(plan.command)}`)
440
+ return 0
441
+ }
442
+
443
+ if (plan.action === 'up-to-date') {
444
+ out(`dsh-opentui upgrade: already up to date (${currentVersion}).`)
445
+ return 0
446
+ }
447
+
448
+ if (plan.action === 'downgrade') {
449
+ err(`dsh-opentui upgrade: refusing to downgrade from ${currentVersion} to ${targetVersion}.`)
450
+ return 1
451
+ }
452
+
453
+ if (plan.action === 'not-global') {
454
+ err(`dsh-opentui upgrade: 当前不是 npm 全局安装,请手动执行 npm i -g ${PACKAGE_NAME}@${targetVersion}${registry ? ` --registry ${displayRegistry(registry)}` : ''}。`)
455
+ return 1
456
+ }
457
+
458
+ out(`dsh-opentui upgrade: ${formatCommand(plan.command)}`)
459
+ // Capture npm output instead of inheriting its file descriptors: every line
460
+ // must pass through this process's redactor before reaching the terminal.
461
+ const install = exec('npm', plan.command.slice(1), {
462
+ stdio: ['ignore', 'pipe', 'pipe'],
463
+ encoding: 'utf8',
464
+ })
465
+ if (install?.stdout) out(String(install.stdout))
466
+ if (install?.stderr) err(String(install.stderr))
467
+ if (install?.error !== undefined || install?.status !== 0) {
468
+ err(`dsh-opentui upgrade: npm 安装失败${install?.status !== undefined ? `(退出 ${install.status})` : ''},已中止。`)
469
+ return 1
470
+ }
471
+ const verified = verifyInstalledVersion({ targetVersion, exec, readVersion })
472
+ if (!verified.ok) {
473
+ err(`dsh-opentui upgrade: 安装后校验失败:${verified.prefix ?? '未知 prefix'} 下找不到版本 ${targetVersion} 的 ${PACKAGE_NAME}。`)
474
+ return 1
475
+ }
476
+ out('dsh-opentui upgrade: 升级完成,退出并重新运行 dsh-opentui。')
477
+ return 0
478
+ }
479
+
480
+ // Direct invocation only: importing this module (from the bin or tests) must
481
+ // never run a registry query.
482
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
483
+ process.exit(await runUpgrade(process.argv.slice(2)))
484
+ }