@aiwayds/dsh-opentui 0.27.1 → 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.
@@ -5,9 +5,10 @@
5
5
  *
6
6
  * Startup chain:
7
7
  * 0. Bin-level flags — `--version` prints `dsh-opentui <version>` and
8
- * exits 0 BEFORE anything else (no provision, no TUI); `--force` resets
9
- * the singleton host before startup continues (needs `--yes` when live
10
- * clients are connected; ADR-0009). `--repair-bridge` is a terminal
8
+ * exits 0 BEFORE anything else (no provision, no TUI); `--force` and
9
+ * `--yes` are deprecated no-ops, retained for compatibility and removed in
10
+ * the next minor release. Use `--repair-bridge` to clear stale instances.
11
+ * `--repair-bridge` is a terminal
11
12
  * maintenance command: it clears this profile's stale instances (TERM
12
13
  * then KILL), runs the in-process bridge self-heal (T7), and exits before
13
14
  * any bun/dsh check, TUI launch, or default-seam change; it always runs
@@ -17,21 +18,13 @@
17
18
  * bun export conditions); no bun on PATH → install guidance, exit 1.
18
19
  * 2. dsh check — the host CLI is the session carrier (profile storage,
19
20
  * config load); no `dsh` on PATH → install guidance, exit 1.
20
- * 3. Profile bootstrap — runs scripts/provision-opentui-profile.mjs on
21
- * EVERY start. The script is idempotent and prints five progress steps
22
- * (profile, model route, plugins, bundles, verify); with nothing to do
23
- * it is a sub-second local pass. It transparently forwards
24
- * --provider/--model/--reasoning-effort and
25
- * --plugins=core|recommended|none (--dry-run prints the commands without
26
- * executing them). A non-zero exit is a WARN: the client still starts
27
- * with the profile as-is.
28
- * 4. One-time migration notice — a pre-retirement profile at
29
- * $DSH_HOME/profiles/dsh-opentui is detected once, its theme /
30
- * config.json preferences are conservatively copied into the opentui
31
- * profile (only keys the target does not already have), a marker file
32
- * ($DSH_HOME/.dsh-opentui-migrated) makes the step once-only. The old
33
- * profile is kept untouched.
34
- * 5. dsh-client-connection resolution guarantee — the client bundle
21
+ * 3. In-process profile bootstrap — runs
22
+ * scripts/provision-inproc-profile.mjs on EVERY start. The script is
23
+ * idempotent and prints eight progress steps (host, manifest/patch,
24
+ * workspace, bridge-copy, companions, verify, identity, shim). A non-zero
25
+ * exit is fatal because the client cannot use its in-process bridge without
26
+ * this profile.
27
+ * 4. dsh-client-connection resolution guarantee — the client bundle
35
28
  * imports `@deepseek-ai/dsh-client-connection/client` at runtime, but
36
29
  * that SDK is NOT on the public npm registry (it exists only inside a
37
30
  * globally-installed dsh's node_modules closure, and it must NEVER be
@@ -42,21 +35,25 @@
42
35
  * the SDK inside the global dsh closure. Idempotent: skipped whenever
43
36
  * the link already resolves; if no global dsh closure can be located,
44
37
  * install guidance is printed and the launch aborts (exit 1).
45
- * 6. Exec `bun <package root>/dist/client/index.js` with the user's
38
+ * 5. Exec `bun <package root>/dist/client/index.js` with the user's
46
39
  * arguments forwarded verbatim, then exits with the client's status.
40
+ * There is no HTTP-host pre-launch: the launcher only provisions and
41
+ * spawns the bun client; the client owns its in-process stdio bridge and
42
+ * the bridge host child lifecycle. The bridge ships in `dist/bridge/`;
43
+ * no separate lifecycle-helper artifact is required.
47
44
  *
48
45
  * Path contract for B3 (package.json wiring): the bin resolves everything
49
46
  * relative to ITS OWN LOCATION (bin/..), i.e. the package root. The
50
47
  * published package must therefore ship `dist/client/index.js` at the
51
- * package root (plus `dist/scripts/idle-reaper.mjs`, which the bundle
52
- * spawns) alongside `bin/` and `scripts/`.
48
+ * package root alongside `bin/`, `scripts/`, `dist/bridge/`, and
49
+ * `dist/locales/`.
53
50
  */
54
51
  import { spawn, spawnSync } from 'node:child_process'
55
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs'
52
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, symlinkSync, unlinkSync } from 'node:fs'
56
53
  import { constants as osConstants, homedir } from 'node:os'
57
54
  import { dirname, join } from 'node:path'
58
- import { fileURLToPath, pathToFileURL } from 'node:url'
59
- import { ancestorPids, formatUpgradeUsage, formatUsage, killStaleProcesses, launcherFlagConflict, LAUNCHER_TIMEOUT_FLAGS, parseLauncherArgs, parseLauncherOptions, parseProcessHomes, parseProcessRows, parseUpgradeArgs, prelaunchFailurePolicy, readLauncherVersion, selectStaleProcesses, validateLauncherArgs } from './lib/launcher.mjs'
55
+ import { fileURLToPath } from 'node:url'
56
+ import { ancestorPids, formatUsage, killStaleProcesses, launcherFlagConflict, LAUNCHER_TIMEOUT_FLAGS, parseLauncherArgs, parseLauncherOptions, parseProcessHomes, parseProcessRows, readLauncherVersion, selectStaleProcesses, validateLauncherArgs } from './lib/launcher.mjs'
60
57
 
61
58
  const pkgRoot = dirname(dirname(fileURLToPath(import.meta.url)))
62
59
  const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
@@ -73,7 +70,9 @@ function capture(cmd, args) {
73
70
  return r.stdout ?? ''
74
71
  }
75
72
 
76
- // --- 0. Bin-level flags: --version short-circuits, --force pre-clears -------
73
+ // --- 0. Bin-level flags: --version short-circuits; --force/--yes parsed -----
74
+ // --force / --yes remain parsed for compatibility as deprecated no-ops.
75
+ // They are removed in the next minor release; use --repair-bridge for stale cleanup.
77
76
  const { version: versionFlag, force: forceFlag, repairBridge: repairBridgeFlag, yes: yesFlag, rest: userArgs, passthrough } = parseLauncherArgs(process.argv.slice(2))
78
77
 
79
78
  if (versionFlag) {
@@ -86,9 +85,15 @@ if (versionFlag) {
86
85
  process.exit(0)
87
86
  }
88
87
 
88
+ // Warn once on non-version invocations carrying --force. A standalone --yes
89
+ // is a usage error below; beside --force or --repair-bridge it is ignored.
90
+ if (forceFlag) {
91
+ console.error('dsh-opentui: --force is deprecated and does nothing in this build; run --repair-bridge to clear stale instances. Removed in the next minor release.')
92
+ }
93
+
89
94
  // P3-3: make flag combinations that used to fall into dead corners explicit.
90
- // Checked here (before the upgrade/help/repair branches) so the same conflict
91
- // wins regardless of which branch a combination would otherwise reach.
95
+ // Checked here (before the help/repair branches) so the same conflict wins
96
+ // regardless of which branch a combination would otherwise reach.
92
97
  const flagConflict = launcherFlagConflict({ force: forceFlag, repairBridge: repairBridgeFlag, yes: yesFlag })
93
98
  if (flagConflict === 'yes-without-force') {
94
99
  console.error('dsh-opentui: --yes is only meaningful together with --force.')
@@ -99,57 +104,10 @@ if (flagConflict === 'repair-force') {
99
104
  process.exit(2)
100
105
  }
101
106
 
102
- // --- 0.5 upgrade subcommand -------------------------------------------------
103
- // `upgrade` is a positional subcommand: only the first remaining argument may
104
- // select it, and here is its ONLY consumer. It must never reach the provision
105
- // forwarder (step 3) or the client (step 6) — the client would take the bare
106
- // `upgrade` for a session name. Placed after `--version` (whose absolute
107
- // short-circuit is unchanged) and BEFORE the bun/dsh checks: upgrading needs
108
- // `npm` and `dsh`, not bun, and must not provision or link anything.
109
- const upgradeResult = parseUpgradeArgs(userArgs)
110
- if (upgradeResult.isUpgrade) {
111
- // P3-3 ②: the upgrade branch precedes the repair branch, so a stray
112
- // --repair-bridge used to be silently swallowed. Say so explicitly.
113
- if (repairBridgeFlag) {
114
- console.error('dsh-opentui: --repair-bridge is skipped during `upgrade` (no bridge repair on the upgrade path).')
115
- }
116
- if (forceFlag) {
117
- console.error('dsh-opentui: --force is not supported with upgrade.')
118
- console.error(formatUpgradeUsage())
119
- process.exit(2)
120
- }
121
- if (upgradeResult.error === 'unknown-flag') {
122
- console.error(`dsh-opentui: unknown flag(s): ${upgradeResult.unknownFlags.join(', ')}`)
123
- console.error(formatUpgradeUsage())
124
- process.exit(2)
125
- }
126
- if (upgradeResult.error === 'missing-tag-value') {
127
- console.error('dsh-opentui: --tag requires a non-empty value.')
128
- console.error(formatUpgradeUsage())
129
- process.exit(2)
130
- }
131
- if (upgradeResult.error === 'invalid-tag') {
132
- console.error(
133
- `dsh-opentui: invalid --tag value: ${upgradeResult.invalidTag} (allowed: A-Z a-z 0-9 . _ -)`,
134
- )
135
- console.error(formatUpgradeUsage())
136
- process.exit(2)
137
- }
138
- if (upgradeResult.error === 'reset-overrides-conflict') {
139
- console.error('dsh-opentui: --reset-overrides cannot be combined with --no-self or --no-plugins.')
140
- console.error(formatUpgradeUsage())
141
- process.exit(2)
142
- }
143
- // Loaded lazily so a normal launch never evaluates the upgrade body.
144
- const { runUpgrade } = await import(pathToFileURL(join(pkgRoot, 'scripts', 'upgrade.mjs')).href)
145
- process.exit(runUpgrade(upgradeResult.opts, { pkgRoot }))
146
- }
147
-
148
- // --- 0.6 usage/help and argument validation --------------------------------
149
- // Placed after --version (absolute short-circuit) and after `upgrade` (whose
150
- // -h/--help belongs to parseUpgradeArgs), but BEFORE provisioning or any TUI
151
- // work: a typo like `--verison` must fail here instead of running a full
152
- // provision pass first.
107
+ // --- 0.5 usage/help and argument validation --------------------------------
108
+ // Placed after --version (absolute short-circuit), but BEFORE provisioning or
109
+ // any TUI work: a typo like `--verison` must fail here instead of running a
110
+ // full provision pass first.
153
111
  function stripLauncherTimeoutFlags(args) {
154
112
  const out = []
155
113
  for (let i = 0; i < args.length; i++) {
@@ -202,7 +160,7 @@ if (validation.unknown.length > 0) {
202
160
  // --- 0.7 --repair-bridge: terminal in-process bridge self-heal (T7) ---------
203
161
  // This is a maintenance command, not a launch. It invokes the SAME provisioner
204
162
  // the default startup path uses, in its repair mode. It deliberately exits here
205
- // — before the bun/dsh checks, the default `opentui` profile bootstrap, the
163
+ // — before the bun/dsh checks, the in-process profile bootstrap, the
206
164
  // client-connection link, and the bun client launch — so it never starts a TUI
207
165
  // and never changes the default seam (that is M2's job). The provisioner owns
208
166
  // the lock, the repair logic and the T5 identity guard; its exit status is ours.
@@ -257,55 +215,16 @@ if (!spawnSync('which', ['dsh'], { encoding: 'utf8' }).stdout.trim()) {
257
215
  exitWithGuidance('the dsh CLI', 'npm i -g @deepseek-ai/dsh')
258
216
  }
259
217
 
260
- // --- 2.5 --force -----------------------------------------------------------
261
- // NOTE (ADR-0009 decision 8): the old bare `--profile opentui` cmdline sweep
262
- // lived here. It is deliberately removed — killing a process needs the THREE
263
- // evidences (registry pid + `--profile opentui` cmdline + `DSH_OPENTUI_SERVER=1`
264
- // env). `--force` is now handled at step 6a inside the host-launch bundle,
265
- // which also enforces the `--yes` guard when live clients are connected.
266
-
267
- // --- 3. Profile bootstrap (every start, best effort, idempotent) -----------
268
- // provision-opentui-profile.mjs is idempotent and understands
269
- // --provider/--model/--reasoning-effort --plugins/--dry-run (both space and
270
- // `=` forms); forward those, ignore the rest. With nothing to do this is a
271
- // local, sub-second pass.
272
- const opentuiProfileDir = join(dshHome, 'profiles', 'opentui')
273
- {
274
- const provisionFlags = []
275
- for (const name of ['provider', 'model', 'reasoning-effort']) {
276
- const inline = userArgs.find((arg) => arg.startsWith(`--${name}=`))
277
- if (inline) {
278
- provisionFlags.push(inline)
279
- continue
280
- }
281
- const i = userArgs.indexOf(`--${name}`)
282
- if (i >= 0 && userArgs[i + 1]) provisionFlags.push(`--${name}`, userArgs[i + 1])
283
- }
284
- const pluginsInline = userArgs.find((arg) => arg.startsWith('--plugins='))
285
- if (pluginsInline) {
286
- provisionFlags.push(pluginsInline)
287
- } else {
288
- const i = userArgs.indexOf('--plugins')
289
- if (i >= 0 && userArgs[i + 1]) provisionFlags.push('--plugins', userArgs[i + 1])
290
- }
291
- if (userArgs.includes('--dry-run')) provisionFlags.push('--dry-run')
292
- const r = spawnSync(process.execPath, [join(pkgRoot, 'scripts', 'provision-opentui-profile.mjs'), ...provisionFlags], {
293
- stdio: 'inherit',
294
- })
295
- if (r.error) {
296
- console.error(`dsh-opentui: profile provisioning failed: ${r.error.message}`)
297
- process.exit(1)
298
- }
299
- if (r.status !== 0) {
300
- console.error(`dsh-opentui: profile provisioning exited ${r.status}; continuing with the profile as-is.`)
301
- }
302
- }
218
+ // --- 2.5 deprecated --force / --yes -----------------------------------------
219
+ // Parsed and warned about at step 0, then deliberately inert here in this
220
+ // in-process-only build: no process is killed or reset. Both flags are removed
221
+ // in the next minor release; stale-instance cleanup belongs to --repair-bridge.
303
222
 
304
- // --- 3b. In-process bridge profile provisioning ----------------------------
305
- // S6: the bridge is the sole seam, so this runs on EVERY launch. The script
306
- // provisions ONLY the `opentui-inproc` profile: bundle manifest + the shipped
307
- // dist/bridge artifact (real directory copy). A non-zero exit is fatal here
308
- // (the bridge cannot work without it), unlike the best-effort path above.
223
+ // --- 3. In-process bridge profile provisioning ------------------------------
224
+ // The bridge is the sole seam, so this runs on EVERY launch. The script
225
+ // provisions ONLY the active in-process profile: bundle manifest + the shipped
226
+ // dist/bridge artifact (real directory copy). A non-zero exit is fatal because
227
+ // the client cannot use its in-process bridge without this profile.
309
228
  {
310
229
  const r = spawnSync(process.execPath, [join(pkgRoot, 'scripts', 'provision-inproc-profile.mjs')], {
311
230
  stdio: 'inherit',
@@ -320,91 +239,9 @@ const opentuiProfileDir = join(dshHome, 'profiles', 'opentui')
320
239
  }
321
240
  }
322
241
 
323
- // --- 4. One-time migration notice from the pre-retirement profile ----------
324
- const legacyProfileDir = join(dshHome, 'profiles', 'dsh-opentui')
325
- const migrationMarker = join(dshHome, '.dsh-opentui-migrated')
326
- if (existsSync(legacyProfileDir) && !existsSync(migrationMarker)) {
327
- console.log('dsh-opentui: found a legacy profiles/dsh-opentui profile (pre-retirement plugin mode).')
328
- console.log('dsh-opentui: the client now uses the \'opentui\' profile; the legacy profile is kept, not deleted.')
329
- try {
330
- migrateLegacyPreferences()
331
- } catch (err) {
332
- console.warn(`dsh-opentui: preference migration skipped (${err?.message ?? err}); the legacy profile is untouched.`)
333
- }
334
- try {
335
- writeFileSync(migrationMarker, new Date().toISOString() + '\n')
336
- } catch (err) {
337
- console.warn(`dsh-opentui: could not write ${migrationMarker} (${err?.message ?? err}).`)
338
- }
339
- }
340
-
341
- /** Best-effort copy of legacy preferences into the opentui profile.
342
- * Merge-only: a key already present in the target config.json wins; the
343
- * legacy profile files are only ever read, never modified. */
344
- function migrateLegacyPreferences() {
345
- const legacyConfigPath = join(legacyProfileDir, 'config.json')
346
- const targetConfigPath = join(opentuiProfileDir, 'config.json')
347
-
348
- let target = {}
349
- try {
350
- target = JSON.parse(readFileSync(targetConfigPath, 'utf8'))
351
- } catch {
352
- /* missing or unparsable → start from an empty object */
353
- }
354
-
355
- // (a) top-level keys from the legacy profile config.json (e.g.
356
- // retentionDays): copied only when the target does not have them.
357
- let legacyConfig = {}
358
- try {
359
- legacyConfig = JSON.parse(readFileSync(legacyConfigPath, 'utf8'))
360
- } catch {
361
- /* no legacy config.json — nothing to copy from here */
362
- }
363
- if (typeof legacyConfig !== 'object' || legacyConfig === null || Array.isArray(legacyConfig)) legacyConfig = {}
364
-
365
- // (b) the theme preference lived in the legacy plugin patch (the retired
366
- // `dsh-opentui` plugin's config block), not in config.json — pull it
367
- // out with a narrow scan of that block only.
368
- let legacyTheme
369
- try {
370
- const patch = readFileSync(join(legacyProfileDir, 'cordis.patch.yml'), 'utf8')
371
- const block = patch.match(/- id: dsh-opentui\b[^\n]*/)?.[0]
372
- if (block) {
373
- const tail = patch.slice(patch.indexOf(block))
374
- legacyTheme = tail.match(/^[ \t]+theme:[ \t]*([^\s#]+)/m)?.[1]
375
- }
376
- } catch {
377
- /* no legacy patch — no theme to copy */
378
- }
379
- if (legacyTheme) legacyTheme = legacyTheme.replace(/^['"]|['"]$/g, '')
380
-
381
- const additions = {}
382
- for (const [key, value] of Object.entries(legacyConfig)) {
383
- if (!(key in target)) additions[key] = value
384
- }
385
- if (legacyTheme && target.theme === undefined) additions.theme = legacyTheme
386
-
387
- const keys = Object.keys(additions)
388
- if (keys.length === 0) {
389
- console.log('dsh-opentui: no legacy preferences to carry over.')
390
- return
391
- }
392
-
393
- mkdirSync(opentuiProfileDir, { recursive: true })
394
- if (existsSync(targetConfigPath)) {
395
- const backupPath = `${targetConfigPath}.bak-${Date.now()}`
396
- renameSync(targetConfigPath, backupPath)
397
- console.log(`dsh-opentui: backed up ${targetConfigPath} to ${backupPath}`)
398
- }
399
- const merged = { ...target, ...additions }
400
- writeFileSync(targetConfigPath, JSON.stringify(merged, null, 2) + '\n')
401
- console.log(`dsh-opentui: carried over legacy preference(s) [${keys.join(', ')}] into ${targetConfigPath}.`)
402
- }
403
-
404
- // --- 5. dsh-client-connection resolution guarantee --------------------------
405
- // The client bundle imports "@deepseek-ai/dsh-client-connection/client" at
406
- // runtime (packages/shell/src/client/transport.ts). That SDK is NOT on the
407
- // public npm registry — it ships only inside a globally-installed dsh's own
242
+ // --- 4. dsh-client-connection resolution guarantee --------------------------
243
+ // The client bundle historically imported "@deepseek-ai/dsh-client-connection/client"
244
+ // at runtime. That SDK is NOT on the public npm registry — it ships only inside a globally-installed dsh's own
408
245
  // node_modules closure, and it must NEVER be bundled into this public
409
246
  // package (that would redistribute DeepSeek private code). A plain npm
410
247
  // global install of this package does not make the closure reachable: module
@@ -479,58 +316,17 @@ function dshClientConnectionCandidates() {
479
316
  return candidates
480
317
  }
481
318
 
482
- // --- 6. Launch the client bundle under bun ---------------------------------
319
+ // --- 5. Launch the client bundle under bun ---------------------------------
483
320
  const clientEntry = join(pkgRoot, 'dist', 'client', 'index.js')
484
321
  if (!existsSync(clientEntry)) {
485
322
  console.error(`dsh-opentui: client bundle not found at ${clientEntry}.`)
486
323
  console.error('dsh-opentui: reinstall the package (npm i -g @aiwayds/dsh-opentui), or rebuild it with `bun scripts/build-client.mjs` from the repo.')
487
324
  process.exit(1)
488
325
  }
489
- // --- 6a. Pre-launch the Host service (registry / port / health) ------------
490
- // ADR-0009 §3: start/adopt the singleton host HERE, while the launcher still
491
- // owns the terminal, so the `spawn → booting → ready + elapsed` progress is
492
- // painted BEFORE the bun client enters its alternate screen. The client's own
493
- // lifecycle.ensureHost then adopts the ready host (no double start). On the
494
- // healthy-attach fast path nothing is printed. The orchestration bundle is a
495
- // separate build artifact (packages/shell/dist/host-launch.mjs); a missing or
496
- // failing pre-launch is best-effort — the client retries host boot itself —
497
- // EXCEPT under `--force`, where a failed import/reset is fatal (P1-5).
498
- // `--dry-run` is side-effect free and skips this step.
499
- if (!clientArgs.includes('--dry-run')) {
500
- try {
501
- const hostLaunchPath = join(pkgRoot, 'dist', 'host-launch.mjs')
502
- const { ensureHost: ensureLaunchHost, createLaunchProgress } = await import(pathToFileURL(hostLaunchPath).href)
503
- await ensureLaunchHost({
504
- home: dshHome,
505
- profile: 'opentui',
506
- cwd: process.cwd(),
507
- ...(forceFlag ? { force: true } : {}),
508
- ...(yesFlag ? { yes: true } : {}),
509
- progress: createLaunchProgress({
510
- isTty: Boolean(process.stderr.isTTY),
511
- write: (text) => process.stderr.write(text),
512
- }),
513
- })
514
- } catch (err) {
515
- // P1-5: a force reset must NEVER silently degrade to a no-op. Only the
516
- // non-force path is best-effort (the client retries host boot itself).
517
- const policy = prelaunchFailurePolicy(err, forceFlag)
518
- if (policy === 'usage-error') {
519
- console.error(`dsh-opentui: ${err?.message ?? err}`)
520
- process.exit(2)
521
- }
522
- if (policy === 'abort') {
523
- console.error(`dsh-opentui: --force host pre-launch failed (${err?.message ?? err}); aborting without reset.`)
524
- process.exit(1)
525
- }
526
- console.error(`dsh-opentui: host pre-launch failed (${err?.message ?? err}); the client will retry host boot.`)
527
- }
528
- }
529
-
530
- // ADR-0009 follow-up (PR B): spawnSync blocked the launcher's event loop for
531
- // the whole TUI session, so SIGCHLD could never be delivered — the detached,
532
- // unref'd host child died but stayed a zombie until the client exited. An
533
- // async spawn keeps libuv alive so the host is reaped as soon as it exits.
326
+ // Async spawn: spawnSync blocked the launcher's event loop for the whole TUI
327
+ // session. The detached host child this originally described is gone with
328
+ // step 6a; an async spawn still keeps libuv alive for signal forwarding and
329
+ // for reaping the bun client as soon as it exits.
534
330
  const child = spawn('bun', [clientEntry, ...clientArgs], {
535
331
  stdio: 'inherit',
536
332
  env: clientEnv,