@aiwayds/dsh-opentui 0.9.1 → 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.
@@ -0,0 +1,456 @@
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
+ export const PROFILE = 'opentui'
10
+ export const PREFIX = 'provision-opentui-profile: '
11
+ export const STEPS = 5
12
+ export const DEFAULT_TIER = 'recommended'
13
+ export const TIERS = ['core', 'recommended', 'none']
14
+
15
+ // The plugin set this launcher ships with. `reason` is printed by
16
+ // `--dry-run --plugins=<tier>` style troubleshooting and documents WHY a
17
+ // package is in the set, so a future reader can re-judge the decision.
18
+ //
19
+ // Ordering contract: `@aiwayds/dsh-ask-router` MUST stay first among the
20
+ // UI/ask bundles — it owns the ask surface every later UI bundle attaches to.
21
+ // `selectPlugins()` preserves this array's order, and the installer appends
22
+ // bundle entries in that order.
23
+ export const PLUGIN_SET = [
24
+ {
25
+ name: '@aiwayds/dsh-ask-router',
26
+ version: '0.7.0',
27
+ tier: 'core',
28
+ reason: 'owns the ask surface; must load before any other UI/ask bundle',
29
+ },
30
+ {
31
+ name: '@aiwayds/dsh-subagent-registry',
32
+ version: '0.19.1',
33
+ tier: 'core',
34
+ reason: 'subagent discovery and registration for the shell',
35
+ },
36
+ {
37
+ name: '@aiwayds/dsh-llm-net-retry',
38
+ version: '0.8.0',
39
+ tier: 'core',
40
+ reason: 'retries transient provider/network failures',
41
+ },
42
+ {
43
+ name: '@aiwayds/dsh-web-search-anysearch',
44
+ version: '0.9.0',
45
+ tier: 'core',
46
+ reason: 'web search without a per-provider key',
47
+ },
48
+ {
49
+ name: '@aiwayds/dsh-approval-policy',
50
+ version: '0.3.0',
51
+ tier: 'core',
52
+ reason: 'tool-approval policy shared with the shell approval cards',
53
+ },
54
+ {
55
+ name: '@aiwayds/dsh-model-sync',
56
+ version: '0.9.0',
57
+ tier: 'core',
58
+ reason: 'keeps the profile model list in sync with the provider catalog',
59
+ },
60
+ {
61
+ name: '@aiwayds/dsh-llm-stats',
62
+ version: '0.9.0',
63
+ tier: 'recommended',
64
+ reason: 'token/cost accounting behind /usage',
65
+ },
66
+ {
67
+ name: '@aiwayds/dsh-topics-memory',
68
+ version: '0.26.0',
69
+ tier: 'recommended',
70
+ reason: 'cross-session topic memory',
71
+ },
72
+ {
73
+ name: '@aiwayds/dsh-cron',
74
+ version: '0.7.0',
75
+ tier: 'recommended',
76
+ reason: 'scheduled prompts',
77
+ },
78
+ {
79
+ name: '@aiwayds/dsh-workflow',
80
+ version: '0.2.1',
81
+ tier: 'recommended',
82
+ reason: 'dynamic workflow runs',
83
+ },
84
+ {
85
+ name: '@aiwayds/dsh-vault',
86
+ version: '0.8.0',
87
+ tier: 'recommended',
88
+ reason: 'secret storage used by the companion plugins',
89
+ },
90
+ ]
91
+
92
+ // Deliberately NOT installed. Kept explicit so a reviewer can see the
93
+ // decision instead of inferring it from an absence.
94
+ export const EXCLUDED_PLUGINS = [
95
+ { name: '@aiwayds/dsh-tui-pi', reason: 'takes over stdout/stdin — hard conflict with the opentui client' },
96
+ { name: '@aiwayds/dsh-dcp', reason: 'web-app-preset isolated; an idle no-op in this profile' },
97
+ { name: '@aiwayds/dsh-feishu', reason: 'claims the ask surface and does not fall back' },
98
+ { name: '@aiwayds/dsh-agent-dispatch', reason: 'not part of the shell workflow' },
99
+ { name: '@aiwayds/dsh-self-improve', reason: 'not part of the shell workflow' },
100
+ { name: '@aiwayds/dsh-llm-proxy', reason: 'not part of the shell workflow' },
101
+ { name: '@aiwayds/dsh-web-search-tavily', reason: 'requires an API key' },
102
+ { name: '@aiwayds/dsh-profile-switch', reason: 'profile switching is the launcher\'s job' },
103
+ ]
104
+
105
+ // Entries a historic opentui profile may still carry. `@aiwayds/dsh-opentui`
106
+ // is the retired plugin-mode package: the global 0.9.2 declares no
107
+ // `dsh.bundle`, so every boot prints a "skipping profile bundle" warning, and
108
+ // the profile's dependency pointed at a tgz that no longer exists.
109
+ export const RETIRED_PROFILE_ENTRIES = ['@aiwayds/dsh-opentui']
110
+
111
+ /** Parse the `--plugins=` value (or the DSH_OPENTUI_PLUGINS env override).
112
+ * Throws on an unknown tier so a typo cannot silently install nothing. */
113
+ export function parseTier(value) {
114
+ if (value === undefined || value === null || value === '') return DEFAULT_TIER
115
+ const tier = String(value).trim().toLowerCase()
116
+ if (!TIERS.includes(tier)) {
117
+ throw new Error(`unknown plugin tier ${JSON.stringify(value)} — expected one of: ${TIERS.join(', ')}`)
118
+ }
119
+ return tier
120
+ }
121
+
122
+ /** True when the run must only print the commands it would execute. */
123
+ export function isDryRun(argv = [], env = {}) {
124
+ return argv.includes('--dry-run') || env.DSH_PROVISION_DRY_RUN === '1'
125
+ }
126
+
127
+ /** The plugins a tier installs, in install order. `recommended` is a superset
128
+ * of `core`; `none` installs nothing. */
129
+ export function selectPlugins(tier) {
130
+ if (tier === 'none') return []
131
+ const wanted = tier === 'core' ? ['core'] : ['core', 'recommended']
132
+ return PLUGIN_SET.filter((plugin) => wanted.includes(plugin.tier))
133
+ }
134
+
135
+ /** package@version specs for `dsh plugin ... add`. */
136
+ export function installSpecs(plugins) {
137
+ return plugins.map((plugin) => `${plugin.name}@${plugin.version}`)
138
+ }
139
+
140
+ /** argv tail for the single batched install. */
141
+ export function pluginAddArgs(profile, specs) {
142
+ return ['plugin', '--profile', profile, 'add', ...specs]
143
+ }
144
+
145
+ /** Human-readable form of `pluginAddArgs` (used by the progress line). */
146
+ export function pluginAddCommand(profile, specs) {
147
+ return ['dsh', ...pluginAddArgs(profile, specs)].join(' ')
148
+ }
149
+
150
+ /** Format one progress line: `[n/m] label` with the value column aligned.
151
+ * Mirrors dsh-tui-pi's onboarding output, with the script name as prefix. */
152
+ export function formatStep(step, label, value = '') {
153
+ return `${PREFIX}[${step}/${STEPS}] ${String(label).padEnd(15)}${value}`
154
+ }
155
+
156
+ // ---------------------------------------------------------------------------
157
+ // Versions — a deliberately small semver subset: exact, ^, ~, >=.
158
+ // ---------------------------------------------------------------------------
159
+ export function parseVersion(version) {
160
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(version).trim())
161
+ if (!match) return null
162
+ return {
163
+ major: Number(match[1]),
164
+ minor: Number(match[2]),
165
+ patch: Number(match[3]),
166
+ pre: match[4] ? match[4].split('.') : [],
167
+ }
168
+ }
169
+
170
+ /** -1 / 0 / 1; unparsable versions compare equal (callers treat that as
171
+ * "unknown, do not downgrade"). */
172
+ export function compareVersions(a, b) {
173
+ const pa = parseVersion(a)
174
+ const pb = parseVersion(b)
175
+ if (!pa || !pb) return 0
176
+ for (const key of ['major', 'minor', 'patch']) {
177
+ if (pa[key] !== pb[key]) return pa[key] < pb[key] ? -1 : 1
178
+ }
179
+ if (pa.pre.length === 0 && pb.pre.length === 0) return 0
180
+ if (pa.pre.length === 0) return 1
181
+ if (pb.pre.length === 0) return -1
182
+ for (let i = 0; i < Math.max(pa.pre.length, pb.pre.length); i += 1) {
183
+ const x = pa.pre[i]
184
+ const y = pb.pre[i]
185
+ if (x === undefined) return -1
186
+ if (y === undefined) return 1
187
+ const xn = Number.parseInt(x, 10)
188
+ const yn = Number.parseInt(y, 10)
189
+ if (!Number.isNaN(xn) && !Number.isNaN(yn) && xn !== yn) return xn < yn ? -1 : 1
190
+ if (x !== y) return x < y ? -1 : 1
191
+ }
192
+ return 0
193
+ }
194
+
195
+ /** Does `installed` satisfy the `wanted` requirement? An empty/unknown
196
+ * `installed` never satisfies. */
197
+ export function satisfiesVersion(installed, wanted) {
198
+ const got = parseVersion(installed)
199
+ if (!got) return false
200
+ const wantedText = String(wanted ?? '').trim()
201
+ if (wantedText === '' || wantedText === '*' || wantedText === 'latest') return true
202
+ const cmp = compareVersions(installed, wantedText.replace(/^[\^~]|^>=/, ''))
203
+ if (/^\^/.test(wantedText)) {
204
+ const want = parseVersion(wantedText.slice(1))
205
+ if (!want) return false
206
+ if (want.major > 0) return got.major === want.major && cmp >= 0
207
+ if (want.minor > 0) return got.major === 0 && got.minor === want.minor && cmp >= 0
208
+ return got.major === 0 && got.minor === 0 && got.patch === want.patch
209
+ }
210
+ if (/^~/.test(wantedText)) {
211
+ const want = parseVersion(wantedText.slice(1))
212
+ if (!want) return false
213
+ return got.major === want.major && got.minor === want.minor && cmp >= 0
214
+ }
215
+ if (/^>=/.test(wantedText)) return cmp >= 0
216
+ return cmp === 0
217
+ }
218
+
219
+ /** Dep specs that point somewhere other than the registry (`link:`, `file:`,
220
+ * `workspace:`, `portal:`). A profile that pins a plugin this way is a local
221
+ * development setup — the installer must not replace it with a registry
222
+ * version, so such a dep always counts as satisfied. */
223
+ export function isLocalSpec(spec) {
224
+ return typeof spec === 'string' && /^(?:link|file|workspace|portal):/.test(spec)
225
+ }
226
+
227
+ // ---------------------------------------------------------------------------
228
+ // Plan
229
+ // ---------------------------------------------------------------------------
230
+
231
+ /**
232
+ * Decide what a run must do for one tier. Pure: every filesystem fact arrives
233
+ * in the inputs.
234
+ *
235
+ * Idempotency rule (all three must hold for a plugin to count as satisfied):
236
+ * 1. the package is a `dependencies` entry in the profile manifest
237
+ * 2. `node_modules/<pkg>/package.json` exists (its version is passed in)
238
+ * 3. that version satisfies the pinned version
239
+ * A dep pinned with a local spec (link/file/workspace) skips 2/3: the local
240
+ * pin wins and is never replaced.
241
+ *
242
+ * @param {{tier: string, dependencies?: Record<string,string>, bundles?: string[], installedVersions?: Record<string,string>}} input
243
+ * @returns {{
244
+ * total: number,
245
+ * satisfied: number,
246
+ * install: Array<{name: string, spec: string, reason: string}>,
247
+ * missingBundles: string[],
248
+ * managedOrder: string[],
249
+ * }}
250
+ */
251
+ export function planPluginInstall({ tier, dependencies = {}, bundles = [], installedVersions = {} }) {
252
+ const plugins = selectPlugins(tier)
253
+ const install = []
254
+ const missingBundles = []
255
+ const managedOrder = plugins.map((plugin) => plugin.name)
256
+
257
+ for (const plugin of plugins) {
258
+ const depSpec = dependencies[plugin.name]
259
+ const installed = installedVersions[plugin.name]
260
+ const depOk = depSpec !== undefined && (isLocalSpec(depSpec) || satisfiesVersion(installed, plugin.version))
261
+ if (!depOk) {
262
+ install.push({ name: plugin.name, spec: `${plugin.name}@${plugin.version}`, reason: plugin.reason })
263
+ continue
264
+ }
265
+ if (!bundles.includes(plugin.name)) missingBundles.push(plugin.name)
266
+ }
267
+
268
+ return {
269
+ total: plugins.length,
270
+ // "satisfied" counts plugins that need no work at all (dep + bundle).
271
+ satisfied: plugins.length - install.length - missingBundles.length,
272
+ install,
273
+ missingBundles,
274
+ managedOrder,
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Merge bundle selection: drop retired entries, append missing managed
280
+ * entries, and keep the managed subset in `managedOrder` (the ask-router-first
281
+ * contract) without disturbing unmanaged entries.
282
+ *
283
+ * @param {string[]} bundles
284
+ * @param {{managedOrder?: string[], retire?: string[]}} input
285
+ * @returns {{bundles: string[], appended: string[], removed: string[], reordered: boolean}}
286
+ */
287
+ export function mergeBundles(bundles, { managedOrder = [], retire = [] } = {}) {
288
+ const removed = bundles.filter((name) => retire.includes(name))
289
+ let next = bundles.filter((name) => !retire.includes(name))
290
+
291
+ const appended = []
292
+ for (const name of managedOrder) {
293
+ if (!next.includes(name)) {
294
+ next.push(name)
295
+ appended.push(name)
296
+ }
297
+ }
298
+
299
+ // Reorder ONLY the managed slots: take the positions managed names currently
300
+ // occupy and refill them in managedOrder. Unmanaged entries keep their
301
+ // index, so dsh-base / dsh-web-app keep loading first.
302
+ const managedSet = new Set(managedOrder)
303
+ const slots = []
304
+ next.forEach((name, index) => {
305
+ if (managedSet.has(name)) slots.push(index)
306
+ })
307
+ const present = managedOrder.filter((name) => next.includes(name))
308
+ const reordered = slots.some((slot, i) => next[slot] !== present[i])
309
+ if (reordered) {
310
+ const copy = [...next]
311
+ slots.forEach((slot, i) => {
312
+ copy[slot] = present[i]
313
+ })
314
+ next = copy
315
+ }
316
+
317
+ return { bundles: next, appended, removed, reordered }
318
+ }
319
+
320
+ /** Remove retired packages from the dependency map. */
321
+ export function cleanupDependencies(dependencies, retire = RETIRED_PROFILE_ENTRIES) {
322
+ const next = { ...dependencies }
323
+ const removed = []
324
+ for (const name of retire) {
325
+ if (name in next) {
326
+ delete next[name]
327
+ removed.push(name)
328
+ }
329
+ }
330
+ return { dependencies: next, removed }
331
+ }
332
+
333
+ // ---------------------------------------------------------------------------
334
+ // Profile patch rows for the model-facing web tools
335
+ //
336
+ // The @deepseek-ai/dsh-web-app bundle disables the ambient `tool-web` row
337
+ // (`disabled: true`) and recomposes it per agent preset. The opentui profile's
338
+ // default preset resolves to `native` (an empty preset), so nothing turns the
339
+ // row back on and the model sees no `web_search`/`web_fetch`. These two rows
340
+ // are appended to the profile patch (the last layer, so they win per id):
341
+ //
342
+ // - tool-web re-enables the ambient row with the shipped tool defaults
343
+ // - web pins the vendor-neutral search provider (anysearch needs no
344
+ // key); the identical row ships in the anysearch bundle patch,
345
+ // repeated here so the profile patch stays self-describing and
346
+ // keeps the choice when `--plugins=none` skips that bundle
347
+ //
348
+ // Idempotency follows the model-route rule but checks the row's *state*, not
349
+ // just its id: a row that is already enabled / pinned is left untouched (a
350
+ // re-run never duplicates it and never rewrites a config the user edited).
351
+ // ---------------------------------------------------------------------------
352
+ export const TOOL_WEB_PATCH = `- id: tool-web
353
+ name: '@deepseek-ai/dsh-tool-web'
354
+ disabled: false
355
+ config:
356
+ fetch: true
357
+ searchTimeoutMs: 60000
358
+ `
359
+ export const WEB_SEARCH_PATCH = `- id: web
360
+ config:
361
+ searchProvider: anysearch
362
+ `
363
+
364
+ const escapeRegExp = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
365
+
366
+ /** The raw text of the first TOP-LEVEL `- id: <id>` entry, or null. Nested
367
+ * ids (`- insert:` rows are indented) never match: the pattern anchors the
368
+ * dash at column 0, the same rule the script's model-route check uses. The
369
+ * block runs to the next column-0 `- ` line. */
370
+ export function patchEntryBlock(text, id) {
371
+ const lines = String(text ?? '').split('\n')
372
+ const idPattern = new RegExp(`^- id: ${escapeRegExp(id)}\\s*$`)
373
+ const start = lines.findIndex((line) => idPattern.test(line))
374
+ if (start < 0) return null
375
+ let end = lines.length
376
+ for (let i = start + 1; i < lines.length; i += 1) {
377
+ if (/^- /.test(lines[i])) {
378
+ end = i
379
+ break
380
+ }
381
+ }
382
+ return lines.slice(start, end).join('\n')
383
+ }
384
+
385
+ /** The value of a key at the entry's own indentation (two spaces), ignoring
386
+ * comments and blank lines. Nested keys are indented deeper and do not match. */
387
+ function entryValue(block, key) {
388
+ const pattern = new RegExp(`^ ${escapeRegExp(key)}:[ \\t]*(.*?)[ \\t]*$`, 'm')
389
+ const match = pattern.exec(block)
390
+ return match ? match[1] : undefined
391
+ }
392
+
393
+ /** True when the row itself states `disabled: false`. An omitted `disabled`
394
+ * inherits the earlier layer's value (the web-app row is `disabled: true`),
395
+ * so only an explicit false counts as enabled. */
396
+ export function isEntryEnabled(block) {
397
+ const value = entryValue(block, 'disabled')
398
+ return value !== undefined && /^(?:false|False|FALSE)$/.test(value)
399
+ }
400
+
401
+ /** True when the row's `config:` block pins `searchProvider: <provider>`. A
402
+ * config block is one map replaced wholesale by an id-targeted patch row, so
403
+ * only the configured provider id counts; an unset provider auto-selects. */
404
+ export function pinsSearchProvider(block, provider) {
405
+ const lines = block.split('\n')
406
+ const configStart = lines.findIndex((line) => /^ config:[ \t]*$/.test(line))
407
+ if (configStart < 0) return false
408
+ for (let i = configStart + 1; i < lines.length; i += 1) {
409
+ const line = lines[i]
410
+ if (line.trim() === '' || line.trim().startsWith('#')) continue
411
+ if ((/^\s*/.exec(line)?.[0].length ?? 0) <= 2) break
412
+ const match = /^ {3,}searchProvider:[ \t]*(.*?)[ \t]*$/.exec(line)
413
+ if (match) return match[1].replace(/^['"]|['"]$/g, '') === provider
414
+ }
415
+ return false
416
+ }
417
+
418
+ /**
419
+ * Plan the web-tool rows a profile patch still needs. Pure: the caller passes
420
+ * the patch text it read.
421
+ *
422
+ * @param {string} existingText
423
+ * @returns {{
424
+ * append: string[],
425
+ * toolWeb: 'missing'|'disabled'|'enabled',
426
+ * web: 'missing'|'unpinned'|'pinned',
427
+ * changed: boolean,
428
+ * }}
429
+ */
430
+ export function planToolPatch(existingText = '') {
431
+ const toolWebBlock = patchEntryBlock(existingText, 'tool-web')
432
+ const webBlock = patchEntryBlock(existingText, 'web')
433
+ const toolWebEnabled = toolWebBlock !== null && isEntryEnabled(toolWebBlock)
434
+ const webPinned = webBlock !== null && pinsSearchProvider(webBlock, 'anysearch')
435
+
436
+ return {
437
+ append: [...(toolWebEnabled ? [] : [TOOL_WEB_PATCH]), ...(webPinned ? [] : [WEB_SEARCH_PATCH])],
438
+ toolWeb: toolWebBlock === null ? 'missing' : toolWebEnabled ? 'enabled' : 'disabled',
439
+ web: webBlock === null ? 'missing' : webPinned ? 'pinned' : 'unpinned',
440
+ changed: !toolWebEnabled || !webPinned,
441
+ }
442
+ }
443
+
444
+ // ---------------------------------------------------------------------------
445
+ // Verify (dsh opentui --dump-config)
446
+ // ---------------------------------------------------------------------------
447
+ export function parseDumpConfig(stdout = '', stderr = '') {
448
+ const layers = String(stdout)
449
+ .split('\n')
450
+ .filter((line) => /^# == /.test(line)).length
451
+ const skipped = String(stderr)
452
+ .split('\n')
453
+ .map((line) => line.trim())
454
+ .filter((line) => line.includes('skipping profile bundle'))
455
+ return { layers, skipped }
456
+ }