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