@aiwayds/dsh-opentui 0.12.1 → 0.12.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/CHANGELOG.md CHANGED
@@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.12.2] - 2026-11-13
9
+
10
+ ### Added
11
+
12
+ - **`--version` prints `dsh-opentui <version>` and exits** without booting the TUI or provisioning.
13
+ - **`--force` kills stale host/client instances sharing the current DSH_HOME** (TERM→KILL ladder, prints `--force: killed N stale instance(s)`) before a clean boot.
14
+
8
15
  ## [0.12.1] - 2026-11-13
9
16
 
10
17
  ### Fixed
@@ -4,6 +4,11 @@
4
4
  * the plugin-mode chain was retired in batch B4).
5
5
  *
6
6
  * Startup chain:
7
+ * 0. Bin-level flags — `--version` prints `dsh-opentui <version>` and
8
+ * exits 0 BEFORE anything else (no provision, no TUI); `--force` kills
9
+ * this profile's stale instances (resident dsh host + bun client, TERM
10
+ * then KILL) before startup continues. Both are consumed by the bin
11
+ * and never forwarded to the client.
7
12
  * 1. bun check — the client bundle runs under bun (FFI, import attributes,
8
13
  * bun export conditions); no bun on PATH → install guidance, exit 1.
9
14
  * 2. dsh check — the host CLI is the session carrier (profile storage,
@@ -47,6 +52,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSyn
47
52
  import { homedir } from 'node:os'
48
53
  import { dirname, join } from 'node:path'
49
54
  import { fileURLToPath } from 'node:url'
55
+ import { ancestorPids, killStaleProcesses, parseLauncherArgs, parseProcessHomes, parseProcessRows, readLauncherVersion, selectStaleProcesses } from './lib/launcher.mjs'
50
56
 
51
57
  const pkgRoot = dirname(dirname(fileURLToPath(import.meta.url)))
52
58
  const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
@@ -57,6 +63,25 @@ function exitWithGuidance(what, installCmd) {
57
63
  process.exit(1)
58
64
  }
59
65
 
66
+ /** Run a helper command and return its stdout ('' on failure). */
67
+ function capture(cmd, args) {
68
+ const r = spawnSync(cmd, args, { encoding: 'utf8' })
69
+ return r.stdout ?? ''
70
+ }
71
+
72
+ // --- 0. Bin-level flags: --version short-circuits, --force pre-clears -------
73
+ const { version: versionFlag, force: forceFlag, rest: userArgs } = parseLauncherArgs(process.argv.slice(2))
74
+
75
+ if (versionFlag) {
76
+ const version = readLauncherVersion(pkgRoot)
77
+ if (!version) {
78
+ console.error(`dsh-opentui: could not read the version from ${join(pkgRoot, 'package.json')}.`)
79
+ process.exit(1)
80
+ }
81
+ console.log(`dsh-opentui ${version}`)
82
+ process.exit(0)
83
+ }
84
+
60
85
  // --- 1. bun: hard runtime dependency of the client chain -------------------
61
86
  if (!spawnSync('which', ['bun'], { encoding: 'utf8' }).stdout.trim()) {
62
87
  exitWithGuidance('bun', 'npm i -g bun')
@@ -67,13 +92,29 @@ if (!spawnSync('which', ['dsh'], { encoding: 'utf8' }).stdout.trim()) {
67
92
  exitWithGuidance('the dsh CLI', 'npm i -g @deepseek-ai/dsh')
68
93
  }
69
94
 
95
+ // --- 2.5 --force: kill this profile's stale instances before starting ------
96
+ // Matches the opentui-profile host (`node <...>/dsh --profile opentui ...`)
97
+ // and the dsh-opentui client (source entry or published bundle) by command
98
+ // line, scoped to THIS dsh home (see lib/launcher.mjs SCOPE). The launcher's
99
+ // own process tree is excluded; TERM first, then KILL for survivors.
100
+ if (forceFlag) {
101
+ const rows = parseProcessRows(capture('ps', ['-A', '-o', 'pid=,ppid=,command=']))
102
+ const homes = parseProcessHomes(capture('ps', ['eww', '-A', '-o', 'pid=,args=']))
103
+ const stale = selectStaleProcesses(rows, {
104
+ homes,
105
+ home: dshHome,
106
+ excludePids: ancestorPids(rows, process.pid),
107
+ })
108
+ const result = await killStaleProcesses(stale)
109
+ console.log(`--force: killed ${result.terminated} stale instance(s)`)
110
+ }
111
+
70
112
  // --- 3. Profile bootstrap (every start, best effort, idempotent) -----------
71
113
  // provision-opentui-profile.mjs is idempotent and understands
72
114
  // --provider/--model/--reasoning-effort --plugins/--dry-run; forward those,
73
115
  // ignore the rest. With nothing to do this is a local, sub-second pass.
74
116
  const opentuiProfileDir = join(dshHome, 'profiles', 'opentui')
75
117
  {
76
- const userArgs = process.argv.slice(2)
77
118
  const provisionFlags = []
78
119
  for (const name of ['provider', 'model', 'reasoning-effort']) {
79
120
  const i = userArgs.indexOf(`--${name}`)
@@ -265,7 +306,7 @@ if (!existsSync(clientEntry)) {
265
306
  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.')
266
307
  process.exit(1)
267
308
  }
268
- const result = spawnSync('bun', [clientEntry, ...process.argv.slice(2)], {
309
+ const result = spawnSync('bun', [clientEntry, ...userArgs], {
269
310
  stdio: 'inherit',
270
311
  })
271
312
  if (result.error) {
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Launcher support for bin/dsh-opentui.mjs — the pure parts behind the
3
+ * `--version` / `--force` flags.
4
+ *
5
+ * WHY A SEPARATE MODULE: the bin is a top-level script (importing it would
6
+ * RUN it — provision, spawn, exit). Everything here is a pure function over
7
+ * plain data so the flags can be unit-tested without a dsh, a profile or a
8
+ * running client. The bin stays the only thing that touches the process.
9
+ *
10
+ * The two capabilities:
11
+ * 1. `--version` — print `dsh-opentui <version>` and exit 0, BEFORE any
12
+ * provision/profile work (see the bin's step 0).
13
+ * 2. `--force` — kill this profile's stale instances (the resident `dsh
14
+ * host and the bun client) before starting.
15
+ *
16
+ * SCOPE (requirement: never touch another profile's instances):
17
+ * a candidate is "ours" only when BOTH hold:
18
+ * - the command line is the host/client shape of the `opentui` profile
19
+ * (`node <...>/dsh --profile opentui ...` for the host; a bun process
20
+ * running the client entry for the client). A `dsh plugin --profile
21
+ * opentui add ...` provision child is NOT a host and never matches.
22
+ * - the process resolves to the SAME dsh home as this launcher (DSH_HOME
23
+ * from the process environment, defaulting to ~/.dsh). The profile
24
+ * instance is identified by (dsh home, profile) — the same key the
25
+ * host lockfile uses — so a parallel session running the same profile
26
+ * under a DIFFERENT DSH_HOME is a different instance and is left alone.
27
+ * NOTE: the DSH_HOME read is a ps-environment lookup, not command-line
28
+ * matching — if it is deemed over-engineered it can be dropped by
29
+ * removing the `theirs !== mine` comparison in selectStaleProcesses
30
+ * (kill selection then degrades to pure command-line matching).
31
+ */
32
+ import { readFileSync, realpathSync } from 'node:fs'
33
+ import { homedir } from 'node:os'
34
+ import { basename, join, resolve } from 'node:path'
35
+
36
+ /** The one product profile (ADR-0005 decision 3). */
37
+ export const PROFILE = 'opentui'
38
+
39
+ /** The default dsh home when DSH_HOME is unset (mirrors lifecycle.ts). */
40
+ export function defaultDshHome() {
41
+ return join(homedir(), '.dsh')
42
+ }
43
+
44
+ /**
45
+ * Split the launcher's argv into the flags the bin consumes itself and the
46
+ * arguments forwarded to the client bundle.
47
+ *
48
+ * `--version` and `--force` are BIN-level flags: they are consumed here and
49
+ * NOT forwarded (the client must never see `--force`).
50
+ */
51
+ export function parseLauncherArgs(argv) {
52
+ const args = Array.isArray(argv) ? argv : []
53
+ let version = false
54
+ let force = false
55
+ const rest = []
56
+ for (const arg of args) {
57
+ if (arg === '--version') {
58
+ version = true
59
+ continue
60
+ }
61
+ if (arg === '--force') {
62
+ force = true
63
+ continue
64
+ }
65
+ rest.push(arg)
66
+ }
67
+ return { version, force, rest }
68
+ }
69
+
70
+ /**
71
+ * The launcher's own version — read from its own package.json (the package
72
+ * root is the bin's grandparent directory). Returns undefined when the
73
+ * manifest is missing/unreadable so the caller can report it instead of
74
+ * printing a lie.
75
+ */
76
+ export function readLauncherVersion(pkgRoot) {
77
+ try {
78
+ const parsed = JSON.parse(readFileSync(join(pkgRoot, 'package.json'), 'utf8'))
79
+ return typeof parsed?.version === 'string' && parsed.version ? parsed.version : undefined
80
+ } catch {
81
+ return undefined
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Parse `ps -A -o pid=,ppid=,command=` output into process rows.
87
+ *
88
+ * @returns [{ pid, ppid, command }]
89
+ */
90
+ export function parseProcessRows(psOutput) {
91
+ const rows = []
92
+ for (const line of String(psOutput ?? '').split('\n')) {
93
+ const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line)
94
+ if (!match) continue
95
+ rows.push({ pid: Number(match[1]), ppid: Number(match[2]), command: match[3] })
96
+ }
97
+ return rows
98
+ }
99
+
100
+ /**
101
+ * Parse `ps eww -A -o pid=,args=` output into a pid → DSH_HOME map.
102
+ *
103
+ * The environment is appended AFTER the command line, so the LAST
104
+ * `DSH_HOME=` token on the line is the environment's own copy (a command
105
+ * line that mentions DSH_HOME= itself therefore still resolves correctly).
106
+ * A pid without DSH_HOME in its environment uses the default home.
107
+ */
108
+ export function parseProcessHomes(psEwwOutput) {
109
+ const homes = new Map()
110
+ for (const line of String(psEwwOutput ?? '').split('\n')) {
111
+ const trimmed = line.trim()
112
+ if (!trimmed) continue
113
+ const pid = Number(trimmed.split(/\s+/)[0])
114
+ if (!Number.isInteger(pid) || pid <= 0) continue
115
+ const tokens = trimmed.split(/\s+/)
116
+ let home
117
+ for (let i = tokens.length - 1; i >= 1; i--) {
118
+ if (tokens[i].startsWith('DSH_HOME=')) {
119
+ home = tokens[i].slice('DSH_HOME='.length)
120
+ break
121
+ }
122
+ }
123
+ homes.set(pid, home)
124
+ }
125
+ return homes
126
+ }
127
+
128
+ /**
129
+ * Classify a process command line.
130
+ *
131
+ * @returns 'host' | 'client' | null
132
+ * host — the resident dsh host of the opentui profile
133
+ * client — a dsh-opentui client process (source tree entry or the
134
+ * published bundle)
135
+ * null — anything else (the shell/tmux wrapper, a `dsh plugin ...`
136
+ * provision run, a grep over these paths, another profile).
137
+ */
138
+ export function classifyProcess(command) {
139
+ const tokens = String(command ?? '')
140
+ .split(/\s+/)
141
+ .filter(Boolean)
142
+ if (tokens.length === 0) return null
143
+
144
+ const exe = basename(tokens[0])
145
+ // Only a real runtime may be the process itself — a shell that merely
146
+ // mentions these paths (`sh -c "dsh --profile opentui"`, a tmux command
147
+ // line) is NOT the host.
148
+ if (exe !== 'node' && exe !== 'bun' && exe !== 'dsh') return null
149
+
150
+ // The host: the dsh binary IS the process or sits right after the
151
+ // runtime (node/bun + script), and is followed by `--profile opentui`.
152
+ // Only the first two tokens may be the dsh binary — a wrapper script
153
+ // (`node wrapper.js dsh --profile opentui`) merely MENTIONS it.
154
+ for (let i = 0; i < Math.min(tokens.length, 2); i++) {
155
+ if (basename(tokens[i]) !== 'dsh') continue
156
+ const next = tokens[i + 1]
157
+ if (next === '--profile' && tokens[i + 2] === PROFILE) return 'host'
158
+ if (next === `--profile=${PROFILE}`) return 'host'
159
+ // `dsh plugin --profile opentui add ...` (provision) and
160
+ // `dsh opentui --dump-config` are not the host.
161
+ return null
162
+ }
163
+
164
+ // The client: the published bundle (`dist/client/index.js`) or the
165
+ // source-tree entry (`client-entry.tsx`).
166
+ for (const token of tokens) {
167
+ if (token.endsWith('client-entry.tsx')) return 'client'
168
+ if (token.endsWith('dist/client/index.js')) return 'client'
169
+ }
170
+ return null
171
+ }
172
+
173
+ /** Normalize a home path for comparison (absolute, symlinks resolved when
174
+ * the path exists — macOS maps /tmp to /private/tmp). */
175
+ export function normalizeHome(path) {
176
+ if (!path) return undefined
177
+ let out = resolve(path)
178
+ try {
179
+ out = realpathSync(out)
180
+ } catch {
181
+ /* not present on disk — the resolved path is what we compare */
182
+ }
183
+ return out
184
+ }
185
+
186
+ /**
187
+ * Pick the stale instances that belong to THIS profile instance.
188
+ *
189
+ * @param rows [{ pid, ppid, command }]
190
+ * @param homes pid → DSH_HOME (from `ps eww`)
191
+ * @param home the launcher's own dsh home
192
+ * @param excludePids pids that must never be killed (this process, its
193
+ * ancestors) — killing the launcher would kill the kill.
194
+ */
195
+ export function selectStaleProcesses(rows, { homes = new Map(), home, excludePids = [] } = {}) {
196
+ const excluded = new Set(excludePids.filter((pid) => typeof pid === 'number'))
197
+ const mine = normalizeHome(home || defaultDshHome())
198
+ const stale = []
199
+ for (const row of rows ?? []) {
200
+ if (!row || typeof row.pid !== 'number') continue
201
+ if (excluded.has(row.pid)) continue
202
+ const kind = classifyProcess(row.command)
203
+ if (!kind) continue
204
+ const theirs = normalizeHome(homes.get(row.pid) || defaultDshHome())
205
+ if (theirs !== mine) continue
206
+ stale.push({ pid: row.pid, kind })
207
+ }
208
+ return stale
209
+ }
210
+
211
+ /** The pids of this process and its ancestors — never kill targets. */
212
+ export function ancestorPids(rows, selfPid) {
213
+ const byPid = new Map((rows ?? []).map((row) => [row.pid, row.ppid]))
214
+ const chain = []
215
+ let pid = selfPid
216
+ for (let i = 0; i < 64 && typeof pid === 'number' && pid > 0; i++) {
217
+ chain.push(pid)
218
+ const parent = byPid.get(pid)
219
+ if (parent === undefined || parent === pid) break
220
+ pid = parent
221
+ }
222
+ return chain
223
+ }
224
+
225
+ /**
226
+ * TERM every target, wait for the grace window, then KILL the survivors.
227
+ * The injected `kill`/`sleep`/`isAlive` keep this testable without signals.
228
+ */
229
+ export async function killStaleProcesses(targets, options = {}) {
230
+ const {
231
+ kill = (pid, signal) => process.kill(pid, signal),
232
+ sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
233
+ isAlive = (pid) => {
234
+ try {
235
+ process.kill(pid, 0)
236
+ return true
237
+ } catch {
238
+ return false
239
+ }
240
+ },
241
+ termWaitMs = 2000,
242
+ killWaitMs = 500,
243
+ pollMs = 50,
244
+ } = options
245
+
246
+ const pids = (targets ?? []).map((t) => t.pid)
247
+ if (pids.length === 0) return { terminated: 0, killed: 0, survivors: [] }
248
+
249
+ for (const pid of pids) {
250
+ try {
251
+ kill(pid, 'SIGTERM')
252
+ } catch {
253
+ /* already gone */
254
+ }
255
+ }
256
+
257
+ const termDeadline = Date.now() + termWaitMs
258
+ while (Date.now() < termDeadline) {
259
+ if (pids.every((pid) => !isAlive(pid))) break
260
+ await sleep(pollMs)
261
+ }
262
+
263
+ const survivors = pids.filter((pid) => isAlive(pid))
264
+ for (const pid of survivors) {
265
+ try {
266
+ kill(pid, 'SIGKILL')
267
+ } catch {
268
+ /* already gone */
269
+ }
270
+ }
271
+ if (survivors.length > 0) {
272
+ const killDeadline = Date.now() + killWaitMs
273
+ while (Date.now() < killDeadline) {
274
+ if (survivors.every((pid) => !isAlive(pid))) break
275
+ await sleep(pollMs)
276
+ }
277
+ }
278
+ return {
279
+ terminated: pids.length,
280
+ killed: survivors.length,
281
+ survivors: survivors.filter((pid) => isAlive(pid)),
282
+ }
283
+ }
@@ -55562,7 +55562,7 @@ var init_agents_panel = __esm(() => {
55562
55562
  import { TextAttributes as TextAttributes11 } from "@opentui/core";
55563
55563
  function resolveVersion() {
55564
55564
  try {
55565
- return "0.12.1";
55565
+ return "0.12.2";
55566
55566
  } catch {
55567
55567
  return "dev";
55568
55568
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwayds/dsh-opentui",
3
- "version": "0.12.1",
3
+ "version": "0.12.2",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "bin": {