@deepseek-harness-tui/dsh-tui 0.18.0 → 0.20.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.
Files changed (318) hide show
  1. package/README.md +90 -59
  2. package/bin/dsh-tui.js +46 -3
  3. package/cordis.patch.yml +5 -3
  4. package/cordis.yml +3 -2
  5. package/guide/dsh-tui-guide/codex-backend.en.md +2 -2
  6. package/guide/dsh-tui-guide/codex-backend.md +2 -2
  7. package/guide/dsh-tui-guide/configuration.en.md +7 -2
  8. package/guide/dsh-tui-guide/configuration.md +7 -2
  9. package/guide/dsh-tui-guide/getting-started.en.md +168 -4
  10. package/guide/dsh-tui-guide/getting-started.md +121 -14
  11. package/guide/dsh-tui-guide/interaction.en.md +11 -10
  12. package/guide/dsh-tui-guide/interaction.md +5 -4
  13. package/guide/dsh-tui-guide/user-guide.en.md +12 -6
  14. package/guide/dsh-tui-guide/user-guide.md +12 -6
  15. package/lib/settings.json +24 -8
  16. package/lib/types/adapter/ports/channel-ui.d.ts +10 -7
  17. package/lib/types/adapter/ports/channel-ui.d.ts.map +1 -1
  18. package/lib/types/adapter/ports/channel-view.d.ts +67 -8
  19. package/lib/types/adapter/ports/channel-view.d.ts.map +1 -1
  20. package/lib/types/agent/events.d.ts +14 -5
  21. package/lib/types/agent/events.d.ts.map +1 -1
  22. package/lib/types/agent/session.d.ts +5 -0
  23. package/lib/types/agent/session.d.ts.map +1 -1
  24. package/lib/types/backends/claude/tools.d.ts.map +1 -1
  25. package/lib/types/backends/claude/tools.js +8 -3
  26. package/lib/types/backends/claude/translate/core.d.ts +2 -2
  27. package/lib/types/backends/claude/translate/core.d.ts.map +1 -1
  28. package/lib/types/backends/claude/translate/core.js +10 -6
  29. package/lib/types/backends/codex/session/commands.d.ts +2 -0
  30. package/lib/types/backends/codex/session/commands.d.ts.map +1 -1
  31. package/lib/types/backends/codex/session/commands.js +8 -4
  32. package/lib/types/backends/codex/session/input.d.ts +11 -7
  33. package/lib/types/backends/codex/session/input.d.ts.map +1 -1
  34. package/lib/types/backends/codex/session/input.js +68 -15
  35. package/lib/types/backends/codex/session/session.d.ts.map +1 -1
  36. package/lib/types/backends/codex/session/session.js +2 -3
  37. package/lib/types/backends/codex/translate/presentation.d.ts.map +1 -1
  38. package/lib/types/backends/codex/translate/presentation.js +5 -2
  39. package/lib/types/channel/interaction.d.ts.map +1 -1
  40. package/lib/types/channel/interaction.js +1 -0
  41. package/lib/types/channel/permissions.d.ts +15 -0
  42. package/lib/types/channel/permissions.d.ts.map +1 -1
  43. package/lib/types/channel/permissions.js +28 -0
  44. package/lib/types/channel/projection.d.ts.map +1 -1
  45. package/lib/types/channel/projection.js +89 -11
  46. package/lib/types/channel/questions.d.ts +45 -3
  47. package/lib/types/channel/questions.d.ts.map +1 -1
  48. package/lib/types/channel/questions.js +43 -0
  49. package/lib/types/channel/sanitize.d.ts.map +1 -1
  50. package/lib/types/channel/sanitize.js +8 -4
  51. package/lib/types/channel/subagent-failure.d.ts +49 -0
  52. package/lib/types/channel/subagent-failure.d.ts.map +1 -0
  53. package/lib/types/channel/subagent-failure.js +59 -0
  54. package/lib/types/channel/transcript.d.ts +17 -0
  55. package/lib/types/channel/transcript.d.ts.map +1 -1
  56. package/lib/types/channel/transcript.js +35 -0
  57. package/lib/types/commands.js +2 -2
  58. package/lib/types/components/MessageList.d.ts.map +1 -1
  59. package/lib/types/components/MessageList.js +14 -10
  60. package/lib/types/components/PromptInput.d.ts.map +1 -1
  61. package/lib/types/components/PromptInput.js +61 -6
  62. package/lib/types/components/SplitDiffView.d.ts.map +1 -1
  63. package/lib/types/components/SplitDiffView.js +3 -2
  64. package/lib/types/components/StarPrompt.d.ts +5 -3
  65. package/lib/types/components/StarPrompt.d.ts.map +1 -1
  66. package/lib/types/components/StarPrompt.js +56 -6
  67. package/lib/types/components/SubagentCard.d.ts.map +1 -1
  68. package/lib/types/components/SubagentCard.js +1 -1
  69. package/lib/types/components/SubagentDashboard.d.ts.map +1 -1
  70. package/lib/types/components/SubagentDashboard.js +9 -2
  71. package/lib/types/components/SubagentDetailScene.d.ts.map +1 -1
  72. package/lib/types/components/SubagentDetailScene.js +1 -1
  73. package/lib/types/components/messages/AssistantToolUseMessage.d.ts.map +1 -1
  74. package/lib/types/components/messages/AssistantToolUseMessage.js +126 -25
  75. package/lib/types/components/questions/AskUserQuestionPanel.d.ts +5 -8
  76. package/lib/types/components/questions/AskUserQuestionPanel.d.ts.map +1 -1
  77. package/lib/types/components/questions/AskUserQuestionPanel.js +7 -4
  78. package/lib/types/components/questions/PlanReviewPanel.d.ts +3 -6
  79. package/lib/types/components/questions/PlanReviewPanel.d.ts.map +1 -1
  80. package/lib/types/components/revealScope.d.ts +15 -0
  81. package/lib/types/components/revealScope.d.ts.map +1 -0
  82. package/lib/types/components/revealScope.js +17 -0
  83. package/lib/types/components/sidePanel/btw/BtwComposer.d.ts +34 -1
  84. package/lib/types/components/sidePanel/btw/BtwComposer.d.ts.map +1 -1
  85. package/lib/types/components/sidePanel/btw/BtwComposer.js +108 -7
  86. package/lib/types/components/sidePanel/btw/BtwPanelAdapter.d.ts.map +1 -1
  87. package/lib/types/components/sidePanel/btw/BtwPanelAdapter.js +1 -1
  88. package/lib/types/components/sidePanel/btw/BtwThreadScene.d.ts.map +1 -1
  89. package/lib/types/components/sidePanel/btw/BtwThreadScene.js +1 -1
  90. package/lib/types/components/smoothReveal.d.ts +36 -6
  91. package/lib/types/components/smoothReveal.d.ts.map +1 -1
  92. package/lib/types/components/smoothReveal.js +92 -21
  93. package/lib/types/components/teamRoster.d.ts +6 -3
  94. package/lib/types/components/teamRoster.d.ts.map +1 -1
  95. package/lib/types/components/workspaces/HomeWorkspaceRow.d.ts +4 -14
  96. package/lib/types/components/workspaces/HomeWorkspaceRow.d.ts.map +1 -1
  97. package/lib/types/components/workspaces/HomeWorkspaceRow.js +26 -17
  98. package/lib/types/dsh-adapter/approvals.d.ts +19 -0
  99. package/lib/types/dsh-adapter/approvals.d.ts.map +1 -1
  100. package/lib/types/dsh-adapter/approvals.js +17 -1
  101. package/lib/types/dsh-adapter/backend/session.d.ts.map +1 -1
  102. package/lib/types/dsh-adapter/backend/session.js +12 -0
  103. package/lib/types/dsh-adapter/backend/translate.d.ts.map +1 -1
  104. package/lib/types/dsh-adapter/backend/translate.js +21 -4
  105. package/lib/types/dsh-adapter/channel/attached-context.d.ts +15 -2
  106. package/lib/types/dsh-adapter/channel/attached-context.d.ts.map +1 -1
  107. package/lib/types/dsh-adapter/channel/attached-context.js +26 -3
  108. package/lib/types/dsh-adapter/channel/binding-events.d.ts +3 -0
  109. package/lib/types/dsh-adapter/channel/binding-events.d.ts.map +1 -1
  110. package/lib/types/dsh-adapter/channel/binding-events.js +43 -2
  111. package/lib/types/dsh-adapter/channel/context-bookkeeping.d.ts +2 -6
  112. package/lib/types/dsh-adapter/channel/context-bookkeeping.d.ts.map +1 -1
  113. package/lib/types/dsh-adapter/channel/context-bookkeeping.js +7 -1
  114. package/lib/types/dsh-adapter/channel/core/compose.d.ts +2 -6
  115. package/lib/types/dsh-adapter/channel/core/compose.d.ts.map +1 -1
  116. package/lib/types/dsh-adapter/channel/core/compose.js +1 -1
  117. package/lib/types/dsh-adapter/channel/core/local-actions.d.ts.map +1 -1
  118. package/lib/types/dsh-adapter/channel/core/local-actions.js +3 -26
  119. package/lib/types/dsh-adapter/channel/emitter.js +1 -1
  120. package/lib/types/dsh-adapter/channel/extensions.d.ts.map +1 -1
  121. package/lib/types/dsh-adapter/channel/extensions.js +15 -4
  122. package/lib/types/dsh-adapter/channel/input-actions.d.ts +2 -2
  123. package/lib/types/dsh-adapter/channel/input-actions.d.ts.map +1 -1
  124. package/lib/types/dsh-adapter/channel/input-actions.js +34 -10
  125. package/lib/types/dsh-adapter/channel/input-delivery.d.ts +3 -7
  126. package/lib/types/dsh-adapter/channel/input-delivery.d.ts.map +1 -1
  127. package/lib/types/dsh-adapter/channel/input-delivery.js +14 -5
  128. package/lib/types/dsh-adapter/channel/local-actions.d.ts.map +1 -1
  129. package/lib/types/dsh-adapter/channel/local-actions.js +7 -3
  130. package/lib/types/dsh-adapter/channel/model-actions.d.ts +4 -1
  131. package/lib/types/dsh-adapter/channel/model-actions.d.ts.map +1 -1
  132. package/lib/types/dsh-adapter/channel/model-actions.js +26 -9
  133. package/lib/types/dsh-adapter/channel/model-selection.d.ts +27 -2
  134. package/lib/types/dsh-adapter/channel/model-selection.d.ts.map +1 -1
  135. package/lib/types/dsh-adapter/channel/model-selection.js +81 -37
  136. package/lib/types/dsh-adapter/channel/model-switch.d.ts +1 -1
  137. package/lib/types/dsh-adapter/channel/model-switch.d.ts.map +1 -1
  138. package/lib/types/dsh-adapter/channel/projection-helpers.d.ts.map +1 -1
  139. package/lib/types/dsh-adapter/channel/projection-helpers.js +4 -2
  140. package/lib/types/dsh-adapter/channel/session-rewind.d.ts.map +1 -1
  141. package/lib/types/dsh-adapter/channel/session-rewind.js +6 -2
  142. package/lib/types/dsh-adapter/channel/session-tree-actions.d.ts.map +1 -1
  143. package/lib/types/dsh-adapter/channel/session-tree-actions.js +8 -4
  144. package/lib/types/dsh-adapter/channel/settings-host.d.ts.map +1 -1
  145. package/lib/types/dsh-adapter/channel/settings-host.js +185 -36
  146. package/lib/types/dsh-adapter/channel/subagent-projection.d.ts +55 -4
  147. package/lib/types/dsh-adapter/channel/subagent-projection.d.ts.map +1 -1
  148. package/lib/types/dsh-adapter/channel/subagent-projection.js +80 -16
  149. package/lib/types/dsh-adapter/channel/subagent-transcript.d.ts +1 -1
  150. package/lib/types/dsh-adapter/channel/subagent-transcript.d.ts.map +1 -1
  151. package/lib/types/dsh-adapter/channel/subagent-transcript.js +6 -5
  152. package/lib/types/dsh-adapter/channel/task-completion.js +2 -10
  153. package/lib/types/dsh-adapter/channel/transcript.d.ts +3 -2
  154. package/lib/types/dsh-adapter/channel/transcript.d.ts.map +1 -1
  155. package/lib/types/dsh-adapter/channel/transcript.js +13 -4
  156. package/lib/types/dsh-adapter/channel/types.d.ts +11 -2
  157. package/lib/types/dsh-adapter/channel/types.d.ts.map +1 -1
  158. package/lib/types/dsh-adapter/compat/compaction-previews.d.ts +11 -0
  159. package/lib/types/dsh-adapter/compat/compaction-previews.d.ts.map +1 -0
  160. package/lib/types/dsh-adapter/compat/compaction-previews.js +38 -0
  161. package/lib/types/dsh-adapter/compat/messages.d.ts +1 -1
  162. package/lib/types/dsh-adapter/compat/messages.d.ts.map +1 -1
  163. package/lib/types/dsh-adapter/compat/messages.js +2 -2
  164. package/lib/types/dsh-adapter/contract.d.ts +29 -3
  165. package/lib/types/dsh-adapter/contract.d.ts.map +1 -1
  166. package/lib/types/dsh-adapter/contract.js +48 -5
  167. package/lib/types/dsh-adapter/experimental-bundles.d.ts +5 -0
  168. package/lib/types/dsh-adapter/experimental-bundles.d.ts.map +1 -1
  169. package/lib/types/dsh-adapter/experimental-bundles.js +0 -2
  170. package/lib/types/dsh-adapter/fresh-agent.d.ts +1 -1
  171. package/lib/types/dsh-adapter/fresh-agent.d.ts.map +1 -1
  172. package/lib/types/dsh-adapter/fresh-agent.js +60 -11
  173. package/lib/types/dsh-adapter/host-access.d.ts.map +1 -1
  174. package/lib/types/dsh-adapter/host-access.js +60 -11
  175. package/lib/types/dsh-adapter/host-contract.d.ts +1 -1
  176. package/lib/types/dsh-adapter/host-contract.d.ts.map +1 -1
  177. package/lib/types/dsh-adapter/host-contract.js +5 -3
  178. package/lib/types/dsh-adapter/host-dsh.d.ts +2 -8
  179. package/lib/types/dsh-adapter/host-dsh.d.ts.map +1 -1
  180. package/lib/types/dsh-adapter/host-dsh.js +30 -6
  181. package/lib/types/dsh-adapter/host-entry.js +4 -0
  182. package/lib/types/dsh-adapter/index.d.ts +9 -1
  183. package/lib/types/dsh-adapter/index.d.ts.map +1 -1
  184. package/lib/types/dsh-adapter/index.js +5 -0
  185. package/lib/types/dsh-adapter/oauth/account-notifications.d.ts +73 -0
  186. package/lib/types/dsh-adapter/oauth/account-notifications.d.ts.map +1 -0
  187. package/lib/types/dsh-adapter/oauth/account-notifications.js +250 -0
  188. package/lib/types/dsh-adapter/oauth/bonus.d.ts +34 -9
  189. package/lib/types/dsh-adapter/oauth/bonus.d.ts.map +1 -1
  190. package/lib/types/dsh-adapter/oauth/bonus.js +47 -5
  191. package/lib/types/dsh-adapter/oauth/deepseek.d.ts +7 -2
  192. package/lib/types/dsh-adapter/oauth/deepseek.d.ts.map +1 -1
  193. package/lib/types/dsh-adapter/oauth/deepseek.js +6 -1
  194. package/lib/types/dsh-adapter/oauth/index.d.ts.map +1 -1
  195. package/lib/types/dsh-adapter/oauth/index.js +44 -0
  196. package/lib/types/dsh-adapter/oauth/profiles.d.ts.map +1 -1
  197. package/lib/types/dsh-adapter/oauth/profiles.js +14 -1
  198. package/lib/types/dsh-adapter/oauth/service.d.ts.map +1 -1
  199. package/lib/types/dsh-adapter/oauth/service.js +5 -6
  200. package/lib/types/dsh-adapter/plugin-manage.d.ts +6 -4
  201. package/lib/types/dsh-adapter/plugin-manage.d.ts.map +1 -1
  202. package/lib/types/dsh-adapter/plugin-manage.js +3 -2
  203. package/lib/types/dsh-adapter/plugin.d.ts +237 -6
  204. package/lib/types/dsh-adapter/plugin.d.ts.map +1 -1
  205. package/lib/types/dsh-adapter/plugin.js +751 -67
  206. package/lib/types/dsh-adapter/presets.d.ts +38 -11
  207. package/lib/types/dsh-adapter/presets.d.ts.map +1 -1
  208. package/lib/types/dsh-adapter/presets.js +46 -17
  209. package/lib/types/dsh-adapter/process-exit.d.ts +1 -1
  210. package/lib/types/dsh-adapter/process-exit.js +1 -1
  211. package/lib/types/dsh-adapter/questions.d.ts +3 -4
  212. package/lib/types/dsh-adapter/questions.d.ts.map +1 -1
  213. package/lib/types/dsh-adapter/questions.js +1 -1
  214. package/lib/types/dsh-adapter/session-list-metadata.js +2 -2
  215. package/lib/types/dsh-adapter/session-projection-store.d.ts +1 -1
  216. package/lib/types/dsh-adapter/session-projection-store.d.ts.map +1 -1
  217. package/lib/types/dsh-adapter/session-projection-store.js +30 -23
  218. package/lib/types/dsh-adapter/sessionTree.d.ts.map +1 -1
  219. package/lib/types/dsh-adapter/sessionTree.js +4 -1
  220. package/lib/types/dsh-adapter/subagents.d.ts +6 -0
  221. package/lib/types/dsh-adapter/subagents.d.ts.map +1 -1
  222. package/lib/types/dsh-adapter/subagents.js +32 -3
  223. package/lib/types/dsh-adapter/team-mode.d.ts +46 -27
  224. package/lib/types/dsh-adapter/team-mode.d.ts.map +1 -1
  225. package/lib/types/dsh-adapter/team-mode.js +157 -29
  226. package/lib/types/dsh-adapter/team-roster.d.ts +53 -18
  227. package/lib/types/dsh-adapter/team-roster.d.ts.map +1 -1
  228. package/lib/types/dsh-adapter/team-roster.js +206 -39
  229. package/lib/types/dsh-adapter/team-tools.d.ts +25 -12
  230. package/lib/types/dsh-adapter/team-tools.d.ts.map +1 -1
  231. package/lib/types/dsh-adapter/team-tools.js +81 -26
  232. package/lib/types/dsh-adapter/tool-scope.d.ts +24 -0
  233. package/lib/types/dsh-adapter/tool-scope.d.ts.map +1 -0
  234. package/lib/types/dsh-adapter/tool-scope.js +127 -0
  235. package/lib/types/dsh-adapter/types.d.ts +2 -1
  236. package/lib/types/dsh-adapter/types.d.ts.map +1 -1
  237. package/lib/types/heldInputs.d.ts +55 -16
  238. package/lib/types/heldInputs.d.ts.map +1 -1
  239. package/lib/types/heldInputs.js +277 -41
  240. package/lib/types/i18n.d.ts +292 -20
  241. package/lib/types/i18n.d.ts.map +1 -1
  242. package/lib/types/i18n.js +89 -13
  243. package/lib/types/ink/components/App.d.ts +2 -0
  244. package/lib/types/ink/components/App.d.ts.map +1 -1
  245. package/lib/types/ink/components/App.js +8 -0
  246. package/lib/types/ink/dom.d.ts.map +1 -1
  247. package/lib/types/ink/dom.js +13 -3
  248. package/lib/types/ink/events/input-event.d.ts.map +1 -1
  249. package/lib/types/ink/events/input-event.js +7 -6
  250. package/lib/types/ink/flush-tick.d.ts +6 -0
  251. package/lib/types/ink/flush-tick.d.ts.map +1 -1
  252. package/lib/types/ink/flush-tick.js +31 -0
  253. package/lib/types/ink/hit-test.d.ts +2 -0
  254. package/lib/types/ink/hit-test.d.ts.map +1 -1
  255. package/lib/types/ink/hit-test.js +10 -0
  256. package/lib/types/ink/hooks/use-program-status.d.ts +1 -1
  257. package/lib/types/ink/hooks/use-program-status.d.ts.map +1 -1
  258. package/lib/types/ink/hooks/use-program-status.js +3 -2
  259. package/lib/types/ink/hooks/use-terminal-title.d.ts +15 -0
  260. package/lib/types/ink/hooks/use-terminal-title.d.ts.map +1 -1
  261. package/lib/types/ink/hooks/use-terminal-title.js +23 -3
  262. package/lib/types/ink/ink.d.ts +1 -0
  263. package/lib/types/ink/ink.d.ts.map +1 -1
  264. package/lib/types/ink/ink.js +7 -4
  265. package/lib/types/ink/jumpback-state.d.ts +33 -0
  266. package/lib/types/ink/jumpback-state.d.ts.map +1 -0
  267. package/lib/types/ink/jumpback-state.js +51 -0
  268. package/lib/types/ink/jumpback.d.ts +78 -0
  269. package/lib/types/ink/jumpback.d.ts.map +1 -0
  270. package/lib/types/ink/jumpback.js +515 -0
  271. package/lib/types/ink/log-update.js +37 -14
  272. package/lib/types/ink/notify-helper/activate.cs +836 -0
  273. package/lib/types/ink/notify-helper/compile.d.ts +30 -0
  274. package/lib/types/ink/notify-helper/compile.d.ts.map +1 -0
  275. package/lib/types/ink/notify-helper/compile.js +235 -0
  276. package/lib/types/ink/parse-keypress.d.ts.map +1 -1
  277. package/lib/types/ink/parse-keypress.js +25 -0
  278. package/lib/types/ink/terminal-notification-windows.d.ts +8 -4
  279. package/lib/types/ink/terminal-notification-windows.d.ts.map +1 -1
  280. package/lib/types/ink/terminal-notification-windows.js +14 -21
  281. package/lib/types/ink/terminal-notification.d.ts +31 -2
  282. package/lib/types/ink/terminal-notification.d.ts.map +1 -1
  283. package/lib/types/ink/terminal-notification.js +51 -0
  284. package/lib/types/ink/terminal.d.ts +15 -3
  285. package/lib/types/ink/terminal.d.ts.map +1 -1
  286. package/lib/types/ink/terminal.js +38 -9
  287. package/lib/types/screens/AgentTranscriptScene.d.ts.map +1 -1
  288. package/lib/types/screens/AgentTranscriptScene.js +1 -1
  289. package/lib/types/screens/Chat.d.ts +4 -3
  290. package/lib/types/screens/Chat.d.ts.map +1 -1
  291. package/lib/types/screens/Chat.js +81 -11
  292. package/lib/types/screens/SessionSupervisor.d.ts +3 -6
  293. package/lib/types/screens/SessionSupervisor.d.ts.map +1 -1
  294. package/lib/types/screens/SessionSupervisor.js +5 -8
  295. package/lib/types/screens/sessionSupervisor/ForeignSessionPanes.d.ts +1 -2
  296. package/lib/types/screens/sessionSupervisor/ForeignSessionPanes.d.ts.map +1 -1
  297. package/lib/types/screens/sessionSupervisor/ForeignSessionPanes.js +2 -2
  298. package/lib/types/screens/sessionSupervisor/model.d.ts +1 -1
  299. package/lib/types/screens/sessionSupervisor/model.js +1 -1
  300. package/lib/types/sessionMounts.d.ts +12 -5
  301. package/lib/types/sessionMounts.d.ts.map +1 -1
  302. package/lib/types/sessionMounts.js +33 -6
  303. package/lib/types/settings/definitions.d.ts +12 -0
  304. package/lib/types/settings/definitions.d.ts.map +1 -1
  305. package/lib/types/settings/definitions.js +15 -7
  306. package/lib/types/update.d.ts +412 -20
  307. package/lib/types/update.d.ts.map +1 -1
  308. package/lib/types/update.js +2094 -193
  309. package/lib/types/updateHost.d.ts +198 -0
  310. package/lib/types/updateHost.d.ts.map +1 -0
  311. package/lib/types/updateHost.js +608 -0
  312. package/lib/types/utils/processName.d.ts +16 -0
  313. package/lib/types/utils/processName.d.ts.map +1 -0
  314. package/lib/types/utils/processName.js +27 -0
  315. package/package.json +114 -111
  316. package/presets/liangshen/agent.cordis.yml +4 -0
  317. package/tui-profile/feed/README.md +1 -1
  318. package/tui-profile/feed/first-party.json +1 -1
@@ -1,14 +1,15 @@
1
1
  import { execFileSync, spawn } from 'node:child_process';
2
- import { createHash } from 'node:crypto';
3
- import { appendFileSync, chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { appendFileSync, chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs';
4
4
  import { homedir } from 'node:os';
5
- import { dirname, join, resolve, sep } from 'node:path';
5
+ import { basename, delimiter, dirname, join, resolve, sep } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  // Per-function imports: this file loads before the first frame.
8
8
  import gt from 'semver/functions/gt.js';
9
9
  import gte from 'semver/functions/gte.js';
10
10
  import lt from 'semver/functions/lt.js';
11
11
  import valid from 'semver/functions/valid.js';
12
+ import validRange from 'semver/ranges/valid.js';
12
13
  import { shellQuote } from './utils/shellQuote.js';
13
14
  import { DATA_DIR } from './utils/paths.js';
14
15
  import { stripResumeArgs } from './sessionHistory.js';
@@ -19,6 +20,9 @@ import { DISABLE_KITTY_KEYBOARD, DISABLE_MODIFY_OTHER_KEYS, DISABLE_WIN32_INPUT_
19
20
  import { DBP, DFE, DISABLE_MOUSE_TRACKING, EXIT_ALT_SCREEN, SHOW_CURSOR } from './ink/termio/dec.js';
20
21
  import { detachHandoffStdin } from './ink/stdin-handoff.js';
21
22
  import { runInstallerProcess } from './updateProcess.js';
23
+ import { UPSTREAM_HOST_PACKAGE, UPSTREAM_HOST_PEER_PACKAGE, installedKernelPackageDir } from './dsh-adapter/contract.js';
24
+ import { PNPM_RELEASE_AGE_ENV, detectHostInstall, hostCompatibility, hostSatisfiesLine, parseHostLineRange, planHostStep, shellEnvPrefix } from './updateHost.js';
25
+ import { t } from './i18n.js';
22
26
  // Re-exported for scripts/verify-update.mjs and the bin launcher, which reads
23
27
  // the compiled copy at lib/types/utils/shellQuote.js.
24
28
  export { shellQuote };
@@ -41,6 +45,39 @@ const MAX_ASSET_BYTES = 512 * 1024 * 1024;
41
45
  const MAX_CHECKSUM_MANIFEST_BYTES = 1024 * 1024;
42
46
  /** env marker set on the /update restart; the new process verifies it at boot. */
43
47
  const UPDATED_FROM_ENV = 'DSH_TUI_UPDATED_FROM';
48
+ /**
49
+ * Engine counterpart of DSH_TUI_UPDATED_FROM: set only when the dsh engine
50
+ * actually changed, so a "TUI was already latest, only the engine moved"
51
+ * update does not trip the TUI version-advance check (#1844 plan §3.6).
52
+ */
53
+ const UPDATED_DSH_FROM_ENV = 'DSH_TUI_UPDATED_DSH_FROM';
54
+ /**
55
+ * The engine-skip report, carried to the replacement: this process tears its
56
+ * screen down as the update starts, and a local row is never restored from
57
+ * backend history, so only the next session can show the guidance.
58
+ */
59
+ const ENGINE_SKIP_REPORT_ENV = 'DSH_TUI_ENGINE_SKIP_REPORT';
60
+ /** `DSH_TUI_UPDATE_ENGINE=0` pins the engine: plan the step, never run it. */
61
+ export const UPDATE_ENGINE_ENV = 'DSH_TUI_UPDATE_ENGINE';
62
+ /**
63
+ * The global launcher's own bin path, exported by shims >= 0.19.0 beside
64
+ * DSH_TUI_LAUNCHER_VERSION. Inside the TUI argv[1] is the PROFILE copy, so
65
+ * without this marker /update can only *see* that the launcher lags, never
66
+ * reach the install it would have to align (issue #1844).
67
+ */
68
+ export const GLOBAL_LAUNCHER_PATH_ENV = 'DSH_TUI_LAUNCHER_PATH';
69
+ /** Launcher generation marker (shims >= 0.8.3); also the PATH-fallback identity. */
70
+ export const GLOBAL_LAUNCHER_VERSION_ENV = 'DSH_TUI_LAUNCHER_VERSION';
71
+ /**
72
+ * One-shot marker for "this launch chain has no global launcher": set on a
73
+ * restart whose plan resolved no launcher (a direct `dsh --profile` boot), so
74
+ * the replacement does not warn about an install that does not exist.
75
+ * Never reuse DSH_TUI_LAUNCHER_VERSION for this - a stale version marker would
76
+ * make the next plan's PATH fallback adopt an unrelated global launcher.
77
+ */
78
+ export const LAUNCHER_ABSENT_ENV = 'DSH_TUI_LAUNCHER_ABSENT';
79
+ /** `DSH_TUI_UPDATE_LAUNCHER=0` skips the launcher step (pinned installs, diagnosis). */
80
+ export const UPDATE_LAUNCHER_ENV = 'DSH_TUI_UPDATE_LAUNCHER';
44
81
  /**
45
82
  * env marker set on the /restart replacement: its boot logs to restart.log
46
83
  * (ordinary launches stay silent, so the file is restart-only evidence).
@@ -953,7 +990,7 @@ export async function checkForTuiUpdate() {
953
990
  function runProcess(command, args, options = {}) {
954
991
  return runInstallerProcess(command, args, {
955
992
  ...options,
956
- category: 'profile-install',
993
+ category: options.category ?? 'profile-install',
957
994
  onStdout: text => { process.stdout.write(text); },
958
995
  onStderr: text => {
959
996
  process.stderr.write(text);
@@ -962,10 +999,20 @@ function runProcess(command, args, options = {}) {
962
999
  onEvent: event => {
963
1000
  if (event.stage === 'cleanup-error')
964
1001
  options.onCleanupError?.();
1002
+ if (event.stage === 'cancel')
1003
+ options.onCancel?.();
965
1004
  logRestartEvent('update installer', { ...event });
966
1005
  if (event.stage === 'timeout' || event.stage === 'cancel' || event.stage === 'cleanup-error' || event.stage === 'error') {
967
1006
  writeHandoffNotice(`dsh-tui: installer ${event.stage}; category=${event.category} pid=${event.pid ?? 'unavailable'} last-output=${event.lastOutputAt === undefined ? 'none' : new Date(event.lastOutputAt).toISOString()}${event.message === undefined ? '' : `: ${event.message}`}\n`);
968
- writeHandoffNotice('Installation may be partial. Check/repair the profile before resuming; no automatic restart.\n');
1007
+ // The profile installer is the only step whose failure leaves an
1008
+ // unusable install; the launcher step is best effort and the update
1009
+ // still restarts, and the engine step is verified separately (a
1010
+ // compatible combination may still restart, see updateTui).
1011
+ writeHandoffNotice(event.category === 'launcher-install'
1012
+ ? 'The global launcher may still be outdated; align it manually if a later launch reports it.\n'
1013
+ : event.category === 'host-install'
1014
+ ? 'The dsh engine install may be partial; /update will verify it before restarting.\n'
1015
+ : 'Installation may be partial. Check/repair the profile before resuming; no automatic restart.\n');
969
1016
  }
970
1017
  },
971
1018
  });
@@ -1550,6 +1597,294 @@ export function removeStalePackageInstall(profile) {
1550
1597
  }
1551
1598
  return removal;
1552
1599
  }
1600
+ /** What the manifest at `dir` says, or undefined when it is not this package. */
1601
+ function launcherManifest(dir) {
1602
+ try {
1603
+ const parsed = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
1604
+ if (!isRecord(parsed) || parsed.name !== PACKAGE_NAME)
1605
+ return undefined;
1606
+ return { version: typeof parsed.version === 'string' ? (valid(parsed.version) ?? undefined) : undefined };
1607
+ }
1608
+ catch {
1609
+ return undefined;
1610
+ }
1611
+ }
1612
+ /** True when `dir` is an installed package (inside a node_modules tree). */
1613
+ function isInstalledPackageDir(dir) {
1614
+ return /(?:^|[\\/])node_modules(?:[\\/]|$)/u.test(dir);
1615
+ }
1616
+ /**
1617
+ * Follow a launcher bin to the package directory it belongs to. `realpath`
1618
+ * collapses the npm bin symlink (`<prefix>/bin/dsh-tui`) onto the js file it
1619
+ * names; from either a bin file or an already-resolved package dir the walk
1620
+ * up accepts only a manifest of OUR package INSIDE a node_modules tree. That
1621
+ * last constraint is what keeps the resolver from treating a source checkout,
1622
+ * an `npm link` target or an unrelated ancestor directory as the global
1623
+ * install it may overwrite (issue #1844 review). npm's Windows layout is
1624
+ * probed beside every level, because there the shim sits directly in the
1625
+ * prefix (`%APPDATA%\npm\dsh-tui.cmd`) while the package lives in
1626
+ * `node_modules`. pnpm's global layout is probed the same way: its bins live
1627
+ * in `<pnpm home>/bin` while the packages sit in a sibling `global/` subtree.
1628
+ *
1629
+ * @param path - A launcher bin path or a launcher package directory.
1630
+ * @returns The real package directory, or undefined when it cannot be proven.
1631
+ */
1632
+ function launcherTargetDir(path) {
1633
+ // Callers may hand over the package directory itself (`alignGlobalLauncher`).
1634
+ // The install-root check runs on the RESOLVED path: a linked package dir
1635
+ // (`node_modules/@scope/name` → a checkout) must not pass on its logical name.
1636
+ // A named package that is not installed fails closed instead of walking on to
1637
+ // some other install that happens to sit above it.
1638
+ const direct = resolve(path);
1639
+ if (launcherManifest(direct) !== undefined) {
1640
+ try {
1641
+ const resolved = realpathSync(direct);
1642
+ return isInstalledPackageDir(resolved) ? resolved : undefined;
1643
+ }
1644
+ catch {
1645
+ return undefined;
1646
+ }
1647
+ }
1648
+ let real;
1649
+ try {
1650
+ real = realpathSync(direct);
1651
+ }
1652
+ catch {
1653
+ return undefined;
1654
+ }
1655
+ let dir = dirname(real);
1656
+ for (let depth = 0; depth < 8; depth++) {
1657
+ for (const candidate of [
1658
+ dir,
1659
+ join(dir, PACKAGE_NAME),
1660
+ join(dir, 'node_modules', PACKAGE_NAME),
1661
+ join(dir, 'lib', 'node_modules', PACKAGE_NAME),
1662
+ ...pnpmGlobalPackages(dir),
1663
+ ]) {
1664
+ if (launcherManifest(candidate) === undefined)
1665
+ continue;
1666
+ let resolved;
1667
+ try {
1668
+ resolved = realpathSync(candidate);
1669
+ }
1670
+ catch {
1671
+ return undefined;
1672
+ }
1673
+ // A linked checkout resolves out of node_modules — never rewrite it.
1674
+ return isInstalledPackageDir(resolved) ? resolved : undefined;
1675
+ }
1676
+ const parent = dirname(dir);
1677
+ if (parent === dir)
1678
+ return undefined;
1679
+ dir = parent;
1680
+ }
1681
+ return undefined;
1682
+ }
1683
+ /**
1684
+ * The pnpm global slots beside `dir`, as package candidates. pnpm puts global
1685
+ * bins in `<pnpm home>/bin` but the packages in a sibling `global/<n>/…`
1686
+ * (pnpm 11) or `global/v<n>/<hash>/…` (pnpm 12) subtree, so on Windows the
1687
+ * `.cmd` shim has no ancestor `node_modules` for the walk to find. Only the
1688
+ * shim's own prefix is read (bounded, never PATH or PNPM_HOME).
1689
+ */
1690
+ function pnpmGlobalPackages(dir) {
1691
+ let slots;
1692
+ try {
1693
+ slots = readdirSync(join(dir, 'global')).filter(name => /^v?\d+$/u.test(name)).slice(0, 8);
1694
+ }
1695
+ catch {
1696
+ return [];
1697
+ }
1698
+ const packages = [];
1699
+ for (const slot of slots) {
1700
+ const slotDir = join(dir, 'global', slot);
1701
+ packages.push(join(slotDir, 'node_modules', PACKAGE_NAME));
1702
+ let groups;
1703
+ try {
1704
+ groups = readdirSync(slotDir).filter(name => name !== 'node_modules').slice(0, 8);
1705
+ }
1706
+ catch {
1707
+ continue;
1708
+ }
1709
+ for (const group of groups)
1710
+ packages.push(join(slotDir, group, 'node_modules', PACKAGE_NAME));
1711
+ }
1712
+ return packages;
1713
+ }
1714
+ /**
1715
+ * The pnpm global install group a path belongs to, from the layout alone:
1716
+ * `<pnpm home>/global/<n>/node_modules/…` (pnpm 11 slots) or
1717
+ * `<pnpm home>/global/v<n>/<group>/node_modules/…` (pnpm 12's isolated
1718
+ * groups). Derived BEFORE realpath: a shim's argv[1] still names the group
1719
+ * even when the package itself resolves into a store rooted elsewhere.
1720
+ */
1721
+ function pnpmGlobalGroupRoot(path) {
1722
+ const match = /^(.*?[\\/]global[\\/](?:v?\d+))(?:[\\/]([^\\/]+))?[\\/]node_modules[\\/]/u.exec(resolve(path));
1723
+ if (match === null || match[1] === '')
1724
+ return undefined;
1725
+ return match[2] === undefined ? match[1] : join(match[1], match[2]);
1726
+ }
1727
+ /** The PNPM_HOME named by a `<home>/global/<slot>…` path. */
1728
+ function pnpmHomeOf(path) {
1729
+ const match = /^(.*?)[\\/]global[\\/](?:v?\d+)(?:[\\/]|$)/u.exec(resolve(path));
1730
+ return match === null || match[1] === '' ? undefined : match[1];
1731
+ }
1732
+ /**
1733
+ * The PNPM_HOME a launcher SHIM was installed from: pnpm writes global bins to
1734
+ * `<home>` (pnpm 11) or `<home>/bin` (pnpm 12, and Windows) beside the
1735
+ * `<home>/global/` subtree that holds the packages. With a real store link the
1736
+ * package realpath keeps no `global/` segment, so the shim is the only
1737
+ * surviving evidence — and desktop launchers, cron and supervisor-started
1738
+ * processes often inherit no PNPM_HOME at all (#1847 review).
1739
+ *
1740
+ * Only a home whose group actually owns `packageDir` is accepted, so an
1741
+ * unrelated `bin` directory on PATH is never mistaken for a pnpm home.
1742
+ */
1743
+ function pnpmHomeOfBin(binPath, packageDir) {
1744
+ let dir = dirname(resolve(binPath));
1745
+ for (let depth = 0; depth < 2; depth++) {
1746
+ if (findPnpmGroupRoot(dir, packageDir) !== undefined)
1747
+ return dir;
1748
+ const parent = dirname(dir);
1749
+ if (parent === dir)
1750
+ return undefined;
1751
+ dir = parent;
1752
+ }
1753
+ return undefined;
1754
+ }
1755
+ /** A matching external npm bin proves more than an arbitrary node_modules path. */
1756
+ function isNpmGlobalPackageDir(packageDir, platform) {
1757
+ const modulesDir = dirname(dirname(packageDir));
1758
+ const prefix = platform === 'win32' ? dirname(modulesDir) : dirname(dirname(modulesDir));
1759
+ if (packageDir !== join(prefix, ...(platform === 'win32' ? [] : ['lib']), 'node_modules', PACKAGE_NAME))
1760
+ return false;
1761
+ const bin = join(packageDir, 'bin', 'dsh-tui.js');
1762
+ for (const name of ['dsh-tui', 'dst']) {
1763
+ try {
1764
+ if (platform === 'win32') {
1765
+ // npm's cmd-shim points from the global prefix into its node_modules;
1766
+ // local npm/npx bins instead live inside node_modules/.bin.
1767
+ const shim = readFileSync(join(prefix, `${name}.cmd`), 'utf8').replaceAll('\\', '/');
1768
+ const target = `node_modules/${PACKAGE_NAME}/bin/dsh-tui.js`;
1769
+ if (shim.includes(`%dp0%/${target}`) || shim.includes(`%~dp0/${target}`))
1770
+ return true;
1771
+ }
1772
+ else if (realpathSync(join(prefix, 'bin', name)) === realpathSync(bin)) {
1773
+ return true;
1774
+ }
1775
+ }
1776
+ catch {
1777
+ // A missing or foreign external bin does not prove a global install.
1778
+ }
1779
+ }
1780
+ return false;
1781
+ }
1782
+ /** Classify only a proven global installation as writable. */
1783
+ function launcherLayout(packageDir, binPath, platform = process.platform) {
1784
+ // The logical bin/group owns the install, even when its shared store lives
1785
+ // under another PNPM_HOME. Store containment is never ownership evidence.
1786
+ const groupRoot = (binPath === undefined ? undefined : pnpmGlobalGroupRoot(binPath))
1787
+ ?? pnpmGlobalGroupRoot(packageDir);
1788
+ if (groupRoot !== undefined) {
1789
+ try {
1790
+ if (realpathSync(join(groupRoot, 'node_modules', PACKAGE_NAME)) === packageDir) {
1791
+ return { layout: 'pnpm', pnpmHome: pnpmHomeOf(groupRoot) };
1792
+ }
1793
+ }
1794
+ catch {
1795
+ // The logical group cannot be verified; do not choose another home.
1796
+ }
1797
+ return { layout: 'unknown', pnpmHome: undefined };
1798
+ }
1799
+ const binHome = binPath === undefined ? undefined : pnpmHomeOfBin(binPath, packageDir);
1800
+ if (binHome !== undefined)
1801
+ return { layout: 'pnpm', pnpmHome: binHome };
1802
+ // A store link must never enter the npm file-copy path. Without its owning
1803
+ // global group the subsequent installer step will refuse it as unresolved.
1804
+ if (/[\\/]v\d+[\\/]links[\\/]/u.test(packageDir))
1805
+ return { layout: 'pnpm', pnpmHome: undefined };
1806
+ if (/[\\/]\.pnpm[\\/]/u.test(packageDir))
1807
+ return { layout: 'unknown', pnpmHome: undefined };
1808
+ return { layout: isNpmGlobalPackageDir(packageDir, platform) ? 'npm' : 'unknown', pnpmHome: undefined };
1809
+ }
1810
+ /** Describe one launcher bin path, or undefined when it is not this package. */
1811
+ function describeLauncher(binPath, platform = process.platform) {
1812
+ const packageDir = launcherTargetDir(binPath);
1813
+ if (packageDir === undefined)
1814
+ return undefined;
1815
+ return {
1816
+ binPath,
1817
+ packageDir,
1818
+ version: launcherManifest(packageDir)?.version,
1819
+ ...launcherLayout(packageDir, binPath, platform),
1820
+ };
1821
+ }
1822
+ /** Each command name has its own PATH lookup; extensions are variants of it. */
1823
+ function launcherBinNames(platform) {
1824
+ return ['dsh-tui', 'dst'].map(name => platform === 'win32' ? [`${name}.cmd`, `${name}.ps1`, name] : [name]);
1825
+ }
1826
+ /**
1827
+ * Find the global launcher this process runs under. New shims export their
1828
+ * own bin path. Older shims export only a version, not the invoked alias:
1829
+ * each alias must resolve to the same package at exactly that version, or
1830
+ * the installation is ambiguous and must remain untouched.
1831
+ *
1832
+ * @returns the located launcher, or undefined (no launcher / can't prove which).
1833
+ */
1834
+ export function resolveGlobalLauncherTarget(env = process.env, platform = process.platform) {
1835
+ const explicit = env[GLOBAL_LAUNCHER_PATH_ENV];
1836
+ if (explicit !== undefined && explicit !== '')
1837
+ return describeLauncher(explicit, platform);
1838
+ const expected = env[GLOBAL_LAUNCHER_VERSION_ENV];
1839
+ if (expected === undefined || valid(expected) === null)
1840
+ return undefined;
1841
+ const dirs = (env.PATH ?? env.Path ?? '').split(delimiter).filter(dir => dir !== '');
1842
+ let selected;
1843
+ for (const names of launcherBinNames(platform)) {
1844
+ const candidate = dirs.flatMap(dir => names.map(name => join(dir, name))).find(path => existsSync(path));
1845
+ if (candidate === undefined)
1846
+ continue;
1847
+ const target = describeLauncher(candidate, platform);
1848
+ if (target?.version !== expected || target.packageDir === undefined)
1849
+ return undefined;
1850
+ if (selected !== undefined && selected.packageDir !== target.packageDir)
1851
+ return undefined;
1852
+ selected ??= target;
1853
+ }
1854
+ return selected;
1855
+ }
1856
+ /** The launcher package this process was loaded from (undefined in source layouts). */
1857
+ function ownLauncherPackageDir() {
1858
+ const here = dirname(fileURLToPath(import.meta.url));
1859
+ for (const relativePath of ['../..', '..']) {
1860
+ try {
1861
+ const candidate = resolve(here, relativePath);
1862
+ if (launcherManifest(candidate) !== undefined)
1863
+ return realpathSync(candidate);
1864
+ }
1865
+ catch {
1866
+ // The compiled-package layout may be missing in a source checkout.
1867
+ }
1868
+ }
1869
+ return undefined;
1870
+ }
1871
+ /**
1872
+ * The launcher bin this process was started from, when argv[1] really is one.
1873
+ * The historical contract only trusted a `dsh-tui.js` argv[1]: a
1874
+ * `dsh --profile` boot has dsh's own bin there, and a real install's package
1875
+ * may sit beside a global dsh-tui that is NOT the launcher of this chain.
1876
+ */
1877
+ function launcherArgvBin() {
1878
+ const path = process.argv[1];
1879
+ if (path === undefined || path === '')
1880
+ return undefined;
1881
+ try {
1882
+ return basename(realpathSync(path)) === 'dsh-tui.js' ? path : undefined;
1883
+ }
1884
+ catch {
1885
+ return undefined;
1886
+ }
1887
+ }
1553
1888
  /**
1554
1889
  * Best-effort migrate the GLOBAL launcher to the delegating shim (0.8.7):
1555
1890
  * after a successful profile update, copy this package's `bin/dsh-tui.js`
@@ -1559,23 +1894,37 @@ export function removeStalePackageInstall(profile) {
1559
1894
  * from lib/ (see its header), so overwriting it inside an older global
1560
1895
  * install cannot dangle a missing helper.
1561
1896
  *
1562
- * Locating the global dir relies on argv[1] being the global `dsh-tui.js`
1563
- * (true when booted through the `dsh-tui` command). Source checkouts and
1564
- * direct `dsh --profile` boots resolve nothing — the migration is a silent
1565
- * no-op there. Write failures (permissions, locked files) are equally
1566
- * silent: the launcher-alignment warning remains the fallback diagnosis.
1897
+ * The destination is given explicitly by /update (issue #1844: inside the TUI
1898
+ * argv[1] is the profile copy, so the old argv[1] rule could never find the
1899
+ * global install). Without an argument the historical argv[1] behaviour is
1900
+ * kept for callers that run in the launcher's own process.
1901
+ *
1902
+ * Never downgrades: a destination at or ahead of this copy stays untouched
1903
+ * (only an unreadable version is repaired, since it cannot be proven newer).
1904
+ * Source checkouts, `npm link` targets and direct `dsh --profile` boots
1905
+ * resolve nothing — the migration is a silent no-op there. Write failures
1906
+ * (permissions, locked files) are equally silent: the launcher-alignment
1907
+ * warning remains the fallback diagnosis.
1567
1908
  *
1909
+ * @param target - Launcher bin path or package dir; defaults to argv[1].
1568
1910
  * @returns true when the global launcher files were replaced.
1569
1911
  */
1570
- export function migrateGlobalLauncher() {
1571
- const launcherBin = process.argv[1];
1572
- if (launcherBin === undefined || !launcherBin.endsWith('dsh-tui.js'))
1912
+ export function migrateGlobalLauncher(target) {
1913
+ const launcherBin = target ?? launcherArgvBin();
1914
+ if (launcherBin === undefined)
1915
+ return false;
1916
+ // Accept it only when it is OUR package and not the copy we are running
1917
+ // from (junction layouts collapse both onto the same real path — copying
1918
+ // onto ourselves would be a no-op at best).
1919
+ const destination = launcherTargetDir(launcherBin);
1920
+ if (destination === undefined)
1921
+ return false;
1922
+ // pnpm keeps installs in a store behind symlinks; replacing files there
1923
+ // desyncs the next install, so only a manager-driven update is allowed.
1924
+ // Reuse the one layout classifier instead of a second copy of its patterns:
1925
+ // a layout added to `launcherLayout` must not leave this write guard behind.
1926
+ if (launcherLayout(destination, launcherBin).layout !== 'npm')
1573
1927
  return false;
1574
- // Walk up from the bin to the containing package; accept it only when it
1575
- // is OUR package and not the profile copy we are running from (junction
1576
- // layouts collapse both onto the same real path — copying onto ourselves
1577
- // would be a no-op at best).
1578
- let dir = dirname(resolve(launcherBin));
1579
1928
  const here = dirname(fileURLToPath(import.meta.url));
1580
1929
  let own;
1581
1930
  // These are the same two layouts accepted by installedTuiVersion(). Read
@@ -1585,13 +1934,16 @@ export function migrateGlobalLauncher() {
1585
1934
  const candidate = resolve(here, relativePath);
1586
1935
  const manifest = readFileSync(join(candidate, 'package.json'));
1587
1936
  const parsed = JSON.parse(manifest.toString('utf8'));
1588
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)
1589
- || parsed.name !== PACKAGE_NAME)
1937
+ if (!isRecord(parsed) || parsed.name !== PACKAGE_NAME)
1938
+ continue;
1939
+ const version = typeof parsed.version === 'string' ? valid(parsed.version) : null;
1940
+ // Without a comparable version the downgrade rule cannot be honoured.
1941
+ if (version === null)
1590
1942
  continue;
1591
1943
  const bin = readFileSync(join(candidate, 'bin', 'dsh-tui.js'));
1592
1944
  if (bin.length === 0)
1593
1945
  continue;
1594
- own = { dir: realpathSync(candidate), bin, manifest };
1946
+ own = { dir: realpathSync(candidate), bin, manifest, version };
1595
1947
  break;
1596
1948
  }
1597
1949
  catch {
@@ -1600,123 +1952,1273 @@ export function migrateGlobalLauncher() {
1600
1952
  }
1601
1953
  if (!own)
1602
1954
  return false;
1603
- for (let depth = 0; depth < 4; depth++) {
1604
- const manifest = join(dir, 'package.json');
1955
+ // Fail closed when the real paths cannot establish distinct roots.
1956
+ if (own.dir === destination)
1957
+ return false;
1958
+ const destinationVersion = launcherManifest(destination)?.version;
1959
+ if (destinationVersion !== undefined && !isVersionNewer(own.version, destinationVersion))
1960
+ return false;
1961
+ try {
1962
+ // Each rename is atomic, not the pair. A partial migration returns false
1963
+ // and can be retried; the standalone bin is safe in either case. The
1964
+ // destination's mode is carried onto the staged file: a fresh inode would
1965
+ // otherwise land as 0644 under the default umask, and the npm bin symlink
1966
+ // pointing here would stop being executable (EACCES on the next launch).
1967
+ const replace = (path, content, fallbackMode) => {
1968
+ const staged = `${path}.dsh-tui-migrate`;
1969
+ let mode = fallbackMode;
1970
+ try {
1971
+ mode = statSync(path).mode & 0o777;
1972
+ }
1973
+ catch {
1974
+ // Missing destination: the caller's fallback is the contract.
1975
+ }
1976
+ writeFileSync(staged, content, { mode });
1977
+ // writeFileSync filters the mode through umask; restore the exact bits
1978
+ // before the atomic rename so the executable bit cannot be lost.
1979
+ if (process.platform !== 'win32')
1980
+ chmodSync(staged, mode);
1981
+ renameSync(staged, path);
1982
+ };
1983
+ replace(join(destination, 'bin', 'dsh-tui.js'), own.bin, 0o755);
1984
+ replace(join(destination, 'package.json'), own.manifest, 0o644);
1985
+ return true;
1986
+ }
1987
+ catch {
1988
+ // Keep the alignment warning as the permission/locked-file fallback.
1989
+ return false;
1990
+ }
1991
+ }
1992
+ /**
1993
+ * pnpm flags every launcher (re)install carries, executed and printed alike.
1994
+ *
1995
+ * A GLOBAL install of the launcher has no use for its peers: every
1996
+ * `@deepseek-ai/*` peer is provided by the profile at runtime (the global copy
1997
+ * is a shim that delegates there), while pnpm's peer auto-install chases them
1998
+ * into the `@deepseek-ai/*` packages themselves, whose peer ranges point at a
1999
+ * stable 0.1.x line that is not published. The result is
2000
+ * `ERR_PNPM_NO_MATCHING_VERSION` on every attempt — so a peer-less install is
2001
+ * the only shape that works on a real registry (#1847 review). This flag is
2002
+ * safe only for a launcher-only group: applying it to other CLIs can remove
2003
+ * their required auto-installed peers. npm uses `--legacy-peer-deps`.
2004
+ */
2005
+ const PNPM_LAUNCHER_FLAGS = ['--config.auto-install-peers=false'];
2006
+ /**
2007
+ * The child environment that makes `pnpm add -g` land in `pnpmHome`: PNPM_HOME
2008
+ * itself, plus the home's own bin directories APPENDED to PATH. pnpm refuses a
2009
+ * global install whose bin dir is not on PATH
2010
+ * (`ERR_PNPM_GLOBAL_BIN_DIR_NOT_IN_PATH`) — exactly the state of a process that
2011
+ * inherited no pnpm shell setup (a desktop launcher or cron), which is the case
2012
+ * the shim-derived home exists for. Appending rather than prepending keeps the
2013
+ * user's own pnpm resolution in charge.
2014
+ */
2015
+ function pnpmHomeEnv(env, pnpmHome) {
2016
+ const key = env.PATH === undefined && env.Path !== undefined ? 'Path' : 'PATH';
2017
+ const current = env[key];
2018
+ const dirs = [join(pnpmHome, 'bin'), pnpmHome];
2019
+ return {
2020
+ PNPM_HOME: pnpmHome,
2021
+ [key]: current === undefined || current === '' ? dirs.join(delimiter) : [current, ...dirs].join(delimiter),
2022
+ };
2023
+ }
2024
+ /** The manual launcher command for a layout (the documented fallback, §10). */
2025
+ function launcherManualCommand(layout, version, specs, pnpmHome) {
2026
+ if (layout === 'npm')
2027
+ return `npm install -g --legacy-peer-deps ${PACKAGE_NAME}@${version}`;
2028
+ // Only a proven launcher-only group has a safe one-shot repair command.
2029
+ // Rebuilding a larger group with launcher-specific peer suppression can
2030
+ // break its other CLIs even when their direct versions stay unchanged.
2031
+ const add = `pnpm add -g ${PNPM_LAUNCHER_FLAGS.join(' ')}`;
2032
+ // Pin the owner home the automated install used: an inherited PNPM_HOME may
2033
+ // belong to a different global install, and repairing that one leaves the
2034
+ // launcher this profile runs untouched (#1849 review R3).
2035
+ const env = pnpmHome === undefined
2036
+ ? PNPM_RELEASE_AGE_ENV
2037
+ : { ...PNPM_RELEASE_AGE_ENV, PNPM_HOME: pnpmHome };
2038
+ return specs !== undefined
2039
+ ? `${shellEnvPrefix(env)}${add} ${specs.join(',')}`
2040
+ : `pnpm list -g --depth 0\n Inspect the install group before aligning ${PACKAGE_NAME}@${version}. Preserve every member and its installed peers; use a separate global prefix if reinstalling the launcher alone.`;
2041
+ }
2042
+ /**
2043
+ * Locate the pnpm global group whose `node_modules` realpath is `packageDir`.
2044
+ * The bin path usually names the group directly; this walk covers older
2045
+ * shims and the Windows `.cmd` layout, where only the package realpath is
2046
+ * known. Bounded to the global slots pnpm itself creates.
2047
+ */
2048
+ function findPnpmGroupRoot(pnpmHome, packageDir) {
2049
+ let slots;
2050
+ try {
2051
+ slots = readdirSync(join(pnpmHome, 'global')).filter(name => /^v?\d+$/u.test(name)).slice(0, 8);
2052
+ }
2053
+ catch {
2054
+ return undefined;
2055
+ }
2056
+ for (const slot of slots) {
2057
+ const slotDir = join(pnpmHome, 'global', slot);
2058
+ const candidates = [slotDir];
1605
2059
  try {
1606
- const parsed = JSON.parse(readFileSync(manifest, 'utf8'));
1607
- if (parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed)
1608
- && parsed.name === PACKAGE_NAME) {
1609
- try {
1610
- // Fail closed when the real paths cannot establish distinct roots.
1611
- if (realpathSync(dir) === own.dir)
1612
- return false;
1613
- // Each rename is atomic, not the pair. A partial migration returns
1614
- // false and can be retried; the standalone bin is safe in either case.
1615
- const replace = (target, content) => {
1616
- const staged = `${target}.dsh-tui-migrate`;
1617
- writeFileSync(staged, content);
1618
- renameSync(staged, target);
1619
- };
1620
- replace(join(dir, 'bin', 'dsh-tui.js'), own.bin);
1621
- replace(manifest, own.manifest);
1622
- return true;
1623
- }
1624
- catch {
1625
- // Keep the alignment warning as the permission/locked-file fallback.
1626
- return false;
1627
- }
2060
+ for (const name of readdirSync(slotDir)) {
2061
+ if (name !== 'node_modules' && candidates.length < 9)
2062
+ candidates.push(join(slotDir, name));
1628
2063
  }
1629
2064
  }
1630
2065
  catch {
1631
- // Unreadable manifest at this level — keep walking up.
2066
+ continue;
2067
+ }
2068
+ for (const root of candidates) {
2069
+ try {
2070
+ if (realpathSync(join(root, 'node_modules', PACKAGE_NAME)) === packageDir)
2071
+ return root;
2072
+ }
2073
+ catch {
2074
+ // Not this group.
2075
+ }
1632
2076
  }
1633
- const parent = dirname(dir);
1634
- if (parent === dir)
1635
- return false;
1636
- dir = parent;
1637
2077
  }
1638
- return false;
2078
+ return undefined;
1639
2079
  }
1640
2080
  /**
1641
- * Install-only half of `/update`: run `dsh plugin add`, refuse boot-deadlock
1642
- * targets, verify the profile actually advanced, and migrate the global
1643
- * launcher. No restart — `updateTuiAndRestart` layers the session-preserving
1644
- * restart on top, and the `dsh-tui update` CLI stops here.
2081
+ * A dependency spec that can be re-created from the registry by package name
2082
+ * and version. Dist-tags, aliases (`npm:`), local links (`file:`/`link:`),
2083
+ * Git and tarball sources are not reproducible from the install state, so a
2084
+ * group containing one cannot be rebuilt safely.
2085
+ */
2086
+ function isRegistryVersionSpec(spec) {
2087
+ return typeof spec === 'string' && spec.trim() !== '' && validRange(spec) !== null;
2088
+ }
2089
+ /**
2090
+ * The install spec for a proven launcher-only pnpm global group.
2091
+ * `pnpm add -g` replaces the whole group (pnpm 11+), and re-adding siblings
2092
+ * without auto-installing peers cannot preserve their runtime dependencies.
2093
+ * Multi-member or unprovable groups stay untouched instead of reconstructing
2094
+ * a dependency closure from their direct package versions.
2095
+ */
2096
+ function pnpmGroupSpecs(target, version) {
2097
+ const groupRoot = pnpmGlobalGroupRoot(target.binPath)
2098
+ ?? (target.packageDir === undefined ? undefined : pnpmGlobalGroupRoot(target.packageDir))
2099
+ ?? (target.pnpmHome === undefined || target.packageDir === undefined
2100
+ ? undefined
2101
+ : findPnpmGroupRoot(target.pnpmHome, target.packageDir));
2102
+ if (groupRoot === undefined)
2103
+ return undefined;
2104
+ try {
2105
+ const parsed = JSON.parse(readFileSync(join(groupRoot, 'package.json'), 'utf8'));
2106
+ if (!isRecord(parsed) || !isRecord(parsed.dependencies))
2107
+ return undefined;
2108
+ const names = Object.keys(parsed.dependencies);
2109
+ if (names.length !== 1 || names[0] !== PACKAGE_NAME)
2110
+ return undefined;
2111
+ // A local, alias, Git or tarball source is not a registry install we may
2112
+ // replace by name, even when it is the group's only direct dependency.
2113
+ if (!isRegistryVersionSpec(parsed.dependencies[PACKAGE_NAME]))
2114
+ return undefined;
2115
+ return [`${PACKAGE_NAME}@${version}`];
2116
+ }
2117
+ catch {
2118
+ return undefined;
2119
+ }
2120
+ }
2121
+ /**
2122
+ * Align the global launcher with this (already updated) profile copy.
1645
2123
  *
1646
- * @param profile - The dsh profile to update.
1647
- * @param targetVersion - Exact version from the preflight registry check, or
1648
- * undefined when that check failed and pnpm should resolve latest.
1649
- * @returns The update exit code plus the before/after versions.
2124
+ * npm layouts get the atomic file overwrite `migrateGlobalLauncher` has always
2125
+ * done. pnpm installs are updated with `pnpm add -g`: their bin is a shim over
2126
+ * the store, and writing through the store's symlinks would corrupt the next
2127
+ * install's bookkeeping.
2128
+ *
2129
+ * Returns a printable repair command on failure. The caller decides whether
2130
+ * restarting is safe: after an engine advance, the old launcher may no longer
2131
+ * compose the updated profile (#1849 review R5).
2132
+ *
2133
+ * @param ownVersion - Version this profile now runs; the launcher target.
2134
+ * @param options - Environment override and cancellation signal.
2135
+ * @returns What happened, for the caller's message.
1650
2136
  */
1651
- export async function updateTui(profile, targetVersion, signal) {
1652
- // Stamp the pre-update version BEFORE pnpm runs: it reads this package's
1653
- // manifest from disk, which the update replaces on the fly — a
1654
- // post-update read already sees the NEW version, and the restarted
1655
- // process then compares new-vs-new and false-alarms "version did not
1656
- // advance" on every successful update (issue #307's screenshots).
1657
- const updatedFrom = installedTuiVersion() ?? '';
1658
- if (signal?.aborted)
1659
- return { code: 130, updatedFrom };
1660
- if (isStandaloneRuntime()) {
1661
- const target = await resolveTuiUpdateTarget(signal);
1662
- if (signal?.aborted)
1663
- return { code: 130, updatedFrom };
1664
- const latestVersion = targetVersion ?? (target.kind === 'update' ? target.latest : undefined);
1665
- const downloadUrl = (target.kind === 'update' && target.downloadUrl)
1666
- ? target.downloadUrl
1667
- : (latestVersion ? `https://github.com/${GITHUB_REPO}/releases/download/v${latestVersion}/${getStandaloneAssetName()}` : undefined);
1668
- const checksumUrl = target.kind === 'update' ? target.checksumUrl : undefined;
1669
- if (downloadUrl === undefined || latestVersion === undefined) {
1670
- process.stderr.write('dsh-tui: 无法解析便携包更新下载地址\n');
1671
- return { code: 1, updatedFrom };
1672
- }
1673
- process.stderr.write(`dsh-tui: 正在更新便携包 (${updatedFrom || 'current'} → ${latestVersion})…\n`);
1674
- const result = await downloadAndReplaceStandaloneBinary(downloadUrl, msg => {
1675
- process.stderr.write(`dsh-tui: ${msg}\n`);
1676
- }, checksumUrl, { signal });
1677
- if (signal?.aborted)
1678
- return { code: 130, updatedFrom };
1679
- if (!result.success) {
1680
- process.stderr.write(`dsh-tui: 便携包更新失败: ${result.error ?? '未知错误'}\n`);
1681
- return { code: 1, updatedFrom };
1682
- }
1683
- return { code: 0, updatedFrom, installed: latestVersion };
2137
+ export async function alignGlobalLauncher(ownVersion = installedTuiVersion(), options = {}) {
2138
+ const env = options.env ?? process.env;
2139
+ if (env[UPDATE_LAUNCHER_ENV] === '0')
2140
+ return { kind: 'none', reason: 'disabled' };
2141
+ // Launchers >= 0.19.0 export their own bin path; 0.8.3–0.18.0 export only the
2142
+ // version (PATH fallback). With neither marker (an older shim, or the
2143
+ // headless CLI's own process) argv[1] IS the launcher bin — the historical
2144
+ // contract, and `launcherArgvBin` refuses anything else (a `dsh --profile`
2145
+ // boot's dsh bin, say) so a neighbouring global dsh-tui is never rewritten
2146
+ // by a launch that never went through it.
2147
+ const marked = env[GLOBAL_LAUNCHER_PATH_ENV] !== undefined || env[GLOBAL_LAUNCHER_VERSION_ENV] !== undefined;
2148
+ let target;
2149
+ if (marked) {
2150
+ target = resolveGlobalLauncherTarget(env);
1684
2151
  }
1685
- const dsh = process.platform === 'win32' ? 'dsh.cmd' : 'dsh';
1686
- const updateArgs = tuiUpdatePluginArgs(profile, targetVersion);
1687
- // pnpm ≥11 hard-fails installs whose dependency tree carries un-allowlisted
1688
- // build scripts (ERR_PNPM_IGNORED_BUILDS). The host's pi-ai adapter pulls in
1689
- // postinstall-only deps (@google/genai/protobufjs), so pre-seed
1690
- // the profile workspace with explicit `false` entries before pnpm runs.
1691
- const allowBuilds = ensureProfileAllowBuilds(profile);
1692
- if (allowBuilds !== undefined && allowBuilds.added.length > 0) {
1693
- process.stderr.write(`dsh-tui: pre-seeded profile pnpm allowBuilds (${allowBuilds.added.join(', ')}) — ` +
1694
- 'postinstall-only deps are explicitly ignored\n');
2152
+ else {
2153
+ const argvBin = launcherArgvBin();
2154
+ target = argvBin === undefined ? undefined : describeLauncher(argvBin);
1695
2155
  }
1696
- // Foreign-platform natives are pure download waste (sharp ~90MB, the Claude
1697
- // SDK's bundles ~1.6GB on the maintainer report); keep the profile's ignore
1698
- // list matching THIS machine (each update recomputes it) so pnpm never
1699
- // fetches them. The SDK is never ADDED here — it only enters a profile
1700
- // through the kernel picker's guided install, and then only for the
1701
- // platform it runs on.
1702
- const platformFilter = ensureProfilePlatformFilter(profile);
1703
- if (platformFilter !== undefined && platformFilter.changed) {
1704
- process.stderr.write(`dsh-tui: platform filter updated (${platformFilter.entries.length} foreign-platform patterns ignored) — ` +
1705
- `this profile's install keeps only the current platform's natives\n`);
2156
+ const targetVersion = ownVersion === undefined ? null : valid(ownVersion);
2157
+ if (target === undefined || targetVersion === null)
2158
+ return { kind: 'none', reason: 'unresolved' };
2159
+ // Running from the launcher's own process (headless `dsh-tui update` invoked
2160
+ // from the profile copy, or a source checkout): there is no second install.
2161
+ if (target.packageDir !== undefined && target.packageDir === ownLauncherPackageDir()) {
2162
+ return { kind: 'none', reason: 'absent' };
1706
2163
  }
1707
- // pnpm ≥11's minimumReleaseAge (24h by default) refuses installs of
1708
- // packages published within the window — on release day that gate rejects
1709
- // the exact version /update pins, surfacing as a failed update that heals
1710
- // itself a day later. Two releases inside the window (issue #1205) trip the
1711
- // same gate on the OLD lockfile entry pnpm verifies before the swap, so
1712
- // both the target and the still-installed updatedFrom are exempted.
1713
- if (targetVersion !== undefined) {
1714
- const releaseAge = ensureProfileReleaseAgeExclude(profile, targetVersion, updatedFrom === '' ? undefined : updatedFrom);
1715
- if (releaseAge !== undefined && releaseAge.changed) {
1716
- const exempted = updatedFrom !== '' && updatedFrom !== targetVersion
1717
- ? `${PACKAGE_NAME}@${targetVersion} || ${updatedFrom}`
1718
- : `${PACKAGE_NAME}@${targetVersion}`;
1719
- process.stderr.write(`dsh-tui: pre-seeded profile release-age exclusion (${exempted}) — ` +
2164
+ if (target.version === targetVersion)
2165
+ return { kind: 'none', reason: 'aligned' };
2166
+ // Never downgrade: an install ahead of this copy is the user's explicit
2167
+ // choice (a newer line); only report the drift.
2168
+ if (target.version !== undefined && !isVersionNewer(targetVersion, target.version)) {
2169
+ return { kind: 'none', reason: 'newer' };
2170
+ }
2171
+ // A project-local pnpm (or dlx) install: neither a file copy nor a global
2172
+ // pnpm install would touch the copy that actually runs.
2173
+ if (target.layout === 'unknown')
2174
+ return { kind: 'none', reason: 'unresolved' };
2175
+ if (options.signal?.aborted)
2176
+ return { kind: 'none', reason: 'cancelled' };
2177
+ if (target.layout === 'pnpm') {
2178
+ // The launcher-specific peer flags are safe only for a proven singleton
2179
+ // group. Leave every multi-member or unprovable group untouched rather
2180
+ // than silently removing a sibling CLI or one of its required peers.
2181
+ const specs = pnpmGroupSpecs(target, targetVersion);
2182
+ const command = launcherManualCommand('pnpm', targetVersion, specs, target.pnpmHome);
2183
+ if (specs === undefined)
2184
+ return { kind: 'failed', reason: 'unresolved', version: targetVersion, command };
2185
+ let cancelled = false;
2186
+ let cleanupUnconfirmed = false;
2187
+ const code = await runProcess('pnpm', ['add', '-g', ...PNPM_LAUNCHER_FLAGS, specs.join(',')], {
2188
+ shell: process.platform === 'win32',
2189
+ category: 'launcher-install',
2190
+ env: {
2191
+ ...env,
2192
+ ...PNPM_RELEASE_AGE_ENV,
2193
+ ...(target.pnpmHome === undefined ? {} : pnpmHomeEnv(env, target.pnpmHome)),
2194
+ },
2195
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
2196
+ onCancel: () => { cancelled = true; },
2197
+ onCleanupError: () => { cleanupUnconfirmed = true; },
2198
+ });
2199
+ // A surviving installer may still rewrite the global install; never let
2200
+ // the update claim success or restart over it, even if the exit code
2201
+ // looked clean.
2202
+ if (cleanupUnconfirmed) {
2203
+ return { kind: 'failed', reason: 'install', version: targetVersion, command, cleanupUnconfirmed: true };
2204
+ }
2205
+ // A cancelled install is not a failure to report a repair command for. The
2206
+ // exit code alone cannot tell the two apart (an installer may exit 130 on
2207
+ // its own), so only the runner's own stop event counts.
2208
+ if (cancelled)
2209
+ return { kind: 'none', reason: 'cancelled' };
2210
+ if (code !== 0)
2211
+ return { kind: 'failed', reason: 'install', version: targetVersion, command };
2212
+ return { kind: 'installed', reason: 'install', version: targetVersion };
2213
+ }
2214
+ const command = launcherManualCommand('npm', targetVersion);
2215
+ if (target.packageDir === undefined)
2216
+ return { kind: 'failed', reason: 'unresolved', command };
2217
+ return migrateGlobalLauncher(target.packageDir)
2218
+ ? { kind: 'copied', reason: 'copy', version: targetVersion }
2219
+ : { kind: 'failed', reason: 'copy', version: targetVersion, command };
2220
+ }
2221
+ /**
2222
+ * The launcher generation marker the replacement process should carry after
2223
+ * this update: the one it inherited describes the OUTER shim that started this
2224
+ * chain, which this update may just have brought up to date. Only a completed
2225
+ * copy/install counts — a skipped or failed step leaves the inherited value
2226
+ * alone so the boot-time warning stays truthful (#1844 review).
2227
+ *
2228
+ * @param launcher - The launcher step's outcome, when it ran.
2229
+ * @returns Marker overrides for `restartChildEnv`.
2230
+ */
2231
+ export function launcherRestartEnv(launcher) {
2232
+ if (launcher === undefined || launcher.version === undefined)
2233
+ return {};
2234
+ if (launcher.kind !== 'copied' && launcher.kind !== 'installed')
2235
+ return {};
2236
+ const env = { [GLOBAL_LAUNCHER_VERSION_ENV]: launcher.version };
2237
+ // pnpm re-creates the global slot on every install (verified on 11.21.0:
2238
+ // `global/v11/6-…` becomes `7-…` and the old slot is pruned), so the bin
2239
+ // path this chain inherited now points at a deleted directory. Blank it:
2240
+ // the resolver treats "" as "no explicit path" and re-locates the launcher
2241
+ // through PATH, where the refreshed version marker must match exactly.
2242
+ if (launcher.kind === 'installed')
2243
+ env[GLOBAL_LAUNCHER_PATH_ENV] = '';
2244
+ return env;
2245
+ }
2246
+ /** Read one installed package's version without throwing. */
2247
+ function readPackageVersion(dir) {
2248
+ try {
2249
+ const parsed = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
2250
+ if (!isRecord(parsed) || typeof parsed.version !== 'string')
2251
+ return undefined;
2252
+ return valid(parsed.version) ?? undefined;
2253
+ }
2254
+ catch {
2255
+ return undefined;
2256
+ }
2257
+ }
2258
+ /** The host's declared JS entry, confined to its real package directory. */
2259
+ function hostPackageEntry(dir) {
2260
+ try {
2261
+ const parsed = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
2262
+ if (!isRecord(parsed) || parsed.name !== UPSTREAM_HOST_PACKAGE || !isRecord(parsed.bin))
2263
+ return undefined;
2264
+ const entry = parsed.bin.dsh;
2265
+ if (typeof entry !== 'string' || entry === '')
2266
+ return undefined;
2267
+ const root = realpathSync(dir);
2268
+ const candidate = resolve(root, entry);
2269
+ if (!candidate.startsWith(root + sep))
2270
+ return undefined;
2271
+ const resolved = realpathSync(candidate);
2272
+ return resolved.startsWith(root + sep) ? resolved : undefined;
2273
+ }
2274
+ catch {
2275
+ return undefined;
2276
+ }
2277
+ }
2278
+ /**
2279
+ * Positive loadability proof for an installed host package: start its declared
2280
+ * `bin.dsh` entry in a fresh node process and require `--version` to exit 0.
2281
+ * Neither a readable manifest nor an existing entry proves its dependencies
2282
+ * survived an interrupted install. Replacement selection additionally requires
2283
+ * the reported version to match `expectedVersion` when supplied.
2284
+ */
2285
+ function hostPackageRuns(dir, env, expectedVersion) {
2286
+ const entry = hostPackageEntry(dir);
2287
+ if (entry === undefined)
2288
+ return false;
2289
+ try {
2290
+ const output = execFileSync(process.execPath, [entry, '--version'], {
2291
+ encoding: 'utf8', timeout: 15000, env, stdio: ['ignore', 'pipe', 'ignore'],
2292
+ });
2293
+ if (expectedVersion === undefined)
2294
+ return true;
2295
+ const match = /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/u.exec(output);
2296
+ return match !== null && valid(match[1]) === expectedVersion;
2297
+ }
2298
+ catch {
2299
+ return false;
2300
+ }
2301
+ }
2302
+ /** A replacement must belong to the original npm install or its rotated pnpm group. */
2303
+ function sameHostInstall(original, candidate) {
2304
+ if (original.installer !== candidate.installer)
2305
+ return false;
2306
+ if (original.installer === 'npm') {
2307
+ return original.prefix !== undefined && original.prefix === candidate.prefix
2308
+ && original.packageDir === candidate.packageDir;
2309
+ }
2310
+ if (original.installer !== 'pnpm' || original.pnpmHome === undefined
2311
+ || candidate.pnpmHome === undefined || candidate.groupRoot === undefined)
2312
+ return false;
2313
+ try {
2314
+ if (realpathSync(original.pnpmHome) !== realpathSync(candidate.pnpmHome))
2315
+ return false;
2316
+ const manifest = JSON.parse(readFileSync(join(candidate.groupRoot, 'package.json'), 'utf8'));
2317
+ return isRecord(manifest) && isRecord(manifest.dependencies)
2318
+ && Object.keys(manifest.dependencies).length === 1
2319
+ && Object.hasOwn(manifest.dependencies, UPSTREAM_HOST_PACKAGE)
2320
+ && realpathSync(join(candidate.groupRoot, 'node_modules', UPSTREAM_HOST_PACKAGE)) === candidate.packageDir;
2321
+ }
2322
+ catch {
2323
+ return false;
2324
+ }
2325
+ }
2326
+ /** This package's installed directory (compiled package or source checkout). */
2327
+ function installedTuiPackageDir() {
2328
+ const here = dirname(fileURLToPath(import.meta.url));
2329
+ for (const relativePath of ['../..', '..']) {
2330
+ const candidate = resolve(here, relativePath);
2331
+ try {
2332
+ const parsed = JSON.parse(readFileSync(join(candidate, 'package.json'), 'utf8'));
2333
+ if (isRecord(parsed) && parsed.name === PACKAGE_NAME)
2334
+ return candidate;
2335
+ }
2336
+ catch {
2337
+ // Try the next layout.
2338
+ }
2339
+ }
2340
+ return undefined;
2341
+ }
2342
+ /**
2343
+ * The profile's `@deepseek-ai/dsh` directory, read straight from disk.
2344
+ *
2345
+ * `installedKernelPackageDir()` goes through `import.meta.resolve`, whose
2346
+ * result Node caches for the life of the process. After a pnpm update
2347
+ * re-points the store link, the cached URL still names the OLD (often pruned)
2348
+ * store directory, so a successful engine install would verify as failed and
2349
+ * an unloadable-engine check would read a path that no longer exists. This
2350
+ * walks the two layout candidates instead: the profile's own node_modules and
2351
+ * the shared `<DSH_HOME>/profiles/node_modules` fallback tree beside it.
2352
+ *
2353
+ * @param tuiDir - This package's directory; defaults to the running copy.
2354
+ * A seam for the regression, which builds both layouts on disk.
2355
+ * @returns The real directory of the installed host package, or undefined.
2356
+ */
2357
+ export function installedKernelDirFresh(tuiDir = installedTuiPackageDir()) {
2358
+ if (tuiDir === undefined)
2359
+ return undefined;
2360
+ const nodeModules = resolve(tuiDir, '..', '..');
2361
+ for (const candidate of [
2362
+ join(nodeModules, '@deepseek-ai', 'dsh'),
2363
+ // The shared fallback tree is a sibling of the profile directory:
2364
+ // `<DSH_HOME>/profiles/node_modules`, i.e. two levels above node_modules.
2365
+ resolve(nodeModules, '..', '..', 'node_modules', '@deepseek-ai', 'dsh'),
2366
+ ]) {
2367
+ if (readPackageVersion(candidate) === undefined)
2368
+ continue;
2369
+ try {
2370
+ return realpathSync(candidate);
2371
+ }
2372
+ catch {
2373
+ return candidate;
2374
+ }
2375
+ }
2376
+ return undefined;
2377
+ }
2378
+ /** One peer range out of a package manifest, when readable. */
2379
+ function readPeerRange(dir, peer) {
2380
+ if (dir === undefined)
2381
+ return undefined;
2382
+ try {
2383
+ const parsed = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'));
2384
+ if (!isRecord(parsed) || !isRecord(parsed.peerDependencies))
2385
+ return undefined;
2386
+ const range = parsed.peerDependencies[peer];
2387
+ return typeof range === 'string' ? range : undefined;
2388
+ }
2389
+ catch {
2390
+ return undefined;
2391
+ }
2392
+ }
2393
+ /** JSON GET with the short update-check timeout; undefined on any failure. */
2394
+ async function fetchRegistryJson(url, accept, signal) {
2395
+ if (signal?.aborted)
2396
+ return undefined;
2397
+ const controller = new AbortController();
2398
+ const timeout = setTimeout(() => controller.abort(), UPDATE_CHECK_TIMEOUT_MS);
2399
+ try {
2400
+ const response = await fetch(url, {
2401
+ headers: { accept },
2402
+ signal: signal === undefined ? controller.signal : AbortSignal.any([controller.signal, signal]),
2403
+ });
2404
+ if (!response.ok)
2405
+ return undefined;
2406
+ return await response.json();
2407
+ }
2408
+ catch {
2409
+ return undefined;
2410
+ }
2411
+ finally {
2412
+ clearTimeout(timeout);
2413
+ }
2414
+ }
2415
+ /** The peer range a specific published package version declares. */
2416
+ async function fetchPackagePeerRange(registryBase, packageName, version, peer, signal) {
2417
+ const payload = await fetchRegistryJson(`${registryBase}/${packageName}/${version}`, 'application/json', signal);
2418
+ if (!isRecord(payload) || !isRecord(payload.peerDependencies))
2419
+ return undefined;
2420
+ const range = payload.peerDependencies[peer];
2421
+ return typeof range === 'string' ? range : undefined;
2422
+ }
2423
+ /** Every published version of a package (abbreviated packument). */
2424
+ async function fetchPackageVersions(registryBase, packageName, signal) {
2425
+ const payload = await fetchRegistryJson(`${registryBase}/${packageName}`, 'application/vnd.npm.install-v1+json', signal);
2426
+ if (!isRecord(payload) || !isRecord(payload.versions))
2427
+ return undefined;
2428
+ return Object.keys(payload.versions);
2429
+ }
2430
+ /**
2431
+ * The target TUI's engine range. When the target IS the installed version the
2432
+ * local manifest answers without a network round trip (the "TUI already
2433
+ * latest, only the engine lags" case must work offline-ish and fast).
2434
+ */
2435
+ async function readTargetHostRange(registryBase, targetVersion, installedTui, signal) {
2436
+ if (installedTui !== undefined && targetVersion === installedTui) {
2437
+ return readPeerRange(installedTuiPackageDir(), UPSTREAM_HOST_PEER_PACKAGE);
2438
+ }
2439
+ return fetchPackagePeerRange(registryBase, PACKAGE_NAME, targetVersion, UPSTREAM_HOST_PEER_PACKAGE, signal);
2440
+ }
2441
+ /**
2442
+ * The host package dir when module resolution cannot see it (an exotic
2443
+ * profile layout). Loaded lazily: a normal profile resolves through
2444
+ * `installedKernelPackageDir()` and never pays for the PATH walk.
2445
+ */
2446
+ async function findHostDshPackageDir(env) {
2447
+ try {
2448
+ const { findHostDsh } = await import('./dsh-adapter/host-dsh.js');
2449
+ const located = findHostDsh(env);
2450
+ return 'packageDir' in located ? located.packageDir : undefined;
2451
+ }
2452
+ catch {
2453
+ return undefined;
2454
+ }
2455
+ }
2456
+ /** Predict the launcher step with the same resolver the alignment uses. */
2457
+ function planLauncherStep(input) {
2458
+ const env = input.env;
2459
+ if (env[UPDATE_LAUNCHER_ENV] === '0')
2460
+ return { kind: 'none', reason: 'disabled' };
2461
+ const marked = env[GLOBAL_LAUNCHER_PATH_ENV] !== undefined || env[GLOBAL_LAUNCHER_VERSION_ENV] !== undefined;
2462
+ let target;
2463
+ if (marked) {
2464
+ target = resolveGlobalLauncherTarget(env);
2465
+ }
2466
+ else {
2467
+ // The headless `dsh-tui update` process IS the launcher: argv[1] is its bin.
2468
+ const argvBin = launcherArgvBin();
2469
+ target = argvBin === undefined ? undefined : describeLauncher(argvBin);
2470
+ }
2471
+ if (target === undefined) {
2472
+ // A launch that carried neither marker and whose argv[1] is not a launcher
2473
+ // bin is a direct `dsh --profile` boot: this installation has no launcher
2474
+ // to align (plan §3.5), so it must not degrade the preflight to "idle".
2475
+ return { kind: 'none', reason: marked ? 'unresolved' : 'absent' };
2476
+ }
2477
+ if (target.packageDir !== undefined && target.packageDir === ownLauncherPackageDir()) {
2478
+ return { kind: 'none', reason: 'absent' };
2479
+ }
2480
+ if (target.version === input.targetVersion)
2481
+ return { kind: 'none', reason: 'aligned', from: target.version };
2482
+ // Never downgrade a launcher ahead of this profile (the user chose a newer line).
2483
+ if (target.version !== undefined && !isVersionNewer(input.targetVersion, target.version)) {
2484
+ return { kind: 'none', reason: 'newer', from: target.version };
2485
+ }
2486
+ if (target.packageDir === undefined || target.layout === 'unknown') {
2487
+ return { kind: 'none', reason: 'unresolved', from: target.version };
2488
+ }
2489
+ if (target.layout === 'pnpm') {
2490
+ // Match the execution path: `pnpm add -g <one package>` replaces the whole
2491
+ // isolated group, so the plan may only promise an install when every
2492
+ // member can be named (issue #1844 review R2).
2493
+ const specs = pnpmGroupSpecs(target, input.targetVersion);
2494
+ if (specs === undefined)
2495
+ return { kind: 'none', reason: 'unresolved', from: target.version };
2496
+ return {
2497
+ kind: 'install',
2498
+ version: input.targetVersion,
2499
+ from: target.version,
2500
+ command: { file: 'pnpm', args: ['add', '-g', specs.join(',')] },
2501
+ };
2502
+ }
2503
+ return { kind: 'copy', version: input.targetVersion, from: target.version, path: target.packageDir };
2504
+ }
2505
+ /**
2506
+ * Compute the whole `/update` plan without writing anything.
2507
+ *
2508
+ * Only the TUI lookup is sequential (the engine range belongs to the target
2509
+ * TUI version); the target manifest and the engine packument then run in
2510
+ * parallel, each bounded by the existing 4s update-check timeout. A failed
2511
+ * lookup degrades that layer only — it never blocks the command for longer
2512
+ * than the network allows and never fabricates a version.
2513
+ *
2514
+ * @param input - Cancellation, a pre-resolved host package dir (the entry has
2515
+ * one), an override for the installed engine version (tests), and the env.
2516
+ */
2517
+ export async function resolveUpdatePlan(input = {}) {
2518
+ const env = input.env ?? process.env;
2519
+ const tui = await resolveTuiUpdateTarget(input.signal);
2520
+ if (isStandaloneRuntime()) {
2521
+ // The portable binary carries its own runtime; engine/launcher layers do
2522
+ // not exist there (the standalone branch of updateTui keeps self-updating).
2523
+ return {
2524
+ tui,
2525
+ host: { kind: 'none', reason: 'disabled' },
2526
+ // The portable binary has no global launcher to align, so this is
2527
+ // "absent" (settled) - "disabled" would claim a switch was ignored.
2528
+ launcher: { kind: 'none', reason: 'absent' },
2529
+ compatible: undefined,
2530
+ hostRange: undefined,
2531
+ currentHost: undefined,
2532
+ blocked: false,
2533
+ };
2534
+ }
2535
+ // Without a target TUI version there is no range to plan an engine against;
2536
+ // keep the existing `--latest` fallback instead of guessing a line.
2537
+ if (tui.kind === 'unknown') {
2538
+ return {
2539
+ tui,
2540
+ host: { kind: 'none', reason: 'unknown-range' },
2541
+ launcher: { kind: 'none', reason: 'unresolved' },
2542
+ compatible: undefined,
2543
+ hostRange: undefined,
2544
+ currentHost: input.installedHost,
2545
+ blocked: false,
2546
+ };
2547
+ }
2548
+ const targetVersion = tui.kind === 'update' ? tui.latest : tui.current;
2549
+ const registryBase = resolveRegistryBase();
2550
+ const hostPackageDir = input.hostPackageDir ?? installedKernelPackageDir() ?? await findHostDshPackageDir(env);
2551
+ const install = hostPackageDir === undefined ? undefined : detectHostInstall(hostPackageDir, env);
2552
+ const currentHost = input.installedHost ?? install?.version;
2553
+ const [hostRange, available] = await Promise.all([
2554
+ readTargetHostRange(registryBase, targetVersion, installedTuiVersion(), input.signal),
2555
+ fetchPackageVersions(registryBase, UPSTREAM_HOST_PACKAGE, input.signal),
2556
+ ]);
2557
+ const host = planHostStep({
2558
+ current: currentHost,
2559
+ range: hostRange,
2560
+ available,
2561
+ install,
2562
+ packageName: UPSTREAM_HOST_PACKAGE,
2563
+ disabled: env[UPDATE_ENGINE_ENV] === '0',
2564
+ });
2565
+ const allowed = parseHostLineRange(hostRange);
2566
+ const compatible = hostCompatibility({ current: currentHost, allowed, step: host });
2567
+ // The official `dsh plugin update` validates the new TUI against the RUNNING
2568
+ // engine (`getDshRuntimeVersion()`), not against the one this plan would
2569
+ // install later. Any engine outside the target's enumerated line — below OR
2570
+ // above — is rejected there and restored before the engine step can run, so
2571
+ // promising `ready` would tear the tree down for an install that cannot
2572
+ // succeed (#1849 review R2). Strict membership, not hostCompatibility: the
2573
+ // latter keeps an ahead engine usable for the boot/restart decision.
2574
+ const currentSupported = hostSatisfiesLine({ current: currentHost, allowed });
2575
+ return {
2576
+ tui,
2577
+ host,
2578
+ launcher: planLauncherStep({ env, targetVersion }),
2579
+ compatible,
2580
+ hostRange,
2581
+ currentHost,
2582
+ blocked: tui.kind === 'update' && currentSupported === false,
2583
+ };
2584
+ }
2585
+ /** How the preflight should treat a plan (empty = nothing to do at all). */
2586
+ export function updatePlanState(plan) {
2587
+ if (plan.blocked)
2588
+ return 'blocked';
2589
+ if (plan.tui.kind === 'update'
2590
+ || plan.tui.kind === 'unknown'
2591
+ || plan.host.kind === 'install'
2592
+ || plan.launcher.kind === 'copy'
2593
+ || plan.launcher.kind === 'install')
2594
+ return 'ready';
2595
+ const hostSettled = plan.host.kind === 'none'
2596
+ && ((plan.host.reason === 'newest' && plan.host.newerPublished === undefined)
2597
+ // An engine ahead of the validated line is never downgraded, but it is
2598
+ // NOT "already aligned": the UI runs outside the range it validates, so
2599
+ // an idle notice must report that drift instead of claiming the set is
2600
+ // current (the boot drift notice says the same).
2601
+ // A disabled step that carries a target means an upgrade WOULD have run;
2602
+ // calling that "already aligned" would be a lie.
2603
+ || (plan.host.reason === 'disabled' && plan.host.to === undefined));
2604
+ const launcherSettled = plan.launcher.kind === 'none'
2605
+ && plan.launcher.reason !== 'unresolved'
2606
+ // DSH_TUI_UPDATE_LAUNCHER=0 resolved nothing: reporting the set as aligned
2607
+ // would be the same lie the engine branch above refuses to tell.
2608
+ && plan.launcher.reason !== 'disabled';
2609
+ return plan.tui.kind === 'latest' && hostSettled && launcherSettled ? 'empty' : 'idle';
2610
+ }
2611
+ /** Human layer summary, e.g. `dsh-tui 0.18.0 → 0.19.0 · dsh 0.2.1-rc.5 → 0.2.2-rc.1`. */
2612
+ export function updatePlanLayers(plan) {
2613
+ const layers = [];
2614
+ if (plan.tui.kind === 'update')
2615
+ layers.push(`dsh-tui ${plan.tui.current} → ${plan.tui.latest}`);
2616
+ // Only a step that will actually run belongs in the promise. `none` with a
2617
+ // target is a disabled or never-downgrade case: the summary must not claim
2618
+ // an engine change (and must not read like the downgrade we never do).
2619
+ if (plan.host.kind === 'install')
2620
+ layers.push(`dsh ${plan.host.from ?? '?'} → ${plan.host.to}`);
2621
+ if (plan.launcher.kind === 'copy' || plan.launcher.kind === 'install') {
2622
+ layers.push(`launcher ${plan.launcher.from ?? '?'} → ${plan.launcher.version}`);
2623
+ }
2624
+ return layers;
2625
+ }
2626
+ /** The installed set, for the "already aligned" notice. */
2627
+ export function updatePlanSuite(plan) {
2628
+ const tui = plan.tui.kind === 'latest' ? plan.tui.current : installedTuiVersion();
2629
+ return [
2630
+ tui === undefined ? undefined : `dsh-tui ${tui}`,
2631
+ plan.currentHost === undefined ? undefined : `dsh ${plan.currentHost}`,
2632
+ ].filter((part) => part !== undefined).join(' · ');
2633
+ }
2634
+ /** Why the launcher layer did not run, or undefined when it settled. */
2635
+ export function describeLauncherStepReason(step) {
2636
+ if (step.kind !== 'none')
2637
+ return undefined;
2638
+ if (step.reason === 'unresolved')
2639
+ return t('update-launcher-unresolved');
2640
+ if (step.reason === 'disabled')
2641
+ return t('update-launcher-disabled');
2642
+ return undefined;
2643
+ }
2644
+ /** Translate the engine step's state for idle and refusal copy. */
2645
+ export function describeHostStepReason(step) {
2646
+ if (step.kind === 'install')
2647
+ return t('update-host-pending');
2648
+ if (step.kind === 'none') {
2649
+ switch (step.reason) {
2650
+ case 'disabled': return t('update-host-disabled');
2651
+ case 'unknown-current': return t('update-host-unknown-current');
2652
+ case 'unknown-range': return t('update-host-unknown-range');
2653
+ case 'newer-than-validated': return t('update-host-newer');
2654
+ case 'newest':
2655
+ return step.newerPublished === undefined
2656
+ ? ''
2657
+ : t('update-host-newer-published', { newer: step.newerPublished });
2658
+ }
2659
+ }
2660
+ switch (step.reason) {
2661
+ case 'offline': return t('update-host-offline');
2662
+ case 'no-version': return t('update-host-no-version');
2663
+ case 'no-installer': return t('update-host-no-installer');
2664
+ case 'not-writable': return t('update-host-not-writable');
2665
+ case 'group-unproven': return t('update-host-group-unproven');
2666
+ }
2667
+ }
2668
+ /** The manual command a blocked or failed engine step points at. */
2669
+ export function hostStepManual(step) {
2670
+ if (step.kind === 'install')
2671
+ return step.manual[0] ?? '';
2672
+ if (step.kind === 'unavailable')
2673
+ return step.manual[0] ?? '';
2674
+ if (step.kind === 'none' && step.manual !== undefined)
2675
+ return step.manual[0] ?? '';
2676
+ return '';
2677
+ }
2678
+ /**
2679
+ * Build the full report for an idle plan whose short notice would hide the
2680
+ * actionable part: an engine release waiting for a TUI that declares support,
2681
+ * or an engine step that cannot be automated but has a repair command.
2682
+ * `offline` and `no-version` are transient lookup failures and keep the short
2683
+ * idle notice; a disabled layer is the user's own choice and must not be
2684
+ * presented as a repair task.
2685
+ *
2686
+ * @param plan - A plan whose state is `idle`.
2687
+ * @returns The report, or undefined when the short idle notice is enough.
2688
+ */
2689
+ export function idleReportMessages(plan) {
2690
+ if (plan.host.kind === 'none' && plan.host.newerPublished !== undefined) {
2691
+ return {
2692
+ title: t('update-plan-newer-title'),
2693
+ report: t('update-plan-newer', {
2694
+ tui: plan.tui.kind === 'latest' ? plan.tui.current : installedTuiVersion() ?? 'unknown',
2695
+ range: plan.hostRange ?? '?',
2696
+ newer: plan.host.newerPublished,
2697
+ }),
2698
+ toast: t('update-plan-newer-toast', { newer: plan.host.newerPublished }),
2699
+ };
2700
+ }
2701
+ if (plan.host.kind !== 'unavailable')
2702
+ return undefined;
2703
+ if (plan.host.reason !== 'group-unproven'
2704
+ && plan.host.reason !== 'not-writable'
2705
+ && plan.host.reason !== 'no-installer')
2706
+ return undefined;
2707
+ const command = hostStepManual(plan.host);
2708
+ if (command === '')
2709
+ return undefined;
2710
+ return {
2711
+ title: t('update-plan-manual-title'),
2712
+ report: t('update-plan-manual', {
2713
+ current: plan.tui.kind === 'latest' ? plan.tui.current : installedTuiVersion() ?? 'unknown',
2714
+ reason: describeHostStepReason(plan.host),
2715
+ command,
2716
+ }),
2717
+ toast: t('update-plan-manual-toast'),
2718
+ };
2719
+ }
2720
+ /**
2721
+ * Build the guidance for a ready plan whose engine step is `unavailable`.
2722
+ *
2723
+ * The TUI/launcher work still runs (the current engine is inside the target
2724
+ * line), but the engine layer was planned and could not be automated, so the
2725
+ * CLI must report it and exit non-zero instead of claiming a whole-set success.
2726
+ * Deliberately not `idleReportMessages`: that copy assumes the TUI is already
2727
+ * current, while this report is shown as the update starts.
2728
+ *
2729
+ * @param plan - A ready plan (the caller has already ruled out `blocked`/`idle`).
2730
+ * @returns The guidance, or undefined when the engine step is not `unavailable`.
2731
+ */
2732
+ export function engineSkipMessages(plan) {
2733
+ if (plan.host.kind !== 'unavailable')
2734
+ return undefined;
2735
+ const reason = describeHostStepReason(plan.host);
2736
+ const manual = plan.host.reason === 'group-unproven'
2737
+ || plan.host.reason === 'not-writable'
2738
+ || plan.host.reason === 'no-installer'
2739
+ ? hostStepManual(plan.host)
2740
+ : '';
2741
+ return {
2742
+ title: t('update-engine-skip-title', { version: plan.host.to ?? plan.currentHost ?? '?' }),
2743
+ report: manual === ''
2744
+ ? t('update-engine-skip', { reason })
2745
+ : t('update-engine-skip-manual', { reason, command: manual }),
2746
+ toast: t('update-engine-skip-toast'),
2747
+ };
2748
+ }
2749
+ /**
2750
+ * The next step for a blocked preflight, split by cause so "wait for a
2751
+ * release", "wait for a TUI that declares the newer engine", "retry the
2752
+ * lookup", "drop the switch", "align the engine first" and "repair the global
2753
+ * install" do not read as one generic refusal (#1849 review).
2754
+ */
2755
+ function blockedNextStep(step) {
2756
+ if (step.kind === 'install') {
2757
+ // The engine CAN be installed, but only before the TUI: the official
2758
+ // manager validates the new TUI against the running engine.
2759
+ return t('update-plan-blocked-next-engine-first', { command: hostStepManual(step) });
2760
+ }
2761
+ if (step.kind === 'unavailable') {
2762
+ if (step.reason === 'no-version')
2763
+ return t('update-plan-blocked-next-wait');
2764
+ if (step.reason === 'offline') {
2765
+ return t('update-plan-blocked-next-retry', { command: hostStepManual(step) });
2766
+ }
2767
+ return t('update-plan-blocked-next-repair', { command: hostStepManual(step) });
2768
+ }
2769
+ if (step.kind === 'none' && step.reason === 'newer-than-validated') {
2770
+ // The engine is ahead of the target line, not installable or downgradeable:
2771
+ // the target TUI needs a release that declares support for it, not a repair
2772
+ // command that would install an unvalidated pair.
2773
+ return t('update-plan-blocked-next-too-new');
2774
+ }
2775
+ if (step.kind === 'none' && step.reason === 'disabled') {
2776
+ return t('update-plan-blocked-next-switch', { command: hostStepManual(step) });
2777
+ }
2778
+ return t('update-plan-blocked-next-repair', { command: hostStepManual(step) });
2779
+ }
2780
+ /**
2781
+ * Build a blocked-plan refusal once, so the CLI, the stderr path and the
2782
+ * in-TUI report cannot drift. The report carries every actionable detail; the
2783
+ * toast is deliberately short because the composer renders one truncated row
2784
+ * and would otherwise hide the command behind the explanation.
2785
+ *
2786
+ * @param plan - A plan whose `blocked` flag is set.
2787
+ */
2788
+ export function blockedUpdateMessages(plan) {
2789
+ const tui = plan.tui.kind === 'update' ? plan.tui.latest : '?';
2790
+ // An installable engine that runs AFTER the TUI cannot rescue the install:
2791
+ // the refusal says "align the engine first", not "the engine cannot be
2792
+ // upgraded" (which would be false). An engine ABOVE the line has no install
2793
+ // to run at all: the next step is a TUI release that declares support.
2794
+ const engineFirst = plan.host.kind === 'install';
2795
+ const tooNew = plan.host.kind === 'none' && plan.host.reason === 'newer-than-validated';
2796
+ const key = engineFirst
2797
+ ? 'update-plan-blocked-engine-first'
2798
+ : tooNew ? 'update-plan-blocked-too-new' : 'update-plan-blocked';
2799
+ return {
2800
+ report: `${t(key, {
2801
+ tui,
2802
+ range: plan.hostRange ?? '?',
2803
+ current: plan.currentHost ?? '?',
2804
+ reason: describeHostStepReason(plan.host),
2805
+ })}\n${blockedNextStep(plan.host)}`,
2806
+ title: t(tooNew ? 'update-plan-blocked-too-new-title' : 'update-plan-blocked-title', { tui }),
2807
+ toast: t(tooNew ? 'update-plan-blocked-too-new-toast' : 'update-plan-blocked-toast', { tui }),
2808
+ };
2809
+ }
2810
+ /**
2811
+ * Whether an entry named `name` sits on PATH, even one that cannot run: a `dsh`
2812
+ * without execute permission is still what boot picks (findHostDsh), and a
2813
+ * dangling link is what an interrupted install leaves where the engine was.
2814
+ *
2815
+ * A throw from the probe below cannot tell "no dsh installed" from "a broken
2816
+ * dsh": execFileSync reports both as an exception. Folding them together let a
2817
+ * broken engine pass as "no evidence" and verify from its manifest alone
2818
+ * (#1849 review R1). This walk is the presence half; only a PATH with no
2819
+ * candidate at all counts as absent.
2820
+ *
2821
+ * @param env - Process environment (`PATH`/`Path` and `PATHEXT` on Windows).
2822
+ */
2823
+ function commandOnPath(name, env) {
2824
+ const key = env.PATH === undefined && env.Path !== undefined ? 'Path' : 'PATH';
2825
+ const raw = env[key];
2826
+ if (raw === undefined || raw === '')
2827
+ return false;
2828
+ const extensions = process.platform === 'win32'
2829
+ ? (env.PATHEXT ?? '.COM;.EXE;.BAT;.CMD').split(';').filter(extension => extension !== '')
2830
+ : [''];
2831
+ for (const entry of raw.split(delimiter)) {
2832
+ // Windows PATH entries may be quoted ("C:\Program Files\…").
2833
+ const dir = entry.length > 2 && entry.startsWith('"') && entry.endsWith('"') ? entry.slice(1, -1) : entry;
2834
+ if (dir === '')
2835
+ continue;
2836
+ for (const extension of extensions) {
2837
+ try {
2838
+ lstatSync(join(dir, name + extension));
2839
+ return true;
2840
+ }
2841
+ catch {
2842
+ // Not here; keep walking the PATH.
2843
+ }
2844
+ }
2845
+ }
2846
+ return false;
2847
+ }
2848
+ /**
2849
+ * Report a skipped engine step on stderr. The screen is already gone when the
2850
+ * update runs, and this covers a run that never reaches the replacement.
2851
+ *
2852
+ * @param plan - The plan about to run.
2853
+ * @returns The report, for the replacement to show as well.
2854
+ */
2855
+ function announceEngineSkip(plan) {
2856
+ const skip = engineSkipMessages(plan);
2857
+ if (skip !== undefined)
2858
+ writeHandoffNotice(`\n${skip.report}\n`);
2859
+ return skip;
2860
+ }
2861
+ /**
2862
+ * The replacement's copy of an engine-skip report.
2863
+ *
2864
+ * @param skip - The report, when the plan skipped the engine.
2865
+ * @returns The restart env entry; empty when nothing was skipped.
2866
+ */
2867
+ export function engineSkipEnv(skip) {
2868
+ return skip === undefined ? {} : { [ENGINE_SKIP_REPORT_ENV]: JSON.stringify(skip) };
2869
+ }
2870
+ /**
2871
+ * Read the report {@link engineSkipEnv} carried over and clear it, so it never
2872
+ * reaches a child process or a later restart.
2873
+ *
2874
+ * @param env - Environment holding the marker.
2875
+ * @returns The report; undefined when absent or unreadable.
2876
+ */
2877
+ export function takeEngineSkipReport(env = process.env) {
2878
+ const raw = env[ENGINE_SKIP_REPORT_ENV];
2879
+ if (raw === undefined)
2880
+ return undefined;
2881
+ delete env[ENGINE_SKIP_REPORT_ENV];
2882
+ try {
2883
+ const parsed = JSON.parse(raw);
2884
+ if (!isRecord(parsed))
2885
+ return undefined;
2886
+ const { report, title, toast } = parsed;
2887
+ if (typeof report !== 'string' || typeof title !== 'string' || typeof toast !== 'string')
2888
+ return undefined;
2889
+ return { report, title, toast };
2890
+ }
2891
+ catch {
2892
+ return undefined;
2893
+ }
2894
+ }
2895
+ /** A carried report no surviving mount has shown yet; see deliverEngineSkipReport. */
2896
+ let heldEngineSkip;
2897
+ /**
2898
+ * Show a carried engine-skip report on one mount. The launcher's boot recompose
2899
+ * disposes the first mount, so the report stays held until a mount shows it, and
2900
+ * goes back when the mount that showed it is disposed: its rows go with it.
2901
+ *
2902
+ * @param channel - The mount's channel.
2903
+ * @param show - Renders the report.
2904
+ * @param env - Environment holding the marker.
2905
+ * @returns The disposer for this mount.
2906
+ */
2907
+ export function deliverEngineSkipReport(channel, show, env = process.env) {
2908
+ heldEngineSkip ??= takeEngineSkipReport(env);
2909
+ const skip = heldEngineSkip;
2910
+ if (skip === undefined)
2911
+ return () => undefined;
2912
+ let disposed = false;
2913
+ let shown = false;
2914
+ const deliver = () => {
2915
+ if (disposed)
2916
+ return;
2917
+ shown = true;
2918
+ heldEngineSkip = undefined;
2919
+ show(skip);
2920
+ };
2921
+ let unsubscribe;
2922
+ if (channel.ready) {
2923
+ deliver();
2924
+ }
2925
+ else {
2926
+ unsubscribe = channel.subscribe(() => {
2927
+ if (!channel.ready)
2928
+ return;
2929
+ unsubscribe?.();
2930
+ // Adoption publishes several synchronous updates after `ready` flips.
2931
+ queueMicrotask(deliver);
2932
+ });
2933
+ }
2934
+ return () => {
2935
+ disposed = true;
2936
+ unsubscribe?.();
2937
+ if (shown)
2938
+ heldEngineSkip ??= skip;
2939
+ };
2940
+ }
2941
+ /**
2942
+ * What `dsh --version` says about the engine the NEXT launch would run.
2943
+ * Windows shells the `.cmd` shim the same way the profile installer does.
2944
+ *
2945
+ * @param env - Environment used for the bounded probe.
2946
+ */
2947
+ function probePathDsh(env) {
2948
+ const present = commandOnPath('dsh', env);
2949
+ try {
2950
+ const output = process.platform === 'win32'
2951
+ ? execFileSync(`dsh ${shellQuote(['--version']).join(' ')}`, [], {
2952
+ encoding: 'utf8', timeout: 15000, env, shell: true, stdio: ['ignore', 'pipe', 'ignore'],
2953
+ })
2954
+ : execFileSync('dsh', ['--version'], {
2955
+ encoding: 'utf8', timeout: 15000, env, stdio: ['ignore', 'pipe', 'ignore'],
2956
+ });
2957
+ const match = /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/u.exec(output);
2958
+ if (match === null)
2959
+ return { kind: 'unreadable' };
2960
+ const version = valid(match[1]);
2961
+ return version === null ? { kind: 'unreadable' } : { kind: 'version', version };
2962
+ }
2963
+ catch {
2964
+ // A `dsh` that exists but exits non-zero is negative proof: the next
2965
+ // launch fails. Only an empty PATH slot is "no evidence".
2966
+ return present ? { kind: 'failed' } : { kind: 'missing' };
2967
+ }
2968
+ }
2969
+ /**
2970
+ * The child environment of an engine installer. pnpm additionally needs its
2971
+ * owner home's bin directories on PATH (`ERR_PNPM_GLOBAL_BIN_DIR_NOT_IN_PATH`
2972
+ * before any registry work), including when the process inherited no pnpm
2973
+ * shell setup; the launcher step already applies the same rule.
2974
+ */
2975
+ function hostInstallEnv(commandEnv, env) {
2976
+ if (commandEnv === undefined)
2977
+ return env;
2978
+ const merged = { ...env, ...commandEnv };
2979
+ return commandEnv.PNPM_HOME === undefined ? merged : { ...merged, ...pnpmHomeEnv(merged, commandEnv.PNPM_HOME) };
2980
+ }
2981
+ /** Capture before pnpm can prune the old target; never adopt profile-local dependencies. */
2982
+ function hostFallbackLink(step, env, tuiDir) {
2983
+ if (tuiDir === undefined || step.command.file !== 'pnpm')
2984
+ return undefined;
2985
+ const install = detectHostInstall(step.packageDir, env);
2986
+ if (install.installer !== 'pnpm' || install.pnpmHome === undefined
2987
+ || install.pnpmHome !== step.command.env?.PNPM_HOME)
2988
+ return undefined;
2989
+ const nodeModules = resolve(tuiDir, '..', '..');
2990
+ if (readPackageVersion(join(nodeModules, '@deepseek-ai', 'dsh')) !== undefined)
2991
+ return undefined;
2992
+ const path = resolve(nodeModules, '..', '..', 'node_modules', '@deepseek-ai', 'dsh');
2993
+ try {
2994
+ if (!lstatSync(path).isSymbolicLink() || realpathSync(path) !== install.packageDir)
2995
+ return undefined;
2996
+ return { path, target: readlinkSync(path), pnpmHome: install.pnpmHome };
2997
+ }
2998
+ catch {
2999
+ return undefined;
3000
+ }
3001
+ }
3002
+ /** Refresh only the unchanged runtime link, to a runnable target in the SAME pnpm home. */
3003
+ async function refreshHostFallback(link, version, env, signal) {
3004
+ // Windows cannot atomically rename a junction over an existing directory.
3005
+ // Keep it unverified rather than unlinking the only surviving fallback first.
3006
+ if (process.platform === 'win32')
3007
+ return;
3008
+ const dir = await findHostDshPackageDir(env);
3009
+ if (dir === undefined || signal?.aborted)
3010
+ return;
3011
+ const install = detectHostInstall(dir, env);
3012
+ if (install.installer !== 'pnpm' || install.pnpmHome !== link.pnpmHome
3013
+ || install.version !== version || !hostPackageRuns(install.packageDir, env))
3014
+ return;
3015
+ const staged = `${link.path}.dsh-tui-${randomUUID()}`;
3016
+ let created = false;
3017
+ try {
3018
+ symlinkSync(install.packageDir, staged, 'dir');
3019
+ created = true;
3020
+ // The installer or another process may have already replaced the link.
3021
+ // Never unlink it first: a failed rename must leave the old fallback intact.
3022
+ if (!lstatSync(link.path).isSymbolicLink() || readlinkSync(link.path) !== link.target)
3023
+ return;
3024
+ renameSync(staged, link.path);
3025
+ created = false;
3026
+ }
3027
+ catch {
3028
+ // The existing verification gate refuses an unrefreshed or broken fallback.
3029
+ }
3030
+ finally {
3031
+ if (created) {
3032
+ try {
3033
+ rmSync(staged, { force: true });
3034
+ }
3035
+ catch { /* Verification still decides the restart. */ }
3036
+ }
3037
+ }
3038
+ }
3039
+ /**
3040
+ * Run one planned engine install and verify the version actually landed.
3041
+ *
3042
+ * The pre-install `packageDir` is the RIGHT target to write but the WRONG
3043
+ * place to read back on pnpm: a global project resolves through a
3044
+ * version-pinned store path (`…/global/<n>/node_modules/.pnpm/@deepseek-ai+dsh@<old>/…`),
3045
+ * which the successful upgrade prunes or leaves at the old version. The gate
3046
+ * therefore re-resolves the host through the profile (what the next boot
3047
+ * imports) and through `dsh --version` on PATH; the explicit-dir read is the
3048
+ * fallback only when neither can answer.
3049
+ *
3050
+ * @param step - A `host` step with kind `install`.
3051
+ * @param options - Environment, cancellation and cleanup uncertainty.
3052
+ */
3053
+ export async function installHostStep(step, options) {
3054
+ const manual = step.manual[0] ?? '';
3055
+ const command = step.command;
3056
+ const fallback = hostFallbackLink(step, options.env, options.tuiDir ?? installedTuiPackageDir());
3057
+ let cancelled = false;
3058
+ let cleanupUnconfirmed = false;
3059
+ const code = await runProcess(command.file, command.args, {
3060
+ // npm's Windows entry is a .cmd shim; the node restart path never uses
3061
+ // shell, but an installer does (same rule as `dsh plugin`).
3062
+ shell: process.platform === 'win32',
3063
+ category: 'host-install',
3064
+ env: hostInstallEnv(command.env, options.env),
3065
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
3066
+ onCleanupError: () => {
3067
+ cleanupUnconfirmed = true;
3068
+ options.onCleanupError();
3069
+ },
3070
+ onCancel: () => { cancelled = true; },
3071
+ });
3072
+ const incomplete = { from: step.from, to: step.to, code, verified: false, cancelled, manual };
3073
+ if (cancelled || options.signal?.aborted || cleanupUnconfirmed)
3074
+ return incomplete;
3075
+ if (code !== 0) {
3076
+ // Non-zero does not roll back a changed pnpm group. Keep fresh observations
3077
+ // for the launcher-failure gate, never a `verified` success or restart stamp.
3078
+ const cli = probePathDsh(options.env);
3079
+ const nextDir = options.nextLaunchDir === undefined ? installedKernelDirFresh(options.tuiDir) : options.nextLaunchDir();
3080
+ const installed = readPackageVersion(nextDir ?? step.packageDir);
3081
+ return {
3082
+ ...incomplete,
3083
+ ...(installed === undefined ? {} : { installed }),
3084
+ ...(cli.kind === 'version' ? { cliVersion: cli.version } : {}),
3085
+ };
3086
+ }
3087
+ const manifestVersion = readPackageVersion(step.packageDir);
3088
+ const cli = probePathDsh(options.env);
3089
+ // pnpm may retain the old store tree behind the shared runtime link. Repair
3090
+ // that link only after the actual PATH install proves the intended version;
3091
+ // the normal two-entry verification still runs afterwards (#1849 review R4).
3092
+ if (fallback !== undefined && !cancelled && !options.signal?.aborted
3093
+ && cli.kind === 'version' && cli.version === step.to) {
3094
+ await refreshHostFallback(fallback, step.to, options.env, options.signal);
3095
+ }
3096
+ const nextDir = options.nextLaunchDir === undefined ? installedKernelDirFresh(options.tuiDir) : options.nextLaunchDir();
3097
+ const resolved = options.resolveInstalled?.()
3098
+ ?? (nextDir === undefined ? undefined : readPackageVersion(nextDir));
3099
+ // The entry the next boot follows is the only one that can testify. A
3100
+ // directory that exists but cannot start is NEGATIVE proof, never "absent":
3101
+ // an installer that exits 0 can still leave a half-written tree behind.
3102
+ const nextRuns = nextDir === undefined ? undefined : hostPackageRuns(nextDir, options.env);
3103
+ const cliVersion = cli.kind === 'version' ? cli.version : undefined;
3104
+ const gate = resolved ?? cliVersion;
3105
+ const verified = nextRuns === false || cli.kind === 'failed'
3106
+ ? false
3107
+ : nextRuns === true
3108
+ ? resolved === step.to && (cliVersion === undefined || cliVersion === step.to)
3109
+ : gate !== undefined
3110
+ ? gate === step.to
3111
+ && (resolved === undefined || resolved === step.to)
3112
+ && (cliVersion === undefined || cliVersion === step.to)
3113
+ : manifestVersion === step.to;
3114
+ return {
3115
+ from: step.from,
3116
+ to: step.to,
3117
+ code,
3118
+ verified,
3119
+ cancelled,
3120
+ ...(manifestVersion === undefined ? {} : { installed: manifestVersion }),
3121
+ ...(cliVersion === undefined ? {} : { cliVersion }),
3122
+ manual,
3123
+ };
3124
+ }
3125
+ /**
3126
+ * Positive proof that a FAILED engine step left the NEXT launch runnable: that
3127
+ * entry must start in a fresh node process. A readable manifest and an existing
3128
+ * entry file are NOT proof — an interrupted install routinely leaves both
3129
+ * behind while a dependency the entry imports is already gone.
3130
+ *
3131
+ * Only the entries the next boot can follow may testify, and both must hold: a
3132
+ * store copy that still runs says nothing when the profile link already points
3133
+ * at the half-written tree (#1849 review R1), and a link that runs says nothing
3134
+ * when the `dsh` on PATH cannot start.
3135
+ *
3136
+ * @param step - The install step that failed.
3137
+ * @param env - Environment used for the bounded probes.
3138
+ * @param nextDir - The directory the next boot resolves; defaults to the
3139
+ * profile's fresh resolution.
3140
+ * @param hadPathDsh - Whether PATH carried a `dsh` before the install.
3141
+ */
3142
+ function engineSurvivesFailure(step, env, nextDir = installedKernelDirFresh(), hadPathDsh = false) {
3143
+ // The default launch boots the first `dsh` on PATH (findHostDsh), so a broken
3144
+ // one refuses even while the profile link still runs, and so does one this
3145
+ // install removed. A PATH that never had one stays fine: only the DSH kernel
3146
+ // needs it, and that session could not have come from here.
3147
+ const cli = probePathDsh(env);
3148
+ if (cli.kind === 'failed' || (cli.kind === 'missing' && hadPathDsh))
3149
+ return false;
3150
+ if (nextDir !== undefined)
3151
+ return hostPackageRuns(nextDir, env);
3152
+ if (cli.kind === 'version')
3153
+ return true;
3154
+ // Neither a profile link nor a PATH entry: the pre-install directory is the
3155
+ // only engine the next launch could use, so its own probe decides.
3156
+ return hostPackageRuns(step.packageDir, env);
3157
+ }
3158
+ /**
3159
+ * Whether a FAILED engine step still permits the restart (§3.4 matrix).
3160
+ *
3161
+ * The plan's `compatible` field is "after the planned install" — true by
3162
+ * construction whenever an install step exists — so the failure decision must
3163
+ * look at the engine that is actually there: only a TUI that moved onto a line
3164
+ * the pre-update engine is outside of forbids the restart. An engine ahead of
3165
+ * the window is kept (never downgraded); an unknown range cannot justify a
3166
+ * refusal.
3167
+ */
3168
+ export function engineFailureAllowsRestart(input) {
3169
+ if (!input.tuiChanged)
3170
+ return true;
3171
+ const compatibility = hostCompatibility({
3172
+ current: input.currentHost,
3173
+ allowed: parseHostLineRange(input.hostRange),
3174
+ step: { kind: 'none', reason: 'disabled' },
3175
+ });
3176
+ return compatibility !== false;
3177
+ }
3178
+ /**
3179
+ * The existing `dsh plugin update` pipeline, unchanged: pre-seed the profile
3180
+ * workspace, run the installer with its retry/EEXIST recovery, refuse the
3181
+ * 0.7.0–0.7.1 boot-deadlock range and verify the version actually advanced.
3182
+ *
3183
+ * @param updatedFrom - Version captured before the installer ran (release-age
3184
+ * exclusion and the #307 stamp).
3185
+ */
3186
+ async function installProfileTui(profile, targetVersion, signal, updatedFrom) {
3187
+ const dsh = process.platform === 'win32' ? 'dsh.cmd' : 'dsh';
3188
+ const updateArgs = tuiUpdatePluginArgs(profile, targetVersion);
3189
+ // pnpm ≥11 hard-fails installs whose dependency tree carries un-allowlisted
3190
+ // build scripts (ERR_PNPM_IGNORED_BUILDS). The host's pi-ai adapter pulls in
3191
+ // postinstall-only deps (@google/genai/protobufjs), so pre-seed
3192
+ // the profile workspace with explicit `false` entries before pnpm runs.
3193
+ const allowBuilds = ensureProfileAllowBuilds(profile);
3194
+ if (allowBuilds !== undefined && allowBuilds.added.length > 0) {
3195
+ process.stderr.write(`dsh-tui: pre-seeded profile pnpm allowBuilds (${allowBuilds.added.join(', ')}) — ` +
3196
+ 'postinstall-only deps are explicitly ignored\n');
3197
+ }
3198
+ // Foreign-platform natives are pure download waste (sharp ~90MB, the Claude
3199
+ // SDK's bundles ~1.6GB on the maintainer report); keep the profile's ignore
3200
+ // list matching THIS machine (each update recomputes it) so pnpm never
3201
+ // fetches them. The SDK is never ADDED here — it only enters a profile
3202
+ // through the kernel picker's guided install, and then only for the
3203
+ // platform it runs on.
3204
+ const platformFilter = ensureProfilePlatformFilter(profile);
3205
+ if (platformFilter !== undefined && platformFilter.changed) {
3206
+ process.stderr.write(`dsh-tui: platform filter updated (${platformFilter.entries.length} foreign-platform patterns ignored) — ` +
3207
+ `this profile's install keeps only the current platform's natives\n`);
3208
+ }
3209
+ // pnpm ≥11's minimumReleaseAge (24h by default) refuses installs of
3210
+ // packages published within the window — on release day that gate rejects
3211
+ // the exact version /update pins, surfacing as a failed update that heals
3212
+ // itself a day later. Two releases inside the window (issue #1205) trip the
3213
+ // same gate on the OLD lockfile entry pnpm verifies before the swap, so
3214
+ // both the target and the still-installed updatedFrom are exempted.
3215
+ if (targetVersion !== undefined) {
3216
+ const releaseAge = ensureProfileReleaseAgeExclude(profile, targetVersion, updatedFrom === '' ? undefined : updatedFrom);
3217
+ if (releaseAge !== undefined && releaseAge.changed) {
3218
+ const exempted = updatedFrom !== '' && updatedFrom !== targetVersion
3219
+ ? `${PACKAGE_NAME}@${targetVersion} || ${updatedFrom}`
3220
+ : `${PACKAGE_NAME}@${targetVersion}`;
3221
+ process.stderr.write(`dsh-tui: pre-seeded profile release-age exclusion (${exempted}) — ` +
1720
3222
  'freshly published versions install without the 24h supply-chain delay\n');
1721
3223
  }
1722
3224
  }
@@ -1730,9 +3232,9 @@ export async function updateTui(profile, targetVersion, signal) {
1730
3232
  // use the same code/stderr as a retryable installer failure. Never overlap
1731
3233
  // a surviving installer with a retry, stale-file removal, repair or restart.
1732
3234
  if (cleanupUnconfirmed)
1733
- return { code: updateCode || 1, updatedFrom };
3235
+ return { code: updateCode || 1 };
1734
3236
  if (signal?.aborted)
1735
- return { code: 130, updatedFrom };
3237
+ return { code: 130 };
1736
3238
  // Transient Windows tmp-rename race (issue #225): retry the identical
1737
3239
  // command once — it succeeds on a clean second run, and only the
1738
3240
  // `_tmp_<pid>` race signature qualifies, never a real resolution error.
@@ -1741,9 +3243,9 @@ export async function updateTui(profile, targetVersion, signal) {
1741
3243
  updateStderr = '';
1742
3244
  updateCode = await runProcess(dsh, updateArgs, installerOptions);
1743
3245
  if (cleanupUnconfirmed)
1744
- return { code: updateCode || 1, updatedFrom };
3246
+ return { code: updateCode || 1 };
1745
3247
  if (signal?.aborted)
1746
- return { code: 130, updatedFrom };
3248
+ return { code: 130 };
1747
3249
  }
1748
3250
  // Deterministic Linux tmp-rename race (issue #479): EEXIST never clears on
1749
3251
  // a plain retry (the staging-dir collision reproduces every run), and a
@@ -1760,12 +3262,12 @@ export async function updateTui(profile, targetVersion, signal) {
1760
3262
  updateStderr = '';
1761
3263
  updateCode = await runProcess(dsh, updateArgs, installerOptions);
1762
3264
  if (cleanupUnconfirmed)
1763
- return { code: updateCode || 1, updatedFrom };
3265
+ return { code: updateCode || 1 };
1764
3266
  if (signal?.aborted)
1765
- return { code: 130, updatedFrom };
3267
+ return { code: 130 };
1766
3268
  }
1767
3269
  if (updateCode !== 0)
1768
- return { code: updateCode, updatedFrom };
3270
+ return { code: updateCode };
1769
3271
  // A --latest fallback (preflight failed) on a stale mirror can still land
1770
3272
  // on the 0.7.0–0.7.1 hard-inject range — restarting into it under an older
1771
3273
  // global-launcher patch is the permanent boot deadlock of issues
@@ -1774,13 +3276,13 @@ export async function updateTui(profile, targetVersion, signal) {
1774
3276
  // boots) and gets the repair hint on the next /update instead.
1775
3277
  const installedNow = installedTuiVersion();
1776
3278
  if (signal?.aborted)
1777
- return { code: 130, updatedFrom };
3279
+ return { code: 130 };
1778
3280
  if (installedNow !== undefined && installedNow !== updatedFrom && isBootDeadlockTarget(installedNow)) {
1779
3281
  process.stderr.write(`dsh-tui: update landed on ${installedNow}, which can permanently deadlock boot under older launcher patches ` +
1780
3282
  `(#183/#307) — NOT restarting into it. Repair with:\n` +
1781
3283
  ` dsh plugin --profile ${profile} add ${PACKAGE_NAME}@latest\n` +
1782
3284
  `(if the mirror has not synced the latest release yet, retry later)\n`);
1783
- return { code: 1, updatedFrom, installed: installedNow };
3285
+ return { code: 1, installed: installedNow };
1784
3286
  }
1785
3287
  // Post-update verification (issue #225): pnpm can report success yet leave
1786
3288
  // the profile half-updated (manifest old / lockfile new). Verify against
@@ -1790,62 +3292,391 @@ export async function updateTui(profile, targetVersion, signal) {
1790
3292
  if (targetVersion !== undefined) {
1791
3293
  let installed = installedTuiVersion();
1792
3294
  if (signal?.aborted)
1793
- return { code: 130, updatedFrom };
3295
+ return { code: 130 };
1794
3296
  if (installed !== targetVersion) {
1795
3297
  const repairCode = await runProcess(dsh, ['plugin', '--profile', profile, 'install'], { shell: true, signal, onCleanupError });
1796
3298
  if (cleanupUnconfirmed)
1797
- return { code: repairCode || 1, updatedFrom };
3299
+ return { code: repairCode || 1 };
1798
3300
  if (signal?.aborted)
1799
- return { code: 130, updatedFrom };
3301
+ return { code: 130 };
1800
3302
  if (repairCode !== 0)
1801
- return { code: repairCode, updatedFrom };
3303
+ return { code: repairCode };
1802
3304
  installed = installedTuiVersion();
1803
3305
  }
1804
3306
  if (installed !== targetVersion) {
1805
3307
  process.stderr.write(`dsh-tui: update completed but the profile still runs ${installed ?? 'an unreadable version'} ` +
1806
3308
  `(expected ${targetVersion}) — the profile is half-updated. Repair manually with:\n` +
1807
3309
  ` dsh plugin --profile ${profile} add ${PACKAGE_NAME}@${targetVersion}\n`);
1808
- return { code: 1, updatedFrom, installed };
3310
+ return { code: 1, installed };
3311
+ }
3312
+ }
3313
+ return { code: 0, installed: installedTuiVersion() };
3314
+ }
3315
+ /**
3316
+ * Whether the completed update should run the launcher alignment step.
3317
+ *
3318
+ * A plan that already proved there is no launcher (`absent`, e.g. a direct
3319
+ * `dsh --profile` boot) must not call the resolver again: it would report
3320
+ * `unresolved`, lose the one-shot LAUNCHER_ABSENT marker and print a bogus
3321
+ * warning after the restart. A disabled step stays skipped too; planned
3322
+ * copy/install work always runs, and a moved TUI re-resolves everything else.
3323
+ *
3324
+ * @param plan - The preflight plan.
3325
+ * @param tuiChanged - Whether the TUI layer actually moved.
3326
+ */
3327
+ export function shouldAlignLauncher(plan, tuiChanged) {
3328
+ if (plan.launcher.kind === 'copy' || plan.launcher.kind === 'install')
3329
+ return true;
3330
+ if (plan.launcher.kind !== 'none')
3331
+ return false;
3332
+ if (plan.launcher.reason === 'disabled' || plan.launcher.reason === 'absent')
3333
+ return false;
3334
+ return tuiChanged;
3335
+ }
3336
+ /**
3337
+ * Install-only half of `/update`: run `dsh plugin add` (unless the TUI is
3338
+ * already at the target), align the dsh engine, then align the global
3339
+ * launcher. No restart — `updateTuiAndRestart` layers the session-preserving
3340
+ * restart on top, and the `dsh-tui update` CLI stops here.
3341
+ *
3342
+ * The order is fixed (TUI → engine → launcher): the profile installer is the
3343
+ * largest failure surface, and leaving the engine untouched until it finishes
3344
+ * keeps a failed update in "old TUI + old engine", a combination that is known
3345
+ * to boot. A new TUI explicitly supports the older engine lines in its peer
3346
+ * range, so "new TUI + old engine" is still bootable when the engine step
3347
+ * fails (the caller then decides whether to restart, see `compatible`).
3348
+ *
3349
+ * @param profile - The dsh profile to update.
3350
+ * @param plan - The preflight plan. Both production callers (plugin's
3351
+ * `/update` and the CLI) always compute one; there is no planless mode.
3352
+ * @param signal - Cancellation from the caller.
3353
+ * @param options - Test seam for the next-boot engine resolution (see
3354
+ * `installHostStep`); production omits it.
3355
+ * @returns The update exit code plus the before/after versions and each step.
3356
+ */
3357
+ export async function updateTui(profile, plan, signal, options = {}) {
3358
+ // Stamp the pre-update version BEFORE pnpm runs: it reads this package's
3359
+ // manifest from disk, which the update replaces on the fly — a
3360
+ // post-update read already sees the NEW version, and the restarted
3361
+ // process then compares new-vs-new and false-alarms "version did not
3362
+ // advance" on every successful update (issue #307's screenshots).
3363
+ const updatedFrom = installedTuiVersion() ?? '';
3364
+ const targetVersion = plan.tui.kind === 'update' ? plan.tui.latest : undefined;
3365
+ const tuiAlreadyLatest = plan.tui.kind === 'latest';
3366
+ if (signal?.aborted)
3367
+ return { code: 130, updatedFrom, compatible: plan.compatible };
3368
+ // A blocked plan must never move the TUI; the preflight already refuses it,
3369
+ // but a direct caller gets the same guarantee here.
3370
+ if (plan.blocked) {
3371
+ // Nothing has run yet here: the preflight refuses before the tree is torn
3372
+ // down, and a direct caller gets the same guarantee. `update-suite-
3373
+ // incompatible` describes a TUI that already moved, which would be a lie.
3374
+ process.stderr.write(`\n${blockedUpdateMessages(plan).report}\n`);
3375
+ return { code: 1, updatedFrom, tuiChanged: false, compatible: false };
3376
+ }
3377
+ if (isStandaloneRuntime()) {
3378
+ if (tuiAlreadyLatest)
3379
+ return { code: 0, updatedFrom, installed: updatedFrom, tuiChanged: false, compatible: plan.compatible };
3380
+ const target = plan.tui.kind === 'update' ? plan.tui : await resolveTuiUpdateTarget(signal);
3381
+ if (signal?.aborted)
3382
+ return { code: 130, updatedFrom };
3383
+ const latestVersion = targetVersion ?? (target.kind === 'update' ? target.latest : undefined);
3384
+ const downloadUrl = (target.kind === 'update' && target.downloadUrl)
3385
+ ? target.downloadUrl
3386
+ : (latestVersion ? `https://github.com/${GITHUB_REPO}/releases/download/v${latestVersion}/${getStandaloneAssetName()}` : undefined);
3387
+ const checksumUrl = target.kind === 'update' ? target.checksumUrl : undefined;
3388
+ if (downloadUrl === undefined || latestVersion === undefined) {
3389
+ process.stderr.write('dsh-tui: 无法解析便携包更新下载地址\n');
3390
+ return { code: 1, updatedFrom };
1809
3391
  }
3392
+ process.stderr.write(`dsh-tui: 正在更新便携包 (${updatedFrom || 'current'} → ${latestVersion})…\n`);
3393
+ const result = await downloadAndReplaceStandaloneBinary(downloadUrl, msg => {
3394
+ process.stderr.write(`dsh-tui: ${msg}\n`);
3395
+ }, checksumUrl, { signal });
3396
+ if (signal?.aborted)
3397
+ return { code: 130, updatedFrom };
3398
+ if (!result.success) {
3399
+ process.stderr.write(`dsh-tui: 便携包更新失败: ${result.error ?? '未知错误'}\n`);
3400
+ return { code: 1, updatedFrom };
3401
+ }
3402
+ return { code: 0, updatedFrom, installed: latestVersion, tuiChanged: true, compatible: plan.compatible };
3403
+ }
3404
+ let installed = updatedFrom;
3405
+ if (tuiAlreadyLatest) {
3406
+ // Constraints #2/#3: an already-current TUI does not short-circuit the
3407
+ // engine and launcher layers.
3408
+ process.stderr.write(`${t('update-tui-already-current', { version: updatedFrom || 'unknown' })}\n`);
3409
+ }
3410
+ else {
3411
+ const result = await installProfileTui(profile, targetVersion, signal, updatedFrom);
3412
+ if (result.code !== 0) {
3413
+ return {
3414
+ code: result.code,
3415
+ updatedFrom,
3416
+ ...(result.installed === undefined ? {} : { installed: result.installed }),
3417
+ tuiChanged: false,
3418
+ compatible: plan.compatible,
3419
+ };
3420
+ }
3421
+ installed = result.installed ?? installedTuiVersion() ?? updatedFrom;
1810
3422
  }
1811
- // Launcher migration (0.8.7): the freshly installed profile carries the
1812
- // delegating shim — stamp it over the global launcher so this is the LAST
1813
- // time the outer copy can lag. Best-effort; the alignment warning stays as
1814
- // the fallback when the copy is impossible.
3423
+ // DSH_TUI_UPDATED_FROM is only meaningful when the TUI itself moved (#307's
3424
+ // false alarm otherwise: "TUI latest, engine-only update" would restart with
3425
+ // the same version stamped). An `unknown` plan (the `--latest` fallback) can
3426
+ // still land on a new version, so that branch compares what actually landed.
3427
+ const tuiChanged = plan.tui.kind === 'update'
3428
+ ? true
3429
+ : plan.tui.kind === 'unknown'
3430
+ ? installed !== updatedFrom
3431
+ : false;
3432
+ // Step 2: the engine. It runs after the profile installer (safety order) and
3433
+ // before the launcher so the restarted process boots the aligned host.
3434
+ let host;
3435
+ let cleanupUnconfirmed = false;
3436
+ const onCleanupError = () => { cleanupUnconfirmed = true; };
3437
+ if (plan.host.kind === 'install') {
3438
+ if (signal?.aborted)
3439
+ return { code: 130, updatedFrom, installed, tuiChanged, compatible: plan.compatible };
3440
+ process.stderr.write(`${t('update-engine-starting', { from: plan.host.from ?? 'unknown', to: plan.host.to })}\n`);
3441
+ const hadPathDsh = commandOnPath('dsh', process.env);
3442
+ host = await installHostStep(plan.host, {
3443
+ env: process.env,
3444
+ signal,
3445
+ onCleanupError,
3446
+ ...(options.nextLaunchDir === undefined ? {} : { nextLaunchDir: options.nextLaunchDir }),
3447
+ });
3448
+ if (cleanupUnconfirmed) {
3449
+ // Ownership of the installer tree is unconfirmed: never open another
3450
+ // installer and never restart into a half-written prefix.
3451
+ return { code: host.code || 1, updatedFrom, installed, host, tuiChanged, compatible: false };
3452
+ }
3453
+ if (signal?.aborted)
3454
+ return { code: 130, updatedFrom, installed, host, tuiChanged, compatible: plan.compatible };
3455
+ // The CLI path has no AbortSignal: Ctrl+C reaches the owned installer,
3456
+ // which stops the tree and reports it as a cancel event. A child that
3457
+ // exits 130/143/129 on its own is a genuine failure and keeps its repair
3458
+ // copy. Running the launcher step after the user asked to stop would write
3459
+ // to the global prefix anyway.
3460
+ if (host.cancelled) {
3461
+ return { code: 130, updatedFrom, installed, host, tuiChanged, compatible: plan.compatible };
3462
+ }
3463
+ if (host.code !== 0 || !host.verified) {
3464
+ const expected = plan.host.to;
3465
+ const actual = host.installed ?? readPackageVersion(plan.host.packageDir) ?? 'unknown';
3466
+ const cliMismatch = host.code === 0 && host.cliVersion !== undefined && host.cliVersion !== expected;
3467
+ process.stderr.write(`\n${cliMismatch
3468
+ ? t('update-engine-path-mismatch', { cli: host.cliVersion ?? 'unknown', expected, command: host.manual })
3469
+ : host.code === 0
3470
+ ? t('update-engine-unverified', { expected, installed: actual, command: host.manual })
3471
+ : t('update-engine-failed', { code: String(host.code), command: host.manual })}\n`);
3472
+ // A failed installer may have removed/replaced the global package before
3473
+ // exiting (EPERM on a loaded native module, ENOSPC, a killed child). Never
3474
+ // restart into an engine that cannot be proven loadable.
3475
+ if (!engineSurvivesFailure(plan.host, process.env, options.nextLaunchDir?.(), hadPathDsh)) {
3476
+ // The plan §10 rule for refusal copy: current version, target range,
3477
+ // why it cannot be automatic, and the command — all four.
3478
+ process.stderr.write(`\n${t('update-engine-unsafe-restart', {
3479
+ current: plan.currentHost ?? host.installed ?? 'unknown',
3480
+ range: plan.hostRange ?? 'unknown',
3481
+ command: host.manual,
3482
+ })}\n`);
3483
+ return { code: 1, updatedFrom, installed, host, tuiChanged, compatible: false };
3484
+ }
3485
+ // The PLAN's `compatible` says "after the planned install", which is
3486
+ // true by construction when a step exists. The restart decision must
3487
+ // look at the engine that is ACTUALLY there after the failure: if the
3488
+ // pre-update engine was already outside the new TUI's line, a new TUI
3489
+ // plus that engine may not boot.
3490
+ if (!engineFailureAllowsRestart({
3491
+ tuiChanged,
3492
+ currentHost: plan.currentHost,
3493
+ hostRange: plan.hostRange,
3494
+ })) {
3495
+ // New TUI + engine outside its line: refuse the restart instead of
3496
+ // handing the user a combination that may not boot.
3497
+ const repin = updatedFrom === ''
3498
+ ? undefined
3499
+ : `dsh plugin --profile ${profile} add ${PACKAGE_NAME}@${updatedFrom}`;
3500
+ const commands = [host.manual, repin].filter((command) => command !== undefined && command !== '');
3501
+ process.stderr.write(`\n${t('update-suite-incompatible', {
3502
+ current: plan.currentHost ?? actual,
3503
+ range: plan.hostRange ?? '?',
3504
+ commands: commands.join('\n '),
3505
+ })}\n`);
3506
+ return { code: 1, updatedFrom, installed, host, tuiChanged, compatible: false };
3507
+ }
3508
+ // Only now, with both the runtime probe and the range check passed, may
3509
+ // the update claim the existing engine is still usable.
3510
+ process.stderr.write(`${t('update-engine-failure-tolerated', {
3511
+ current: plan.currentHost ?? host.installed ?? actual,
3512
+ range: plan.hostRange ?? 'unknown',
3513
+ })}\n`);
3514
+ }
3515
+ }
3516
+ // Step 3: the global launcher. Re-resolve after the install so the step sees
3517
+ // the version that actually landed; skip only when the plan proved there is
3518
+ // nothing to align (or the layer is switched off) AND the TUI did not move
3519
+ // under the plan.
3520
+ const shouldAlign = shouldAlignLauncher(plan, tuiChanged);
3521
+ let launcher;
1815
3522
  if (signal?.aborted)
1816
- return { code: 130, updatedFrom };
1817
- if (migrateGlobalLauncher()) {
3523
+ return { code: 130, updatedFrom, installed, ...(host === undefined ? {} : { host }), tuiChanged, compatible: plan.compatible };
3524
+ if (shouldAlign) {
3525
+ launcher = await alignGlobalLauncher(installed === '' ? undefined : installed, { signal });
3526
+ }
3527
+ else if (plan.launcher.kind === 'none') {
3528
+ launcher = { kind: 'none', reason: plan.launcher.reason };
3529
+ }
3530
+ // A launcher installer whose process tree could not be proven stopped may
3531
+ // still be writing the global install. Do not report success and do not
3532
+ // restart into a replacement while that is possible.
3533
+ if (launcher?.cleanupUnconfirmed === true) {
3534
+ process.stderr.write('dsh-tui: the global launcher installer could not be confirmed stopped — not restarting. ' +
3535
+ `Inspect the global install, then update it manually with:\n ${launcher.command ?? launcherManualCommand('npm', installed || 'latest')}\n`);
3536
+ return { code: 1, updatedFrom, installed, ...(host === undefined ? {} : { host }), tuiChanged, compatible: false };
3537
+ }
3538
+ // The installer runner stops its own tree on SIGINT/SIGTERM without aborting
3539
+ // the caller's signal, so an interrupted launcher step must end the update as
3540
+ // an interrupt — otherwise the CLI exits 0 and the TUI restarts even though
3541
+ // the user interrupted the install.
3542
+ if (launcher?.reason === 'cancelled') {
3543
+ return { code: 130, updatedFrom, installed, ...(host === undefined ? {} : { host }), tuiChanged, compatible: plan.compatible };
3544
+ }
3545
+ if (launcher?.kind === 'copied') {
1818
3546
  process.stderr.write('dsh-tui: global launcher aligned to the delegating shim (no manual npm i -g needed anymore).\n');
1819
3547
  }
1820
- const installed = installedTuiVersion();
1821
- return { code: signal?.aborted ? 130 : 0, updatedFrom, installed };
3548
+ else if (launcher?.kind === 'installed') {
3549
+ process.stderr.write(`dsh-tui: global launcher updated with pnpm add -g (${launcher.version ?? 'unknown'}).\n`);
3550
+ }
3551
+ else if (launcher?.kind === 'failed') {
3552
+ const command = launcher.command ?? launcherManualCommand('npm', installed || 'latest');
3553
+ const previousHost = host?.from ?? plan.currentHost;
3554
+ const advancedHost = [
3555
+ host?.verified === true ? host.to : undefined,
3556
+ host?.installed,
3557
+ host?.cliVersion,
3558
+ plan.host.kind === 'install' ? readPackageVersion(plan.host.packageDir) : undefined,
3559
+ ].find(version => version !== undefined && previousHost !== undefined && isVersionNewer(version, previousHost));
3560
+ if (advancedHost !== undefined) {
3561
+ // npm can resolve the old launcher from the engine's own prefix instead
3562
+ // of the updated profile. A new engine + failed launcher alignment is not
3563
+ // the old, known-bootable combination, even if both CLIs report versions.
3564
+ process.stderr.write(`\n${t('update-launcher-unsafe-restart', { version: advancedHost, command })}\n`);
3565
+ return { code: 1, updatedFrom, installed, host, launcher, tuiChanged, compatible: false };
3566
+ }
3567
+ process.stderr.write(`dsh-tui: global launcher could not be aligned automatically (${launcher.reason}); update it manually with:\n` +
3568
+ ` ${command}\n`);
3569
+ }
3570
+ const compatible = host !== undefined && host.code === 0 && host.verified
3571
+ ? true
3572
+ : plan.compatible;
3573
+ return {
3574
+ code: signal?.aborted ? 130 : 0,
3575
+ updatedFrom,
3576
+ installed,
3577
+ ...(host === undefined ? {} : { host }),
3578
+ ...(launcher === undefined ? {} : { launcher }),
3579
+ tuiChanged,
3580
+ ...(compatible === undefined ? {} : { compatible }),
3581
+ };
3582
+ }
3583
+ /**
3584
+ * The replacement's env markers for one completed update, pure.
3585
+ *
3586
+ * `DSH_TUI_UPDATED_FROM` only when the TUI itself moved (#307's new-vs-new
3587
+ * false alarm); `DSH_TUI_UPDATED_DSH_FROM` only for a verified engine advance;
3588
+ * the launcher generation marker only when the alignment actually completed.
3589
+ *
3590
+ * @param outcome - The install-only outcome.
3591
+ */
3592
+ export function restartEnvFor(outcome) {
3593
+ const env = {};
3594
+ if (outcome.tuiChanged === true)
3595
+ env[UPDATED_FROM_ENV] = outcome.updatedFrom;
3596
+ const host = outcome.host;
3597
+ if (host !== undefined && host.code === 0 && host.verified && host.from !== undefined && isVersionNewer(host.to, host.from)) {
3598
+ env[UPDATED_DSH_FROM_ENV] = host.from;
3599
+ }
3600
+ Object.assign(env, launcherRestartEnv(outcome.launcher));
3601
+ if (outcome.launcher?.kind === 'none' && outcome.launcher.reason === 'absent')
3602
+ env[LAUNCHER_ABSENT_ENV] = '1';
3603
+ return env;
1822
3604
  }
1823
3605
  /**
1824
3606
  * Update the installed dsh-tui package and restart the same launcher while
1825
3607
  * preserving the active session. The TUI must already be unmounted before
1826
3608
  * this is called so pnpm output cannot corrupt the rendered terminal frame.
1827
3609
  *
1828
- * When the preflight registry check resolved an exact target, pass that
1829
- * version to pnpm instead of resolving `latest` a second time. This avoids a
1830
- * stale mirror/dist-tag response between the check and install. If preflight
1831
- * failed, retain the `--latest` fallback: a plain `pnpm update` stays inside
1832
- * the manifest range and can restart unchanged across minor releases.
3610
+ * When the preflight resolved a plan, pass it here: its TUI target pins the
3611
+ * exact version (no second registry round trip), and its engine/launcher
3612
+ * layers run after the profile installer.
1833
3613
  *
1834
3614
  * @param sessionId - Session to resume in the replacement process.
1835
3615
  * @param profile - The dsh profile this TUI was launched with; updating any
1836
3616
  * other profile would leave the running install untouched.
1837
- * @param targetVersion - Exact version returned by the preflight registry
1838
- * check, or undefined when that check failed and pnpm should resolve latest.
3617
+ * @param plan - The preflight plan computed before the tree was torn down.
1839
3618
  * @param kernel - The kernel this process runs (TuiRestartOptions.kernel).
1840
3619
  * @returns Exit codes for the update run and the replacement process.
1841
3620
  */
1842
- export async function updateTuiAndRestart(sessionId, profile, targetVersion, kernel,
3621
+ export async function updateTuiAndRestart(sessionId, profile, plan, kernel,
1843
3622
  /** The standalone entry's supervision hooks (TuiRestartOptions.onSpawn / onTerminationSignal). */
1844
3623
  supervision = {}, signal) {
1845
- const outcome = await updateTui(profile, targetVersion, signal);
1846
- const { updatedFrom } = outcome;
3624
+ const engineSkip = announceEngineSkip(plan);
3625
+ // Prove the direct DSH entry before pnpm can delete its logical group path.
3626
+ // Source/custom launchers and the package-owned host entry keep their route.
3627
+ let directInstall;
3628
+ const hostEntry = process.env[HOST_ENTRY_PATH_ENV];
3629
+ if (plan.host.kind === 'install' && (hostEntry === undefined || hostEntry === '' || hostEntryDisabled())) {
3630
+ const entry = hostPackageEntry(plan.host.packageDir);
3631
+ try {
3632
+ if (entry !== undefined && process.argv[1] !== undefined && realpathSync(process.argv[1]) === entry) {
3633
+ directInstall = detectHostInstall(plan.host.packageDir, process.env);
3634
+ }
3635
+ }
3636
+ catch { /* An unproven script must never be replaced by a different CLI. */ }
3637
+ }
3638
+ const outcome = await updateTui(profile, plan, signal);
1847
3639
  if (outcome.code !== 0)
1848
3640
  return { updateCode: outcome.code, restartCode: outcome.code };
3641
+ if (signal?.aborted)
3642
+ return { updateCode: 130, restartCode: 130 };
3643
+ let dshEntry;
3644
+ if (directInstall !== undefined && outcome.host !== undefined && plan.host.kind === 'install') {
3645
+ // npm updates its original package in place; pnpm may rotate the group.
3646
+ // PATH can name an unrelated (even older) install, so it is a last resort
3647
+ // and must prove the same ownership as the profile/original candidates.
3648
+ const candidates = new Set([plan.host.packageDir, installedKernelDirFresh(), await findHostDshPackageDir(process.env)]);
3649
+ const allowed = parseHostLineRange(plan.hostRange);
3650
+ for (const dir of candidates) {
3651
+ if (dir === undefined)
3652
+ continue;
3653
+ const candidate = detectHostInstall(dir, process.env);
3654
+ if (!sameHostInstall(directInstall, candidate))
3655
+ continue;
3656
+ const version = candidate.version;
3657
+ if (version === undefined || directInstall.version === undefined || lt(version, directInstall.version))
3658
+ continue;
3659
+ if (outcome.host.verified && version !== outcome.host.to)
3660
+ continue;
3661
+ // Failure tolerance never licenses a downgrade or an unsupported engine,
3662
+ // even when the TUI itself did not change (engine-only update).
3663
+ if (hostSatisfiesLine({ current: version, allowed }) !== true)
3664
+ continue;
3665
+ const entry = hostPackageEntry(candidate.packageDir);
3666
+ if (entry !== undefined && hostPackageRuns(candidate.packageDir, process.env, version)) {
3667
+ dshEntry = entry;
3668
+ break;
3669
+ }
3670
+ }
3671
+ if (dshEntry === undefined) {
3672
+ process.stderr.write(`\n${t('update-engine-entry-unresolved', {
3673
+ current: outcome.host.cliVersion ?? outcome.host.installed ?? plan.currentHost ?? 'unknown',
3674
+ range: plan.hostRange ?? 'unknown',
3675
+ command: outcome.host.manual,
3676
+ })}\n`);
3677
+ return { updateCode: 1, restartCode: 1 };
3678
+ }
3679
+ }
1849
3680
  if (signal?.aborted)
1850
3681
  return { updateCode: 130, restartCode: 130 };
1851
3682
  // Restart through the same hardened handoff as /restart (issues
@@ -1855,9 +3686,19 @@ supervision = {}, signal) {
1855
3686
  // child's keypresses, and capture a fast-death stderr report. The old
1856
3687
  // plain inherit spawn raced the interpreter for input on Windows
1857
3688
  // Terminal (issue #483: "cannot type anything after /update").
3689
+ //
3690
+ // The launcher generation marker inherited from the OLD outer shim is
3691
+ // refreshed when this update aligned the launcher: the replacement would
3692
+ // otherwise print "launcher still outdated" about an install it just
3693
+ // brought up to date (#1844 review). The TUI and engine stamps are applied
3694
+ // only to the layer that actually moved, so a "TUI latest, engine-only"
3695
+ // update cannot trip the TUI version-advance check (§3.6).
3696
+ const restartEnv = restartEnvFor(outcome);
3697
+ Object.assign(restartEnv, engineSkipEnv(engineSkip));
1858
3698
  const restartCode = await restartTui(sessionId, {
1859
- env: { [UPDATED_FROM_ENV]: updatedFrom },
3699
+ env: restartEnv,
1860
3700
  kind: 'update',
3701
+ ...(dshEntry === undefined ? {} : { dshEntry }),
1861
3702
  ...(kernel === undefined ? {} : { kernel }),
1862
3703
  ...supervision,
1863
3704
  });
@@ -1873,57 +3714,113 @@ supervision = {}, signal) {
1873
3714
  * @returns Process exit code: 0 on success or already-latest, 1 otherwise.
1874
3715
  */
1875
3716
  export async function cliUpdate(profile) {
1876
- const target = await resolveTuiUpdateTarget();
1877
- if (target.kind === 'latest') {
1878
- process.stdout.write(`dsh-tui: already the latest version (${target.current}).\n`);
3717
+ const plan = await resolveUpdatePlan();
3718
+ const state = updatePlanState(plan);
3719
+ if (state === 'blocked') {
3720
+ process.stderr.write(`${blockedUpdateMessages(plan).report}\n`);
3721
+ return 1;
3722
+ }
3723
+ if (state === 'empty') {
3724
+ process.stdout.write(`${t('update-plan-empty', { layers: updatePlanSuite(plan) })}\n`);
3725
+ return 0;
3726
+ }
3727
+ if (state === 'idle') {
3728
+ const report = idleReportMessages(plan);
3729
+ if (report !== undefined) {
3730
+ process.stdout.write(`${report.report}\n`);
3731
+ }
3732
+ else {
3733
+ process.stdout.write(`${t('update-plan-idle', {
3734
+ current: plan.tui.kind === 'latest' ? plan.tui.current : installedTuiVersion() ?? 'unknown',
3735
+ reason: describeLauncherStepReason(plan.launcher) ?? describeHostStepReason(plan.host),
3736
+ })}\n`);
3737
+ }
1879
3738
  return 0;
1880
3739
  }
1881
3740
  if (isStandaloneRuntime()) {
1882
- if (target.kind === 'update') {
1883
- process.stdout.write(`dsh-tui: updating standalone binary ${target.current} → ${target.latest}…\n`);
1884
- const outcome = await updateTui(profile, target.latest);
1885
- if (outcome.code === 0) {
1886
- process.stdout.write(`dsh-tui: standalone binary updated successfully (${outcome.updatedFrom || target.current} → ${outcome.installed}).\n`);
1887
- }
1888
- return outcome.code;
3741
+ if (plan.tui.kind === 'unknown') {
3742
+ process.stderr.write('dsh-tui: version check failed (offline or unreachable registry).\n');
3743
+ return 1;
1889
3744
  }
1890
- process.stderr.write('dsh-tui: version check failed (offline or unreachable registry).\n');
1891
- return 1;
3745
+ if (plan.tui.kind === 'update') {
3746
+ process.stdout.write(`dsh-tui: updating standalone binary ${plan.tui.current} → ${plan.tui.latest}…\n`);
3747
+ }
3748
+ const outcome = await updateTui(profile, plan);
3749
+ if (outcome.code === 0) {
3750
+ process.stdout.write(`dsh-tui: standalone binary updated successfully (${outcome.updatedFrom || 'current'} → ${outcome.installed}).\n`);
3751
+ }
3752
+ return outcome.code;
1892
3753
  }
1893
- let targetVersion;
1894
- if (target.kind === 'update') {
1895
- // Mirror the /update flow exactly: refuse the 0.7.0–0.7.1 hard-inject
1896
- // range (permanent boot deadlock under older launcher patches, #183/#307)
1897
- // instead of installing it.
1898
- if (isBootDeadlockTarget(target.latest)) {
1899
- process.stderr.write(`dsh-tui: refusing to update onto ${target.latest} — that range can permanently deadlock boot ` +
1900
- `(#183/#307). Latest on the official registry: ${target.authoritative ?? target.latest}. ` +
3754
+ if (plan.tui.kind === 'update') {
3755
+ // Mirror the /update refusal exactly: 0.7.0–0.7.1 hard-inject the
3756
+ // workspaces row and permanently deadlock boot under older launcher
3757
+ // patches (#183/#307), so never install that range.
3758
+ if (isBootDeadlockTarget(plan.tui.latest)) {
3759
+ process.stderr.write(`dsh-tui: refusing to update onto ${plan.tui.latest} — that range can permanently deadlock boot ` +
3760
+ `(#183/#307). Latest on the official registry: ${plan.tui.authoritative ?? plan.tui.latest}. ` +
1901
3761
  `If you use a mirror, retry after it syncs.\n`);
1902
3762
  return 1;
1903
3763
  }
1904
- if (target.authoritative !== undefined) {
1905
- process.stdout.write(`dsh-tui: note — your registry serves ${target.latest} while npmjs.org has ${target.authoritative} (mirror lag).\n`);
3764
+ if (plan.tui.authoritative !== undefined) {
3765
+ process.stdout.write(`dsh-tui: note — your registry serves ${plan.tui.latest} while npmjs.org has ${plan.tui.authoritative} (mirror lag).\n`);
1906
3766
  }
1907
- targetVersion = target.latest;
1908
- process.stdout.write(`dsh-tui: updating ${target.current} → ${target.latest}…\n`);
3767
+ process.stdout.write(`dsh-tui: updating ${plan.tui.current} → ${plan.tui.latest}…\n`);
1909
3768
  }
1910
- else {
3769
+ else if (plan.tui.kind === 'unknown') {
1911
3770
  process.stdout.write('dsh-tui: version check failed (offline or unreadable install) — falling back to `--latest`.\n');
1912
3771
  }
1913
- const outcome = await updateTui(profile, targetVersion);
1914
- if (outcome.code === 0) {
1915
- // A preflight-less run (`--latest` fallback) can "succeed" as a pnpm
1916
- // no-op: same manifest before and after. Say so instead of printing a
1917
- // vacuous `updated X → X` — the /update path surfaces the same state via
1918
- // the DSH_TUI_UPDATED_FROM stamp on restart.
1919
- if (targetVersion === undefined && outcome.installed !== undefined && outcome.installed === outcome.updatedFrom) {
3772
+ const layers = updatePlanLayers(plan);
3773
+ if (layers.length > 0)
3774
+ process.stdout.write(`${t('update-cli-starting', { layers: layers.join(' · ') })}\n`);
3775
+ const outcome = await updateTui(profile, plan);
3776
+ if (outcome.code === 0 && plan.tui.kind !== 'latest') {
3777
+ if (plan.tui.kind === 'unknown' && outcome.installed !== undefined && outcome.installed === outcome.updatedFrom) {
3778
+ // A preflight-less run can "succeed" as a pnpm no-op: say so instead of
3779
+ // printing a vacuous `updated X → X`.
1920
3780
  process.stdout.write(`dsh-tui: version did not advance (still ${outcome.installed}) — already the latest, or the registry has no newer release yet.\n`);
1921
3781
  }
1922
3782
  else {
1923
- process.stdout.write(`dsh-tui: updated ${outcome.updatedFrom || '(unknown)'} → ${outcome.installed ?? '(unreadable)'}.\n`);
3783
+ process.stdout.write(`dsh-tui: TUI ${outcome.updatedFrom || '(unknown)'} → ${outcome.installed ?? '(unreadable)'}.\n`);
3784
+ }
3785
+ }
3786
+ else if (outcome.code === 0) {
3787
+ process.stdout.write(`dsh-tui: TUI already ${outcome.installed ?? outcome.updatedFrom}.\n`);
3788
+ }
3789
+ if (outcome.host !== undefined) {
3790
+ if (outcome.host.code === 0 && outcome.host.verified) {
3791
+ process.stdout.write(`dsh-tui: engine ${outcome.host.from ?? '(unknown)'} → ${outcome.host.to}.\n`);
3792
+ }
3793
+ else {
3794
+ process.stderr.write(`dsh-tui: engine not aligned — ${outcome.host.manual}\n`);
1924
3795
  }
1925
3796
  }
1926
- return outcome.code;
3797
+ if (outcome.launcher?.kind === 'copied' || outcome.launcher?.kind === 'installed') {
3798
+ process.stdout.write(`dsh-tui: launcher → ${outcome.launcher.version ?? 'current'}.\n`);
3799
+ }
3800
+ else if (outcome.launcher?.kind === 'failed') {
3801
+ process.stderr.write(`dsh-tui: launcher not aligned — ${outcome.launcher.command ?? ''}\n`);
3802
+ }
3803
+ if (outcome.code === 0 && plan.host.kind === 'unavailable') {
3804
+ // The TUI/launcher work succeeded, but the engine layer was planned and
3805
+ // could not be automated: report the guidance and make the whole-set
3806
+ // verdict non-zero (the same rule as a failed launcher alignment).
3807
+ const skip = engineSkipMessages(plan);
3808
+ if (skip !== undefined)
3809
+ process.stderr.write(`${skip.report}\n`);
3810
+ return 1;
3811
+ }
3812
+ if (outcome.code !== 0)
3813
+ return outcome.code;
3814
+ // Verification failure is a non-zero exit even when the TUI itself updated
3815
+ // and the current combination still boots (§3.4).
3816
+ if (outcome.host !== undefined && (outcome.host.code !== 0 || !outcome.host.verified))
3817
+ return 1;
3818
+ // Launcher alignment stays best effort for the RESTART (it only affects the
3819
+ // next launch), but this command's exit status is the whole set's verdict:
3820
+ // reporting success while a layer was not aligned is what automation reads.
3821
+ if (outcome.launcher?.kind === 'failed')
3822
+ return 1;
3823
+ return 0;
1927
3824
  }
1928
3825
  /**
1929
3826
  * The replacement's env, pure: the resume marker, the /restart child stamp,
@@ -1997,7 +3894,10 @@ export function restartArgv(input) {
1997
3894
  const appArgs = separator === -1 ? [] : input.argv.slice(separator + 1);
1998
3895
  return [...input.execArgv, input.hostEntry, ...strip(appArgs)];
1999
3896
  }
2000
- return [...input.execArgv, ...strip(input.argv.slice(1))];
3897
+ const args = strip(input.argv.slice(1));
3898
+ if (input.dshEntry !== undefined && args.length > 0)
3899
+ args[0] = input.dshEntry;
3900
+ return [...input.execArgv, ...args];
2001
3901
  }
2002
3902
  export async function restartTui(sessionId, options = {}) {
2003
3903
  const kind = options.kind ?? 'restart';
@@ -2009,6 +3909,7 @@ export async function restartTui(sessionId, options = {}) {
2009
3909
  switching: options.backend !== undefined,
2010
3910
  fresh: sessionId === '',
2011
3911
  hostEntry: hostEntry === undefined || hostEntry === '' || hostEntryDisabled() ? undefined : hostEntry,
3912
+ dshEntry: options.dshEntry,
2012
3913
  });
2013
3914
  logRestartEvent(`${tag}: spawning replacement`, {
2014
3915
  node: process.execPath,