@acryldev/harness-runtime 0.0.0-stage → 0.2.12

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.
Files changed (167) hide show
  1. package/LICENSE +49 -0
  2. package/README.md +14 -2
  3. package/lib/index.mjs +5693 -0
  4. package/lib/index.mjs.map +1 -0
  5. package/lib/types/acryl-home.d.ts +81 -0
  6. package/lib/types/app/new-app.d.ts +65 -0
  7. package/lib/types/app/start-source.d.ts +47 -0
  8. package/lib/types/blueprint/blueprint.d.ts +74 -0
  9. package/lib/types/blueprint/brand-identity.d.ts +26 -0
  10. package/lib/types/blueprint/compose.d.ts +53 -0
  11. package/lib/types/blueprint/definition.d.ts +22 -0
  12. package/lib/types/blueprint/index.d.ts +7 -0
  13. package/lib/types/blueprint/manifest.d.ts +35 -0
  14. package/lib/types/blueprint/selection.d.ts +19 -0
  15. package/lib/types/cli-market-install.d.ts +97 -0
  16. package/lib/types/cli-market-plugins.d.ts +81 -0
  17. package/lib/types/coding-capabilities.d.ts +29 -0
  18. package/lib/types/durable-message.d.ts +18 -0
  19. package/lib/types/engine-dsh.d.ts +181 -0
  20. package/lib/types/engine-files.d.ts +8 -0
  21. package/lib/types/engine-host.d.ts +32 -0
  22. package/lib/types/engine-tools.d.ts +11 -0
  23. package/lib/types/index.d.ts +67 -0
  24. package/lib/types/instance/announce-self.d.ts +38 -0
  25. package/lib/types/instance/app-instance.d.ts +125 -0
  26. package/lib/types/instance/index.d.ts +6 -0
  27. package/lib/types/instance/offline-lock.d.ts +29 -0
  28. package/lib/types/instance/online-secret.d.ts +29 -0
  29. package/lib/types/instance/registry.d.ts +26 -0
  30. package/lib/types/instance/select.d.ts +43 -0
  31. package/lib/types/module-hooks.d.ts +19 -0
  32. package/lib/types/module-resolution.d.ts +31 -0
  33. package/lib/types/package-overlay.d.ts +41 -0
  34. package/lib/types/pinned-pnpm.d.ts +15 -0
  35. package/lib/types/plugin-acryl-workspace-status.d.ts +24 -0
  36. package/lib/types/plugin-doctor.d.ts +49 -0
  37. package/lib/types/plugin-lifecycle-state.d.ts +92 -0
  38. package/lib/types/plugin-lifecycle.d.ts +87 -0
  39. package/lib/types/profile-layout.d.ts +17 -0
  40. package/lib/types/profile-owner.d.ts +25 -0
  41. package/lib/types/profile-repair/backup.d.ts +37 -0
  42. package/lib/types/profile-repair/findings.d.ts +29 -0
  43. package/lib/types/profile-repair/index.d.ts +9 -0
  44. package/lib/types/profile-repair/inspector.d.ts +11 -0
  45. package/lib/types/profile-repair/repair.d.ts +38 -0
  46. package/lib/types/profile-resolution/moved-framework.d.ts +21 -0
  47. package/lib/types/profile-resolution/resolver.d.ts +41 -0
  48. package/lib/types/profile-resolution/service.d.ts +22 -0
  49. package/lib/types/prompt-budget.d.ts +44 -0
  50. package/lib/types/session-bridge.d.ts +57 -0
  51. package/lib/types/session-log-exporter.d.ts +31 -0
  52. package/lib/types/system-prompt-capture.d.ts +29 -0
  53. package/lib/types/web-favicon-data.d.ts +5 -0
  54. package/lib/types/web-favicon.d.ts +23 -0
  55. package/lib/types/web-market-install.d.ts +114 -0
  56. package/lib/types/web-market-plugins.d.ts +106 -0
  57. package/lib/types/web-port.d.ts +15 -0
  58. package/package.json +211 -3
  59. package/src/acryl-home.ts +103 -0
  60. package/src/app/new-app.ts +239 -0
  61. package/src/app/start-source.ts +110 -0
  62. package/src/blueprint/blueprint.ts +141 -0
  63. package/src/blueprint/brand-identity.ts +75 -0
  64. package/src/blueprint/compose.ts +222 -0
  65. package/src/blueprint/definition.ts +92 -0
  66. package/src/blueprint/index.ts +20 -0
  67. package/src/blueprint/manifest.ts +145 -0
  68. package/src/blueprint/selection.ts +74 -0
  69. package/src/cli-market-install.ts +181 -0
  70. package/src/cli-market-plugins.ts +176 -0
  71. package/src/coding-capabilities.ts +61 -0
  72. package/src/durable-message.ts +23 -0
  73. package/src/engine-dsh.ts +856 -0
  74. package/src/engine-files.ts +9 -0
  75. package/src/engine-host.ts +128 -0
  76. package/src/engine-tools.ts +26 -0
  77. package/src/index.ts +436 -0
  78. package/src/instance/announce-self.ts +88 -0
  79. package/src/instance/app-instance.ts +240 -0
  80. package/src/instance/index.ts +45 -0
  81. package/src/instance/offline-lock.ts +71 -0
  82. package/src/instance/online-secret.ts +55 -0
  83. package/src/instance/registry.ts +53 -0
  84. package/src/instance/select.ts +134 -0
  85. package/src/module-hooks.ts +41 -0
  86. package/src/module-resolution.ts +187 -0
  87. package/src/package-overlay.ts +160 -0
  88. package/src/pinned-pnpm.ts +67 -0
  89. package/src/plugin-acryl-workspace-status.ts +99 -0
  90. package/src/plugin-doctor.ts +141 -0
  91. package/src/plugin-lifecycle-state.ts +347 -0
  92. package/src/plugin-lifecycle.ts +223 -0
  93. package/src/profile-layout.ts +97 -0
  94. package/src/profile-owner.ts +52 -0
  95. package/src/profile-repair/backup.ts +119 -0
  96. package/src/profile-repair/findings.ts +43 -0
  97. package/src/profile-repair/index.ts +10 -0
  98. package/src/profile-repair/inspector.ts +156 -0
  99. package/src/profile-repair/repair.ts +137 -0
  100. package/src/profile-resolution/moved-framework.ts +64 -0
  101. package/src/profile-resolution/resolver.ts +876 -0
  102. package/src/profile-resolution/service.ts +99 -0
  103. package/src/prompt-budget.ts +118 -0
  104. package/src/session-bridge.ts +350 -0
  105. package/src/session-log-exporter.ts +68 -0
  106. package/src/system-prompt-capture.ts +99 -0
  107. package/src/web-favicon-data.ts +6 -0
  108. package/src/web-favicon.ts +43 -0
  109. package/src/web-market-install.ts +206 -0
  110. package/src/web-market-plugins.ts +215 -0
  111. package/src/web-port.ts +39 -0
  112. package/tests/account-callback.spec.ts +173 -0
  113. package/tests/acryl-home.spec.ts +39 -0
  114. package/tests/agent-self-hosting.spec.ts +101 -0
  115. package/tests/announce-self.spec.ts +84 -0
  116. package/tests/app-lifecycle.spec.ts +99 -0
  117. package/tests/blank-blueprint.spec.ts +110 -0
  118. package/tests/blueprint-definition.spec.ts +128 -0
  119. package/tests/blueprint.spec.ts +138 -0
  120. package/tests/bulkhead.spec.ts +187 -0
  121. package/tests/coding-vocabulary.spec.ts +15 -0
  122. package/tests/dump-system-prompt.spec.ts +65 -0
  123. package/tests/e2e-real-model.spec.ts +71 -0
  124. package/tests/e2e-restart-real-model.spec.ts +77 -0
  125. package/tests/engine-dsh.spec.ts +340 -0
  126. package/tests/engine-host-mount-root-include.spec.ts +118 -0
  127. package/tests/engine-host.spec.ts +176 -0
  128. package/tests/engine-optional.spec.ts +81 -0
  129. package/tests/extension-examples.spec.ts +261 -0
  130. package/tests/hooks-thread-stack.ts +27 -0
  131. package/tests/instance-patches.spec.ts +25 -0
  132. package/tests/instance.spec.ts +235 -0
  133. package/tests/live/community-plugins.spec.ts +83 -0
  134. package/tests/module-hooks.spec.ts +35 -0
  135. package/tests/module-resolution.spec.ts +265 -0
  136. package/tests/moved-framework.spec.ts +61 -0
  137. package/tests/new-app.spec.ts +132 -0
  138. package/tests/organizer-growth.spec.ts +117 -0
  139. package/tests/pinned-pnpm.spec.ts +34 -0
  140. package/tests/plugin-acryl-workspace-status.spec.ts +63 -0
  141. package/tests/plugin-context.spec.ts +640 -0
  142. package/tests/plugin-doctor.spec.ts +183 -0
  143. package/tests/plugin-enablement-one-store.spec.ts +130 -0
  144. package/tests/plugin-lifecycle-state.spec.ts +169 -0
  145. package/tests/profile-layout.spec.ts +58 -0
  146. package/tests/profile-owner.spec.ts +38 -0
  147. package/tests/profile-repair/profile-repair.spec.ts +231 -0
  148. package/tests/profile-resolution-port.spec.ts +30 -0
  149. package/tests/profile-resolution-service.spec.ts +273 -0
  150. package/tests/profile-resolution-swap.spec.ts +69 -0
  151. package/tests/profile-resolution.spec.ts +2535 -0
  152. package/tests/profile.spec.ts +70 -0
  153. package/tests/project-registry.spec.ts +81 -0
  154. package/tests/prompt-budget.spec.ts +58 -0
  155. package/tests/real-home-guard.spec.ts +178 -0
  156. package/tests/session-bridge.spec.ts +316 -0
  157. package/tests/start-source.spec.ts +65 -0
  158. package/tests/system-prompt-shape.spec.ts +95 -0
  159. package/tests/three-levels.spec.ts +84 -0
  160. package/tests/tool-gateway.spec.ts +116 -0
  161. package/tests/tool-schemas.spec.ts +41 -0
  162. package/tests/web-favicon.spec.ts +42 -0
  163. package/tests/web-port.spec.ts +38 -0
  164. package/tests/web-startup-hold.spec.ts +79 -0
  165. package/tsconfig.json +24 -0
  166. package/tsdown.config.ts +2 -0
  167. package/vitest.config.ts +18 -0
@@ -0,0 +1,856 @@
1
+ /**
2
+ * The `dsh` engine provider (spec 028): mounts the pinned Harness profile as
3
+ * one Loader row under `createAcrylEngineHost`'s persistent root, instead of
4
+ * the second Cordis root `boot()`/`bootAcrylHarnessProfile` creates. Performs
5
+ * the identical composition - the HMR guard, workspace-status/session-log-
6
+ * exporter wiring - so selecting `dsh` behaves exactly like today's direct
7
+ * boot (SC-004).
8
+ *
9
+ * Two entry points share the mounting primitive (`mountDshEngine`) but differ
10
+ * in where the composition comes from: {@link createDshEngineDefinition} is
11
+ * the CLI/TUI flavor, resolving a named profile through this package's own
12
+ * profile system; {@link createDshEngineDefinitionFromComposition} takes an
13
+ * already-resolved `{rootConfig, patches, bareModuleBaseUrl}` a surface with
14
+ * its own profile pipeline (Desktop's `prepareDesktopProfile()`) produced
15
+ * itself. Neither does the other's job.
16
+ *
17
+ * `mountRootInclude` (unlike `boot()`) composes onto an already-initialized
18
+ * Loader rather than creating its own, but it does not scope the Include row
19
+ * it creates to the calling plugin's own fiber - this plugin owns and
20
+ * removes it explicitly via `ctx.effect()`. Verified with a real Loader
21
+ * activation in `tests/engine-host-mount-root-include.spec.ts` before this
22
+ * file trusted the pattern.
23
+ */
24
+
25
+ import { brandWebIndex } from './web-favicon.ts'
26
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
27
+ import { createRequire, findPackageJSON } from 'node:module'
28
+ import { basename, dirname, join } from 'node:path'
29
+ import { fileURLToPath, pathToFileURL } from 'node:url'
30
+ import type { Context } from '@deepseek-ai/cordis'
31
+ import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
32
+ import {
33
+ DEFAULT_PROFILE_BUNDLES,
34
+ PROFILE_TEMPLATES,
35
+ composeEntries,
36
+ createRuntimeResolution,
37
+ initProfile,
38
+ loadOverlayPatches,
39
+ loadProfile,
40
+ removeLinkProjections,
41
+ mountRootInclude,
42
+ resolveProfileDir,
43
+ type Profile,
44
+ type ProfileContext,
45
+ type RuntimeResolution,
46
+ } from '@deepseek-ai/dsh-app-boot'
47
+ import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
48
+ import { homePluginsDir } from '@acryldev/plugin-hub-core'
49
+ import { provideAcrylTools } from './engine-tools.ts'
50
+ import * as acrylWebService from '@acryldev/web'
51
+ import type {} from '@deepseek-ai/dsh-host-webserver'
52
+
53
+ import { provideCliMarketInstall } from './cli-market-install.ts'
54
+ import { provideCliMarketPlugins } from './cli-market-plugins.ts'
55
+ import type { AcrylCodingCapabilityId, AcrylShellMode, AcrylSurface } from './coding-capabilities.ts'
56
+ import type { AcrylEngineDefinition } from './engine-host.ts'
57
+ import { installAcrylWorkspaceStatusTool } from './plugin-acryl-workspace-status.ts'
58
+ import { blueprintFromEnvironment, composeBlueprintRows, currentModule, packageOfModule } from './blueprint/index.ts'
59
+ import { findFreeWebPort, loopbackPortIsFree, webPortPatch } from './web-port.ts'
60
+ import { LOOPBACK_WEB_HOST, selectInstance, type AppInstance } from './instance/index.ts'
61
+ import { claimProfile } from './profile-owner.ts'
62
+ import { pluginLifecyclePatches, readUserMutableBundleNames, resolvePluginLifecycleStatePath } from './plugin-lifecycle-state.ts'
63
+ import { ProfilePluginPackages } from './profile-resolution/service.ts'
64
+ import { installSessionLogExporter } from './session-log-exporter.ts'
65
+ import { provideWebMarketInstall } from './web-market-install.ts'
66
+ import { provideWebMarketPlugins } from './web-market-plugins.ts'
67
+
68
+ const require = createRequire(import.meta.url)
69
+ const dshInstallAnchor = require.resolve('@deepseek-ai/dsh/package.json')
70
+ const profileRoot = '[]\n'
71
+
72
+ /** The agent presets DSH 0.2 ships, in roster order. */
73
+ const SHIPPED_PRESET_NAMES: readonly string[] = ['standard', 'ptc', 'minimal', 'cordis']
74
+
75
+ /**
76
+ * The terminal's agent presets. DSH 0.2 declares each preset as a bundle patch of `dsh-web-app` (`presets/<name>.patch.yml`
77
+ * inserts a `preset-<name>` row) and has no terminal app bundle, so a terminal profile on `dsh-base` alone has an empty roster.
78
+ * ACRYL layers the same four files in, skipping any preset row the profile already composes (a Web-shaped profile booted by the CLI).
79
+ */
80
+ function terminalPresetPatches(existingRowIds: ReadonlySet<string>): PatchOptions[] {
81
+ const presetsDir = join(dirname(require.resolve('@deepseek-ai/dsh-web-app/package.json')), 'presets')
82
+ const presets = SHIPPED_PRESET_NAMES.flatMap(name => loadOverlayPatches('acryl', join(presetsDir, `${name}.patch.yml`)).flatMap((patch) => {
83
+ if (!('insert' in patch) || patch.insert === undefined) return [patch]
84
+ const insert = patch.insert.filter(row => row.id === undefined || !existingRowIds.has(row.id))
85
+ return insert.length === 0 ? [] : [{ ...patch, insert }]
86
+ }))
87
+ // The presets' delegation tools run with `modelSelectionSettings: true`, which requires the settings row `dsh-web-app` itself composes
88
+ // next to them; without it every preset's subagent tool failed to load in the terminal.
89
+ return existingRowIds.has(SUBAGENT_MODEL_SETTINGS_ROW.id) ? presets : [{ insert: [SUBAGENT_MODEL_SETTINGS_ROW] }, ...presets]
90
+ }
91
+
92
+ /** `dsh-web-app`'s Host row that the presets' `modelSelectionSettings` delegation tools require. */
93
+ const SUBAGENT_MODEL_SETTINGS_ROW = { id: 'subagent-model-selection-settings', name: '@deepseek-ai/dsh-tool-subagent/model-selection-settings' } as const
94
+
95
+ /** An already-resolved dsh composition: what one surface's own profile pipeline produced. */
96
+ export interface DshEngineComposition {
97
+ readonly rootConfig: string
98
+ readonly patches: readonly PatchOptions[]
99
+ /** Resolves worker-only bare-module URLs (e.g. `/plugins/...`); omitted when the surface serves no such URLs. */
100
+ readonly bareModuleBaseUrl?: string
101
+ /** Which ACRYL surface this is (`tui`, `web`, `desktop`) - becomes part of the durable session-log filename. */
102
+ readonly surface: string
103
+ /** The product name the page title carries (the Blueprint's brand); defaults to `ACRYL`. */
104
+ readonly productName?: string
105
+ /** The stock ACRYL brand (not a Blueprint's own): the served page wears the ACRYL icon. */
106
+ readonly stockBrand?: boolean
107
+ /** The app this composition belongs to; provided to plugins as the `appInstance` service. Chosen by the surface's composition root. */
108
+ readonly instance?: AppInstance
109
+ /** File URL of the surface's own `package.json` (where ACRYL-owned workspace packages resolve from); provided to plugins
110
+ * as the `acrylFrameworkPackages` service. Omitted where materializing an ACRYL framework package into a local
111
+ * extension's profile does not apply (for example, a composition root with its own separate profile pipeline). */
112
+ readonly installPackageUrl?: string
113
+ /**
114
+ * The package table `@deepseek-ai/dsh-app-boot` computes for this profile (DSH 0.2). Since 0.2 a profile no longer carries link
115
+ * projections of the installation's packages; the `pluginPackages` service (ACRYL's `ProfilePluginPackages`) answers every bare-package import from this table, so
116
+ * the engine mounts it before the profile include. Compute it with {@link createProfileRuntimeResolution} after every
117
+ * ACRYL-owned package has been materialized into the profile.
118
+ */
119
+ readonly runtimeResolution?: RuntimeResolution
120
+ /**
121
+ * The profile facts DSH 0.2 reads for live configuration. `config-editor`, `settings` (the Models page, where credentials are
122
+ * entered) and the plugin manager are only enabled while a `profileContext` exists, exactly as stock `dsh` provides one.
123
+ * Never named `desktop`: that name would also switch on upstream's product telemetry rows.
124
+ */
125
+ readonly profileContext?: ProfileContext
126
+ }
127
+ /**
128
+ * The surface's coding-capability composition, handed to an engine definition by the app that owns it: the plugins package for the
129
+ * rows, the package names, the anchor they resolve from, and the rows the advanced shell replaces. `@acryldev/coding-capabilities` is
130
+ * the one implementation; the runtime never imports it (its Blueprint vocabulary lives in `coding-capabilities.ts`).
131
+ */
132
+ export interface CodingCapabilities {
133
+ /** Installations whose `node_modules` may hold a package the composition names, in order (the surface's, then the composition package's). */
134
+ readonly anchors: readonly string[]
135
+ patches(surface: ReadonlySet<AcrylSurface>, existingRowIds: ReadonlySet<string>, only: ReadonlySet<AcrylCodingCapabilityId>): readonly PatchOptions[]
136
+ shellPatches(surface: ReadonlySet<AcrylSurface>, shellMode: AcrylShellMode, existingRowIds: ReadonlySet<string>, only: ReadonlySet<AcrylCodingCapabilityId>): readonly PatchOptions[]
137
+ /** The ACRYL-owned packages a surface must make resolvable for the capabilities it composes. */
138
+ packages(surface: ReadonlySet<AcrylSurface>, only: ReadonlySet<AcrylCodingCapabilityId>): readonly string[]
139
+ /** The rows the advanced shell replaces (`ADVANCED_SHELL_PATCHES`), for a Blueprint with an `app-shell` row. */
140
+ readonly appFramePatches: readonly PatchOptions[]
141
+ }
142
+
143
+
144
+ /**
145
+ * ACRYL's own patches out of a composed list laid out as `[bundle layers..., ACRYL additions..., profile's own patches..., later ACRYL
146
+ * additions...]`. DSH 0.2's live configuration (`config-editor`, `hmr`) rebuilds the Loader from stock sources (bundle layers, the
147
+ * profile file, the home file) plus `ProfileContext.overlays`; ACRYL's capability rows, blueprint rows, presets and plugin-lifecycle
148
+ * toggles exist only in memory, so they must be handed over as overlays or the first edit would reload them away and be rolled back.
149
+ */
150
+ function acrylAdditions(
151
+ patches: readonly PatchOptions[],
152
+ layout: { readonly layerPatches: number, readonly userPatches: number, readonly composedBeforeLater: number },
153
+ ): PatchOptions[] {
154
+ const userStart = layout.composedBeforeLater - layout.userPatches
155
+ return [...patches.slice(layout.layerPatches, userStart), ...patches.slice(layout.composedBeforeLater)]
156
+ }
157
+
158
+ /** Module HMR is never wanted (see `mountDshEngine`); it has to be part of every reload as well as of the first mount. */
159
+ const HMR_OFF: PatchOptions = { id: 'hmr', disabled: true }
160
+
161
+ /**
162
+ * DeepSeek's own product analytics, which DSH's Web bundle switches on for any profile named `desktop` (Desktop's profile is) and which report
163
+ * to DeepSeek's collector. ACRYL is not that product: they are off on every surface, at the first mount and at every reload, instead of
164
+ * depending on a profile name. Mounted, the Host row also failed its config at every start, since only DeepSeek's shell sets its
165
+ * `serviceVersion` (`DSH_CLIENT_VERSION`).
166
+ */
167
+ export const UPSTREAM_PRODUCT_ANALYTICS_OFF: readonly PatchOptions[] = Object.freeze([
168
+ { id: 'desktop-product-telemetry', disabled: true },
169
+ { id: 'product-analytics', disabled: true },
170
+ ])
171
+
172
+ /**
173
+ * The patches an app instance contributes to every composition: an instance that must not use the OS user's Documents folder points the chat's first
174
+ * workspace at its own `documents` folder. A patch for a row the surface does not compose (the terminal has no workspace controller) is ignored.
175
+ */
176
+ export function instancePatches(instance: AppInstance | undefined): readonly PatchOptions[] {
177
+ return instance?.documentsDirectory === undefined ? [] : [{ id: 'workspace-controller', config: { documentsDirectory: instance.documentsDirectory } }]
178
+ }
179
+
180
+ /** The profile facts a launcher hands to DSH's live configuration (stock `dsh`: `profile-boot`, `runProfile`). */
181
+ export function createProfileContext(
182
+ profile: Profile,
183
+ options: {
184
+ readonly installAnchor?: string
185
+ readonly home: string
186
+ readonly packageManager?: ProfileContext['packageManager']
187
+ /** ACRYL's in-memory patches that a configuration reload must keep applying (see {@link acrylAdditions}). */
188
+ readonly overlays?: readonly PatchOptions[]
189
+ /** The app instance, whose own patches (see {@link instancePatches}) a reload must keep applying as well. */
190
+ readonly instance?: AppInstance
191
+ },
192
+ ): ProfileContext {
193
+ return {
194
+ name: profile.name,
195
+ ...(options.packageManager === undefined ? {} : { packageManager: options.packageManager }),
196
+ dir: profile.dir,
197
+ patchPath: profile.patchPath,
198
+ installAnchor: options.installAnchor ?? dshInstallAnchor,
199
+ cwd: process.cwd(),
200
+ home: options.home,
201
+ startedBundles: profile.layers.map(layer => layer.packageName),
202
+ overlays: [...(options.overlays ?? []), HMR_OFF, ...UPSTREAM_PRODUCT_ANALYTICS_OFF, ...instancePatches(options.instance)],
203
+ telemetryDisabledEnv: process.env.DSH_TELEMETRY_DISABLED,
204
+ }
205
+ }
206
+
207
+ /**
208
+ * The runtime resolution for a loaded profile, as stock `dsh` computes it (`profile-boot`: `composeProfile`).
209
+ * @param installAnchor - the `package.json` whose dependency closure the profile may import from. Defaults to the `dsh`
210
+ * package; a surface that ships ACRYL-owned packages (Desktop) passes its own, so those resolve like any dependency.
211
+ */
212
+ export function createProfileRuntimeResolution(profile: Profile, installAnchor: string = dshInstallAnchor): Promise<RuntimeResolution> {
213
+ return createRuntimeResolution({ installAnchor, profile })
214
+ }
215
+
216
+ /**
217
+ * Mount an already-resolved dsh composition under the given already-
218
+ * initialized Loader `ctx`. Does no profile resolution of its own - the
219
+ * caller (a CLI `--profile` name resolved via `resolveProfileDir`/
220
+ * `loadProfile`, or Desktop's own `prepareDesktopProfile()`) already
221
+ * produced `rootConfig`/`patches`/`bareModuleBaseUrl`.
222
+ */
223
+ async function mountDshEngine(ctx: Context, composition: DshEngineComposition): Promise<void> {
224
+ // DSH 0.2 enables the `hmr` row whenever a `profileContext` exists. It only watches the profile files for edits made outside the app
225
+ // (and needs Loader internals plus a launcher readiness signal); in-app edits (`config-editor`, Settings, Models) reconcile the Loader
226
+ // themselves. ACRYL activates and reloads plugins through Loader entries and `livePluginActivation`, so every composition switches it off.
227
+ // Left on, it also stalls engine disposal after a swap (its queued reload waits on a tree that is unloading).
228
+ const patches: PatchOptions[] = [...composition.patches, HMR_OFF, ...UPSTREAM_PRODUCT_ANALYTICS_OFF, ...instancePatches(composition.instance ?? selectInstance())]
229
+ // This assignment feeds mountRootInclude's own nested composition tree
230
+ // (constructed below, from this ctx) - not the host root's own top-level
231
+ // tree, whose baseUrl is a one-time snapshot taken when `createAcrylEngineHost`
232
+ // calls `ctx.plugin(Loader)`, long before this plugin function ever runs
233
+ // (see engine-host.ts's `HOST_ROOT_BASE_URL`). Setting `ctx.baseUrl` here
234
+ // reaches only entries nested inside mountRootInclude's own subtree (the
235
+ // real DSH profile plugins) - the "acryl-engine-<id>" and sibling
236
+ // "cordis:include" rows at the host's own top level are unaffected by
237
+ // anything this function does.
238
+ ctx.baseUrl = pathToFileURL(dirname(composition.rootConfig)).href + '/'
239
+ // mountRootInclude's Include entry lands as a sibling of this plugin's own
240
+ // entry in the shared host Loader tree, not a descendant of it (the same
241
+ // fact behind the disposal fix above) - ctx.provide() on this plugin's own
242
+ // forked ctx would not be an ancestor of that sibling's consumers.
243
+ // ctx.root is the one scope every entry in the tree shares. dshHomePath is
244
+ // a static, engine-agnostic value (home-path resolution helpers, not
245
+ // per-engine state), so it is provided once and left on the host's root
246
+ // rather than disposed per engine swap - re-providing it on a later
247
+ // re-mount of `dsh` would otherwise throw "service already registered".
248
+ if (ctx.root.get('dshHomePath') === undefined) ctx.root.provide('dshHomePath', dshHomePath)
249
+ // The app's resource family (instance/): plugins read where their app keeps things from here, never from the environment or the OS home.
250
+ const provided = ctx.root.get('appInstance' as never) as AppInstance | undefined
251
+ const instance = provided ?? composition.instance ?? selectInstance()
252
+ if (provided === undefined) ctx.root.provide('appInstance', instance)
253
+ if (composition.installPackageUrl !== undefined && ctx.root.get('acrylFrameworkPackages' as never) === undefined) {
254
+ ctx.root.provide('acrylFrameworkPackages', createAcrylFrameworkPackages(ctx, composition.installPackageUrl))
255
+ }
256
+ // Owned by this engine's fiber (not the root), so an engine swap releases the interception with the profile it served.
257
+ if (composition.runtimeResolution !== undefined) await ctx.plugin(ProfilePluginPackages, { resolution: composition.runtimeResolution })
258
+ if (composition.profileContext !== undefined && ctx.root.get('profileContext' as never) === undefined) ctx.root.provide('profileContext', composition.profileContext)
259
+ // The include is recorded under the context it is mounted on, and DSH's profile reload (`config-editor`, `hmr`) looks it up on the
260
+ // root context, so mount it there: a reload then finds "the root Include entry" and an edit can be applied and kept.
261
+ const entry = await mountRootInclude(ctx.root, composition.rootConfig, patches, composition.bareModuleBaseUrl)
262
+ // mountRootInclude creates its Include row at the Loader's own top level -
263
+ // it has no `parent` parameter and is not scoped to this plugin's own
264
+ // fiber the way ctx.effect() resources are. Without this, an engine swap
265
+ // away from `dsh` would leave the whole profile tree mounted forever.
266
+ if (entry !== undefined) {
267
+ // Loader 1.0.5's `remove` starts the row's disposal without waiting for it, so wait for the include's fiber here:
268
+ // a swap away from `dsh` must not return while the profile's services are still registered.
269
+ ctx.effect(() => async () => {
270
+ const fiber = entry.fiber
271
+ ctx.loader.remove(entry.options.id)
272
+ // On a swap the root stays up and the caller must see the profile gone; when the whole root is disposing, the include goes with it
273
+ // and waiting on it here would wait on the very disposal that is running this effect.
274
+ if (ctx.root.fiber.state === 2) await fiber?.dispose()
275
+ })
276
+ }
277
+ // Do not call ctx.loader.await() here: this function is itself running as
278
+ // part of one Loader entry's activation, and awaiting the same loader from
279
+ // inside it deadlocks. createAcrylEngineHost's own ctx.loader.await(),
280
+ // called from outside any entry after ctx.loader.create()/update()
281
+ // resolves, already settles this nested tree too - proven in
282
+ // tests/engine-host-mount-root-include.spec.ts.
283
+ //
284
+ // installAcrylWorkspaceStatusTool does bare ctx.tools property access,
285
+ // which is topology-sensitive and requires a declared injection (not
286
+ // satisfied by this plugin's own forked ctx, for the same sibling-not-
287
+ // descendant reason as the dshHomePath fix above). ctx.inject(['tools'])
288
+ // resolves that safely. Neither installAcrylWorkspaceStatusTool nor its
289
+ // own `apply()` Cordis-plugin form wraps ctx.tools.register()'s returned
290
+ // disposer in ctx.effect() (true of its other two callers too, harmless
291
+ // there only because they own a whole process-lifetime root) - this
292
+ // plugin must own that disposer itself, or an engine swap away from and
293
+ // back to `dsh` would double-register the tool.
294
+ // Guarded exactly like bootAcrylHarnessProfile's original check - some
295
+ // profile variants legitimately have no ctx.tools at all (SC-004: this
296
+ // extraction must not change that behavior).
297
+ if (ctx.get('tools') !== undefined) {
298
+ ctx.inject(['tools'], toolsCtx => {
299
+ const disposeTool = installAcrylWorkspaceStatusTool(toolsCtx)
300
+ ctx.effect(() => disposeTool)
301
+ })
302
+ }
303
+ // ctx.logger is an ambient Cordis primitive, not a topology-sensitive
304
+ // injected service (unlike ctx.tools), and ctx.logger.exporter() already
305
+ // ties its own disposal to the ctx that registers it (see
306
+ // installSessionLogExporter's own doc comment) - this plugin's own ctx is
307
+ // correct here, unlike the two cases above.
308
+ installSessionLogExporter(ctx, { surface: composition.surface, dshHome: instance.dshHome })
309
+ // Web only: the shell HTML dsh-web-app serves is a pinned
310
+ // @deepseek-ai/dsh-web-frontend build artifact with a hardcoded
311
+ // "DeepSeek Harness" <title> - not part of the pluggable Cordis Client
312
+ // slot system the brand-swap patch (resolveWebEngineComposition) actually
313
+ // covers, so swapping ui-brand-official for ui-acryl alone leaves the
314
+ // visible browser-tab title wrong. Reproduced directly: a real served
315
+ // index still read "<title>DeepSeek Harness</title>" after the brand-swap
316
+ // patch landed. Desktop does not have this gap - electron-shell-
317
+ // generation.ts already suppresses page-title-updated and keeps its
318
+ // native window title fixed at the OS level, so this vendored HTML's
319
+ // <title> never reaches anything the user sees there; Web has no native
320
+ // window, so this served HTML's own <title> IS the visible artifact.
321
+ // dsh-host-webserver's WebServer service exposes tapIndex(transform) as
322
+ // its own designed escape hatch for exactly this class of rewrite ("no
323
+ // IndexInjection row exists for this", per its own doc comment) -
324
+ // registering a tap here, rather than editing the vendored
325
+ // dsh-web-frontend package, which the project's own repo rules forbid.
326
+ // The same tap swaps the favicon for the ACRYL logo, inlined as a data URL
327
+ // (web-favicon.ts), so no route or static asset is needed.
328
+ // The web port ACRYL's own plugins depend on (instead of DSH's `webServer`): Web and Desktop have a page, the terminal has none.
329
+ // The same plugin every Blends app mounts (row acryl-web); it waits for webServer by its own inject.
330
+ if (composition.surface !== 'tui') ctx.plugin(acrylWebService)
331
+ // The tools port every surface can offer (the terminal's chat has the same registry).
332
+ ctx.inject(['tools'], toolsCtx => { provideAcrylTools(toolsCtx) })
333
+ if (composition.surface === 'web') {
334
+ ctx.inject(['webServer'], webServerCtx => {
335
+ // A custom brand ships its own favicon (@acryldev/brand); only the stock ACRYL brand gets the ACRYL logo (`productName` is always set, so it cannot tell).
336
+ const disposeTap = webServerCtx.webServer.tapIndex(html => brandWebIndex(html, composition))
337
+ ctx.effect(() => disposeTap)
338
+ })
339
+ // Web's own desktopPlugins/livePluginActivation (spec 034 T006) - mounted
340
+ // BEFORE desktopProfiles/desktopPnpm below on purpose. dsh-community-
341
+ // market's own ctx.inject(['desktopProfiles', 'desktopPnpm'], ...) reads
342
+ // ctx.get('livePluginActivation') exactly once, opportunistically, the
343
+ // moment that inject's dependencies first resolve - not reactively, so a
344
+ // livePluginActivation provided AFTER that moment is captured as
345
+ // `undefined` for the fiber's whole life. Reproduced directly: with the
346
+ // reverse order, a real install through the Market succeeded but the
347
+ // installed plugin never became active without a full process restart -
348
+ // no error anywhere, just a silently-missed live-activation opportunity.
349
+ // Web has no shared plugin-lifecycle mount at all before this - CLI's and
350
+ // Desktop's own each mount it separately, so this is the first time Web
351
+ // gets one. Guarded like dshHomePath above: an engine swap away from and
352
+ // back to `dsh` must not re-provide an already-registered service.
353
+ if (ctx.root.get('desktopPlugins') === undefined) {
354
+ const profileDir = dirname(composition.rootConfig)
355
+ provideWebMarketPlugins(ctx.root, {
356
+ profileName: 'web',
357
+ profileDir,
358
+ statePath: resolvePluginLifecycleStatePath(),
359
+ binName: 'acryl-web',
360
+ // `createDshPluginLifecycleHost`'s own internal wrapper already
361
+ // appends "/package.json" before calling this callback - despite the
362
+ // option's own parameter being named `packageName`, what actually
363
+ // arrives here is the full "<packageName>/package.json" specifier
364
+ // already. Reproduced directly: a real live-activation attempt threw
365
+ // ERR_PACKAGE_PATH_NOT_EXPORTED on a literal "package.json/package.json"
366
+ // subpath before this fix - the same latent bug exists in acryl-cli's
367
+ // own plugin-command.ts, just never exercised there (the CLI has no
368
+ // install/live-activation path yet, spec 034 T006).
369
+ resolvePackageJson: specifier => createRequire(pathToFileURL(join(profileDir, 'package.json'))).resolve(specifier),
370
+ })
371
+ }
372
+ // Web's own desktopProfiles/desktopPnpm (spec 034 T006, scoped v1) - what
373
+ // @acryldev/cordis-plugin-market's install service needs for its Install/Uninstall
374
+ // buttons to do a real operation instead of showing "ACRYL is required".
375
+ // Both are stateless besides this one profile's own fixed name/directory,
376
+ // so - also like dshHomePath - never disposed; there is nothing to
377
+ // invalidate by leaving them registered for the process's whole life.
378
+ if (ctx.root.get('desktopProfiles') === undefined) {
379
+ provideWebMarketInstall(ctx.root, dirname(composition.rootConfig))
380
+ }
381
+ }
382
+ // CLI/TUI's own desktopPlugins/livePluginActivation + desktopProfiles/
383
+ // desktopPnpm (spec 034 T006, completing the third surface) - same
384
+ // ordering constraint as Web above (mount desktopPlugins first, since
385
+ // @acryldev/cordis-plugin-market's own ctx.inject(['desktopProfiles', 'desktopPnpm'])
386
+ // reads ctx.get('livePluginActivation') exactly once, opportunistically).
387
+ // Unlike Web, the CLI has more than one named profile, so the profile name
388
+ // comes from this composition's own directory rather than a literal - see
389
+ // dsh-app-boot's own `$DSH_HOME/profiles/<name>` layout contract.
390
+ if (composition.surface === 'tui') {
391
+ const profileDir = dirname(composition.rootConfig)
392
+ const profileName = basename(profileDir)
393
+ if (ctx.root.get('desktopPlugins') === undefined) {
394
+ provideCliMarketPlugins(ctx.root, {
395
+ profileName,
396
+ profileDir,
397
+ statePath: resolvePluginLifecycleStatePath(),
398
+ binName: 'acryl',
399
+ // Same double-append trap as web-market-plugins.ts's own resolvePackageJson
400
+ // and acryl-cli's own plugin-command.ts: createDshPluginLifecycleHost's
401
+ // internal wrapper already appends "/package.json" before calling this.
402
+ resolvePackageJson: specifier => createRequire(pathToFileURL(join(profileDir, 'package.json'))).resolve(specifier),
403
+ })
404
+ }
405
+ if (ctx.root.get('desktopProfiles') === undefined) {
406
+ provideCliMarketInstall(ctx.root, { name: profileName, dir: profileDir })
407
+ }
408
+ }
409
+ }
410
+
411
+ /** An app folder's own definition is its Blueprint unless one was chosen explicitly. */
412
+ function instanceBlueprintEnvironment(instance: AppInstance): NodeJS.ProcessEnv {
413
+ const explicit = process.env.ACRYL_BLUEPRINT
414
+ return explicit === undefined || explicit.trim() === '' ? { ...process.env, ...(instance.definitionFile === undefined ? {} : { ACRYL_BLUEPRINT: instance.definitionFile }) } : process.env
415
+ }
416
+
417
+ /** Resolve the pinned Harness `acryl` profile by name into a mountable composition (the CLI/TUI flavor). */
418
+ async function resolveDshEngineComposition(profileName: string, capabilities: CodingCapabilities | undefined): Promise<DshEngineComposition> {
419
+ // The composition root for the CLI surface: the app instance is chosen here, once. The pinned harness reads its home from DSH_HOME, so the instance is
420
+ // handed across that boundary through the environment.
421
+ const instance = selectInstance()
422
+ process.env.DSH_HOME = instance.dshHome
423
+ // Read by `acryl_workspace_status`: the agent must learn the real surface and profile, not a fallback label.
424
+ process.env.ACRYL_SURFACE = 'tui'
425
+ process.env.ACRYL_PROFILE = profileName
426
+ const profileDirectory = resolveProfileDir(profileName)
427
+ initProfile(profileDirectory, DEFAULT_PROFILE_BUNDLES)
428
+ removeLinkProjections(profileDirectory)
429
+ const profile = loadProfile('acryl', profileName, dshInstallAnchor)
430
+ const rootConfig = join(profile.dir, 'cordis.yml')
431
+ // Refuse to re-link a profile another live ACRYL installation is running from (profile-owner.ts).
432
+ claimProfile(profile.dir, installationRoot(import.meta.url))
433
+ writeFileSync(rootConfig, profileRoot)
434
+ const profileLayerPatches = profile.layers.flatMap(layer => layer.patches)
435
+ // A profile directory booted through this CLI/TUI flavor is not necessarily
436
+ // tui-shaped: `--profile <name>` can point at one created by Desktop/Web's
437
+ // own richer template, whose bundle already composes agent-presets/persona/
438
+ // session-stats natively. Without this, ACRYL's own tui-only insert of the
439
+ // same row ids collides at boot (spec 034 T008).
440
+ const existingRowIds = new Set(composeEntries([profileLayerPatches]).map(entry => entry.id))
441
+ const blueprint = blueprintFromEnvironment(instanceBlueprintEnvironment(instance))
442
+ process.env.ACRYL_BLUEPRINT_ID = blueprint.id
443
+ process.env.ACRYL_BLUEPRINT_NAME = blueprint.name
444
+ const rowsComposition = composeBlueprintRows(blueprint, 'tui', existingRowIds, capabilities?.appFramePatches ?? [])
445
+ const patches = structuredClone([
446
+ ...profileLayerPatches,
447
+ ...(capabilities?.patches(new Set(['tui']), existingRowIds, new Set(blueprint.capabilities)) ?? []),
448
+ ...profile.patches,
449
+ ])
450
+ const composedBeforeLater = patches.length
451
+ // The Blueprint's ACRYL-owned rows (extension pack, prompt shaping) and the terminal UI library (a plain library a
452
+ // terminal plugin imports, so it is only made resolvable). Rows the profile's own bundle already composes are skipped
453
+ // by `composeBlueprintRows` (a Desktop/Web-shaped profile booted through the CLI).
454
+ // The ACRYL packages the terminal's coding capabilities name (`@acryldev/settings`), resolvable from this profile like the Web surface's.
455
+ const tuiCapabilityPackages = capabilities?.packages(new Set(['tui'] as const), new Set(blueprint.capabilities)) ?? []
456
+ for (const packageName of [...tuiCapabilityPackages, ...rowsComposition.packages]) materializeFrom(profile.dir, packageName, [...(capabilities?.anchors ?? []), import.meta.url])
457
+ patches.push(...rowsComposition.patches)
458
+ patches.push(...terminalPresetPatches(existingRowIds))
459
+ // The profile's own user overrides come from the shared store, not from this
460
+ // surface: `acryl plugin disable` on a TUI writes the same file the Desktop
461
+ // panel and the Web surface read, so the next boot of any of them composes
462
+ // the same plugin set.
463
+ patches.push(...pluginLifecyclePatches({
464
+ profileName,
465
+ statePath: resolvePluginLifecycleStatePath(),
466
+ }, rowIdsOf(patches)))
467
+ return { rootConfig, patches, surface: 'tui', instance, installPackageUrl: import.meta.url, runtimeResolution: await createProfileRuntimeResolution(profile), profileContext: createProfileContext(profile, { home: instance.dshHome, instance, overlays: acrylAdditions(patches, { layerPatches: profileLayerPatches.length, userPatches: profile.patches.length, composedBeforeLater }) }) }
468
+ }
469
+
470
+ /**
471
+ * Build the `dsh` engine definition for `createAcrylEngineHost`, bound to
472
+ * one profile name resolved at host-creation time (a CLI `--profile`
473
+ * argument, not something an engine swap changes later).
474
+ */
475
+ export function createDshEngineDefinition(profileName: string, capabilities?: CodingCapabilities): AcrylEngineDefinition {
476
+ if (profileName.trim() === '') throw new Error('ACRYL dsh engine profile must not be empty')
477
+ return {
478
+ id: 'dsh',
479
+ plugin: async (ctx: Context) => mountDshEngine(ctx, await resolveDshEngineComposition(profileName, capabilities)),
480
+ }
481
+ }
482
+
483
+ /**
484
+ * Add one declared dependency to a Loader row's `inject` metadata. A patch
485
+ * replaces the whole value, so the row's own declaration is preserved in either
486
+ * the list or the map form Cordis accepts.
487
+ */
488
+ function withDeclaredDependency(inject: unknown, name: string): string[] | Record<string, unknown> {
489
+ if (Array.isArray(inject)) return inject.includes(name) ? [...inject] : [...inject, name]
490
+ if (inject !== null && typeof inject === 'object') {
491
+ const declared = inject as Record<string, unknown>
492
+ return name in declared ? { ...declared } : { ...declared, [name]: null }
493
+ }
494
+ return [name]
495
+ }
496
+
497
+ /**
498
+ * Symlink one ACRYL-owned package into a profile's own `node_modules`, so
499
+ * Node's ordinary bare-specifier resolution - the only mechanism
500
+ * `HostResolvedRootInclude`'s composed rows use, verified directly by
501
+ * logging every `resolve()` call: `context.parentURL` is always the
502
+ * profile's own `package.json`, never `@deepseek-ai/cordis-plugin-loader`'s
503
+ * own entry - can find it. A resolution-hook overlay (matching
504
+ * `acryl-desktop`'s `installProfilePackageResolver`) cannot help here: it
505
+ * only intercepts imports whose parent is the Loader's own entry module,
506
+ * which this composition style never uses. Idempotent: replaces a stale
507
+ * symlink pointing elsewhere, leaves an already-correct one untouched.
508
+ *
509
+ * The "stale" case is not hypothetical - it is the actual CI failure mode.
510
+ * `release-cli.yml`'s `web` job runs the test suite and
511
+ * `verify-npm-web-entrypoint.mjs` *before* building and smoke-testing the
512
+ * release archive, in the same job, against the same shared
513
+ * `~/.acryl/.dsh` home. Both earlier steps materialize this exact symlink
514
+ * pointing at their own temporary staging directories, then delete those
515
+ * directories in their own cleanup - leaving a **dangling** symlink behind
516
+ * in the shared profile, not a missing one. The later archive-smoke step's
517
+ * own `materializeProfilePackage` call then hits `EEXIST` (something is
518
+ * there) and, before this fix, called `realpathSync.native` on it to
519
+ * decide whether to replace it - which throws `ENOENT` on a dangling
520
+ * symlink instead of returning a comparable path, crashing where the
521
+ * function should simply have replaced the stale link. (An earlier pass
522
+ * misdiagnosed this as an N-way in-process race and added a same-process
523
+ * memo guard; that guard was harmless but irrelevant - every reproduction
524
+ * that actually matched CI's real symptom involved *no* concurrency at
525
+ * all, just one process inheriting another, earlier process's leftover
526
+ * dangling link.)
527
+ */
528
+ /**
529
+ * Materialize one package from the first anchor that has it: an ACRYL capability package comes from the surface's composition
530
+ * (`@acryldev/coding-capabilities`), while the Blueprint's framework-kit packages (`acrylblends`, `@acryldev/ui`) come from the runtime's own
531
+ * installation. Either anchor is a real installation; the first that resolves wins (spec 051 T021).
532
+ */
533
+ function materializeFrom(profileDir: string, packageName: string, anchors: readonly (string | undefined)[]): void {
534
+ let failure: unknown
535
+ for (const anchor of anchors) {
536
+ if (anchor === undefined) continue
537
+ try {
538
+ materializeProfilePackage(profileDir, packageName, anchor)
539
+ return
540
+ } catch (error) {
541
+ failure = error
542
+ }
543
+ }
544
+ throw failure
545
+ }
546
+
547
+ /** The installation a module belongs to: the directory of its nearest package.json (the runtime or surface package of that checkout or install). */
548
+ function installationRoot(moduleUrl: string): string {
549
+ const manifest = findPackageJSON(moduleUrl)
550
+ return manifest === undefined ? fileURLToPath(moduleUrl) : dirname(manifest)
551
+ }
552
+
553
+ export function materializeProfilePackage(profileDir: string, packageName: string, installPackageUrl: string): void {
554
+ const manifestPath = findPackageJSON(packageName, installPackageUrl)
555
+ if (manifestPath === undefined) {
556
+ throw new Error(`ACRYL web profile: cannot resolve package ${JSON.stringify(packageName)} from the acryl-web installation`)
557
+ }
558
+ const sourceDir = dirname(manifestPath)
559
+ const linkPath = join(profileDir, 'node_modules', packageName)
560
+ mkdirSync(dirname(linkPath), { recursive: true })
561
+ // `lstatSync` (not `existsSync`/`realpathSync`, both of which follow the
562
+ // symlink and would throw or report "missing" for a dangling one) is the
563
+ // only one of the three that answers "is there a filesystem entry at
564
+ // this exact path at all" without caring whether it resolves.
565
+ const hasEntry = (() => {
566
+ try {
567
+ lstatSync(linkPath)
568
+ return true
569
+ } catch {
570
+ return false
571
+ }
572
+ })()
573
+ if (hasEntry) {
574
+ // realpathSync throws on a dangling symlink rather than returning a
575
+ // comparable path - that case means "stale", exactly like a mismatch.
576
+ let existingTarget: string | undefined
577
+ try {
578
+ existingTarget = realpathSync.native(linkPath)
579
+ } catch {
580
+ existingTarget = undefined
581
+ }
582
+ if (existingTarget === realpathSync.native(sourceDir)) return
583
+ rmSync(linkPath, { force: true, recursive: true })
584
+ }
585
+ symlinkSync(sourceDir, linkPath, 'dir')
586
+ }
587
+
588
+ /**
589
+ * Resolves an ACRYL-owned workspace package by name into its live on-disk install and symlinks it into a
590
+ * profile, the same way the Blueprint's own fixed rows do ({@link materializeProfilePackage}) - these
591
+ * packages are not published, so a local extension's `package.json` cannot name one as an ordinary npm
592
+ * dependency. Consumed by `@acryldev/plugin-context`'s local-plugin install path (`dsh.requiresAcrylPackages`
593
+ * in an extension's `package.json`), which also activates the materialized package as a live Loader entry
594
+ * through the existing `livePluginActivation` service - this object only makes the package resolvable.
595
+ */
596
+ export interface AcrylFrameworkPackages {
597
+ /** Symlink the package of module `name` (read under its current name) into `profileDir`'s `node_modules`, replacing a stale link; throws if it does not resolve from this installation. */
598
+ materialize(profileDir: string, name: string): void
599
+ /**
600
+ * What a required name is today: its module, the package that module lives in, and whether a Loader row of that module is mounted
601
+ * and enabled now. A module inside a package (`acrylblends/cordis/router`) is not a DSH bundle of its own, so it can only be used
602
+ * live when it is already mounted; a plugin in the app's `plugins/` folder that declares it gets the row at the next start.
603
+ */
604
+ describe(name: string): RequiredFrameworkModule
605
+ }
606
+
607
+ export interface RequiredFrameworkModule {
608
+ readonly module: string
609
+ readonly packageName: string
610
+ readonly mounted: boolean
611
+ }
612
+
613
+ function createAcrylFrameworkPackages(ctx: Context, installPackageUrl: string): AcrylFrameworkPackages {
614
+ return {
615
+ materialize: (profileDir, name) => { materializeProfilePackage(profileDir, packageOfModule(currentModule(name)), installPackageUrl) },
616
+ describe: (name) => {
617
+ const module = currentModule(name)
618
+ // Read at call time: the service outlives an engine swap, and the live tree is what a plugin will run against.
619
+ const mounted = [...ctx.root.loader.entries()].some(entry => entry.options.name === module && entry.options.disabled !== true)
620
+ return { module, packageName: packageOfModule(module), mounted }
621
+ },
622
+ }
623
+ }
624
+
625
+ declare module '@deepseek-ai/cordis' {
626
+ interface Context {
627
+ /** Resolves an ACRYL-owned workspace package by name for a local extension to depend on (see {@link AcrylFrameworkPackages}). */
628
+ acrylFrameworkPackages: AcrylFrameworkPackages
629
+ }
630
+ }
631
+
632
+ /**
633
+ * ACRYL-owned framework packages the app's own committed plugins (`<app home>/plugins/*`, `homePluginsDir`) declare
634
+ * through `dsh.requiresAcrylPackages` in their `package.json`. Read at compose time, not through
635
+ * `@acryldev/plugin-context`'s dynamic agent-runtime install path: `livePluginActivation.activate()`'s group
636
+ * resolution (`PluginLifecycleController`'s `bundleGroup()`, a fixed-point-free heuristic over the live Loader
637
+ * tree) failed a real, reproduced activation of `@acryldev/app-shell` through that path ("invalid plugin... received
638
+ * object") for reasons that trace into vendored Cordis internals this repo does not edit. A static row, inserted
639
+ * the same way the Blueprint's own fixed rows are (`composeBlueprintRows`/`materializeProfilePackage`), sidesteps
640
+ * dynamic activation entirely and is what every one of those fixed rows already relies on successfully.
641
+ * Never throws: a missing or malformed `package.json` is skipped, not fatal to boot.
642
+ */
643
+ export function pluginRequiredFrameworkPackages(appHome: string): readonly string[] {
644
+ const pluginsDir = homePluginsDir(appHome)
645
+ if (!existsSync(pluginsDir)) return []
646
+ const names = new Set<string>()
647
+ for (const entry of readdirSync(pluginsDir, { withFileTypes: true })) {
648
+ if (entry.isDirectory()) for (const module of requiredModulesOf(join(pluginsDir, entry.name, 'package.json'))) names.add(module)
649
+ }
650
+ return [...names]
651
+ }
652
+
653
+ /**
654
+ * The modules inside a package (`acrylblends/cordis/state`) that the plugins installed in a profile (its user bundles) declare through
655
+ * `dsh.requiresAcrylPackages`. A running app mounts such a module's row when one of them is installed (spec 049 T001); composing the same
656
+ * rows at start keeps the next start's tree what the running one had. A whole package a plugin requires is a profile bundle of its own and
657
+ * composes as one, so it is not listed here. Never throws: an unreadable manifest is skipped.
658
+ */
659
+ export function profileRequiredFrameworkModules(profileDir: string): readonly string[] {
660
+ const modules = new Set<string>()
661
+ for (const bundle of readUserMutableBundleNames(profileDir)) {
662
+ for (const module of requiredModulesOf(join(profileDir, 'node_modules', bundle, 'package.json'))) {
663
+ if (module !== packageOfModule(module)) modules.add(module)
664
+ }
665
+ }
666
+ return [...modules]
667
+ }
668
+
669
+ /** The modules one plugin's `package.json` declares in `dsh.requiresAcrylPackages`, by today's names; none when it is missing or malformed. */
670
+ function requiredModulesOf(manifestPath: string): readonly string[] {
671
+ if (!existsSync(manifestPath)) return []
672
+ try {
673
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as { dsh?: { requiresAcrylPackages?: unknown } }
674
+ const required = manifest.dsh?.requiresAcrylPackages
675
+ // Each entry is a module, mounted as its own row; a name from before the framework moved to acrylblends is read as today's module.
676
+ return Array.isArray(required) ? required.filter((name): name is string => typeof name === 'string').map(currentModule) : []
677
+ } catch { return [] /* a malformed plugin package.json is the plugin's own problem, reported when it installs, not here */ }
678
+ }
679
+
680
+ /** Resolve the pinned Harness `web` profile into a mountable composition (the Web flavor). */
681
+ async function resolveWebEngineComposition(installPackageUrl: string, capabilities: CodingCapabilities | undefined): Promise<DshEngineComposition> {
682
+ const profileName = 'web'
683
+ // The composition root for the Web surface: the app instance is chosen here, once (see the CLI flavor above).
684
+ const instance = selectInstance()
685
+ process.env.DSH_HOME = instance.dshHome
686
+ process.env.ACRYL_SURFACE = 'web'
687
+ process.env.ACRYL_PROFILE = profileName
688
+ const profileDirectory = resolveProfileDir(profileName)
689
+ // The shipped `web` template (PROFILE_TEMPLATES.web) bundles dsh-web-app
690
+ // (dsh-client-connection, webStartup, the auth-gated index) on top of
691
+ // dsh-base - DEFAULT_PROFILE_BUNDLES is only ['@deepseek-ai/dsh-base'], the
692
+ // generic fallback loadProfile() uses for a *custom-named* profile with no
693
+ // shipped template (the CLI/TUI flavor's own 'acryl'/'--profile' names).
694
+ // initProfile() only writes package.json when one doesn't exist yet, so
695
+ // calling it here with the wrong (too-minimal) bundle list on a profile
696
+ // loadProfile() would otherwise auto-initialize correctly *pre-empts* that
697
+ // correct initialization - a fresh 'web' profile then permanently has no
698
+ // dsh-web-app bundle, so ctx.get('connection')/ctx.get('webStartup') never
699
+ // exist and the served index falls back to its own "authentication
700
+ // required" client-side message rather than ever serving the app.
701
+ // Reproduced directly: a fresh profile's Loader entries contained no
702
+ // "connection" or "web-startup" row at all (not pending, not failed -
703
+ // absent) before this fix.
704
+ const webTemplate = PROFILE_TEMPLATES.web
705
+ initProfile(profileDirectory, webTemplate?.bundles ?? DEFAULT_PROFILE_BUNDLES)
706
+ removeLinkProjections(profileDirectory)
707
+ const profile = loadProfile('web', profileName, dshInstallAnchor)
708
+ const rootConfig = join(profile.dir, 'cordis.yml')
709
+ claimProfile(profile.dir, installationRoot(installPackageUrl))
710
+ writeFileSync(rootConfig, profileRoot)
711
+ const profileLayerPatches = profile.layers.flatMap(layer => layer.patches)
712
+ // Same reasoning as the CLI/TUI flavor above: this profile's own bundle may
713
+ // already compose a row ACRYL's own capability table would otherwise insert
714
+ // a second time (spec 034 T008).
715
+ const existingRowIds = new Set(composeEntries([profileLayerPatches]).map(entry => entry.id))
716
+ // Web runs the same ACRYL shell and workspace Desktop does (spec 040, "Surface sharing"): both come from the
717
+ // shared capability declarations, and the ACRYL packages they name are made resolvable from this profile.
718
+ const blueprint = blueprintFromEnvironment(instanceBlueprintEnvironment(instance))
719
+ process.env.ACRYL_BLUEPRINT_ID = blueprint.id
720
+ process.env.ACRYL_BLUEPRINT_NAME = blueprint.name
721
+ const webSurfaces = new Set(['web'] as const)
722
+ const enabledCapabilities = new Set(blueprint.capabilities)
723
+ const rowsComposition = composeBlueprintRows(blueprint, 'web', existingRowIds, capabilities?.appFramePatches ?? [])
724
+ for (const packageName of [...(capabilities?.packages(webSurfaces, enabledCapabilities) ?? []), ...rowsComposition.packages]) {
725
+ materializeFrom(profile.dir, packageName, [...(capabilities?.anchors ?? []), installPackageUrl])
726
+ }
727
+ // The app's own committed plugins may each need an ACRYL-owned framework package (see
728
+ // `pluginRequiredFrameworkPackages`'s own doc comment for why this is a static row, not the dynamic
729
+ // agent-runtime install path `@acryldev/plugin-context` otherwise uses), and a plugin installed into the
730
+ // profile may need a module whose row the running app mounted for it (`profileRequiredFrameworkModules`).
731
+ const composedRowIds = new Set(rowsComposition.patches.flatMap(patch => patch.insert ?? []).map(row => row.id))
732
+ const requiredFrameworkPackages = [...new Set([...pluginRequiredFrameworkPackages(instance.home), ...profileRequiredFrameworkModules(profile.dir)])]
733
+ .filter(module => !existingRowIds.has(module) && !composedRowIds.has(module))
734
+ for (const module of requiredFrameworkPackages) materializeProfilePackage(profile.dir, packageOfModule(module), installPackageUrl)
735
+ // A Blueprint that never enables the IDE's own `workspace` capability (every Blank-grown project) keeps the
736
+ // stock `ui-layout` row active, because the advanced-shell capability's disabling patch is gated behind
737
+ // `ACRYL_CODING_CAPABILITIES`' own capability table, which a third-party extension cannot opt into - it is
738
+ // the IDE's, not a general extension mechanism. An extension that requires `@acryldev/app-shell` is claiming the
739
+ // advanced shell exactly the same way that capability does, so it needs the identical row toggle (measured
740
+ // live: without it, `@acryldev/app-shell`'s own layout service and the still-active stock one both try to
741
+ // register the `layout` service and the Loader throws "service \"layout\" has been registered").
742
+ const claimsAdvancedShell = requiredFrameworkPackages.includes('@acryldev/app-shell')
743
+ const patches = structuredClone([
744
+ ...profileLayerPatches,
745
+ ...(capabilities?.patches(webSurfaces, existingRowIds, enabledCapabilities) ?? []),
746
+ ...(capabilities?.shellPatches(webSurfaces, 'advanced', existingRowIds, enabledCapabilities) ?? []),
747
+ ...requiredFrameworkPackages.map(name => ({ insert: [{ id: name, name }] })),
748
+ ...(claimsAdvancedShell ? [{ id: 'ui-layout', disabled: true }, { id: 'ui-sidebar', disabled: false }, { id: 'ui-conversation', disabled: false }] : []),
749
+ ...profile.patches,
750
+ ])
751
+ const composedBeforeLater = patches.length
752
+ // Brand swap: same technique and same row id as acryl-desktop's own
753
+ // (independent) brand swap in profile.ts - the stock DeepSeek Harness
754
+ // identity (`@deepseek-ai/dsh-client-ui-brand-official`, already composed
755
+ // by the base dsh-web-app bundle at row id `ui-brand-official`) and
756
+ // `@acryldev/brand-client` are standalone, independently swappable
757
+ // Cordis Client plugins carrying the same slot contract
758
+ // (`sidebar.brand.mark`/`.name`, `conversation.hero.brand.mark`) - exactly
759
+ // one is ever enabled. Validated against the real composed row (not
760
+ // assumed) so a future dsh-web-app bundle change that renames or removes
761
+ // this row fails loud here instead of silently keeping the DeepSeek brand.
762
+ const officialBrandRow = composeEntries([patches]).find(entry => entry.id === 'ui-brand-official')
763
+ if (officialBrandRow?.name !== '@deepseek-ai/dsh-client-ui-brand-official') {
764
+ throw new Error('ACRYL web profile must use @deepseek-ai/dsh-client-ui-brand-official in the ui-brand-official row')
765
+ }
766
+ // `@deepseek-ai/dsh-client-connection` resolves `webServer` from the Context
767
+ // its own row was built with while registering a caller's
768
+ // `connection.rpc.handle(...)` channel. Cordis resolves an undeclared name
769
+ // only along the provider's fiber chain, and the web server row is a sibling
770
+ // of the connection row, so any third-party profile plugin (for example
771
+ // acryl-dsh-editor-plugin) failed the whole tree with `cannot get property
772
+ // "webServer" without inject`. Same declaration acryl-desktop's
773
+ // prepareDesktopProfile makes for the same row.
774
+ const connectionRow = composeEntries([patches]).find(entry => entry.id === 'connection')
775
+ if (connectionRow?.name === '@deepseek-ai/dsh-client-connection') {
776
+ patches.push({
777
+ id: 'connection',
778
+ name: connectionRow.name,
779
+ inject: withDeclaredDependency(connectionRow.inject, 'webServer'),
780
+ // A patch replaces the row's whole config, so the trusted names (a proxy's public host, from the instance's web access) merge into what the
781
+ // profile already set rather than dropping its recovery or cookie settings.
782
+ ...(instance.webAccess.trustedHosts.length === 0 ? {} : { config: { ...connectionConfig(connectionRow.config), trustedHosts: [...instance.webAccess.trustedHosts] } }),
783
+ })
784
+ }
785
+ // Every ACRYL-owned row (brand, Market, extension pack, prompt shaping, UI library, shortcuts, mount anchors) comes from
786
+ // the selected Blueprint (spec 036): the row table lives in `blueprint/compose.ts`, and the packages were made resolvable
787
+ // from this profile above (they are ACRYL-owned workspace packages outside @deepseek-ai/dsh's dependency closure, so
788
+ // `healProfilesModuleFallback` cannot find them; see `materializeProfilePackage`).
789
+ patches.push(...rowsComposition.patches)
790
+ // A second instance beside one on the default port (spec 036): ACRYL_WEB_PORT moves the server.
791
+ // The port is part of the app's family: a stable start, and the next free one when it is taken (never a fight with another app).
792
+ // The listening address is part of it too: loopback, unless a container entry point asked for every interface (ACRYL_WEB_HOST).
793
+ const webHost = instance.webAccess.host
794
+ if (instance.webPort.scan) {
795
+ const webPort = await findFreeWebPort(instance.webPort.start, port => loopbackPortIsFree(port, webHost))
796
+ if (webPort !== instance.webPort.start) process.stdout.write(`ACRYL: port ${String(instance.webPort.start)} is in use, using ${String(webPort)}\n`)
797
+ patches.push(webPortPatch(webPort, webHost))
798
+ } else if (webHost !== LOOPBACK_WEB_HOST) {
799
+ patches.push(webPortPatch(instance.webPort.start, webHost))
800
+ }
801
+ // Last, so a user override beats every composition decision above it - the
802
+ // same shared store the CLI and the Desktop panel write (spec 034).
803
+ patches.push(...pluginLifecyclePatches({
804
+ profileName,
805
+ statePath: resolvePluginLifecycleStatePath(),
806
+ }, rowIdsOf(patches)))
807
+ return { rootConfig, patches, surface: 'web', instance, installPackageUrl, runtimeResolution: await createProfileRuntimeResolution(profile), profileContext: createProfileContext(profile, { home: instance.dshHome, instance, overlays: acrylAdditions(patches, { layerPatches: profileLayerPatches.length, userPatches: profile.patches.length, composedBeforeLater }) }), productName: blueprint.brand.kind === 'custom' ? blueprint.brand.identity.name : 'ACRYL', stockBrand: blueprint.brand.kind === 'acryl' }
808
+ }
809
+
810
+ /** The Loader row ids a list of patches composes, for overrides that apply only to rows that exist. */
811
+ function rowIdsOf(patches: readonly PatchOptions[]): ReadonlySet<string> {
812
+ return new Set(composeEntries([[...patches]]).flatMap(row => (typeof row.id === 'string' ? [row.id] : [])))
813
+ }
814
+
815
+ /** A Loader row's config as a plain object to merge into, or an empty one when the profile set none. */
816
+ function connectionConfig(config: unknown): Record<string, unknown> {
817
+ return typeof config === 'object' && config !== null && !Array.isArray(config) ? { ...(config as Record<string, unknown>) } : {}
818
+ }
819
+
820
+ /**
821
+ * Build the `dsh` engine definition for the Web surface's `web` profile
822
+ * (`dsh-base` + `dsh-web-app`) - the same shared `mountDshEngine` primitive
823
+ * as {@link createDshEngineDefinition}, resolved through this package's own
824
+ * profile system like the CLI flavor (Web has no external profile pipeline
825
+ * of its own, unlike Desktop's `prepareDesktopProfile()`).
826
+ * @param installPackageUrl - file URL of `acryl-web`'s own `package.json`,
827
+ * used to materialize `@acryldev/brand-client` and `@acryldev/cordis-plugin-market`
828
+ * into the profile (see {@link resolveWebEngineComposition}'s own comments
829
+ * for why that is needed).
830
+ */
831
+ export function createWebEngineDefinition(installPackageUrl: string, capabilities?: CodingCapabilities): AcrylEngineDefinition {
832
+ return {
833
+ id: 'dsh',
834
+ plugin: async (ctx: Context) => mountDshEngine(ctx, await resolveWebEngineComposition(installPackageUrl, capabilities)),
835
+ }
836
+ }
837
+
838
+ /**
839
+ * Build the `dsh` engine definition from a composition a surface already
840
+ * resolved itself (Desktop's `prepareDesktopProfile()`: its own profile
841
+ * selection, market/editor/BLEND patch layering, and worker bare-module base
842
+ * URL). Performs no profile resolution of its own - unlike
843
+ * {@link createDshEngineDefinition}, which is the CLI/TUI flavor that
844
+ * resolves a profile by name through `@acryldev/harness-runtime`'s own profile
845
+ * system. Handing an already-resolved composition to that function would
846
+ * silently discard it and resolve a different profile instead.
847
+ */
848
+ export function createDshEngineDefinitionFromComposition(
849
+ composition: DshEngineComposition,
850
+ ): AcrylEngineDefinition {
851
+ if (composition.surface.trim() === '') throw new Error('ACRYL dsh engine surface must not be empty')
852
+ return {
853
+ id: 'dsh',
854
+ plugin: (ctx: Context) => mountDshEngine(ctx, composition),
855
+ }
856
+ }