@aiwayds/dsh-opentui 0.9.2 → 0.9.3

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