@aiwayds/dsh-opentui 0.27.2 → 0.28.1

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.
@@ -1,806 +0,0 @@
1
- #!/usr/bin/env node
2
- // provision-opentui-profile.mjs — idempotent bootstrap of the fixed `opentui`
3
- // host profile (ADR-0005 decisions 3 and 5).
4
- //
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:
7
- //
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). Also retires
34
- // orphan patchedDependencies entries from the profile's
35
- // pnpm-workspace.yaml — a patch whose target package is
36
- // no longer a dependency fails every pnpm install with
37
- // ERR_PNPM_UNUSED_PATCH (the plugin-mode installer
38
- // registered a solid-js patch that 0.9.7 profiles no
39
- // longer need). The patch files in patches/ are kept.
40
- // [5/5] verify — `dsh opentui --dump-config`; "skipping profile
41
- // bundle" lines become WARN lines, never a failure.
42
- //
43
- // Idempotency contract (step 3): a plugin needs no work only when
44
- // (a) it is in the profile `dependencies`,
45
- // (b) `node_modules/<pkg>/package.json` exists and its version satisfies the
46
- // effective pin — the shipped pin, or the newer version recorded in
47
- // `upgrade-overrides.json` by `dsh-opentui upgrade` — and
48
- // (c) its name is in `dsh.profile.bundles`.
49
- // A dep pinned with a local spec (link:/file:/workspace:) always counts as
50
- // satisfied — a local development pin is never replaced by a registry version.
51
- // Missing deps/versions → ONE batched `dsh plugin --profile opentui add
52
- // <specs...>`; on failure the pnpm build-script skeleton is approved and each
53
- // package is installed on its own with bounded spaced retries (a transient
54
- // registry failure — TLS reset / ERR_PNPM_META_FETCH_FAIL — dies in seconds,
55
- // a re-attempt after a short gap rides the burst out). A DETERMINISTIC
56
- // failure (ERR_PNPM_UNUSED_PATCH, ERR_PNPM_NO_MATCHING_VERSION, 404-class,
57
- // EACCES/EPERM — classifyPluginAddFailure) skips the retries outright and is
58
- // reported first with an actionable hint; unknown failures still retry.
59
- // A still-failing package is a WARN, never a hard stop (the client still
60
- // launches).
61
- //
62
- // Step 4 reparses the profile manifest after the install: `dsh plugin add`
63
- // already reconciles bundles for new dependencies, so this only fills the gaps
64
- // (historic profiles) and enforces the managed order. Any manifest write is
65
- // preceded by a `.bak-<ts>` copy.
66
- //
67
- // Hard guard: this script only ever touches the ONE profile named `opentui`.
68
- //
69
- // Dry run: `--dry-run` (or DSH_PROVISION_DRY_RUN=1) prints what it would do —
70
- // commands, entry counts — and writes nothing.
71
- //
72
- // Requires a global `dsh` on PATH for the creating/installing/verifying steps;
73
- // a dry run needs neither. The provider key is read by the host from the
74
- // apiKeyEnv environment variable (this script only names it in the patch; it
75
- // never handles key values).
76
-
77
- import { spawnSync } from 'node:child_process'
78
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
79
- import { homedir } from 'node:os'
80
- import { join } from 'node:path'
81
- import {
82
- DEFAULT_TIER,
83
- PREFIX,
84
- PROFILE,
85
- RETIRED_PROFILE_ENTRIES,
86
- cleanupDependencies,
87
- formatStep,
88
- isDryRun,
89
- mergeBundles,
90
- orderPluginAddFailures,
91
- parseDumpConfig,
92
- parseTier,
93
- partitionInstallByRetryState,
94
- planMcpPatch,
95
- planOrphanPatchCleanup,
96
- planPluginInstall,
97
- planToolPatch,
98
- pluginAddArgs,
99
- pluginAddCommand,
100
- pluginAddRetryDecision,
101
- selectPlugins,
102
- verifyInstalledPins,
103
- } from './lib/provision-plan.mjs'
104
- import {
105
- emptyState,
106
- parseState,
107
- recordInstallOutcomes,
108
- serializeState,
109
- } from './lib/provision-state.mjs'
110
-
111
- const TEMPLATE = 'web'
112
- const INSTALL_TIMEOUT_MS = 10 * 60 * 1000
113
- // Bounded retry schedule for a single-spec install that failed (the fallback
114
- // loop below). A transient registry failure (TLS reset / ERR_PNPM_META_FETCH_
115
- // FAIL) exits within seconds, so 3 attempts spaced 5s apart ride the burst
116
- // out without meaningfully extending a healthy provisioning run: the worst
117
- // case adds ~2 fast failures + 2 x 5s per FAILING spec, and a hung `dsh
118
- // plugin add` is still bounded by INSTALL_TIMEOUT_MS per invocation.
119
- // DETERMINISTIC failures (ERR_PNPM_UNUSED_PATCH, ERR_PNPM_NO_MATCHING_VERSION,
120
- // 404/ENOTFOUND, EACCES/EPERM — see classifyPluginAddFailure) are exempt:
121
- // retrying cannot fix them, so the spec gives up on the first hit and the
122
- // summary reports it first with an actionable hint.
123
- const PLUGIN_ADD_ATTEMPTS = 3
124
- const PLUGIN_ADD_BACKOFF_MS = 5000
125
-
126
- const args = process.argv.slice(2)
127
- /** --name=value or --name value. */
128
- const opt = (name) => {
129
- const inline = args.find((arg) => arg.startsWith(`--${name}=`))
130
- if (inline) return inline.slice(name.length + 3)
131
- const i = args.indexOf(`--${name}`)
132
- return i >= 0 ? args[i + 1] : undefined
133
- }
134
-
135
- const provider = opt('provider') || 'zai-coding-cn'
136
- const model = opt('model') || 'glm-5.3-flash'
137
- const reasoningEffort = opt('reasoning-effort') || 'high'
138
- const dryRun = isDryRun(args, process.env)
139
- const tier = parseTier(opt('plugins') ?? process.env.DSH_OPENTUI_PLUGINS ?? DEFAULT_TIER)
140
- // dsh convention: deriveKeyRef — uppercased, non-alnum → underscore, +_API_KEY
141
- const apiKeyEnv = `${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`
142
-
143
- const say = (step, label, value = '') => console.log(formatStep(step, label, value))
144
- const warn = (message) => console.error(`${PREFIX}WARN ${message}`)
145
-
146
- function fail(message, detail = '') {
147
- console.error(`${PREFIX}FAIL — ${message}`)
148
- if (detail) console.error(detail.trimEnd())
149
- process.exit(1)
150
- }
151
-
152
- // ---------------------------------------------------------------------------
153
- // 1. Resolve the dsh home and the profile.
154
- // ---------------------------------------------------------------------------
155
- const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
156
- const profileDir = join(dshHome, 'profiles', PROFILE)
157
- const manifestPath = join(profileDir, 'package.json')
158
- // Written by `dsh-opentui upgrade` (never by this script): the versions that
159
- // command installed above the shipped pins. Read-only here.
160
- const overridePath = join(profileDir, 'upgrade-overrides.json')
161
- // Cross-launch failure memory (see lib/provision-state.mjs). Sits next to
162
- // `.plugin-manager/`, so it travels with the profile and nowhere else.
163
- const statePath = join(profileDir, '.provision-state.json')
164
- console.log(`${PREFIX}dsh home ${dshHome}`)
165
-
166
- const requireDsh = () => {
167
- const which = spawnSync('which', ['dsh'], { encoding: 'utf8' })
168
- if (which.status !== 0 || !which.stdout.trim()) {
169
- fail('no global `dsh` on PATH — install the dsh host CLI first')
170
- }
171
- }
172
-
173
- if (existsSync(profileDir)) {
174
- say(1, 'profile', `reusing ${profileDir}`)
175
- } else {
176
- say(1, 'profile', `creating from ${TEMPLATE} template…`)
177
- if (!dryRun) {
178
- requireDsh()
179
- const run = spawnSync('dsh', [PROFILE, '--from-default-profile', TEMPLATE, '--dump-config'], {
180
- // DSH_HOME is explicit so the profile lands in the resolved home even
181
- // when the caller's env was missing or divergent.
182
- env: { ...process.env, DSH_HOME: dshHome },
183
- encoding: 'utf8',
184
- maxBuffer: 64 * 1024 * 1024,
185
- })
186
- if (run.error) fail(`failed to run dsh: ${run.error.message}`)
187
- if (run.status !== 0) {
188
- fail(
189
- `\`dsh ${PROFILE} --from-default-profile ${TEMPLATE} --dump-config\` exited ${run.status}`,
190
- [run.stderr, run.stdout].filter(Boolean).join('\n').slice(-2000),
191
- )
192
- }
193
- if (!existsSync(profileDir)) {
194
- fail(
195
- `dsh exited 0 but ${profileDir} was not created — unexpected CLI behavior; refusing to continue`,
196
- run.stdout.slice(-2000),
197
- )
198
- }
199
- }
200
- }
201
-
202
- // ---------------------------------------------------------------------------
203
- // Manifest helpers — everything below reads the profile through these.
204
- // ---------------------------------------------------------------------------
205
- /** The parsed profile manifest, or null when absent/unreadable. Callers that
206
- * write must distinguish null (do not clobber a corrupt file) from {}. */
207
- function readManifest() {
208
- try {
209
- const parsed = JSON.parse(readFileSync(manifestPath, 'utf8'))
210
- return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? parsed : null
211
- } catch {
212
- return null
213
- }
214
- }
215
-
216
- const manifestDependencies = (manifest) =>
217
- typeof manifest.dependencies === 'object' && manifest.dependencies !== null ? manifest.dependencies : {}
218
- const manifestBundles = (manifest) =>
219
- Array.isArray(manifest.dsh?.profile?.bundles) ? manifest.dsh.profile.bundles : []
220
-
221
- function installedVersion(name) {
222
- try {
223
- return JSON.parse(readFileSync(join(profileDir, 'node_modules', ...name.split('/'), 'package.json'), 'utf8')).version
224
- } catch {
225
- return undefined
226
- }
227
- }
228
-
229
- /** The `packages` map of `upgrade-overrides.json`, or {} when the file is
230
- * absent, unreadable, not JSON, or not the documented shape. Every failure
231
- * degrades to "no overrides", which keeps a damaged side file from changing
232
- * (or interrupting) provisioning in any way. A MISSING file is the normal
233
- * path and stays silent; a present-but-unusable one is worth a warning,
234
- * because silently reverting to the shipped pins can downgrade plugins. */
235
- function readUpgradeOverrides() {
236
- if (!existsSync(overridePath)) return {}
237
- let parsed
238
- try {
239
- parsed = JSON.parse(readFileSync(overridePath, 'utf8'))
240
- } catch {
241
- console.error(
242
- `${PREFIX}warning: ignoring upgrade overrides; shipped pins will be used (${overridePath} is unreadable or not valid JSON)`,
243
- )
244
- return {}
245
- }
246
- if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
247
- console.error(
248
- `${PREFIX}warning: ignoring upgrade overrides; shipped pins will be used (${overridePath} is not a JSON object)`,
249
- )
250
- return {}
251
- }
252
- const packages = parsed.packages
253
- if (typeof packages !== 'object' || packages === null || Array.isArray(packages)) {
254
- console.error(
255
- `${PREFIX}warning: ignoring upgrade overrides; shipped pins will be used (${overridePath} has no "packages" object)`,
256
- )
257
- return {}
258
- }
259
- return packages
260
- }
261
-
262
- /** The failure memory of previous launches. A missing file is the normal
263
- * first-run path; an unreadable one degrades to "no memory" (everything is
264
- * retried) and is NOT reported: the file is an optimisation, and a warning
265
- * on every start would be noise the user cannot act on. The raw text is
266
- * returned too, so the caller can skip a write when nothing changed. */
267
- function readProvisionState() {
268
- let text = ''
269
- try {
270
- text = readFileSync(statePath, 'utf8')
271
- } catch {
272
- return { state: emptyState(), text: '' }
273
- }
274
- return { state: parseState(text) ?? emptyState(), text }
275
- }
276
-
277
- /** Persist the failure memory only when it changed. Same-directory temp then
278
- * rename: a crash mid-write cannot leave a torn JSON document that the next
279
- * start would silently ignore. A write failure is a WARN, never a failed
280
- * provisioning run — the state file only ever removes retries. */
281
- function writeProvisionState(state, previousText) {
282
- const text = serializeState(state)
283
- if (text === previousText) return false
284
- try {
285
- mkdirSync(profileDir, { recursive: true })
286
- const tmpPath = `${statePath}.tmp`
287
- writeFileSync(tmpPath, text)
288
- renameSync(tmpPath, statePath)
289
- return true
290
- } catch (err) {
291
- warn(`could not write ${statePath}: ${err?.message ?? err}`)
292
- return false
293
- }
294
- }
295
-
296
- /** Last non-empty stderr line, flattened to the state file's single-line
297
- * budget. `dsh plugin add` puts pnpm's error code on that line. */
298
- function lastStderrLine(stderr) {
299
- const text = typeof stderr === 'string' ? stderr : stderr?.toString() ?? ''
300
- const lines = text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== '')
301
- return lines.length > 0 ? lines[lines.length - 1].slice(-200) : ''
302
- }
303
-
304
- /** Backup-then-write the profile manifest (the backup is the contract: a
305
- * failed run never leaves the user without their previous manifest). */
306
- function writeManifest(manifest) {
307
- if (existsSync(manifestPath)) {
308
- const backupPath = `${manifestPath}.bak-${Date.now()}`
309
- renameSync(manifestPath, backupPath)
310
- console.log(`${PREFIX}backed up ${manifestPath} to ${backupPath}`)
311
- } else {
312
- mkdirSync(profileDir, { recursive: true })
313
- }
314
- writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
315
- }
316
-
317
- // ---------------------------------------------------------------------------
318
- // 2. Model route: write/merge the provider route into cordis.patch.yml.
319
- // Per-entry idempotent append: an entry already present is left untouched,
320
- // so a re-run never duplicates entries or clobbers an edited model.
321
- // ---------------------------------------------------------------------------
322
- const patchPath = join(profileDir, 'cordis.patch.yml')
323
-
324
- const providerEntry = `- id: llm-pi-ai
325
- name: "@deepseek-ai/dsh-llm-pi-ai"
326
- config:
327
- providers:
328
- ${provider}:
329
- apiKeyEnv: ${apiKeyEnv}
330
- models:
331
- - id: ${model}
332
- name: ${model}
333
- input:
334
- - text
335
- `
336
- const modelEntry = `- id: agent-default-model
337
- name: "@deepseek-ai/dsh-agent-default-model"
338
- config:
339
- provider: ${provider}
340
- model: ${model}
341
- reasoningEffort: ${reasoningEffort}
342
- `
343
-
344
- // Top-level entries only: the file is a YAML array of `- id:` entries, and
345
- // nested plugin ids are indented — the ^ anchor keeps the check off them.
346
- const hasEntry = (text, id) => new RegExp(`^- id: ${id}\\s*$`, 'm').test(text)
347
-
348
- // True when the patch layer carries NO top-level entries at all (missing file,
349
- // empty, comments only, or a bare `[]` flow document — the shipped web
350
- // template writes exactly that). Such a file has nothing to merge into: it is
351
- // replaced rather than appended to, because appending after the `[]` document
352
- // terminator would produce an invalid two-document YAML stream.
353
- const isEmptyListDoc = (text) => {
354
- const body = text
355
- .split('\n')
356
- .filter((line) => { const t = line.trim(); return t !== '' && !t.startsWith('#') })
357
- .join('\n')
358
- .trim()
359
- return body === '' || body === '[]'
360
- }
361
-
362
- let existingPatch = ''
363
- try {
364
- existingPatch = readFileSync(patchPath, 'utf8')
365
- } catch {
366
- /* no patch layer yet — created below */
367
- }
368
-
369
- const missingRoute = [
370
- ['llm-pi-ai', providerEntry],
371
- ['agent-default-model', modelEntry],
372
- ].filter(([id, body]) => !hasEntry(existingPatch, id))
373
- // The model-facing web tools are managed independently of the plugin tier:
374
- // re-enabling `tool-web` and pinning the provider are what make `web_search`
375
- // visible, and the anysearch bundle only installs the provider behind it.
376
- const toolPatch = planToolPatch(existingPatch)
377
- // The default MCP server row rides the adapter, so it is tier-scoped:
378
- // `--plugins=none` installs neither and writes neither (the client alone
379
- // would surface unfolded `mcp__*` schemas, which is not the promised setup).
380
- const mcpPatch = planMcpPatch(existingPatch, { enabled: tier !== 'none' })
381
- const pendingPatchEntries = missingRoute.length + toolPatch.append.length + mcpPatch.append.length
382
- // Stable state suffix for the progress line (task-visible on a dry run too).
383
- const webState = `; tool-web ${toolPatch.toolWeb === 'enabled' ? 'enabled' : 'to enable'}, ` +
384
- `web search ${toolPatch.web === 'pinned' ? 'pinned' : 'to pin anysearch'}, ` +
385
- `mcp context7 ${mcpPatch.mcp === 'configured' ? 'configured' : mcpPatch.mcp === 'missing' ? 'to add' : 'skipped (--plugins=none)'}`
386
-
387
- if (pendingPatchEntries === 0) {
388
- say(2, 'model route', `${provider}/${model} (already pinned)${webState}`)
389
- } else if (dryRun) {
390
- say(2, 'model route', `${provider}/${model} (would write ${pendingPatchEntries} patch entries)${webState}`)
391
- } else {
392
- const routeBanner = missingRoute.length > 0
393
- ? `# model route (managed by provision-opentui-profile.mjs — provider ${provider}, ` +
394
- `key read by the host from ${apiKeyEnv}):\n`
395
- : ''
396
- const routeBody = missingRoute.map(([, body]) => body).join('')
397
- const webBanner = toolPatch.append.length > 0
398
- ? `${missingRoute.length > 0 ? '\n' : ''}# model-facing web tools (managed by ` +
399
- `provision-opentui-profile.mjs — anysearch needs no key; tool-web is disabled by ` +
400
- `@deepseek-ai/dsh-web-app and re-enabled here):\n`
401
- : ''
402
- const mcpBanner = mcpPatch.append.length > 0
403
- ? `${missingRoute.length > 0 || toolPatch.append.length > 0 ? '\n' : ''}# MCP (managed by ` +
404
- `provision-opentui-profile.mjs — the adapter's mcp_list/mcp_call need a client row; ` +
405
- `context7 needs no key and a failed/offline connection is non-fatal):\n`
406
- : ''
407
- const patchBody = `${routeBanner}${routeBody}${webBanner}${toolPatch.append.join('')}${mcpBanner}${mcpPatch.append.join('')}`
408
- const backupPatch = () => {
409
- if (!existingPatch) return
410
- const backupPath = `${patchPath}.bak-${Date.now()}`
411
- renameSync(patchPath, backupPath)
412
- console.log(`${PREFIX}backed up existing patch to ${backupPath}`)
413
- }
414
- if (existingPatch && !isEmptyListDoc(existingPatch)) {
415
- backupPatch()
416
- writeFileSync(patchPath, `${existingPatch.replace(/\n*$/, '\n\n')}${patchBody}`)
417
- } else {
418
- backupPatch()
419
- mkdirSync(profileDir, { recursive: true })
420
- writeFileSync(patchPath, patchBody)
421
- }
422
- say(2, 'model route', `${provider}/${model} (wrote ${pendingPatchEntries} patch entries)${webState}`)
423
- }
424
-
425
- // ---------------------------------------------------------------------------
426
- // 3. Plugins: one batched `dsh plugin add` for everything unsatisfied.
427
- // ---------------------------------------------------------------------------
428
- const plugins = selectPlugins(tier)
429
-
430
- /** Fill pnpm's allowBuilds skeleton (or write one for our packages) so the
431
- * retry can pass pnpm ≥10's ignored-builds gate. Only the closure-linker
432
- * postinstalls of these plugins are approved; they no-op on published
433
- * tarballs. A user-written allowBuilds block is never overwritten.
434
- * Returns whether the workspace file was updated. */
435
- function approvePrintedBuilds(names) {
436
- const workspace = join(profileDir, 'pnpm-workspace.yaml')
437
- try {
438
- const text = readFileSync(workspace, 'utf8')
439
- if (text.includes('set this to true or false')) {
440
- writeFileSync(workspace, text.replaceAll('set this to true or false', 'true'))
441
- return true
442
- }
443
- if (text.includes('allowBuilds:')) return false
444
- const block = ['allowBuilds:', ...names.map((name) => ` '${name}': true`)].join('\n')
445
- writeFileSync(workspace, `${text.replace(/\n*$/, '\n')}${block}\n`)
446
- return true
447
- } catch {
448
- return false
449
- }
450
- }
451
-
452
- function runPluginAdd(specs, { captureStderr = false } = {}) {
453
- return spawnSync('dsh', pluginAddArgs(PROFILE, specs), {
454
- // The per-spec retry captures stderr (the batch install keeps it live) so
455
- // the failure classifier can read pnpm's error codes; the captured text
456
- // is echoed back right after the run so nothing the user used to see is
457
- // swallowed.
458
- stdio: captureStderr ? ['inherit', 'inherit', 'pipe'] : 'inherit',
459
- env: { ...process.env, DSH_HOME: dshHome },
460
- timeout: INSTALL_TIMEOUT_MS,
461
- maxBuffer: 16 * 1024 * 1024,
462
- })
463
- }
464
-
465
- /** Echo a captured stderr back to the terminal (tail only — pnpm banners can
466
- * be long, the error code is at the end). */
467
- function echoCapturedStderr(stderr) {
468
- const text = typeof stderr === 'string' ? stderr : stderr?.toString() ?? ''
469
- if (text.trim()) console.error(text.trimEnd().slice(-2000))
470
- }
471
-
472
- /** Synchronous pause (this script is spawnSync end to end; there is no event
473
- * loop to await on). */
474
- function pauseSync(ms) {
475
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
476
- }
477
-
478
- const failedInstalls = [] // { spec, failure: { kind, code, hint } }
479
-
480
- if (tier === 'none') {
481
- say(3, 'plugins', 'skipped (--plugins=none)')
482
- } else {
483
- const manifest = readManifest() ?? {}
484
- const dependencies = manifestDependencies(manifest)
485
- const bundles = manifestBundles(manifest)
486
- const installedVersions = Object.fromEntries(
487
- plugins.map((plugin) => [plugin.name, installedVersion(plugin.name)]),
488
- )
489
- // A version recorded by `dsh-opentui upgrade` raises the effective pin, so an
490
- // already-upgraded plugin is satisfied at that version instead of being
491
- // pulled back to the shipped pin on every start.
492
- const overrides = readUpgradeOverrides()
493
- const plan = planPluginInstall({ tier, dependencies, bundles, installedVersions, overrides })
494
- // Failure memory: what previous launches learned about these pins. The file
495
- // only ever REMOVES retries (see lib/provision-state.mjs); a missing or
496
- // unreadable one is read as "no memory", silently.
497
- const { state: retryState, text: stateText } = readProvisionState()
498
- // The launch time decides which pins are inside their backoff window. It is
499
- // NOT the failure timestamp: that one is taken when the installs finish (see
500
- // recordInstallOutcomes below), so a long failing batch still buys the full
501
- // backoff window.
502
- const launchIso = new Date().toISOString()
503
- const { install: targets, skips } = partitionInstallByRetryState({
504
- install: plan.install,
505
- state: retryState,
506
- now: launchIso,
507
- })
508
- const specs = targets.map((entry) => entry.spec)
509
- const satisfied = plan.total - plan.install.length
510
- const skipped = satisfied + skips.length
511
- let nextState = retryState
512
-
513
- if (skips.length > 0) {
514
- const detail = skips
515
- .map((row) => `${row.name}@${row.pin} (${row.attempts} attempt${row.attempts === 1 ? '' : 's'}, since ${row.lastFailedAt})`)
516
- .join(', ')
517
- console.error(
518
- `${PREFIX}skipping ${skips.length} package(s) after repeated failures: ${detail}` +
519
- ` (retry in 24h, or rm ${statePath} to retry now)`,
520
- )
521
- }
522
-
523
- if (plan.install.length === 0) {
524
- say(3, 'plugins', `already satisfied (${plan.total}/${plan.total})`)
525
- } else if (dryRun) {
526
- if (specs.length === 0) {
527
- say(3, 'plugins', `found ${satisfied}/${plan.total}, installing 0… (${skips.length} in failure backoff)`)
528
- } else {
529
- say(3, 'plugins', `found ${satisfied}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
530
- }
531
- say(3, 'plugins', `dry run: skipped the install (${satisfied} already satisfied)`)
532
- } else if (specs.length === 0) {
533
- // Every unsatisfied pin is inside its backoff window: spawn nothing.
534
- say(3, 'plugins', `installed 0, skipped ${skipped} (${skips.length} in failure backoff)`)
535
- } else {
536
- requireDsh()
537
- say(3, 'plugins', `found ${satisfied}/${plan.total}, installing ${specs.length}… → running: ${pluginAddCommand(PROFILE, specs)}`)
538
- // name -> { ok, error }: the final word on each target, recorded ONCE at
539
- // the end of the run so the batch set and the single-spec fallback cannot
540
- // double-count one launch.
541
- const outcomes = new Map()
542
- let degraded = 0
543
- // Captured so the batch's last stderr line can be stored as the failure
544
- // reason; the text is echoed below, so nothing the user used to see on the
545
- // terminal is lost.
546
- const batch = runPluginAdd(specs, { captureStderr: true })
547
- if (!batch.error && batch.status === 0) {
548
- // Readback: compare what actually landed with the EFFECTIVE pin (the
549
- // shipped pin, or the newer version an override raises it to). A batch
550
- // that exits 0 is not proof that the profile is at the pinned version.
551
- const landed = Object.fromEntries(targets.map((entry) => [entry.name, installedVersion(entry.name)]))
552
- for (const result of verifyInstalledPins({ install: targets, installedVersions: landed })) {
553
- if (result.ok) outcomes.set(result.name, { ok: true })
554
- else {
555
- outcomes.set(result.name, {
556
- ok: false,
557
- error: `installed ${result.installed ?? 'nothing'}, expected ${result.pin}`,
558
- })
559
- }
560
- }
561
- } else {
562
- if (batch.error) {
563
- warn(`plugin install failed to start: ${batch.error.message}`)
564
- } else {
565
- echoCapturedStderr(batch.stderr)
566
- warn(`plugin install exited ${batch.status}`)
567
- }
568
- // The whole batch failed, so every target is a failure until its own
569
- // fallback attempt proves otherwise. `batchError` is the last stderr
570
- // line (pnpm's error code), which the summary below must not hide.
571
- const batchError =
572
- lastStderrLine(batch.stderr) ||
573
- (batch.error ? batch.error.message : `dsh plugin add exited ${batch.status}`)
574
- for (const entry of targets) outcomes.set(entry.name, { ok: false, error: batchError })
575
- if (approvePrintedBuilds(plugins.map((plugin) => plugin.name))) {
576
- say(3, 'plugins', 'approved the printed build scripts (pnpm allowBuilds) — retrying one by one…')
577
- }
578
- // Single-package fallback: one bad package must not sink the rest.
579
- // Each failing spec gets bounded spaced retries (PLUGIN_ADD_ATTEMPTS /
580
- // PLUGIN_ADD_BACKOFF_MS): a transient registry failure rides the burst
581
- // out instead of WARN-ing the plugin away on the first drop. A
582
- // DETERMINISTIC failure (pluginAddRetryDecision) is exempt — retrying
583
- // cannot fix it, so the spec gives up on the first hit. The terminal
584
- // failure stays a WARN + failedInstalls entry — never a silent pass
585
- // (the e2e npm-install boot leg asserts the delivered set).
586
- for (const entry of targets) {
587
- let installed = false
588
- for (let attempt = 1; attempt <= PLUGIN_ADD_ATTEMPTS && !installed; attempt += 1) {
589
- if (attempt > 1) {
590
- say(3, 'plugins', `${entry.spec} failed — retry ${attempt - 1}/${PLUGIN_ADD_ATTEMPTS - 1} in ${PLUGIN_ADD_BACKOFF_MS / 1000}s…`)
591
- pauseSync(PLUGIN_ADD_BACKOFF_MS)
592
- }
593
- const retry = runPluginAdd([entry.spec], { captureStderr: true })
594
- echoCapturedStderr(retry.stderr)
595
- const decision = pluginAddRetryDecision(retry, { attempt, attempts: PLUGIN_ADD_ATTEMPTS })
596
- if (decision.action === 'installed') {
597
- installed = true
598
- // A fallback success still lands at whatever the registry served:
599
- // verify it rather than trusting the exit code.
600
- const actual = installedVersion(entry.name)
601
- if (actual === entry.pin) outcomes.set(entry.name, { ok: true })
602
- else {
603
- outcomes.set(entry.name, {
604
- ok: false,
605
- error: `installed ${actual ?? 'nothing'}, expected ${entry.pin}`,
606
- })
607
- }
608
- } else if (decision.action === 'failed') {
609
- const detail = retry.error ? retry.error.message : `(exit ${retry.status})`
610
- failedInstalls.push({ spec: entry.spec, failure: decision.failure, detail })
611
- outcomes.set(entry.name, { ok: false, error: lastStderrLine(retry.stderr) || detail })
612
- if (decision.failure.kind === 'deterministic') {
613
- say(3, 'plugins', `${entry.spec}: ${decision.failure.code} — deterministic, not retrying`)
614
- }
615
- break
616
- }
617
- }
618
- }
619
- }
620
- // One write per run: success clears the entry, failure grows it (or starts
621
- // a fresh 24-hour round once the pin has been failing that long). The
622
- // timestamp is taken HERE, after the last install returned, and shared by
623
- // the whole batch: the backoff window is measured from the failure, not
624
- // from process start (a 9-minute failing batch would otherwise leave 1
625
- // minute of the 10-minute window).
626
- const recorded = recordInstallOutcomes({
627
- state: nextState,
628
- now: new Date().toISOString(),
629
- rows: targets.map((entry) => {
630
- const outcome = outcomes.get(entry.name)
631
- return {
632
- name: entry.name,
633
- pin: entry.pin,
634
- ok: outcome?.ok === true,
635
- error: outcome?.error ?? 'install did not complete',
636
- }
637
- }),
638
- })
639
- nextState = recorded.state
640
- degraded += recorded.failed.length
641
- // Only a real change is persisted: a clean successful run must not create
642
- // an empty state file, and a damaged one is left alone until a failure or
643
- // a success actually rewrites the memory.
644
- if (serializeState(nextState) !== serializeState(retryState)) {
645
- writeProvisionState(nextState, stateText)
646
- }
647
- // Summary: deterministic failures first, each with its one-line fix; the
648
- // retried-then-failed ones follow without a hint.
649
- for (const { spec, failure, detail } of orderPluginAddFailures(failedInstalls)) {
650
- warn(
651
- `could not install ${spec}${failure.code ? `: ${failure.code}` : ` ${detail}`}` +
652
- ` — continuing${failure.hint ? ` — ${failure.hint}` : ''}`,
653
- )
654
- }
655
- // The summary counts VERIFIED packages, not attempts: a batch that exited 0
656
- // while leaving a package at another version must not read as a full
657
- // install next to the degraded line below. Skips (already satisfied, or
658
- // held back by the failure backoff) and the not-at-pin packages are named
659
- // separately; the attempt count is the denominator.
660
- const verified = targets.reduce((count, entry) => (outcomes.get(entry.name)?.ok === true ? count + 1 : count), 0)
661
- const hardFailed = failedInstalls.length
662
- const notAtPin = Math.max(0, degraded - hardFailed)
663
- if (degraded === 0 && skips.length === 0) {
664
- say(3, 'plugins', `installed ${verified}, skipped ${skipped}`)
665
- } else {
666
- const parts = []
667
- if (satisfied > 0) parts.push(`${satisfied} already installed`)
668
- if (skips.length > 0) parts.push(`${skips.length} in failure backoff`)
669
- if (notAtPin > 0) parts.push(`${notAtPin} not at the pinned version`)
670
- if (hardFailed > 0) parts.push(`${hardFailed} failed`)
671
- say(3, 'plugins', `installed ${verified} of ${plan.install.length} (${parts.join(', ')})`)
672
- }
673
- // The launcher must still start (exit code stays 0), but a version the pin
674
- // did not reach is not silence: the next start skips this pin and the user
675
- // needs to know why.
676
- if (degraded > 0) {
677
- console.error(
678
- `${PREFIX}degraded — ${degraded} plugin(s) not at the pinned version; see the lines above` +
679
- ` (plugins stay on their installed versions; run "dsh-opentui upgrade" after the registry catches up)`,
680
- )
681
- }
682
- }
683
- }
684
-
685
- // ---------------------------------------------------------------------------
686
- // 4. Bundles: clean retired entries, append missing managed bundles in the
687
- // install order (ask-router first); retire orphan pnpm patches whose
688
- // target package left the dependency graph (they hard-fail every install
689
- // with ERR_PNPM_UNUSED_PATCH).
690
- // ---------------------------------------------------------------------------
691
- {
692
- const parsedManifest = readManifest()
693
- const manifest = parsedManifest ?? {}
694
- const dependencies = manifestDependencies(manifest)
695
- // In a dry run the install above did not run: treat its specs as delivered
696
- // so the bundle plan still prints what a real run would append.
697
- const plannedNames = new Set(selectPlugins(tier).map((plugin) => plugin.name))
698
- const effectiveDependencies = { ...dependencies }
699
- if (dryRun) for (const name of plannedNames) if (!(name in effectiveDependencies)) effectiveDependencies[name] = 'dry-run'
700
-
701
- const depClean = cleanupDependencies(effectiveDependencies)
702
- // Only bundles whose dependency actually landed: a failed install must not
703
- // leave a bundle entry that cannot resolve at boot.
704
- const managedOrder = tier === 'none'
705
- ? []
706
- : selectPlugins(tier).map((plugin) => plugin.name).filter((name) => name in effectiveDependencies)
707
- const merged = mergeBundles(manifestBundles(manifest), { managedOrder, retire: RETIRED_PROFILE_ENTRIES })
708
- const changed = depClean.removed.length > 0 || merged.removed.length > 0 || merged.appended.length > 0 || merged.reordered
709
-
710
- // Orphan pnpm patches: a patchedDependencies entry whose target package is
711
- // no longer a dependency makes every `pnpm` install fail with
712
- // ERR_PNPM_UNUSED_PATCH (the retired plugin-mode installer registered such
713
- // a solid-js patch). The check runs against the post-cleanup dependency
714
- // set — the same set pnpm sees — and is orthogonal to the manifest write
715
- // below: bundles can be up to date while a stale patch still blocks
716
- // installs. The patch FILE in patches/ is kept (record of what was applied);
717
- // only the workspace registration is dropped. No pnpm-workspace.yaml means
718
- // nothing to clean — none is created.
719
- const workspacePath = join(profileDir, 'pnpm-workspace.yaml')
720
- const patchPlan = parsedManifest !== null && existsSync(workspacePath)
721
- ? planOrphanPatchCleanup(readFileSync(workspacePath, 'utf8'), Object.keys(depClean.dependencies))
722
- : null
723
-
724
- if (parsedManifest === null && existsSync(manifestPath)) {
725
- warn(`${manifestPath} is not a valid JSON manifest — leaving it untouched`)
726
- say(4, 'bundles', 'skipped (unreadable profile manifest)')
727
- } else if (!changed) {
728
- say(4, 'bundles', `up to date (${merged.bundles.length} entries)`)
729
- } else if (dryRun) {
730
- const parts = []
731
- if (merged.removed.length > 0) parts.push(`would remove ${merged.removed.length} legacy entry (${merged.removed.join(', ')})`)
732
- if (merged.appended.length > 0) parts.push(`would append ${merged.appended.length} bundle entries`)
733
- if (merged.reordered) parts.push('would reorder managed bundles (ask-router first)')
734
- say(4, 'bundles', `${parts.join('; ')} (dry run)`)
735
- } else {
736
- const next = { ...manifest, dependencies: depClean.dependencies }
737
- next.dsh = {
738
- ...(manifest.dsh ?? {}),
739
- profile: { ...(manifest.dsh?.profile ?? {}), bundles: merged.bundles },
740
- }
741
- writeManifest(next)
742
- let reported = false
743
- if (merged.removed.length > 0 || depClean.removed.length > 0) {
744
- const removed = [...new Set([...merged.removed, ...depClean.removed])]
745
- say(4, 'bundles', `removed ${removed.length} legacy entry (${removed.join(', ')})`)
746
- reported = true
747
- }
748
- if (merged.appended.length > 0) {
749
- say(4, 'bundles', `appended ${merged.appended.length} bundle entries`)
750
- reported = true
751
- }
752
- if (merged.reordered) {
753
- say(4, 'bundles', `${merged.appended.length > 0 ? 'also ' : ''}reordered managed bundles (ask-router first)`)
754
- reported = true
755
- }
756
- if (!reported) say(4, 'bundles', `up to date (${merged.bundles.length} entries)`)
757
- }
758
-
759
- // Retire orphan patches AFTER the manifest write: the logs read as bundle
760
- // summary first, orphan-patch retirement second. `patchPlan` is null
761
- // without a readable manifest or without a pnpm-workspace.yaml — both are
762
- // no-ops (a corrupt manifest already warned above; no workspace file is
763
- // ever created here).
764
- if (patchPlan?.opaque) {
765
- warn('pnpm-workspace.yaml patchedDependencies is not a flat map — leaving it untouched')
766
- } else if (patchPlan?.removed.length > 0) {
767
- if (dryRun) {
768
- say(4, 'bundles', `would retire ${patchPlan.removed.length} orphan patch (${patchPlan.removed.map(([key]) => key).join(', ')}) (dry run)`)
769
- } else {
770
- const backupPath = `${workspacePath}.bak-${Date.now()}`
771
- renameSync(workspacePath, backupPath)
772
- console.log(`${PREFIX}backed up ${workspacePath} to ${backupPath}`)
773
- writeFileSync(workspacePath, patchPlan.text)
774
- for (const [key] of patchPlan.removed) {
775
- say(4, 'bundles', `retired orphan patch ${key} (its target is no longer a dependency)`)
776
- }
777
- }
778
- }
779
- }
780
-
781
- // ---------------------------------------------------------------------------
782
- // 5. Verify: compose the profile and report skipped bundles as WARN.
783
- // ---------------------------------------------------------------------------
784
- if (dryRun) {
785
- say(5, 'verify', 'dry run: skipped')
786
- } else if (!existsSync(manifestPath)) {
787
- say(5, 'verify', 'skipped (no profile manifest)')
788
- } else {
789
- requireDsh()
790
- const run = spawnSync('dsh', [PROFILE, '--dump-config'], {
791
- env: { ...process.env, DSH_HOME: dshHome },
792
- encoding: 'utf8',
793
- maxBuffer: 64 * 1024 * 1024,
794
- timeout: 2 * 60 * 1000,
795
- })
796
- if (run.error || run.status !== 0) {
797
- warn(`verify: \`dsh ${PROFILE} --dump-config\` ${run.error ? `failed: ${run.error.message}` : `exited ${run.status}`}`)
798
- say(5, 'verify', `failed${run.error ? '' : ` (exit ${run.status})`} — the client will report boot details`)
799
- } else {
800
- const { layers, skipped } = parseDumpConfig(run.stdout, run.stderr)
801
- for (const line of skipped) warn(line)
802
- say(5, 'verify', `composed ${layers} layers, ${skipped.length} skipped`)
803
- }
804
- }
805
-
806
- console.log(`${PREFIX}PASS`)