@aiwayds/dsh-opentui 0.27.1 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,899 +0,0 @@
1
- // Pure planning logic for provision-opentui-profile.mjs.
2
- //
3
- // Nothing in this module touches the filesystem or spawns a process: the
4
- // script feeds it a profile manifest it read, and the unit tests feed it
5
- // fixtures. That split is what makes the idempotency rules (dep present,
6
- // node_modules version satisfies, bundle entry present) testable without a
7
- // network or a real dsh profile.
8
- //
9
- // The failure-memory policy lives in ./provision-state.mjs (also pure); this
10
- // module only applies it to a plan, so "which specs does this launch actually
11
- // run" is testable end to end without a profile.
12
-
13
- import { shouldSkipRetry } from './provision-state.mjs'
14
-
15
- export const PROFILE = 'opentui'
16
- export const PREFIX = 'provision-opentui-profile: '
17
- export const STEPS = 5
18
- export const DEFAULT_TIER = 'recommended'
19
- export const TIERS = ['core', 'recommended', 'none']
20
-
21
- // The plugin set this launcher ships with. `reason` is printed by
22
- // `--dry-run --plugins=<tier>` style troubleshooting and documents WHY a
23
- // package is in the set, so a future reader can re-judge the decision.
24
- //
25
- // Ordering contract: `@aiwayds/dsh-ask-router` MUST stay first among the
26
- // UI/ask bundles — it owns the ask surface every later UI bundle attaches to.
27
- // `selectPlugins()` preserves this array's order, and the installer appends
28
- // bundle entries in that order.
29
- export const PLUGIN_SET = [
30
- {
31
- name: '@aiwayds/dsh-ask-router',
32
- version: '0.7.0',
33
- tier: 'core',
34
- reason: 'owns the ask surface; must load before any other UI/ask bundle',
35
- },
36
- {
37
- name: '@aiwayds/dsh-subagent-registry',
38
- version: '0.20.1',
39
- tier: 'core',
40
- reason: 'subagent discovery and registration for the shell',
41
- },
42
- {
43
- name: '@aiwayds/dsh-llm-net-retry',
44
- version: '0.8.0',
45
- tier: 'core',
46
- reason: 'retries transient provider/network failures',
47
- },
48
- {
49
- name: '@aiwayds/dsh-web-search-anysearch',
50
- version: '0.9.0',
51
- tier: 'core',
52
- reason: 'web search without a per-provider key',
53
- },
54
- {
55
- name: '@aiwayds/dsh-mcp-adapter',
56
- version: '0.8.0',
57
- tier: 'core',
58
- reason: 'MCP catalog/dispatch meta-tools paired with the default context7 server row',
59
- },
60
- {
61
- name: '@aiwayds/dsh-approval-policy',
62
- version: '0.3.0',
63
- tier: 'core',
64
- reason: 'tool-approval policy shared with the shell approval cards',
65
- },
66
- {
67
- name: '@aiwayds/dsh-model-sync',
68
- version: '0.9.0',
69
- tier: 'core',
70
- reason: 'keeps the profile model list in sync with the provider catalog',
71
- },
72
- {
73
- name: '@aiwayds/dsh-llm-stats',
74
- version: '0.9.0',
75
- tier: 'recommended',
76
- reason: 'token/cost accounting behind /usage',
77
- },
78
- {
79
- name: '@aiwayds/dsh-topics-memory',
80
- version: '0.26.0',
81
- tier: 'recommended',
82
- reason: 'cross-session topic memory',
83
- },
84
- {
85
- name: '@aiwayds/dsh-cron',
86
- version: '0.7.0',
87
- tier: 'recommended',
88
- reason: 'scheduled prompts',
89
- },
90
- {
91
- name: '@aiwayds/dsh-workflow',
92
- version: '0.2.1',
93
- tier: 'recommended',
94
- reason: 'dynamic workflow runs',
95
- },
96
- {
97
- name: '@aiwayds/dsh-vault',
98
- version: '0.8.2',
99
- tier: 'recommended',
100
- reason: 'secret storage used by the companion plugins',
101
- },
102
- ]
103
-
104
- // Deliberately NOT installed. Kept explicit so a reviewer can see the
105
- // decision instead of inferring it from an absence.
106
- export const EXCLUDED_PLUGINS = [
107
- { name: '@aiwayds/dsh-tui-pi', reason: 'takes over stdout/stdin — hard conflict with the opentui client' },
108
- { name: '@aiwayds/dsh-dcp', reason: 'web-app-preset isolated; an idle no-op in this profile' },
109
- { name: '@aiwayds/dsh-feishu', reason: 'claims the ask surface and does not fall back' },
110
- { name: '@aiwayds/dsh-agent-dispatch', reason: 'not part of the shell workflow' },
111
- { name: '@aiwayds/dsh-self-improve', reason: 'not part of the shell workflow' },
112
- { name: '@aiwayds/dsh-llm-proxy', reason: 'not part of the shell workflow' },
113
- { name: '@aiwayds/dsh-web-search-tavily', reason: 'requires an API key' },
114
- { name: '@aiwayds/dsh-profile-switch', reason: 'profile switching is the launcher\'s job' },
115
- ]
116
-
117
- // Entries a historic opentui profile may still carry. `@aiwayds/dsh-opentui`
118
- // is the retired plugin-mode package: the global 0.9.2 declares no
119
- // `dsh.bundle`, so every boot prints a "skipping profile bundle" warning, and
120
- // the profile's dependency pointed at a tgz that no longer exists.
121
- export const RETIRED_PROFILE_ENTRIES = ['@aiwayds/dsh-opentui']
122
-
123
- /** Parse the `--plugins=` value (or the DSH_OPENTUI_PLUGINS env override).
124
- * Throws on an unknown tier so a typo cannot silently install nothing. */
125
- export function parseTier(value) {
126
- if (value === undefined || value === null || value === '') return DEFAULT_TIER
127
- const tier = String(value).trim().toLowerCase()
128
- if (!TIERS.includes(tier)) {
129
- throw new Error(`unknown plugin tier ${JSON.stringify(value)} — expected one of: ${TIERS.join(', ')}`)
130
- }
131
- return tier
132
- }
133
-
134
- /** True when the run must only print the commands it would execute. */
135
- export function isDryRun(argv = [], env = {}) {
136
- return argv.includes('--dry-run') || env.DSH_PROVISION_DRY_RUN === '1'
137
- }
138
-
139
- /** The plugins a tier installs, in install order. `recommended` is a superset
140
- * of `core`; `none` installs nothing. */
141
- export function selectPlugins(tier) {
142
- if (tier === 'none') return []
143
- const wanted = tier === 'core' ? ['core'] : ['core', 'recommended']
144
- return PLUGIN_SET.filter((plugin) => wanted.includes(plugin.tier))
145
- }
146
-
147
- /** package@version specs for `dsh plugin ... add`. */
148
- export function installSpecs(plugins) {
149
- return plugins.map((plugin) => `${plugin.name}@${plugin.version}`)
150
- }
151
-
152
- /** argv tail for the single batched install. */
153
- export function pluginAddArgs(profile, specs) {
154
- return ['plugin', '--profile', profile, 'add', ...specs]
155
- }
156
-
157
- /** Human-readable form of `pluginAddArgs` (used by the progress line). */
158
- export function pluginAddCommand(profile, specs) {
159
- return ['dsh', ...pluginAddArgs(profile, specs)].join(' ')
160
- }
161
-
162
- // ---------------------------------------------------------------------------
163
- // Plugin-add failure classification (the bounded retry policy)
164
- //
165
- // The script's per-spec fallback retry (PLUGIN_ADD_ATTEMPTS x
166
- // PLUGIN_ADD_BACKOFF_MS) used to treat every failure as transient. Real 0.9.7
167
- // upgrades said otherwise: one orphan patchedDependencies entry makes every
168
- // `pnpm add` exit at once with ERR_PNPM_UNUSED_PATCH, so each spec burned 3
169
- // attempts x 5s and repeated the same red error. A DETERMINISTIC failure can
170
- // never succeed on a retry; the classification below reads only the captured
171
- // stderr / spawn-error text (where `dsh plugin add` surfaces pnpm's codes) and
172
- // maps the known shapes:
173
- // deterministic — ERR_PNPM_UNUSED_PATCH, ERR_PNPM_NO_MATCHING_VERSION,
174
- // 404-class (but NOT ERR_PNPM_META_FETCH_FAIL, which is
175
- // registry-side flakiness), ENOTFOUND, EACCES, EPERM
176
- // transient — ECONNRESET, ETIMEDOUT, ECONNREFUSED, socket disconnected,
177
- // TLS/SSL, HTTP 5xx, ERR_PNPM_META_FETCH_FAIL
178
- // unknown — anything else, retried: an unrecognized error is never
179
- // treated as deterministic (conservative).
180
- // ERR_PNPM_META_FETCH_FAIL is checked FIRST: its cause chain may print
181
- // ENOTFOUND/404, but pnpm's own code is authoritative for transientness.
182
- // ---------------------------------------------------------------------------
183
-
184
- /** Deterministic failure → one actionable fix line each. The 404 rule pairs
185
- * the status with "not found" prose (or the ERR_PNPM_FETCH_404 code) so
186
- * coincidental numbers in progress output ("reused 404") cannot stop a retry. */
187
- const PLUGIN_ADD_DETERMINISTIC_RULES = [
188
- {
189
- code: 'ERR_PNPM_UNUSED_PATCH',
190
- re: /ERR_PNPM_UNUSED_PATCH/,
191
- hint: 'a patchedDependencies entry in pnpm-workspace.yaml no longer matches any dependency — remove that entry, then re-run',
192
- },
193
- {
194
- code: 'ERR_PNPM_NO_MATCHING_VERSION',
195
- re: /ERR_PNPM_NO_MATCHING_VERSION/,
196
- hint: 'no registry version matches the requested spec — check the pinned version against the registry, then re-run',
197
- },
198
- {
199
- code: 'HTTP 404',
200
- re: /ERR_PNPM_FETCH_404|(?<![\d.])404(?![\d.])[^\n]{0,80}not[ -]?found|not[ -]?found[^\n]{0,80}(?<![\d.])404(?![\d.])/i,
201
- hint: 'the package or version was not found on the registry (404) — check the spec and the registry URL, then re-run',
202
- },
203
- {
204
- code: 'ENOTFOUND',
205
- re: /\bENOTFOUND\b/,
206
- hint: 'a registry host did not resolve (ENOTFOUND) — check the registry URL and DNS, then re-run',
207
- },
208
- {
209
- code: 'EACCES',
210
- re: /\bEACCES\b/,
211
- hint: 'permission denied (EACCES) — check ownership of the profile directory (node_modules, pnpm-workspace.yaml), then re-run',
212
- },
213
- {
214
- code: 'EPERM',
215
- re: /\bEPERM\b/,
216
- hint: 'operation not permitted (EPERM) — check file permissions or locks in the profile directory, then re-run',
217
- },
218
- ]
219
-
220
- const PLUGIN_ADD_TRANSIENT_RULES = [
221
- { code: 'ECONNRESET', re: /\bECONNRESET\b/ },
222
- { code: 'ETIMEDOUT', re: /\bETIMEDOUT\b/ },
223
- { code: 'ECONNREFUSED', re: /\bECONNREFUSED\b/ },
224
- { code: 'disconnected', re: /disconnect/i },
225
- { code: 'TLS/SSL', re: /\bTLS\b|\bSSL\b/ },
226
- { code: 'HTTP 5xx', re: /(?<![\d.])5\d\d(?![\d.])/ },
227
- ]
228
-
229
- /** Classify one failed `dsh plugin add` attempt. Pure: the captured run
230
- * output in, `{ kind, code, hint }` out. `hint` is a non-null actionable
231
- * fix only for deterministic failures. */
232
- export function classifyPluginAddFailure({ stderr = '', error = null } = {}) {
233
- const text = [
234
- typeof stderr === 'string' ? stderr : Buffer.isBuffer(stderr) ? stderr.toString() : '',
235
- error?.code ?? '',
236
- error?.message ?? '',
237
- ]
238
- .filter(Boolean)
239
- .join('\n')
240
- if (/ERR_PNPM_META_FETCH_FAIL/.test(text)) {
241
- return { kind: 'transient', code: 'ERR_PNPM_META_FETCH_FAIL', hint: null }
242
- }
243
- for (const rule of PLUGIN_ADD_DETERMINISTIC_RULES) {
244
- if (rule.re.test(text)) return { kind: 'deterministic', code: rule.code, hint: rule.hint }
245
- }
246
- for (const rule of PLUGIN_ADD_TRANSIENT_RULES) {
247
- if (rule.re.test(text)) return { kind: 'transient', code: rule.code, hint: null }
248
- }
249
- return { kind: 'unknown', code: null, hint: null }
250
- }
251
-
252
- /** The next step of the bounded per-spec retry after one attempt. Pure: the
253
- * spawnSync result of one `dsh plugin add` run in, a decision out.
254
- * { action: 'installed' }
255
- * { action: 'retry' } — transient/unknown and attempts remain
256
- * { action: 'failed', failure } — deterministic (never retried), or the
257
- * attempt budget is exhausted
258
- */
259
- export function pluginAddRetryDecision(run, { attempt, attempts } = {}) {
260
- if (!run?.error && run?.status === 0) return { action: 'installed' }
261
- const failure = classifyPluginAddFailure({ stderr: run?.stderr, error: run?.error })
262
- if (failure.kind !== 'deterministic' && attempt < attempts) return { action: 'retry' }
263
- return { action: 'failed', failure }
264
- }
265
-
266
- /** Terminal per-spec failures for the summary, DETERMINISTIC FIRST (each
267
- * carries the one-line fix; a stable sort keeps install order within the
268
- * groups). */
269
- export function orderPluginAddFailures(failures) {
270
- return [...failures].sort(
271
- (a, b) => (a.failure.kind === 'deterministic' ? 0 : 1) - (b.failure.kind === 'deterministic' ? 0 : 1),
272
- )
273
- }
274
-
275
- /** Format one progress line: `[n/m] label` with the value column aligned.
276
- * Mirrors dsh-tui-pi's onboarding output, with the script name as prefix. */
277
- export function formatStep(step, label, value = '') {
278
- return `${PREFIX}[${step}/${STEPS}] ${String(label).padEnd(15)}${value}`
279
- }
280
-
281
- // ---------------------------------------------------------------------------
282
- // Versions — a deliberately small semver subset: exact, ^, ~, >=.
283
- // ---------------------------------------------------------------------------
284
- export function parseVersion(version) {
285
- const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(version).trim())
286
- if (!match) return null
287
- return {
288
- major: Number(match[1]),
289
- minor: Number(match[2]),
290
- patch: Number(match[3]),
291
- pre: match[4] ? match[4].split('.') : [],
292
- }
293
- }
294
-
295
- /** -1 / 0 / 1; unparsable versions compare equal (callers treat that as
296
- * "unknown, do not downgrade"). */
297
- export function compareVersions(a, b) {
298
- const pa = parseVersion(a)
299
- const pb = parseVersion(b)
300
- if (!pa || !pb) return 0
301
- for (const key of ['major', 'minor', 'patch']) {
302
- if (pa[key] !== pb[key]) return pa[key] < pb[key] ? -1 : 1
303
- }
304
- if (pa.pre.length === 0 && pb.pre.length === 0) return 0
305
- if (pa.pre.length === 0) return 1
306
- if (pb.pre.length === 0) return -1
307
- for (let i = 0; i < Math.max(pa.pre.length, pb.pre.length); i += 1) {
308
- const x = pa.pre[i]
309
- const y = pb.pre[i]
310
- if (x === undefined) return -1
311
- if (y === undefined) return 1
312
- const xn = Number.parseInt(x, 10)
313
- const yn = Number.parseInt(y, 10)
314
- if (!Number.isNaN(xn) && !Number.isNaN(yn) && xn !== yn) return xn < yn ? -1 : 1
315
- if (x !== y) return x < y ? -1 : 1
316
- }
317
- return 0
318
- }
319
-
320
- /** Does `installed` satisfy the `wanted` requirement? An empty/unknown
321
- * `installed` never satisfies. */
322
- export function satisfiesVersion(installed, wanted) {
323
- const got = parseVersion(installed)
324
- if (!got) return false
325
- const wantedText = String(wanted ?? '').trim()
326
- if (wantedText === '' || wantedText === '*' || wantedText === 'latest') return true
327
- const cmp = compareVersions(installed, wantedText.replace(/^[\^~]|^>=/, ''))
328
- if (/^\^/.test(wantedText)) {
329
- const want = parseVersion(wantedText.slice(1))
330
- if (!want) return false
331
- if (want.major > 0) return got.major === want.major && cmp >= 0
332
- if (want.minor > 0) return got.major === 0 && got.minor === want.minor && cmp >= 0
333
- return got.major === 0 && got.minor === 0 && got.patch === want.patch
334
- }
335
- if (/^~/.test(wantedText)) {
336
- const want = parseVersion(wantedText.slice(1))
337
- if (!want) return false
338
- return got.major === want.major && got.minor === want.minor && cmp >= 0
339
- }
340
- if (/^>=/.test(wantedText)) return cmp >= 0
341
- return cmp === 0
342
- }
343
-
344
- /** Dep specs that point somewhere other than the registry (`link:`, `file:`,
345
- * `workspace:`, `portal:`). A profile that pins a plugin this way is a local
346
- * development setup — the installer must not replace it with a registry
347
- * version, so such a dep always counts as satisfied. */
348
- export function isLocalSpec(spec) {
349
- return typeof spec === 'string' && /^(?:link|file|workspace|portal):/.test(spec)
350
- }
351
-
352
- // ---------------------------------------------------------------------------
353
- // upgrade-overrides: the profile's "do not downgrade me" list
354
- //
355
- // `dsh-opentui upgrade` installs versions newer than the shipped pins and
356
- // records them in `$DSH_HOME/profiles/opentui/upgrade-overrides.json`, because
357
- // provisioning runs on EVERY start and would otherwise pull the profile back
358
- // to the pins. The file is a side manifest, not a relaxation of the pins:
359
- //
360
- // {
361
- // "version": 1,
362
- // "updatedAt": "<iso>",
363
- // "packages": {
364
- // "@aiwayds/dsh-cron": { "version": "0.7.2", "shippedPin": "0.7.0", "updatedAt": "<iso>" }
365
- // }
366
- // }
367
- //
368
- // An override raises the effective pin ONLY when it is strictly newer than the
369
- // shipped pin: once a release raises the pin past the override, the override
370
- // stops applying by itself and the shipped pin wins again — a stale override
371
- // can never downgrade a profile.
372
- // ---------------------------------------------------------------------------
373
-
374
- /** The versions a shipped pin may be raised to by an override. Lookup is by
375
- * package name, so an entry for a package this launcher does not manage can
376
- * never take effect (PLUGIN_SET is the allowlist). */
377
- const OVERRIDEABLE_PLUGINS = new Set(PLUGIN_SET.map((plugin) => plugin.name))
378
-
379
- /**
380
- * The version a managed plugin must be installed at: the shipped pin, or the
381
- * override version when the profile carries a VALID override that is strictly
382
- * newer than the pin.
383
- *
384
- * An override is ignored (the shipped pin is returned) when any of these holds:
385
- * - `name` is not in PLUGIN_SET (unknown keys are silently ignored)
386
- * - the entry is not an object, or its `version` is not a semver string
387
- * - the override version equals or precedes the shipped pin
388
- *
389
- * @param {{name: string, shippedPin: string, overrides?: Record<string, {version?: string}>}} input
390
- * @returns {string} the effective pin
391
- */
392
- export function resolveEffectivePin({ name, shippedPin, overrides = {} }) {
393
- if (!OVERRIDEABLE_PLUGINS.has(name)) return shippedPin
394
- if (typeof overrides !== 'object' || overrides === null || Array.isArray(overrides)) return shippedPin
395
- const entry = overrides[name]
396
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return shippedPin
397
- const parsed = typeof entry.version === 'string' ? parseVersion(entry.version) : null
398
- if (parsed === null) return shippedPin
399
- // Canonical form so an install spec never carries a `v` prefix or build
400
- // metadata (`pkg@v1.2.3` is not a version pnpm resolves reliably).
401
- const candidate = `${parsed.major}.${parsed.minor}.${parsed.patch}${parsed.pre.length ? `-${parsed.pre.join('.')}` : ''}`
402
- return compareVersions(candidate, shippedPin) > 0 ? candidate : shippedPin
403
- }
404
-
405
- // ---------------------------------------------------------------------------
406
- // Plan
407
- // ---------------------------------------------------------------------------
408
-
409
- /**
410
- * Decide what a run must do for one tier. Pure: every filesystem fact arrives
411
- * in the inputs.
412
- *
413
- * Idempotency rule (all three must hold for a plugin to count as satisfied):
414
- * 1. the package is a `dependencies` entry in the profile manifest
415
- * 2. `node_modules/<pkg>/package.json` exists (its version is passed in)
416
- * 3. that version satisfies the effective pin (see resolveEffectivePin)
417
- * A dep pinned with a local spec (link/file/workspace) skips 2/3: the local
418
- * pin wins and is never replaced.
419
- *
420
- * `overrides` is optional and empty by default, so a profile without the
421
- * upgrade-overrides manifest plans exactly as it did before overrides existed.
422
- *
423
- * @param {{tier: string, dependencies?: Record<string,string>, bundles?: string[], installedVersions?: Record<string,string>, overrides?: Record<string,{version?: string}>}} input
424
- * @returns {{
425
- * total: number,
426
- * satisfied: number,
427
- * install: Array<{name: string, spec: string, reason: string}>,
428
- * missingBundles: string[],
429
- * managedOrder: string[],
430
- * }}
431
- */
432
- export function planPluginInstall({ tier, dependencies = {}, bundles = [], installedVersions = {}, overrides = {} }) {
433
- const plugins = selectPlugins(tier)
434
- const install = []
435
- const missingBundles = []
436
- const managedOrder = plugins.map((plugin) => plugin.name)
437
-
438
- for (const plugin of plugins) {
439
- const effectivePin = resolveEffectivePin({ name: plugin.name, shippedPin: plugin.version, overrides })
440
- const depSpec = dependencies[plugin.name]
441
- const installed = installedVersions[plugin.name]
442
- const depOk = depSpec !== undefined && (isLocalSpec(depSpec) || satisfiesVersion(installed, effectivePin))
443
- if (!depOk) {
444
- // `pin` is the EFFECTIVE pin (shipped pin or a newer override), so the
445
- // caller can compare the installed version and the failure state against
446
- // exactly the version this install asked for.
447
- install.push({ name: plugin.name, pin: effectivePin, spec: `${plugin.name}@${effectivePin}`, reason: plugin.reason })
448
- continue
449
- }
450
- if (!bundles.includes(plugin.name)) missingBundles.push(plugin.name)
451
- }
452
-
453
- return {
454
- total: plugins.length,
455
- // "satisfied" counts plugins that need no work at all (dep + bundle).
456
- satisfied: plugins.length - install.length - missingBundles.length,
457
- install,
458
- missingBundles,
459
- managedOrder,
460
- }
461
- }
462
-
463
- /**
464
- * Split a plan's install rows into the specs this launch runs and the pins it
465
- * skips after repeated failures (see provision-state.mjs for the policy:
466
- * backoff, attempt cap, 24-hour reset).
467
- *
468
- * The pin compared is `row.pin` — the EFFECTIVE pin computed by
469
- * planPluginInstall. Using the shipped pin here would make an override-raised
470
- * package look permanently failed: its install spec says 0.7.2 while the
471
- * recorded failure (from an older launch) says 0.7.0.
472
- *
473
- * Pure: `state` is the parsed state document, `now` a Date / ISO string /
474
- * epoch ms. Returns the surviving rows and one summary row per skipped pin.
475
- *
476
- * @param {{
477
- * install?: Array<{name: string, pin: string, spec: string}>,
478
- * state?: object|null,
479
- * now?: Date|string|number,
480
- * backoffMs?: number,
481
- * maxAttempts?: number,
482
- * }} input
483
- * @returns {{
484
- * install: Array<{name: string, pin: string, spec: string}>,
485
- * skips: Array<{name: string, pin: string, reason: string, attempts: number, lastFailedAt: string}>,
486
- * }}
487
- */
488
- export function partitionInstallByRetryState({ install = [], state, now, backoffMs, maxAttempts } = {}) {
489
- const pending = []
490
- const skips = []
491
- for (const row of Array.isArray(install) ? install : []) {
492
- if (!row || typeof row.name !== 'string' || row.name === '') {
493
- pending.push(row)
494
- continue
495
- }
496
- const pin = typeof row.pin === 'string' && row.pin !== '' ? row.pin : specPin(row.spec)
497
- const verdict = shouldSkipRetry({ state, name: row.name, pin, now, backoffMs, maxAttempts })
498
- if (!verdict.skip) {
499
- pending.push(pin === row.pin ? row : { ...row, pin })
500
- continue
501
- }
502
- skips.push({
503
- name: row.name,
504
- pin: verdict.entry.pin,
505
- reason: verdict.reason,
506
- attempts: verdict.entry.attempts,
507
- lastFailedAt: verdict.entry.lastFailedAt,
508
- })
509
- }
510
- return { install: pending, skips }
511
- }
512
-
513
- /** `@scope/pkg@1.2.3` -> `1.2.3`. Only a fallback for rows without `pin`. */
514
- function specPin(spec) {
515
- if (typeof spec !== 'string') return ''
516
- const at = spec.lastIndexOf('@')
517
- return at > 0 ? spec.slice(at + 1) : ''
518
- }
519
-
520
- /**
521
- * Compare the versions that actually landed against the plan's effective pins.
522
- * Exact match only: `dsh plugin add` was asked for an exact version, so a
523
- * newer or older version is a degraded install, not a satisfied one.
524
- *
525
- * @param {{
526
- * install?: Array<{name: string, pin: string}>,
527
- * installedVersions?: Record<string, string|undefined>,
528
- * }} input
529
- * @returns {Array<{name: string, pin: string, installed: string|null, ok: boolean}>}
530
- */
531
- export function verifyInstalledPins({ install = [], installedVersions = {} } = {}) {
532
- const versions = installedVersions && typeof installedVersions === 'object' ? installedVersions : {}
533
- return (Array.isArray(install) ? install : []).map((row) => {
534
- const actual = row && typeof row.name === 'string' ? versions[row.name] : undefined
535
- const installed = typeof actual === 'string' && actual !== '' ? actual : null
536
- return { name: row?.name, pin: row?.pin, installed, ok: installed !== null && installed === row?.pin }
537
- })
538
- }
539
-
540
- /**
541
- * Merge bundle selection: drop retired entries, append missing managed
542
- * entries, and keep the managed subset in `managedOrder` (the ask-router-first
543
- * contract) without disturbing unmanaged entries.
544
- *
545
- * @param {string[]} bundles
546
- * @param {{managedOrder?: string[], retire?: string[]}} input
547
- * @returns {{bundles: string[], appended: string[], removed: string[], reordered: boolean}}
548
- */
549
- export function mergeBundles(bundles, { managedOrder = [], retire = [] } = {}) {
550
- const removed = bundles.filter((name) => retire.includes(name))
551
- let next = bundles.filter((name) => !retire.includes(name))
552
-
553
- const appended = []
554
- for (const name of managedOrder) {
555
- if (!next.includes(name)) {
556
- next.push(name)
557
- appended.push(name)
558
- }
559
- }
560
-
561
- // Reorder ONLY the managed slots: take the positions managed names currently
562
- // occupy and refill them in managedOrder. Unmanaged entries keep their
563
- // index, so dsh-base / dsh-web-app keep loading first.
564
- const managedSet = new Set(managedOrder)
565
- const slots = []
566
- next.forEach((name, index) => {
567
- if (managedSet.has(name)) slots.push(index)
568
- })
569
- const present = managedOrder.filter((name) => next.includes(name))
570
- const reordered = slots.some((slot, i) => next[slot] !== present[i])
571
- if (reordered) {
572
- const copy = [...next]
573
- slots.forEach((slot, i) => {
574
- copy[slot] = present[i]
575
- })
576
- next = copy
577
- }
578
-
579
- return { bundles: next, appended, removed, reordered }
580
- }
581
-
582
- /** Remove retired packages from the dependency map. */
583
- export function cleanupDependencies(dependencies, retire = RETIRED_PROFILE_ENTRIES) {
584
- const next = { ...dependencies }
585
- const removed = []
586
- for (const name of retire) {
587
- if (name in next) {
588
- delete next[name]
589
- removed.push(name)
590
- }
591
- }
592
- return { dependencies: next, removed }
593
- }
594
-
595
- // ---------------------------------------------------------------------------
596
- // Orphan pnpm patches (ERR_PNPM_UNUSED_PATCH)
597
- //
598
- // The plugin-mode installer (retired with 0.9.7) registered
599
- // `patchedDependencies: solid-js@1.9.17: patches/...` in the profile's
600
- // pnpm-workspace.yaml to pin the host bundle's solid-js client build. That
601
- // dependency is gone from 0.9.7 profiles, and pnpm hard-fails EVERY install
602
- // with ERR_PNPM_UNUSED_PATCH while a patchedDependencies entry names a package
603
- // outside the dependency graph — one stale line blocks all plugin installs on
604
- // upgraded profiles. The cleanup below drops exactly those orphan entries and
605
- // never touches the patch files themselves (patches/ is kept for the record).
606
- //
607
- // The reader is a port of the retired solid-js-pin.mjs parsePatchBlocks (the
608
- // shape it merged on real 0.4.3→0.5.0 migrations), because pnpm's
609
- // patchedDependencies IS a flat `pkg@version: relpath` string map and no YAML
610
- // parser is available in this dependency-free script.
611
- // ---------------------------------------------------------------------------
612
-
613
- const PATCH_HEADER_RE = /^patchedDependencies:\s*$/
614
- // A flat-map entry line: ` <key>: <value>` (keys like `solid-js@1.9.17`
615
- // carry no colon; values are patch relpaths). Nested-map or list lines do
616
- // NOT match, and a bare `key:` with no value (nested-map form) has an empty
617
- // value — both mark the block opaque.
618
- const PATCH_ENTRY_RE = /^[ \t]+([^:\s][^:]*):(?:[ \t]+(.*))?$/
619
-
620
- /** The package a patch key patches: `solid-js@1.9.17` → `solid-js`,
621
- * `@scope/pkg@1.2.3` → `@scope/pkg` (the LAST `@` separates the version; a
622
- * bare `pkg` key names itself). A YAML-quoted key (`'@scope/pkg@1.2.3'`) is
623
- * unquoted first — the quotes are syntax, never part of the name. */
624
- export function patchTargetName(key) {
625
- const name = String(key).replace(/^(['"])(.*)\1$/, '$2')
626
- const at = name.lastIndexOf('@')
627
- return at > 0 ? name.slice(0, at) : name
628
- }
629
-
630
- /** Parse every top-level `patchedDependencies:` block in the yaml into its
631
- * flat `pkg@version: relpath` entries, in first-seen order (a duplicated key
632
- * keeps its first occurrence), plus the [start, end) line range of each
633
- * block, and `opaque: true` when some block holds lines this reader cannot
634
- * reproduce — an unparseable line, or an entry with NO inline value (a
635
- * nested-map form such as pnpm's `key:` + `path:`/`hashed:` rows). The
636
- * caller must not rewrite what it cannot reproduce: flattening a nested
637
- * block would corrupt the file. */
638
- export function parsePatchedDependencies(lines) {
639
- const entries = []
640
- const seen = new Set()
641
- const ranges = []
642
- let opaque = false
643
- let i = 0
644
- while (i < lines.length) {
645
- if (!PATCH_HEADER_RE.test(lines[i])) {
646
- i += 1
647
- continue
648
- }
649
- const start = i
650
- i += 1
651
- while (i < lines.length && /^[ \t]+\S/.test(lines[i])) {
652
- const match = PATCH_ENTRY_RE.exec(lines[i])
653
- const value = match ? (match[2] ?? '').trim() : ''
654
- if (!match || value === '') {
655
- opaque = true
656
- break
657
- }
658
- const key = match[1].trim()
659
- if (!seen.has(key)) {
660
- seen.add(key)
661
- entries.push([key, value])
662
- }
663
- i += 1
664
- }
665
- ranges.push([start, i])
666
- }
667
- return { entries, ranges, opaque }
668
- }
669
-
670
- /**
671
- * Plan the orphan-patch cleanup for one pnpm-workspace.yaml text. Pure: text
672
- * in, plan + rewritten text out.
673
- *
674
- * A patch entry is an ORPHAN when its target package (`patchTargetName(key)`)
675
- * is not among `dependencyNames` — the caller passes the profile's FINAL
676
- * dependency set (after retired-entry cleanup and this run's installs), the
677
- * same set pnpm checks when it raises ERR_PNPM_UNUSED_PATCH.
678
- *
679
- * With removals, ONE block is written back at the first block's position (the
680
- * duplicate-block collapse of the retired installer's merge); every other
681
- * line is preserved byte-for-byte, and no entry left means no block at all.
682
- * An opaque block is returned untouched. With nothing to remove the text is
683
- * returned byte-identical.
684
- *
685
- * @param {string} text
686
- * @param {string[]} dependencyNames
687
- * @returns {{removed: Array<[string,string]>, kept: Array<[string,string]>, text: string, changed: boolean, opaque: boolean}}
688
- */
689
- export function planOrphanPatchCleanup(text, dependencyNames = []) {
690
- const source = String(text ?? '')
691
- const lines = source.split('\n')
692
- const { entries, ranges, opaque } = parsePatchedDependencies(lines)
693
- if (opaque) return { removed: [], kept: entries, text: source, changed: false, opaque: true }
694
- const names = new Set(dependencyNames)
695
- const removed = entries.filter(([key]) => !names.has(patchTargetName(key)))
696
- if (removed.length === 0) {
697
- return { removed, kept: entries, text: source, changed: false, opaque: false }
698
- }
699
- const removedKeys = new Set(removed.map(([key]) => key))
700
- const kept = entries.filter(([key]) => !removedKeys.has(key))
701
- const mergedBlock = [
702
- 'patchedDependencies:',
703
- ...kept.map(([key, value]) => ` ${key}:${value ? ` ${value}` : ''}`),
704
- ]
705
- const out = []
706
- let range = 0
707
- for (let i = 0; i < lines.length; ) {
708
- if (range < ranges.length && i === ranges[range][0]) {
709
- if (range === 0 && kept.length > 0) out.push(...mergedBlock)
710
- i = ranges[range][1]
711
- range += 1
712
- continue
713
- }
714
- out.push(lines[i])
715
- i += 1
716
- }
717
- return { removed, kept, text: out.join('\n'), changed: true, opaque: false }
718
- }
719
-
720
- // ---------------------------------------------------------------------------
721
- // Profile patch rows for the model-facing web tools
722
- //
723
- // The @deepseek-ai/dsh-web-app bundle disables the ambient `tool-web` row
724
- // (`disabled: true`) and recomposes it per agent preset. The opentui profile's
725
- // default preset resolves to `native` (an empty preset), so nothing turns the
726
- // row back on and the model sees no `web_search`/`web_fetch`. These two rows
727
- // are appended to the profile patch (the last layer, so they win per id):
728
- //
729
- // - tool-web re-enables the ambient row with the shipped tool defaults
730
- // - web pins the vendor-neutral search provider (anysearch needs no
731
- // key); the identical row ships in the anysearch bundle patch,
732
- // repeated here so the profile patch stays self-describing and
733
- // keeps the choice when `--plugins=none` skips that bundle
734
- //
735
- // Idempotency follows the model-route rule but checks the row's *state*, not
736
- // just its id: a row that is already enabled / pinned is left untouched (a
737
- // re-run never duplicates it and never rewrites a config the user edited).
738
- // ---------------------------------------------------------------------------
739
- export const TOOL_WEB_PATCH = `- id: tool-web
740
- name: '@deepseek-ai/dsh-tool-web'
741
- disabled: false
742
- config:
743
- fetch: true
744
- searchTimeoutMs: 60000
745
- `
746
- export const WEB_SEARCH_PATCH = `- id: web
747
- config:
748
- searchProvider: anysearch
749
- `
750
-
751
- const escapeRegExp = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
752
-
753
- /** The raw text of the first TOP-LEVEL `- id: <id>` entry, or null. Nested
754
- * ids (`- insert:` rows are indented) never match: the pattern anchors the
755
- * dash at column 0, the same rule the script's model-route check uses. The
756
- * block runs to the next column-0 `- ` line. */
757
- export function patchEntryBlock(text, id) {
758
- const lines = String(text ?? '').split('\n')
759
- const idPattern = new RegExp(`^- id: ${escapeRegExp(id)}\\s*$`)
760
- const start = lines.findIndex((line) => idPattern.test(line))
761
- if (start < 0) return null
762
- let end = lines.length
763
- for (let i = start + 1; i < lines.length; i += 1) {
764
- if (/^- /.test(lines[i])) {
765
- end = i
766
- break
767
- }
768
- }
769
- return lines.slice(start, end).join('\n')
770
- }
771
-
772
- /** The value of a key at the entry's own indentation (two spaces), ignoring
773
- * comments and blank lines. Nested keys are indented deeper and do not match. */
774
- function entryValue(block, key) {
775
- const pattern = new RegExp(`^ ${escapeRegExp(key)}:[ \\t]*(.*?)[ \\t]*$`, 'm')
776
- const match = pattern.exec(block)
777
- return match ? match[1] : undefined
778
- }
779
-
780
- /** True when the row itself states `disabled: false`. An omitted `disabled`
781
- * inherits the earlier layer's value (the web-app row is `disabled: true`),
782
- * so only an explicit false counts as enabled. */
783
- export function isEntryEnabled(block) {
784
- const value = entryValue(block, 'disabled')
785
- return value !== undefined && /^(?:false|False|FALSE)$/.test(value)
786
- }
787
-
788
- /** True when the row's `config:` block pins `searchProvider: <provider>`. A
789
- * config block is one map replaced wholesale by an id-targeted patch row, so
790
- * only the configured provider id counts; an unset provider auto-selects. */
791
- export function pinsSearchProvider(block, provider) {
792
- const lines = block.split('\n')
793
- const configStart = lines.findIndex((line) => /^ config:[ \t]*$/.test(line))
794
- if (configStart < 0) return false
795
- for (let i = configStart + 1; i < lines.length; i += 1) {
796
- const line = lines[i]
797
- if (line.trim() === '' || line.trim().startsWith('#')) continue
798
- if ((/^\s*/.exec(line)?.[0].length ?? 0) <= 2) break
799
- const match = /^ {3,}searchProvider:[ \t]*(.*?)[ \t]*$/.exec(line)
800
- if (match) return match[1].replace(/^['"]|['"]$/g, '') === provider
801
- }
802
- return false
803
- }
804
-
805
- /**
806
- * Plan the web-tool rows a profile patch still needs. Pure: the caller passes
807
- * the patch text it read.
808
- *
809
- * @param {string} existingText
810
- * @returns {{
811
- * append: string[],
812
- * toolWeb: 'missing'|'disabled'|'enabled',
813
- * web: 'missing'|'unpinned'|'pinned',
814
- * changed: boolean,
815
- * }}
816
- */
817
- export function planToolPatch(existingText = '') {
818
- const toolWebBlock = patchEntryBlock(existingText, 'tool-web')
819
- const webBlock = patchEntryBlock(existingText, 'web')
820
- const toolWebEnabled = toolWebBlock !== null && isEntryEnabled(toolWebBlock)
821
- const webPinned = webBlock !== null && pinsSearchProvider(webBlock, 'anysearch')
822
-
823
- return {
824
- append: [...(toolWebEnabled ? [] : [TOOL_WEB_PATCH]), ...(webPinned ? [] : [WEB_SEARCH_PATCH])],
825
- toolWeb: toolWebBlock === null ? 'missing' : toolWebEnabled ? 'enabled' : 'disabled',
826
- web: webBlock === null ? 'missing' : webPinned ? 'pinned' : 'unpinned',
827
- changed: !toolWebEnabled || !webPinned,
828
- }
829
- }
830
-
831
- // ---------------------------------------------------------------------------
832
- // Profile patch rows for MCP (adapter + one default server)
833
- //
834
- // @aiwayds/dsh-mcp-adapter is a prompt-side shim over the official
835
- // @deepseek-ai/dsh-mcp-client: the client owns the connection and registers
836
- // `mcp__<server>__<tool>` on ctx.tools, the adapter exposes the constant
837
- // `mcp_list` / `mcp_call` meta-tools on top of those registrations. Without at
838
- // least one client row the adapter's catalog is empty, so the pair ships
839
- // together: the plugin set installs the adapter, and this row starts one
840
- // server.
841
- //
842
- // The row is INSIDE an `- insert:` list (the same form the tui profile uses),
843
- // so the id check must match nested entries — the top-level `patchEntryBlock`
844
- // deliberately does not. Detection is by id alone: an existing
845
- // `mcp-context7` row is the user's (possibly edited) row and is never
846
- // rewritten or duplicated. `--plugins=none` writes no row at all: without the
847
- // adapter the client's tools would surface unfolded, which is not the
848
- // promised setup.
849
- //
850
- // context7 is the default server because it needs no API key, starts fast
851
- // over streamable HTTP, and is read-only documentation lookup. A failed or
852
- // offline connection is non-fatal by contract: mcp-client's
853
- // `failOnStartupError` defaults to false and the host boots without its tools.
854
- // ---------------------------------------------------------------------------
855
- export const MCP_CONTEXT7_PATCH = `- insert:
856
- - id: mcp-context7
857
- name: '@deepseek-ai/dsh-mcp-client'
858
- config:
859
- serverName: context7
860
- transport: streamable-http
861
- url: https://mcp.context7.com/mcp
862
- `
863
-
864
- /** True when `<id>` appears as a patch row at ANY indentation (top-level id
865
- * entries and rows nested under `- insert:`). */
866
- export function hasAnyEntry(text, id) {
867
- return new RegExp(`^[ \\t]*- id: ${escapeRegExp(id)}[ \\t]*$`, 'm').test(String(text ?? ''))
868
- }
869
-
870
- /**
871
- * Plan the MCP client row a profile patch still needs. Pure.
872
- *
873
- * @param {string} existingText
874
- * @param {{enabled?: boolean}} options `enabled: false` is `--plugins=none`.
875
- * @returns {{append: string[], mcp: 'configured'|'missing'|'skipped', changed: boolean}}
876
- */
877
- export function planMcpPatch(existingText = '', { enabled = true } = {}) {
878
- const present = hasAnyEntry(existingText, 'mcp-context7')
879
- if (!enabled) return { append: [], mcp: 'skipped', changed: false }
880
- return {
881
- append: present ? [] : [MCP_CONTEXT7_PATCH],
882
- mcp: present ? 'configured' : 'missing',
883
- changed: !present,
884
- }
885
- }
886
-
887
- // ---------------------------------------------------------------------------
888
- // Verify (dsh opentui --dump-config)
889
- // ---------------------------------------------------------------------------
890
- export function parseDumpConfig(stdout = '', stderr = '') {
891
- const layers = String(stdout)
892
- .split('\n')
893
- .filter((line) => /^# == /.test(line)).length
894
- const skipped = String(stderr)
895
- .split('\n')
896
- .map((line) => line.trim())
897
- .filter((line) => line.includes('skipping profile bundle'))
898
- return { layers, skipped }
899
- }