@aiwayds/dsh-opentui 0.21.1 → 0.23.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,195 @@ 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.23.0] - 2026-11-19
9
+
10
+ ### Changed
11
+
12
+ - **The in-process bridge is now the default.** A plain `dsh-opentui` boot
13
+ provisions the `opentui-inproc` profile and drives the TUI through the bridge
14
+ seam — no flag or env var needed. `DSH_OPENTUI_INPROC=1` remains valid
15
+ (idempotent). Setting `DSH_OPENTUI_INPROC=0` is the escape hatch back to the
16
+ legacy remote thin-client seam. A failed bridge handshake / fingerprint check
17
+ still fails fast with a diagnosis, a repair command and a mode notice, and
18
+ never silently falls back.
19
+ - **`--remote` has been removed.** It is no longer accepted as a launch flag;
20
+ passing it exits with a usage error (exit 2). The legacy remote seam is now
21
+ reachable only through the `DSH_OPENTUI_INPROC=0` env escape hatch.
22
+
23
+ ### Fixed
24
+
25
+ - **Ghost subagent rows are swept at turn boundaries.** When a parent turn is
26
+ aborted the host never journals the subagent's settle notice, so the child
27
+ stayed `running` forever. The bridge seam now reconciles its catalog against
28
+ the host session list at every turn terminal and after session recovery, and
29
+ settles any child the host no longer reports as running. Best-effort and
30
+ idempotent; still no wall-clock fallback.
31
+ - **ctrl+g subagent views show real progress.** `rounds`, `lastLine` and
32
+ `model` are now read from each subagent's own journal (lazily, cached, and
33
+ re-read once the child settles), so the viewer no longer shows 0 rounds, an
34
+ empty last line, and a missing model.
35
+
36
+ ## [0.22.0] - 2026-11-19
37
+
38
+ ### Changed
39
+
40
+ - **Opt-in in-process bridge (no default change).** Setting `DSH_OPENTUI_INPROC=1`
41
+ provisions the `opentui-inproc` host profile and routes the TUI through a
42
+ bridge bundle running inside that host (stdio JSON-lines), so session
43
+ identity, turns, asks and journal replay share one data source. Without that
44
+ env var a plain `dsh-opentui` boot still starts the remote thin-client seam,
45
+ exactly as in 0.21.x. Flipping the default to the bridge is planned for
46
+ 0.23.0. `--remote` remains the explicit remote selector and is deprecated,
47
+ slated for removal in 0.23.0; passing it prints one deprecation notice per
48
+ launch naming the removal line. When opt-in is on, both seams coexist and a
49
+ failed inproc handshake/fingerprint check fails fast with a diagnosis, a
50
+ repair command (`dsh-opentui --repair-bridge`) and a mode notice — it never
51
+ silently falls back to the remote seam.
52
+
53
+ ### User decisions (2026-11-19 merge-footer review)
54
+
55
+ - Three rulings on the merged inproc footer, final (do not re-litigate):
56
+ 1. The 🆔 session-id footer segment is removed entirely — segment, v2-entry
57
+ wiring, recovery-ui callback and tests. Session identity stays queryable
58
+ through `/session info` (ADR-0010 I5 carries a revision record).
59
+ 2. The `bridgeStatus` footer segment hides only the normal `✓ ready` state;
60
+ `⚠ dead` / `⟳ recovering` still render during a fault / recovery and
61
+ disappear automatically once the link returns to ready. Recovery logic is
62
+ untouched — only the powerline render condition changed. The 80-column
63
+ priority table keeps `bridgeStatus` at the lowest priority (-2); it now
64
+ only occupies a slot in an abnormal state.
65
+ 3. The 🧠 context and ⚡ cache-hit-rate footer segments render again under
66
+ the inproc bridge (the former P3-2 Known debt, paid early).
67
+
68
+ ### Added
69
+
70
+ - **Real session resume.** `session.open{resume}` calls the host's `ctx.agents.resume`
71
+ eagerly instead of silently creating a fresh session. Model context and the
72
+ on-screen journal now point at the same persisted session, fixing the
73
+ "screen still shows history, model forgot everything" split (the
74
+ dsh-opentui-amnesia incident). `/resume`, `--session` and `--resume-last` all
75
+ take the resume path; abort leaves the session id unchanged.
76
+ - **Approval cards and tighter defaults.** The generated profile pins
77
+ `defaultPreset: workspace-write` (`approval: ask`) and arms a pre-execute gate
78
+ for `bash`, `write`, `edit` and `apply_patch`. Those tools pop a TUI approval
79
+ card before execution (Enter = allow, Esc = reject, fail-closed); read-only
80
+ tools pass straight through. Escape hatch: `DSH_OPENTUI_APPROVAL_GATE=off
81
+ dsh-opentui` restores the old `danger-full-access` default.
82
+ - **User-questions panel over the bridge.** Host `user-questions` requests are
83
+ forwarded as `ask.request` events and surface on the TUI's ask dock, where
84
+ they can be answered back through `ask.response`. Missing provider/service,
85
+ answer errors and timeouts settle fail-closed with an explicit error code and
86
+ UI notice instead of being silently swallowed; first answer wins, and turn
87
+ end closes every pending ask.
88
+ - **APPEND_SYSTEM.md injected for real in inproc mode.** The bridge registers
89
+ an agent-scoped `systemPrompt.section` (`order: 200`) that lazily reads
90
+ `~/.dsh/APPEND_SYSTEM.md`, caches by mtime, and truncates at 64 KiB on a UTF-8
91
+ character boundary. Existing `opentui-append-system` sessions carry that id
92
+ as inert metadata on resume (no migration, no cleaning, no `preset` passed to
93
+ `agents.resume`); the appended text comes only from the bridge section.
94
+ - **DEAD recovery, phase one (host-crash recovery).** A bridge/host exit shows a
95
+ DEAD notice immediately with the exit code/signal, even when idle. `R`
96
+ reconnects: respawn the child, re-handshake with three checks (protocol
97
+ version, fingerprint fields, host-compat window), eager `session.open{resume}`,
98
+ then a `journal.replay` drain to fill the transcript. Pending approval cards
99
+ at DEAD turn into terminal "invalidated" cards (acknowledge-only, never an
100
+ implicit allow); an in-flight turn is judged by the journal's terminal row —
101
+ a silent journal yields a local `INTERRUPTED` marker (`seq:null`, `source:local`)
102
+ that is never written to the journal. Automatic retry/backoff and heartbeats
103
+ are deferred to a later version.
104
+
105
+ ### Fixed
106
+
107
+ - **Inproc bridge subagent rows converge; tool callId / isError reach the view.**
108
+ Follow-up to the 9190946 subagent/tool fix (oldfox P1×2+P2×3+P3×3):
109
+ - A plain `subagent` child now settles when the host journals a
110
+ `user/message` `source.kind=subagent-settled` notice — paired by
111
+ `senderSessionId` to the catalog child's `childId` (no runId needed),
112
+ `stopReason`→status conservatively mapped. Settled rows freeze their
113
+ duration; unknown stop reasons never paint a false failure. An ABORTED
114
+ parent turn leaves no such notice, so its ghost row stays `running` — a
115
+ documented known residue with no wall-clock fallback (ADR-0010).
116
+ - Catalog-family rows may revive a settled child on a later same-childId
117
+ catalog (a new run); the tool-workflow family keeps its no-revive guard.
118
+ `sessionInfo`'s incremental drain now folds these rows too, so an async
119
+ child settles outside any turn. Catalog replay anchors `startedAt` to the
120
+ host's real `childCreatedAt`.
121
+ - `turn.tool` call/result frames carry the `callId` end-to-end; the seam
122
+ passes it into `onToolStart`/`onToolRun`, so two same-name tools
123
+ interleaving no longer collide on one row and args stay with their call.
124
+ The result frame carries the host's `isError`, mapped to `ok` (a failed
125
+ tool is no longer painted as a success). Corrected 9190946's inaccurate
126
+ claim that callId preserved the args — that came from the seam-rows
127
+ empty-argsPretty fallback.
128
+ - **🧠 context and ⚡ cache-hit segments render under the inproc bridge.**
129
+ The in-process bridge exposes no `session` / `projections` RPC (only
130
+ `session.list`), so `BridgeSessionSeam` derives `contextTokens()` /
131
+ `contextWindow()` / `cacheHitRate()` from journal rows rather than a live
132
+ projection. The caliber is deliberately LAYERED, not a wholesale parity
133
+ claim:
134
+ - ⚡ cache-hit rate — same formula as remote: `lastMessage` is
135
+ `cacheRead / (prompt + cacheRead + cacheWrite)` of the latest billed row,
136
+ `session` is `ΣcacheRead / (Σprompt + ΣcacheRead + ΣcacheWrite)`.
137
+ - 🧠 context occupancy — a DEGRADED local caliber. The numerator is the
138
+ journal's latest billed `assistant/message.data.usage.totalTokens`
139
+ (≈ remote `ContextTokenMeter` billed base `input + cacheRead + cacheWrite
140
+ + output`); it carries no pending-item estimate and no next-request
141
+ projection, so unlike remote it does NOT climb with pending text while a
142
+ turn is in flight. The denominator is the host-resolved
143
+ `request/context.contextWindow` for the live route, guarded by the same
144
+ `currentModelSelection()` route check.
145
+ All three ride the existing incremental `sessionInfo()` tally (no new cache,
146
+ no double counting) and read the same host usage data the remote seam reads
147
+ off its live chunks — remote reads the live usage chunk, the bridge the
148
+ journal row that carries it. The `/session` panel's `cache read/write 0 / 0`
149
+ was a field-name mismatch — the journal row carried `cacheReadTokens` but the
150
+ seam only read `cacheRead`; the alias mapping (remote `scanUsageChunk` parity)
151
+ fixes both the panel and the footer rate.
152
+ - **Writer-held as a localized diagnostic.** `SESSION_LOCKED` now renders as a
153
+ `writer-held` message that includes the host-reported holder session id,
154
+ instead of the raw host error. In inproc mode the footer brand shows as `dsh`.
155
+ - **Footer `💬` and `⚡` now render on the opt-in inproc path.** The bridge
156
+ seam's `sessionInfo()` derives `msgCount` from journal `assistant/message`
157
+ rows — the same single `💬 N msgs` unit defined in 0.21.1 — and `tps` when it
158
+ can be derived, so the counter and token-rate segments are no longer blank
159
+ under the inproc seam. `messageCount` remains the `/session` panel's data.
160
+
161
+ ### 用户裁决 — activity 面板重设计(2026-11-19)
162
+
163
+ 用户逐条拍板的最终规则表,覆盖此前"think / tool 各自独立锚点"的旧法则:
164
+
165
+ | 场景 | think | tool | todo | subagent |
166
+ | --- | --- | --- | --- | --- |
167
+ | A. subagent 活跃 | 1 行,置顶 | 1 行,置顶 | 1 行摘要 `todo 完成数/总数 时长s` | 列表占剩余行(沿用现有滚动裁剪) |
168
+ | B. 无 subagent、think 可见(活跃 + 2s exit hold) | 齿轮行数(≤10) | 隐藏 | 隐藏 | — |
169
+ | C. 无 subagent、无 think | — | ≤3 行(固定值,不吃齿轮) | 1 行(现行完整格式) | — |
170
+
171
+ 1. **面板封顶 10 行。** 内容区随内容伸缩、硬上限 `MERGED_DOCK_TOTAL_LINES = 10`(不含边框);废除 `all` 档的 2/3 终端增长规则和 halfBudget 帧钳制。无内容整体隐藏(D5)不变。
172
+ 2. **齿轮只管 think。** `session.activity_panel_height` 语义改为仅 think 显示行数:1/5/7/10;`all` 保留兼容(不迁移用户 config)但等于 10。tool 恢复固定 3 行。settings 行文案与 en/zh 文案改义(key 名不动)。
173
+ 3. **场景 B 互斥。** think 可见期间藏 tool 与 todo;若 subagent 仅有历史残留行而 think 活跃,按场景 B 处理(subagent 行也让位)。优先级:subagent 活跃 > think 独占。
174
+ 4. **场景 A 的 todo 摘要行。** 只显示 `todo 完成数/总数 时长s`(如 `todo 1/3 300s`),不显示当前任务文本。时长 = 当前任务集建立至今的秒数:按任务文本集合(忽略状态翻转、与顺序无关)首次出现的时刻起算;换任务集重置,同一集内 1/3→2/3 不重置,跨会话清空。
175
+ 5. **伸缩动画。** 面板高度变化走共享动画钟(busy 才给 rate)驱动的整数行数逐帧插值,200ms smoothstep;非常驻、终态精确等于目标行数;共享钟 idle 不给 tick 时按挂钟取终态。动画结束帧后自校验行数 = 目标,规避仓内常驻动画撞 diff-paint 丢行的前科。**动画仅作用于增长**(新行逐行出现);收缩为瞬时(被删行无法参与过渡)——这是设计内的不对称,不是缺陷。
176
+
177
+ 置顶顺序:场景 A 中 think 行、tool 行、todo 行在 subagent 列表上方。
178
+
179
+ ### Known debt (0.22.0 transitional)
180
+
181
+ - The default inproc launch still runs two host processes: an HTTP host owns the
182
+ config plane (`configSave`, theme/skin persistence, profile/workspace overlay
183
+ reads) because `BridgeSessionSeam` has no config frame, while the bridge host
184
+ owns the session plane. 0.23.0 folds config into the bridge (or local files)
185
+ and removes the `ensureHost`/`RemoteHostSession` path.
186
+ - The old automatic reconnect (backoff retry) is not implemented; recovery in
187
+ 0.22.0 is manual (`R`, with a 5s cooldown) only.
188
+ - The inproc bridge's `subagentViews` field set matches the remote seam's, but
189
+ its VALUES are approximate: the bridge only sees the parent journal, so
190
+ `rounds` stays 0, `lastLine` / `model` are absent, and a settled row's
191
+ `elapsedSec` is frozen at discovery time. No whole-parity claim is made.
192
+ - ~~`BridgeSessionSeam` does not implement `contextTokens()` / `contextWindow()`;
193
+ the 🧠 context-occupancy segment does not render under the inproc bridge.~~
194
+ **RESOLVED in 0.22.0** (user decision 2026-11-19, paid ahead of the later
195
+ seam-capability batch): see the Fixed entry above for the journal-derived
196
+ implementation and the ⚡ cache-rate parity fix.
8
197
  ## [0.21.1] - 2026-11-17
9
198
 
10
199
  ### Changed
package/README.md CHANGED
@@ -6,8 +6,11 @@ new architecture, not a reskin of dsh-tui-pi. Built on
6
6
  running on Bun.
7
7
 
8
8
  The repo's product is the **architecture**; the shipped Shell is a working
9
- chat agent TUI on top of it, distributed as a **client-only** package: a thin
10
- OpenTUI client that talks to a resident dsh host over the host's remote API.
9
+ chat agent TUI on top of it. By default it boots an in-process session bridge
10
+ inside the dsh host and drives the OpenTUI client over a stdio JSON-lines
11
+ channel; the legacy thin client over the host's remote API is retained only as
12
+ an escape hatch (`DSH_OPENTUI_INPROC=0`). The `--remote` flag was removed in
13
+ 0.23.0.
11
14
 
12
15
  | Package | What it is |
13
16
  |---|---|
@@ -18,7 +21,8 @@ OpenTUI client that talks to a resident dsh host over the host's remote API.
18
21
  See [CONTEXT.md](CONTEXT.md) for the glossary and [docs/adr/](docs/adr/)
19
22
  for decisions: Solid (0001), two integration channels with no compat shim
20
23
  (0002), Bun single-process distribution (0003), host profile route (0004),
21
- client mode (0005).
24
+ client mode (0005, superseded as the sole TUI path by the in-process bridge,
25
+ 0009), session seam lifecycle (0010) and the ask/permission channel (0011).
22
26
 
23
27
  ## Install
24
28
 
@@ -33,6 +37,12 @@ npm i -g @aiwayds/dsh-opentui
33
37
  dsh-opentui
34
38
  ```
35
39
 
40
+ The first launch automatically provisions the `opentui-inproc` profile (bridge
41
+ dependencies are symlinked from the dsh install, never copied). If that bridge
42
+ install is damaged, rerun with `dsh-opentui --repair-bridge`. To fall back to
43
+ the legacy remote thin client for a launch, set `DSH_OPENTUI_INPROC=0` — that
44
+ skips in-process provisioning and selects the remote seam.
45
+
36
46
  Run `dsh-opentui --help` for the full list of launcher options.
37
47
 
38
48
  ## Upgrading
@@ -98,9 +108,16 @@ confirmation prompt is refused.
98
108
 
99
109
  ## Client mode
100
110
 
101
- `dsh-opentui` starts a thin client TUI (`dist/client/index.js` under Bun) that
102
- connects to a resident `dsh --profile opentui` host process. The launcher
103
- handles everything on startup:
111
+ > Since 0.23.0 the default TUI path is the in-process session bridge
112
+ > (`opentui-inproc` profile, see ADR-0009). The thin-client topology below is
113
+ > the legacy path, reachable only through the `DSH_OPENTUI_INPROC=0` escape
114
+ > hatch. The old `--remote` flag was removed in 0.23.0; passing it is a usage
115
+ > error (exit 2).
116
+
117
+ With `DSH_OPENTUI_INPROC=0`, `dsh-opentui` starts a thin client TUI
118
+ (`dist/client/index.js` under Bun) that connects to a resident
119
+ `dsh --profile opentui` host process. The launcher handles everything on
120
+ startup:
104
121
 
105
122
  - **Profile bootstrap** — `$DSH_HOME/profiles/opentui` is provisioned on
106
123
  EVERY launch (idempotent; a no-op pass is sub-second). Pass `--provider` /
@@ -210,11 +227,24 @@ carries a heavy accent frame; the unfocused one dims. Mouse reporting is on, so
210
227
  hold **Shift** while dragging for the terminal's native selection (then
211
228
  Cmd/Ctrl+C copies it); a plain drag is copied on release per `terminal.copy`.
212
229
  The model's thinking streams
213
- dim; tool calls (bash / read_file / write_file) pop an approval card — `y`
214
- allow, `n` decline; `esc` ×2 + confirm stops a running turn. Ctrl+C twice quits. Commands:
230
+ dim; write-class tool calls (bash / write / edit / apply_patch) pop an approval
231
+ card — **Enter** allows once, **Esc** declines (fail-closed); read-only tools
232
+ such as read_file pass straight through. `esc` ×2 + confirm stops a running
233
+ turn. Ctrl+C twice quits. Commands:
215
234
  `/help` `/model [provider/id]` `/usage` `/clear` `/login` `/logout` `/resume`
216
235
  `/search` `/new` `/quit` and more — see `/help` inside the TUI.
217
236
 
237
+ **Approval by default (inproc profile)**: the generated profile pins
238
+ `defaultPreset: workspace-write` (`approval: ask`) and arms the pre-execute
239
+ gate for the write tools the host registers — `bash`, `write`, `edit`,
240
+ `apply_patch`. Those tools pop the approval card before running; read-only
241
+ tools run straight through; writes outside the workspace are denied by the
242
+ sandbox with an escalation hint. **Escape hatch**: launch with
243
+ `DSH_OPENTUI_APPROVAL_GATE=off dsh-opentui` to disable the gate and restore the
244
+ pre-T9 `danger-full-access` default. The gate is ON by default — do not set
245
+ that variable for normal use. See `docs/adr/0011-ask-permission-bridge-channel.md`
246
+ §6 and `tickets/2026-11-18-approval-trigger-mechanism.md`.
247
+
218
248
  **Session restore on launch (opt-in)**: a plain launch starts a new, empty
219
249
  session. To reopen the newest non-empty session from the launch workspace that
220
250
  was active within the last 7 days — with a `resumed <title> · <time ago>`
@@ -5,10 +5,14 @@
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` 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.
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
11
+ * maintenance command: it clears this profile's stale instances (TERM
12
+ * then KILL), runs the in-process bridge self-heal (T7), and exits before
13
+ * any bun/dsh check, TUI launch, or default-seam change; it always runs
14
+ * full in-process provisioning (bridge is the default since 0.23.0).
15
+ * All three are consumed by the bin and never forwarded to the client.
12
16
  * 1. bun check — the client bundle runs under bun (FFI, import attributes,
13
17
  * bun export conditions); no bun on PATH → install guidance, exit 1.
14
18
  * 2. dsh check — the host CLI is the session carrier (profile storage,
@@ -52,7 +56,7 @@ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSyn
52
56
  import { constants as osConstants, homedir } from 'node:os'
53
57
  import { dirname, join } from 'node:path'
54
58
  import { fileURLToPath, pathToFileURL } from 'node:url'
55
- import { formatUpgradeUsage, formatUsage, LAUNCHER_TIMEOUT_FLAGS, parseLauncherArgs, parseLauncherOptions, parseUpgradeArgs, prelaunchFailurePolicy, readLauncherVersion, validateLauncherArgs } from './lib/launcher.mjs'
59
+ import { ancestorPids, formatUpgradeUsage, formatUsage, killStaleProcesses, launcherFlagConflict, LAUNCHER_TIMEOUT_FLAGS, parseLauncherArgs, parseLauncherOptions, parseProcessHomes, parseProcessRows, parseUpgradeArgs, prelaunchFailurePolicy, readLauncherVersion, selectStaleProcesses, validateLauncherArgs } from './lib/launcher.mjs'
56
60
 
57
61
  const pkgRoot = dirname(dirname(fileURLToPath(import.meta.url)))
58
62
  const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
@@ -63,8 +67,14 @@ function exitWithGuidance(what, installCmd) {
63
67
  process.exit(1)
64
68
  }
65
69
 
70
+ /** Run a helper command and return its stdout ('' on failure). */
71
+ function capture(cmd, args) {
72
+ const r = spawnSync(cmd, args, { encoding: 'utf8' })
73
+ return r.stdout ?? ''
74
+ }
75
+
66
76
  // --- 0. Bin-level flags: --version short-circuits, --force pre-clears -------
67
- const { version: versionFlag, force: forceFlag, yes: yesFlag, rest: userArgs, passthrough } = parseLauncherArgs(process.argv.slice(2))
77
+ const { version: versionFlag, force: forceFlag, repairBridge: repairBridgeFlag, yes: yesFlag, rest: userArgs, passthrough } = parseLauncherArgs(process.argv.slice(2))
68
78
 
69
79
  if (versionFlag) {
70
80
  const version = readLauncherVersion(pkgRoot)
@@ -76,10 +86,18 @@ if (versionFlag) {
76
86
  process.exit(0)
77
87
  }
78
88
 
79
- if (yesFlag && !forceFlag) {
89
+ // 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.
92
+ const flagConflict = launcherFlagConflict({ force: forceFlag, repairBridge: repairBridgeFlag, yes: yesFlag })
93
+ if (flagConflict === 'yes-without-force') {
80
94
  console.error('dsh-opentui: --yes is only meaningful together with --force.')
81
95
  process.exit(2)
82
96
  }
97
+ if (flagConflict === 'repair-force') {
98
+ console.error('dsh-opentui: --repair-bridge and --force are mutually exclusive; choose one.')
99
+ process.exit(2)
100
+ }
83
101
 
84
102
  // --- 0.5 upgrade subcommand -------------------------------------------------
85
103
  // `upgrade` is a positional subcommand: only the first remaining argument may
@@ -90,6 +108,11 @@ if (yesFlag && !forceFlag) {
90
108
  // `npm` and `dsh`, not bun, and must not provision or link anything.
91
109
  const upgradeResult = parseUpgradeArgs(userArgs)
92
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
+ }
93
116
  if (forceFlag) {
94
117
  console.error('dsh-opentui: --force is not supported with upgrade.')
95
118
  console.error(formatUpgradeUsage())
@@ -166,6 +189,12 @@ const validation = validateLauncherArgs(userArgs, { skip: LAUNCHER_TIMEOUT_FLAGS
166
189
  if (validation.unknown.length > 0) {
167
190
  for (const flag of validation.unknown) {
168
191
  console.error(`dsh-opentui: unknown option '${flag}'`)
192
+ // P2-4b: the removed --remote flag has a launch-level replacement — point
193
+ // users at it instead of leaving a dead end. Other unknown flags get only
194
+ // the generic did-you-mean rule (no misleading migration advice).
195
+ if (flag === '--remote') {
196
+ console.error('dsh-opentui: use DSH_OPENTUI_INPROC=0 for the legacy remote seam')
197
+ }
169
198
  if (validation.suggestions[flag]) {
170
199
  console.error(`dsh-opentui: did you mean '${validation.suggestions[flag]}'?`)
171
200
  }
@@ -174,6 +203,37 @@ if (validation.unknown.length > 0) {
174
203
  process.exit(2)
175
204
  }
176
205
 
206
+ // --- 0.7 --repair-bridge: terminal in-process bridge self-heal (T7) ---------
207
+ // This is a maintenance command, not a launch. It invokes the SAME provisioner
208
+ // the default startup path uses, in its repair mode. It deliberately exits here
209
+ // — before the bun/dsh checks, the default `opentui` profile bootstrap, the
210
+ // client-connection link, and the bun client launch — so it never starts a TUI
211
+ // and never changes the default seam (that is M2's job). The provisioner owns
212
+ // the lock, the repair logic and the T5 identity guard; its exit status is ours.
213
+ if (repairBridgeFlag) {
214
+ // Clean up this profile's stale instances first (the old `--force` sweep),
215
+ // scoped to THIS dsh home; the launcher's own process tree is excluded.
216
+ const rows = parseProcessRows(capture('ps', ['-A', '-o', 'pid=,ppid=,command=']))
217
+ const homes = parseProcessHomes(capture('ps', ['eww', '-A', '-o', 'pid=,args=']))
218
+ const stale = selectStaleProcesses(rows, {
219
+ homes,
220
+ home: dshHome,
221
+ excludePids: ancestorPids(rows, process.pid),
222
+ })
223
+ const killed = await killStaleProcesses(stale)
224
+ console.log(`--repair-bridge: killed ${killed.terminated} stale instance(s)`)
225
+ // Then repair the bridge itself; the provisioner owns the lock, repair logic
226
+ // and identity guard, and its exit status is ours.
227
+ const r = spawnSync(process.execPath, [join(pkgRoot, 'scripts', 'provision-inproc-profile.mjs'), '--repair'], {
228
+ stdio: 'inherit',
229
+ })
230
+ if (r.error) {
231
+ console.error(`dsh-opentui: in-process bridge repair failed: ${r.error.message}`)
232
+ process.exit(1)
233
+ }
234
+ process.exit(r.status ?? 0)
235
+ }
236
+
177
237
  // Write a timeout to the client env only when the user supplied that flag:
178
238
  // defaults must not clobber a value already set in the shell environment.
179
239
  const clientEnv = { ...process.env }
@@ -245,6 +305,27 @@ const opentuiProfileDir = join(dshHome, 'profiles', 'opentui')
245
305
  }
246
306
  }
247
307
 
308
+ // --- 3b. In-process bridge profile provisioning (default since 0.23.0) -----
309
+ // The bridge is the default, so this runs on EVERY launch; only the explicit
310
+ // escape hatch DSH_OPENTUI_INPROC=0 skips it (legacy remote thin client). "1"
311
+ // is still accepted and is now a no-op-equivalent (idempotent). The script
312
+ // provisions ONLY the `opentui-inproc` profile: bundle manifest + absolute
313
+ // symlink to the embedded dist/bridge artifact. A non-zero exit is fatal here
314
+ // (the bridge cannot work without it), unlike the best-effort path above.
315
+ if (process.env.DSH_OPENTUI_INPROC !== '0') {
316
+ const r = spawnSync(process.execPath, [join(pkgRoot, 'scripts', 'provision-inproc-profile.mjs')], {
317
+ stdio: 'inherit',
318
+ })
319
+ if (r.error) {
320
+ console.error(`dsh-opentui: in-process profile provisioning failed: ${r.error.message}`)
321
+ process.exit(1)
322
+ }
323
+ if (r.status !== 0) {
324
+ console.error(`dsh-opentui: in-process profile provisioning exited ${r.status}; aborting.`)
325
+ process.exit(1)
326
+ }
327
+ }
328
+
248
329
  // --- 4. One-time migration notice from the pre-retirement profile ----------
249
330
  const legacyProfileDir = join(dshHome, 'profiles', 'dsh-opentui')
250
331
  const migrationMarker = join(dshHome, '.dsh-opentui-migrated')
@@ -10,8 +10,9 @@
10
10
  * The capabilities:
11
11
  * 1. `--version` — print `dsh-opentui <version>` and exit 0, BEFORE any
12
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.
13
+ * 2. `--force` — reset the singleton host before starting (needs `--yes`
14
+ * when live clients are connected; ADR-0009). Stale-instance cleanup is a
15
+ * `--repair-bridge` maintenance action.
15
16
  * 3. `upgrade` — the positional upgrade subcommand: its argv is parsed
16
17
  * here (pure) and dispatched by the bin to scripts/upgrade.mjs. The
17
18
  * subcommand and its flags are consumed by the bin and NEVER forwarded
@@ -49,8 +50,10 @@ export function defaultDshHome() {
49
50
  * Split the launcher's argv into the flags the bin consumes itself and the
50
51
  * arguments forwarded to the client bundle.
51
52
  *
52
- * `-v`/`--version` and `--force` are BIN-level flags: they are consumed here
53
- * and NOT forwarded (the client must never see `--force`).
53
+ * `-v`/`--version`, `--force` and `--repair-bridge` are BIN-level flags: they
54
+ * are consumed here and NOT forwarded (the client must never see them).
55
+ * `--repair-bridge` is a terminal maintenance command: the bin runs the
56
+ * in-process bridge self-heal and exits without launching the TUI.
54
57
  *
55
58
  * A standalone `--` ends launcher parsing: every token after it (even one that
56
59
  * spells a launcher flag) goes to `passthrough` verbatim and is never
@@ -61,6 +64,7 @@ export function parseLauncherArgs(argv) {
61
64
  const args = Array.isArray(argv) ? argv : []
62
65
  let version = false
63
66
  let force = false
67
+ let repairBridge = false
64
68
  let yes = false
65
69
  const rest = []
66
70
  const passthrough = []
@@ -82,6 +86,10 @@ export function parseLauncherArgs(argv) {
82
86
  force = true
83
87
  continue
84
88
  }
89
+ if (arg === '--repair-bridge') {
90
+ repairBridge = true
91
+ continue
92
+ }
85
93
  // `--yes` confirms a --force reset when live clients exist (ADR-0009 §7).
86
94
  // Consumed by the bin, never forwarded to dsh/the client.
87
95
  if (arg === '--yes') {
@@ -90,7 +98,7 @@ export function parseLauncherArgs(argv) {
90
98
  }
91
99
  rest.push(arg)
92
100
  }
93
- return { version, force, yes, rest, passthrough }
101
+ return { version, force, repairBridge, yes, rest, passthrough }
94
102
  }
95
103
 
96
104
  /**
@@ -231,6 +239,7 @@ export function validateLauncherArgs(rest, { skip = [] } = {}) {
231
239
  '--version',
232
240
  '-v',
233
241
  '--force',
242
+ '--repair-bridge',
234
243
  ...LAUNCHER_TIMEOUT_FLAGS,
235
244
  '-h',
236
245
  '--help',
@@ -278,6 +287,23 @@ export function validateLauncherArgs(rest, { skip = [] } = {}) {
278
287
  }
279
288
  }
280
289
 
290
+ /**
291
+ * P3-3 — explicit handling of launcher flag combinations that previously fell
292
+ * into dead corners (silently ignored one flag or ran the wrong branch). Pure
293
+ * so the bin's reject/notice decisions are unit-testable without spawning.
294
+ *
295
+ * Returns a conflict code, or null when the combination is fine:
296
+ * 'repair-force' --repair-bridge + --force → mutually exclusive
297
+ * 'yes-without-force' --yes without --force/--repair-bridge (under
298
+ * --repair-bridge, --yes is tolerated — the repair branch
299
+ * never reads it — and is intentionally allowed through)
300
+ */
301
+ export function launcherFlagConflict({ force, repairBridge, yes } = {}) {
302
+ if (repairBridge && force) return 'repair-force'
303
+ if (yes && !force && !repairBridge) return 'yes-without-force'
304
+ return null
305
+ }
306
+
281
307
  /** Usage text for the normal launcher (not the `upgrade` subcommand). */
282
308
  export function formatUsage() {
283
309
  return [
@@ -287,8 +313,9 @@ export function formatUsage() {
287
313
  '',
288
314
  'Options:',
289
315
  ' -v, --version print the launcher version and exit',
290
- ' --force reset the singleton host before starting (needs --yes if clients are live)',
316
+ ' --force reset the singleton host before starting (needs --yes if clients are live; no-op under --dry-run)',
291
317
  ' --yes confirm a --force reset that would disconnect live clients',
318
+ ' --repair-bridge kill stale instances, repair the in-process bridge symlink / manifest, re-verify its identity, then exit (no TUI)',
292
319
  ' --boot-timeout <sec> seconds to wait for the host to cold-start (default: 30; /reload keeps its own 30s)',
293
320
  ' --mux-timeout <sec> seconds to wait for the host mux to serve (default: 20)',
294
321
  ' --connect-timeout <sec> seconds to wait for the first connection (default: 30)',
@@ -300,6 +327,7 @@ export function formatUsage() {
300
327
  ' -h, --help print this help and exit',
301
328
  '',
302
329
  'Environment:',
330
+ ' DSH_OPENTUI_INPROC=0 use the legacy remote thin-client seam instead of the default in-process bridge (escape hatch); unset or 1 = bridge',
303
331
  ' DSH_OPENTUI_BOOT_TIMEOUT_MS host cold-start budget in ms (CLI flag wins)',
304
332
  ' DSH_OPENTUI_MUX_TIMEOUT_MS mux readiness budget in ms (CLI flag wins)',
305
333
  ' DSH_OPENTUI_CONNECT_TIMEOUT_MS first-connect budget in ms (CLI flag wins)',
@@ -0,0 +1,89 @@
1
+ // ../bridge/src/approval-gate.ts
2
+ var WRITE_TOOL_POLICY = Object.freeze({
3
+ bash: "ask",
4
+ write: "ask",
5
+ edit: "ask",
6
+ apply_patch: "ask"
7
+ });
8
+ var DEFAULT_GATE_REASON = "Write operations require human approval";
9
+ function isRecord(value) {
10
+ return value !== null && typeof value === "object" && !Array.isArray(value);
11
+ }
12
+ function resolveApprovalGateConfig(config) {
13
+ if (!isRecord(config)) {
14
+ return { enabled: false, tools: Object.freeze({}), reason: DEFAULT_GATE_REASON };
15
+ }
16
+ const tools = {};
17
+ if (isRecord(config.tools)) {
18
+ for (const [name, directive] of Object.entries(config.tools)) {
19
+ if (name !== "" && directive === "ask")
20
+ tools[name] = "ask";
21
+ }
22
+ }
23
+ const reason = typeof config.reason === "string" && config.reason !== "" ? config.reason : DEFAULT_GATE_REASON;
24
+ const result = {
25
+ enabled: config.enabled !== false,
26
+ tools: Object.freeze(tools),
27
+ reason
28
+ };
29
+ if (isRecord(config.displayReason) && typeof config.displayReason.en === "string") {
30
+ const display = {};
31
+ for (const [locale, text] of Object.entries(config.displayReason)) {
32
+ if (typeof text === "string")
33
+ display[locale] = text;
34
+ }
35
+ result.displayReason = Object.freeze(display);
36
+ }
37
+ return result;
38
+ }
39
+ function decideAsk(exec, config) {
40
+ if (!config.enabled)
41
+ return;
42
+ const name = exec !== null && exec !== undefined ? exec.name : undefined;
43
+ if (typeof name !== "string" || name === "")
44
+ return;
45
+ if (config.tools[name] !== "ask")
46
+ return;
47
+ const decision = { kind: "ask", reason: config.reason };
48
+ if (config.displayReason !== undefined) {
49
+ decision.displayReason = config.displayReason;
50
+ }
51
+ return decision;
52
+ }
53
+ function createPreExecuteListener(config) {
54
+ return (exec, next) => {
55
+ const decision = decideAsk(exec, config);
56
+ if (decision !== undefined)
57
+ return Promise.resolve(decision);
58
+ return next();
59
+ };
60
+ }
61
+ var name = "dsh-opentui-approval-gate";
62
+ function apply(ctx, config) {
63
+ const policy = resolveApprovalGateConfig(config);
64
+ const tools = Object.keys(policy.tools);
65
+ ctx.logger?.info("[approval-gate] armed enabled=%s tools=%s reason=%s", String(policy.enabled), tools.length === 0 ? "(none — inert)" : tools.join(","), policy.reason);
66
+ const effect = () => {
67
+ if (typeof ctx.on !== "function") {
68
+ ctx.logger?.warn("[approval-gate] ctx.on unavailable — gate not registered (all tools pass)");
69
+ return () => {};
70
+ }
71
+ const listener = createPreExecuteListener(policy);
72
+ const unsub = ctx.on("tools/pre-execute", listener);
73
+ return () => {
74
+ try {
75
+ unsub();
76
+ } catch {}
77
+ };
78
+ };
79
+ return ctx.effect(effect, "dsh-opentui-approval-gate");
80
+ }
81
+ export {
82
+ DEFAULT_GATE_REASON,
83
+ WRITE_TOOL_POLICY,
84
+ apply,
85
+ createPreExecuteListener,
86
+ decideAsk,
87
+ name,
88
+ resolveApprovalGateConfig
89
+ };
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "@aiwayds/dsh-opentui-bridge",
3
+ "version": "0.1.0",
4
+ "sha256": "746fea7d4feac36427f0e42971c5417d5e7df59d95664d76f9713225dd8c6f03"
5
+ }
@@ -0,0 +1,8 @@
1
+ # dsh-opentui-bridge bundle patch (T2a skeleton).
2
+ #
3
+ # Mounts the bridge under a stable entry id so a profile that lists this
4
+ # bundle gets the plugin registered. The skeleton only emits lifecycle logs;
5
+ # it does not disable any host plugin and does not override any config row.
6
+ - insert:
7
+ - id: dsh-opentui-bridge
8
+ name: '@aiwayds/dsh-opentui-bridge'