@aiwayds/dsh-opentui 0.9.2 → 0.9.4

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.
@@ -2,119 +2,205 @@
2
2
  // provision-opentui-profile.mjs — idempotent bootstrap of the fixed `opentui`
3
3
  // host profile (ADR-0005 decisions 3 and 5).
4
4
  //
5
- // What it does:
6
- // 1. resolves $DSH_HOME (env or ~/.dsh)
7
- // 2. if $DSH_HOME/profiles/opentui already exists → keeps it (idempotent,
8
- // never recreates); otherwise recreates it from the shipped `web`
9
- // template via `dsh opentui --from-default-profile web --dump-config`
10
- // (--dump-config makes dsh compose-and-exit, so the template copy
11
- // happens WITHOUT booting the profile; verified against the shipped CLI
12
- // whose help documents "dsh rescue --from-default-profile web — recreate
13
- // rescue from the shipped web template")
14
- // 3. writes/merges the model route into the profile's `cordis.patch.yml`
15
- // — the shipped web template ships NO provider route, so without this
16
- // the profile cannot complete a real model turn (provider auth fails).
17
- // Flags: --provider <id> --model <id> --reasoning-effort <id>
18
- // (defaults zai-coding-cn / glm-5.3-flash / high — the same defaults as
19
- // scripts/install-profile.mjs). Same patch-body shape as
20
- // install-profile.mjs: an `llm-pi-ai` provider entry (apiKeyEnv derived
21
- // the dsh way — uppercased, non-alnum → underscore, + _API_KEY) plus an
22
- // `agent-default-model` row.
23
- // 4. prints what it did and the plugin-install next step:
24
- // `dsh plugin --profile opentui add <pkg>`
5
+ // Runs on EVERY launcher start (bin/dsh-opentui.mjs), so every step is
6
+ // idempotent and cheap when there is nothing to do. Five progress steps:
25
7
  //
26
- // Route idempotency contract (follows install-profile.mjs): per managed
27
- // entry (`llm-pi-ai`, `agent-default-model`), an entry already present in the
28
- // patch layer is left untouched — a re-run never duplicates entries and never
29
- // clobbers a model/provider the user edited. Missing entries are appended
30
- // (never rewritten) so the template's own patch entries survive; the file is
31
- // backed up (*.bak-<ts>) before the first modification.
8
+ // [1/5] profile — keep an existing $DSH_HOME/profiles/opentui, else
9
+ // recreate it from the shipped `web` template via
10
+ // `dsh opentui --from-default-profile web --dump-config`
11
+ // (--dump-config makes dsh compose-and-exit, so the
12
+ // template copy happens WITHOUT booting the profile).
13
+ // [2/5] model route — write/merge the provider route into the profile's
14
+ // `cordis.patch.yml`. The web template ships NO
15
+ // provider route, so without this the profile cannot
16
+ // complete a real model turn. Flags: --provider <id>
17
+ // --model <id> --reasoning-effort <id> (defaults
18
+ // zai-coding-cn / glm-5.3-flash / high). The same step
19
+ // re-enables `tool-web` (the dsh-web-app bundle ships
20
+ // it disabled and the `native` preset never turns it
21
+ // back on) and pins `web.searchProvider` to anysearch —
22
+ // with or without a plugin tier: this is what makes
23
+ // `web_search` visible to the model. It also inserts
24
+ // the default `mcp-context7` client row (streamable
25
+ // HTTP, no key) so the MCP adapter's mcp_list has a
26
+ // server to catalog; skipped under `--plugins=none`.
27
+ // [3/5] plugins — install the default plugin set when a plugin is not
28
+ // already satisfied (see lib/provision-plan.mjs for the
29
+ // table and the idempotency rule). `--plugins=core`
30
+ // narrows the set, `--plugins=none` installs nothing.
31
+ // [4/5] bundles — clean retired entries out of `dsh.profile.bundles` /
32
+ // `dependencies` and append missing managed bundles in
33
+ // install order (ask-router first).
34
+ // [5/5] verify — `dsh opentui --dump-config`; "skipping profile
35
+ // bundle" lines become WARN lines, never a failure.
36
+ //
37
+ // Idempotency contract (step 3): a plugin needs no work only when
38
+ // (a) it is in the profile `dependencies`,
39
+ // (b) `node_modules/<pkg>/package.json` exists and its version satisfies the
40
+ // pinned version, and
41
+ // (c) its name is in `dsh.profile.bundles`.
42
+ // A dep pinned with a local spec (link:/file:/workspace:) always counts as
43
+ // satisfied — a local development pin is never replaced by a registry version.
44
+ // Missing deps/versions → ONE batched `dsh plugin --profile opentui add
45
+ // <specs...>`; on failure the pnpm build-script skeleton is approved and each
46
+ // package is retried once on its own; a still-failing package is a WARN, never
47
+ // a hard stop (the client still launches).
48
+ //
49
+ // Step 4 reparses the profile manifest after the install: `dsh plugin add`
50
+ // already reconciles bundles for new dependencies, so this only fills the gaps
51
+ // (historic profiles) and enforces the managed order. Any manifest write is
52
+ // preceded by a `.bak-<ts>` copy.
32
53
  //
33
54
  // Hard guard: this script only ever touches the ONE profile named `opentui`.
34
- // It never touches any other profile — in particular the pre-existing
35
- // `dsh-opentui` dev profile (which install-profile.mjs owns).
36
55
  //
37
- // Requires a global `dsh` on PATH (the real host CLI). The first host boot
38
- // resolves the profile's bundles (@deepseek-ai/dsh-base + dsh-web-app) from
39
- // the installed dsh closure; no explicit pnpm install is needed. The provider
40
- // key is read by the host from the apiKeyEnv environment variable (this
41
- // script only names it in the patch; it never handles key values).
56
+ // Dry run: `--dry-run` (or DSH_PROVISION_DRY_RUN=1) prints what it would do —
57
+ // commands, entry counts — and writes nothing.
58
+ //
59
+ // Requires a global `dsh` on PATH for the creating/installing/verifying steps;
60
+ // a dry run needs neither. The provider key is read by the host from the
61
+ // apiKeyEnv environment variable (this script only names it in the patch; it
62
+ // never handles key values).
42
63
 
43
64
  import { spawnSync } from 'node:child_process'
44
65
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
45
66
  import { homedir } from 'node:os'
46
67
  import { join } from 'node:path'
68
+ import {
69
+ DEFAULT_TIER,
70
+ PREFIX,
71
+ PROFILE,
72
+ RETIRED_PROFILE_ENTRIES,
73
+ cleanupDependencies,
74
+ formatStep,
75
+ isDryRun,
76
+ mergeBundles,
77
+ parseDumpConfig,
78
+ parseTier,
79
+ planMcpPatch,
80
+ planPluginInstall,
81
+ planToolPatch,
82
+ pluginAddArgs,
83
+ pluginAddCommand,
84
+ selectPlugins,
85
+ } from './lib/provision-plan.mjs'
47
86
 
48
- const PROFILE = 'opentui'
49
87
  const TEMPLATE = 'web'
88
+ const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
50
89
 
51
90
  const args = process.argv.slice(2)
52
- const flag = (name) => {
91
+ /** --name=value or --name value. */
92
+ const opt = (name) => {
93
+ const inline = args.find((arg) => arg.startsWith(`--${name}=`))
94
+ if (inline) return inline.slice(name.length + 3)
53
95
  const i = args.indexOf(`--${name}`)
54
96
  return i >= 0 ? args[i + 1] : undefined
55
97
  }
56
98
 
57
- const provider = flag('provider') || 'zai-coding-cn'
58
- const model = flag('model') || 'glm-5.3-flash'
59
- const reasoningEffort = flag('reasoning-effort') || 'high'
99
+ const provider = opt('provider') || 'zai-coding-cn'
100
+ const model = opt('model') || 'glm-5.3-flash'
101
+ const reasoningEffort = opt('reasoning-effort') || 'high'
102
+ const dryRun = isDryRun(args, process.env)
103
+ const tier = parseTier(opt('plugins') ?? process.env.DSH_OPENTUI_PLUGINS ?? DEFAULT_TIER)
60
104
  // dsh convention: deriveKeyRef — uppercased, non-alnum → underscore, +_API_KEY
61
105
  const apiKeyEnv = `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`
62
106
 
107
+ const say = (step, label, value = '') => console.log(formatStep(step, label, value))
108
+ const warn = (message) => console.error(`${PREFIX}WARN ${message}`)
109
+
63
110
  function fail(message, detail = '') {
64
- console.error(`provision-opentui-profile: FAIL — ${message}`)
111
+ console.error(`${PREFIX}FAIL — ${message}`)
65
112
  if (detail) console.error(detail.trimEnd())
66
113
  process.exit(1)
67
114
  }
68
115
 
69
116
  // ---------------------------------------------------------------------------
70
- // 1. Resolve the dsh home.
117
+ // 1. Resolve the dsh home and the profile.
71
118
  // ---------------------------------------------------------------------------
72
119
  const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
73
120
  const profileDir = join(dshHome, 'profiles', PROFILE)
74
- console.log(`provision-opentui-profile: dsh home ${dshHome}`)
121
+ const manifestPath = join(profileDir, 'package.json')
122
+ console.log(`${PREFIX}dsh home ${dshHome}`)
75
123
 
76
- // ---------------------------------------------------------------------------
77
- // 2. The profile: keep an existing one; otherwise recreate from the shipped
78
- // web template, without booting.
79
- // ---------------------------------------------------------------------------
80
- if (!existsSync(profileDir)) {
124
+ const requireDsh = () => {
81
125
  const which = spawnSync('which', ['dsh'], { encoding: 'utf8' })
82
126
  if (which.status !== 0 || !which.stdout.trim()) {
83
127
  fail('no global `dsh` on PATH — install the dsh host CLI first')
84
128
  }
129
+ }
85
130
 
86
- console.log(`provision-opentui-profile: creating ${profileDir} from the shipped '${TEMPLATE}' template`)
87
- const run = spawnSync(
88
- 'dsh',
89
- [PROFILE, '--from-default-profile', TEMPLATE, '--dump-config'],
90
- {
131
+ if (existsSync(profileDir)) {
132
+ say(1, 'profile', `reusing ${profileDir}`)
133
+ } else {
134
+ say(1, 'profile', `creating from ${TEMPLATE} template…`)
135
+ if (!dryRun) {
136
+ requireDsh()
137
+ const run = spawnSync('dsh', [PROFILE, '--from-default-profile', TEMPLATE, '--dump-config'], {
91
138
  // DSH_HOME is explicit so the profile lands in the resolved home even
92
139
  // when the caller's env was missing or divergent.
93
140
  env: { ...process.env, DSH_HOME: dshHome },
94
141
  encoding: 'utf8',
95
142
  maxBuffer: 64 * 1024 * 1024,
96
- },
97
- )
98
- if (run.error) fail(`failed to run dsh: ${run.error.message}`)
99
- if (run.status !== 0) {
100
- fail(
101
- `\`dsh ${PROFILE} --from-default-profile ${TEMPLATE} --dump-config\` exited ${run.status}`,
102
- [run.stderr, run.stdout].filter(Boolean).join('\n').slice(-2000),
103
- )
143
+ })
144
+ if (run.error) fail(`failed to run dsh: ${run.error.message}`)
145
+ if (run.status !== 0) {
146
+ fail(
147
+ `\`dsh ${PROFILE} --from-default-profile ${TEMPLATE} --dump-config\` exited ${run.status}`,
148
+ [run.stderr, run.stdout].filter(Boolean).join('\n').slice(-2000),
149
+ )
150
+ }
151
+ if (!existsSync(profileDir)) {
152
+ fail(
153
+ `dsh exited 0 but ${profileDir} was not created — unexpected CLI behavior; refusing to continue`,
154
+ run.stdout.slice(-2000),
155
+ )
156
+ }
104
157
  }
105
- if (!existsSync(profileDir)) {
106
- fail(
107
- `dsh exited 0 but ${profileDir} was not created — unexpected CLI behavior; refusing to continue`,
108
- run.stdout.slice(-2000),
109
- )
158
+ }
159
+
160
+ // ---------------------------------------------------------------------------
161
+ // Manifest helpers — everything below reads the profile through these.
162
+ // ---------------------------------------------------------------------------
163
+ /** The parsed profile manifest, or null when absent/unreadable. Callers that
164
+ * write must distinguish null (do not clobber a corrupt file) from {}. */
165
+ function readManifest() {
166
+ try {
167
+ const parsed = JSON.parse(readFileSync(manifestPath, 'utf8'))
168
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed : null
169
+ } catch {
170
+ return null
110
171
  }
111
- } else {
112
- console.log(`provision-opentui-profile: ${profileDir} already provisioned — leaving it untouched`)
172
+ }
173
+
174
+ const manifestDependencies = (manifest) =>
175
+ typeof manifest.dependencies === 'object' && manifest.dependencies !== null ? manifest.dependencies : {}
176
+ const manifestBundles = (manifest) =>
177
+ Array.isArray(manifest.dsh?.profile?.bundles) ? manifest.dsh.profile.bundles : []
178
+
179
+ function installedVersion(name) {
180
+ try {
181
+ return JSON.parse(readFileSync(join(profileDir, 'node_modules', ...name.split('/'), 'package.json'), 'utf8')).version
182
+ } catch {
183
+ return undefined
184
+ }
185
+ }
186
+
187
+ /** Backup-then-write the profile manifest (the backup is the contract: a
188
+ * failed run never leaves the user without their previous manifest). */
189
+ function writeManifest(manifest) {
190
+ if (existsSync(manifestPath)) {
191
+ const backupPath = `${manifestPath}.bak-${Date.now()}`
192
+ renameSync(manifestPath, backupPath)
193
+ console.log(`${PREFIX}backed up ${manifestPath} to ${backupPath}`)
194
+ } else {
195
+ mkdirSync(profileDir, { recursive: true })
196
+ }
197
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
113
198
  }
114
199
 
115
200
  // ---------------------------------------------------------------------------
116
- // 3. Model route: write/merge the provider route into cordis.patch.yml.
117
- // Per-entry idempotent append (see the contract in the header).
201
+ // 2. Model route: write/merge the provider route into cordis.patch.yml.
202
+ // Per-entry idempotent append: an entry already present is left untouched,
203
+ // so a re-run never duplicates entries or clobbers an edited model.
118
204
  // ---------------------------------------------------------------------------
119
205
  const patchPath = join(profileDir, 'cordis.patch.yml')
120
206
 
@@ -142,12 +228,11 @@ const modelEntry = `- id: agent-default-model
142
228
  // nested plugin ids are indented — the ^ anchor keeps the check off them.
143
229
  const hasEntry = (text, id) => new RegExp(`^- id: ${id}\\s*$`, 'm').test(text)
144
230
 
145
- // True when the patch layer carries NO top-level entries at all (missing
146
- // file, empty, comments only, or a bare `[]` flow document — the shipped web
231
+ // True when the patch layer carries NO top-level entries at all (missing file,
232
+ // empty, comments only, or a bare `[]` flow document — the shipped web
147
233
  // template writes exactly that). Such a file has nothing to merge into: it is
148
234
  // replaced rather than appended to, because appending after the `[]` document
149
- // terminator would produce an invalid two-document YAML stream (the host's
150
- // single-document parser rejects it at boot).
235
+ // terminator would produce an invalid two-document YAML stream.
151
236
  const isEmptyListDoc = (text) => {
152
237
  const body = text
153
238
  .split('\n')
@@ -157,56 +242,235 @@ const isEmptyListDoc = (text) => {
157
242
  return body === '' || body === '[]'
158
243
  }
159
244
 
160
- let existing = ''
245
+ let existingPatch = ''
161
246
  try {
162
- existing = readFileSync(patchPath, 'utf8')
247
+ existingPatch = readFileSync(patchPath, 'utf8')
163
248
  } catch {
164
249
  /* no patch layer yet — created below */
165
250
  }
166
251
 
167
- const missing = [
252
+ const missingRoute = [
168
253
  ['llm-pi-ai', providerEntry],
169
254
  ['agent-default-model', modelEntry],
170
- ].filter(([id, body]) => !hasEntry(existing, id))
255
+ ].filter(([id, body]) => !hasEntry(existingPatch, id))
256
+ // The model-facing web tools are managed independently of the plugin tier:
257
+ // re-enabling `tool-web` and pinning the provider are what make `web_search`
258
+ // visible, and the anysearch bundle only installs the provider behind it.
259
+ const toolPatch = planToolPatch(existingPatch)
260
+ // The default MCP server row rides the adapter, so it is tier-scoped:
261
+ // `--plugins=none` installs neither and writes neither (the client alone
262
+ // would surface unfolded `mcp__*` schemas, which is not the promised setup).
263
+ const mcpPatch = planMcpPatch(existingPatch, { enabled: tier !== 'none' })
264
+ const pendingPatchEntries = missingRoute.length + toolPatch.append.length + mcpPatch.append.length
265
+ // Stable state suffix for the progress line (task-visible on a dry run too).
266
+ const webState = `; tool-web ${toolPatch.toolWeb === 'enabled' ? 'enabled' : 'to enable'}, ` +
267
+ `web search ${toolPatch.web === 'pinned' ? 'pinned' : 'to pin anysearch'}, ` +
268
+ `mcp context7 ${mcpPatch.mcp === 'configured' ? 'configured' : mcpPatch.mcp === 'missing' ? 'to add' : 'skipped (--plugins=none)'}`
171
269
 
172
- if (missing.length === 0) {
173
- console.log(
174
- 'provision-opentui-profile: model route already in cordis.patch.yml (llm-pi-ai + agent-default-model) — leaving it untouched',
175
- )
270
+ if (pendingPatchEntries === 0) {
271
+ say(2, 'model route', `${provider}/${model} (already pinned)${webState}`)
272
+ } else if (dryRun) {
273
+ say(2, 'model route', `${provider}/${model} (would write ${pendingPatchEntries} patch entries)${webState}`)
176
274
  } else {
177
- const routeBody = missing.map(([, body]) => body).join('')
178
- const banner =
179
- `# model route (managed by provision-opentui-profile.mjs — provider ${provider}, ` +
180
- `key read by the host from ${apiKeyEnv}):\n`
181
- if (existing && !isEmptyListDoc(existing)) {
182
- // Append after the existing entries; back up before the first
183
- // modification, like install-profile.mjs.
275
+ const routeBanner = missingRoute.length > 0
276
+ ? `# model route (managed by provision-opentui-profile.mjs — provider ${provider}, ` +
277
+ `key read by the host from ${apiKeyEnv}):\n`
278
+ : ''
279
+ const routeBody = missingRoute.map(([, body]) => body).join('')
280
+ const webBanner = toolPatch.append.length > 0
281
+ ? `${missingRoute.length > 0 ? '\n' : ''}# model-facing web tools (managed by ` +
282
+ `provision-opentui-profile.mjs — anysearch needs no key; tool-web is disabled by ` +
283
+ `@deepseek-ai/dsh-web-app and re-enabled here):\n`
284
+ : ''
285
+ const mcpBanner = mcpPatch.append.length > 0
286
+ ? `${missingRoute.length > 0 || toolPatch.append.length > 0 ? '\n' : ''}# MCP (managed by ` +
287
+ `provision-opentui-profile.mjs — the adapter's mcp_list/mcp_call need a client row; ` +
288
+ `context7 needs no key and a failed/offline connection is non-fatal):\n`
289
+ : ''
290
+ const patchBody = `${routeBanner}${routeBody}${webBanner}${toolPatch.append.join('')}${mcpBanner}${mcpPatch.append.join('')}`
291
+ const backupPatch = () => {
292
+ if (!existingPatch) return
184
293
  const backupPath = `${patchPath}.bak-${Date.now()}`
185
294
  renameSync(patchPath, backupPath)
186
- console.log(`provision-opentui-profile: backed up existing patch to ${backupPath}`)
187
- writeFileSync(patchPath, `${existing.replace(/\n*$/, '\n\n')}${banner}${routeBody}`)
188
- console.log(
189
- `provision-opentui-profile: appended route entries [${missing.map(([id]) => id).join(', ')}] to cordis.patch.yml`,
190
- )
295
+ console.log(`${PREFIX}backed up existing patch to ${backupPath}`)
296
+ }
297
+ if (existingPatch && !isEmptyListDoc(existingPatch)) {
298
+ backupPatch()
299
+ writeFileSync(patchPath, `${existingPatch.replace(/\n*$/, '\n\n')}${patchBody}`)
191
300
  } else {
192
- // Missing file or an entry-less document (`[]`): write the list fresh.
193
- if (existing) {
194
- const backupPath = `${patchPath}.bak-${Date.now()}`
195
- renameSync(patchPath, backupPath)
196
- console.log(`provision-opentui-profile: backed up existing patch to ${backupPath}`)
197
- }
301
+ backupPatch()
198
302
  mkdirSync(profileDir, { recursive: true })
199
- writeFileSync(patchPath, `${banner}${routeBody}`)
200
- console.log(
201
- `provision-opentui-profile: wrote route entries [${missing.map(([id]) => id).join(', ')}] to cordis.patch.yml`,
202
- )
303
+ writeFileSync(patchPath, patchBody)
203
304
  }
305
+ say(2, 'model route', `${provider}/${model} (wrote ${pendingPatchEntries} patch entries)${webState}`)
204
306
  }
205
307
 
206
308
  // ---------------------------------------------------------------------------
207
- // 4. Report.
309
+ // 3. Plugins: one batched `dsh plugin add` for everything unsatisfied.
208
310
  // ---------------------------------------------------------------------------
209
- console.log(`provision-opentui-profile: model pinned to ${provider}/${model} (effort ${reasoningEffort}, key env ${apiKeyEnv})`)
210
- console.log('provision-opentui-profile: PASS')
211
- console.log(`the '${PROFILE}' profile serves the host Remote protocol (web-app template)`)
212
- console.log(`launch the client with: dsh-opentui (the bin re-runs this provisioning idempotently)`)
311
+ const plugins = selectPlugins(tier)
312
+
313
+ /** Fill pnpm's allowBuilds skeleton (or write one for our packages) so the
314
+ * retry can pass pnpm ≥10's ignored-builds gate. Only the closure-linker
315
+ * postinstalls of these plugins are approved; they no-op on published
316
+ * tarballs. A user-written allowBuilds block is never overwritten.
317
+ * Returns whether the workspace file was updated. */
318
+ function approvePrintedBuilds(names) {
319
+ const workspace = join(profileDir, 'pnpm-workspace.yaml')
320
+ try {
321
+ const text = readFileSync(workspace, 'utf8')
322
+ if (text.includes('set this to true or false')) {
323
+ writeFileSync(workspace, text.replaceAll('set this to true or false', 'true'))
324
+ return true
325
+ }
326
+ if (text.includes('allowBuilds:')) return false
327
+ const block = ['allowBuilds:', ...names.map((name) => ` '${name}': true`)].join('\n')
328
+ writeFileSync(workspace, `${text.replace(/\n*$/, '\n')}${block}\n`)
329
+ return true
330
+ } catch {
331
+ return false
332
+ }
333
+ }
334
+
335
+ function runPluginAdd(specs) {
336
+ return spawnSync('dsh', pluginAddArgs(PROFILE, specs), {
337
+ stdio: 'inherit',
338
+ env: { ...process.env, DSH_HOME: dshHome },
339
+ timeout: INSTALL_TIMEOUT_MS,
340
+ })
341
+ }
342
+
343
+ const failedInstalls = []
344
+ let installedCount = 0
345
+
346
+ if (tier === 'none') {
347
+ say(3, 'plugins', 'skipped (--plugins=none)')
348
+ } else {
349
+ const manifest = readManifest() ?? {}
350
+ const dependencies = manifestDependencies(manifest)
351
+ const bundles = manifestBundles(manifest)
352
+ const installedVersions = Object.fromEntries(
353
+ plugins.map((plugin) => [plugin.name, installedVersion(plugin.name)]),
354
+ )
355
+ const plan = planPluginInstall({ tier, dependencies, bundles, installedVersions })
356
+ const specs = plan.install.map((entry) => entry.spec)
357
+ const skipped = plan.total - plan.install.length
358
+
359
+ if (plan.install.length === 0) {
360
+ say(3, 'plugins', `already satisfied (${plan.total}/${plan.total})`)
361
+ } else if (dryRun) {
362
+ say(3, 'plugins', `found ${skipped}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
363
+ say(3, 'plugins', `dry run: skipped the install (${skipped} already satisfied)`)
364
+ } else {
365
+ requireDsh()
366
+ say(3, 'plugins', `found ${skipped}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
367
+ const batch = runPluginAdd(specs)
368
+ if (!batch.error && batch.status === 0) {
369
+ installedCount = specs.length
370
+ } else {
371
+ if (batch.error) warn(`plugin install failed to start: ${batch.error.message}`)
372
+ else warn(`plugin install exited ${batch.status}`)
373
+ if (approvePrintedBuilds(plugins.map((plugin) => plugin.name))) {
374
+ say(3, 'plugins', 'approved the printed build scripts (pnpm allowBuilds) — retrying one by one…')
375
+ }
376
+ // Single-package fallback: one bad package must not sink the rest.
377
+ for (const spec of specs) {
378
+ const retry = runPluginAdd([spec])
379
+ if (!retry.error && retry.status === 0) {
380
+ installedCount += 1
381
+ } else {
382
+ failedInstalls.push(spec)
383
+ warn(`could not install ${spec}${retry.error ? `: ${retry.error.message}` : ` (exit ${retry.status})`} — continuing`)
384
+ }
385
+ }
386
+ }
387
+ const failedSuffix = failedInstalls.length > 0 ? `, failed ${failedInstalls.length}` : ''
388
+ say(3, 'plugins', `installed ${installedCount}, skipped ${skipped}${failedSuffix}`)
389
+ }
390
+ }
391
+
392
+ // ---------------------------------------------------------------------------
393
+ // 4. Bundles: clean retired entries, append missing managed bundles in the
394
+ // install order (ask-router first).
395
+ // ---------------------------------------------------------------------------
396
+ {
397
+ const parsedManifest = readManifest()
398
+ const manifest = parsedManifest ?? {}
399
+ const dependencies = manifestDependencies(manifest)
400
+ // In a dry run the install above did not run: treat its specs as delivered
401
+ // so the bundle plan still prints what a real run would append.
402
+ const plannedNames = new Set(selectPlugins(tier).map((plugin) => plugin.name))
403
+ const effectiveDependencies = { ...dependencies }
404
+ if (dryRun) for (const name of plannedNames) if (!(name in effectiveDependencies)) effectiveDependencies[name] = 'dry-run'
405
+
406
+ const depClean = cleanupDependencies(effectiveDependencies)
407
+ // Only bundles whose dependency actually landed: a failed install must not
408
+ // leave a bundle entry that cannot resolve at boot.
409
+ const managedOrder = tier === 'none'
410
+ ? []
411
+ : selectPlugins(tier).map((plugin) => plugin.name).filter((name) => name in effectiveDependencies)
412
+ const merged = mergeBundles(manifestBundles(manifest), { managedOrder, retire: RETIRED_PROFILE_ENTRIES })
413
+ const changed = depClean.removed.length > 0 || merged.removed.length > 0 || merged.appended.length > 0 || merged.reordered
414
+
415
+ if (parsedManifest === null && existsSync(manifestPath)) {
416
+ warn(`${manifestPath} is not a valid JSON manifest — leaving it untouched`)
417
+ say(4, 'bundles', 'skipped (unreadable profile manifest)')
418
+ } else if (!changed) {
419
+ say(4, 'bundles', `up to date (${merged.bundles.length} entries)`)
420
+ } else if (dryRun) {
421
+ const parts = []
422
+ if (merged.removed.length > 0) parts.push(`would remove ${merged.removed.length} legacy entry (${merged.removed.join(', ')})`)
423
+ if (merged.appended.length > 0) parts.push(`would append ${merged.appended.length} bundle entries`)
424
+ if (merged.reordered) parts.push('would reorder managed bundles (ask-router first)')
425
+ say(4, 'bundles', `${parts.join('; ')} (dry run)`)
426
+ } else {
427
+ const next = { ...manifest, dependencies: depClean.dependencies }
428
+ next.dsh = {
429
+ ...(manifest.dsh ?? {}),
430
+ profile: { ...(manifest.dsh?.profile ?? {}), bundles: merged.bundles },
431
+ }
432
+ writeManifest(next)
433
+ let reported = false
434
+ if (merged.removed.length > 0 || depClean.removed.length > 0) {
435
+ const removed = [...new Set([...merged.removed, ...depClean.removed])]
436
+ say(4, 'bundles', `removed ${removed.length} legacy entry (${removed.join(', ')})`)
437
+ reported = true
438
+ }
439
+ if (merged.appended.length > 0) {
440
+ say(4, 'bundles', `appended ${merged.appended.length} bundle entries`)
441
+ reported = true
442
+ }
443
+ if (merged.reordered) {
444
+ say(4, 'bundles', `${merged.appended.length > 0 ? 'also ' : ''}reordered managed bundles (ask-router first)`)
445
+ reported = true
446
+ }
447
+ if (!reported) say(4, 'bundles', `up to date (${merged.bundles.length} entries)`)
448
+ }
449
+ }
450
+
451
+ // ---------------------------------------------------------------------------
452
+ // 5. Verify: compose the profile and report skipped bundles as WARN.
453
+ // ---------------------------------------------------------------------------
454
+ if (dryRun) {
455
+ say(5, 'verify', 'dry run: skipped')
456
+ } else if (!existsSync(manifestPath)) {
457
+ say(5, 'verify', 'skipped (no profile manifest)')
458
+ } else {
459
+ requireDsh()
460
+ const run = spawnSync('dsh', [PROFILE, '--dump-config'], {
461
+ env: { ...process.env, DSH_HOME: dshHome },
462
+ encoding: 'utf8',
463
+ maxBuffer: 64 * 1024 * 1024,
464
+ timeout: 2 * 60 * 1000,
465
+ })
466
+ if (run.error || run.status !== 0) {
467
+ warn(`verify: \`dsh ${PROFILE} --dump-config\` ${run.error ? `failed: ${run.error.message}` : `exited ${run.status}`}`)
468
+ say(5, 'verify', `failed${run.error ? '' : ` (exit ${run.status})`} — the client will report boot details`)
469
+ } else {
470
+ const { layers, skipped } = parseDumpConfig(run.stdout, run.stderr)
471
+ for (const line of skipped) warn(line)
472
+ say(5, 'verify', `composed ${layers} layers, ${skipped.length} skipped`)
473
+ }
474
+ }
475
+
476
+ console.log(`${PREFIX}PASS`)