profile-boot.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. /**
  2. * Shared profile boot for every `dsh` surface: resolve the profile, stack its
  3. * patch layers (bundle layers in `dsh.profile.bundles` order, the profile's own
  4. * `cordis.patch.yml`, `--patch` overlays, flag-derived patches, the telemetry
  5. * switch), mount the tree over the profile's empty root config, keep the
  6. * profile patch layer live, and wire fail-loud plus bounded shutdown.
  7. * @module @deepseek-ai/dsh/profile-boot
  8. */
  9. import { writeFileSync } from 'node:fs'
  10. import { join, resolve } from 'node:path'
  11. import { fileURLToPath } from 'node:url'
  12. import { FiberState, type Context } from '@deepseek-ai/cordis'
  13. import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  14. import { dshHomePath } from '@deepseek-ai/dsh-paths'
  15. import {
  16. boot,
  17. composeEntries,
  18. healProfilesModuleFallback,
  19. installFailLoud,
  20. loadOptionalPatches,
  21. loadOverlayPatches,
  22. loadProfile,
  23. PROFILE_PATCH_FILENAME,
  24. watchUserPatches,
  25. type Profile,
  26. } from '@deepseek-ai/dsh-app-boot'
  27. import { resolveDshHome } from '@deepseek-ai/dsh-paths'
  28. /** Shipped agent-preset root: beside this app's own config, in both source and built layouts. */
  29. const SHIPPED_PRESET_ROOT = fileURLToPath(new URL('../config/agent-presets/', import.meta.url))
  30. /** Harness-home directory holding locally authored agent presets. */
  31. const USER_PRESET_DIR = '.agent-presets'
  32. import { DSH_ENVIRONMENT_KEY, type EnvironmentSnapshot } from '@deepseek-ai/dsh-environment'
  33. import type { HeadlessIo } from '@deepseek-ai/dsh-headless'
  34. import { createProcessShutdown, type ProcessShutdown } from './process-shutdown.ts'
  35. import { resolveWindowsShellLayer } from './windows-shell.ts'
  36. const NAME = 'dsh'
  37. /**
  38. * The home-level user patch layer (`$DSH_HOME/cordis.patch.yml`), applied
  39. * over every profile's own layer. Resolved per call, not at module load:
  40. * `$DSH_HOME` may be set by the test or launcher after import.
  41. * @returns the absolute patch-file path.
  42. */
  43. export function homePatchPath(): string {
  44. return join(resolveDshHome(), PROFILE_PATCH_FILENAME)
  45. }
  46. /** Absolute path of this dsh installation's package.json (both anchors: src/ and lib/ sit one level under apps/cli). */
  47. export const INSTALL_ANCHOR = fileURLToPath(new URL('../package.json', import.meta.url))
  48. /** The session-telemetry row id the DSH_TELEMETRY_DISABLED switch targets. */
  49. const TELEMETRY_ROW_ID = 'telemetry-otel'
  50. /** The one-shot runner row a `dsh run` task requires and configures. */
  51. const HEADLESS_ROW_ID = 'headless-runner'
  52. /** The empty root entry list every profile tree patches over. */
  53. const PROFILE_ROOT_CONFIG = `# dsh profile root — an empty entry list. The tree is composed as patches:
  54. # each bundle in package.json's dsh.profile.bundles, then cordis.patch.yml, then any
  55. # --patch overlays. Edit cordis.patch.yml, not this file.
  56. []
  57. `
  58. /** Root config filename inside a profile directory. */
  59. export const PROFILE_ROOT_FILENAME = 'cordis.yml'
  60. /**
  61. * Resolve the telemetry opt-out switch into its boot patch. ANY non-empty
  62. * value (including `'0'`/`'false'`) disables: a privacy switch prefers
  63. * off-by-mistake over on-by-mistake. A composition without the telemetry row
  64. * exports nothing, so the switch is then trivially satisfied and no patch is
  65. * generated — custom profiles need not mount telemetry to run with the
  66. * switch set.
  67. * @param disabledEnv - the raw `DSH_TELEMETRY_DISABLED` value (`undefined` when unset).
  68. * @param hasRow - whether the composition carries the telemetry row.
  69. * @returns the disable patch, or `undefined` when telemetry stays enabled or is not mounted.
  70. */
  71. export function resolveTelemetryPatch(disabledEnv: string | undefined, hasRow: boolean): PatchOptions | undefined {
  72. if ((disabledEnv ?? '') === '' || !hasRow) return undefined
  73. return { id: TELEMETRY_ROW_ID, disabled: true }
  74. }
  75. /**
  76. * Load a resolved profile for `name`: heal the shared module fallback, then
  77. * (re)write the empty root config. The root is always rewritten: the whole
  78. * composition is patch layers, and the vendored Loader's tree write-back (a
  79. * plugin self-disposing persists the current tree) can bake composed rows
  80. * into this file — which would duplicate every bundle insert on the next
  81. * boot. The file exists on disk only because the Loader needs a real include
  82. * root to anchor `baseUrl` at the profile directory (the config dump anchors
  83. * on the same file, so both compose over the identical base).
  84. * @param name - the profile name.
  85. * @param userLayer - `false` skips parsing `cordis.patch.yml` (the default dump).
  86. * @returns the loaded profile.
  87. */
  88. export function prepareProfile(name: string, userLayer = true): Profile {
  89. healProfilesModuleFallback(INSTALL_ANCHOR)
  90. const profile = loadProfile(NAME, name, INSTALL_ANCHOR, undefined, { userLayer })
  91. writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG)
  92. return profile
  93. }
  94. /** Read-only row index of a profile composition before launcher flag patches. */
  95. export type ProfileRows = ReadonlyMap<string, { name?: string; config?: unknown }>
  96. /** One profile's patch layers (application order) and the row index of its pre-flag composition. */
  97. interface ComposedProfile {
  98. profile: Profile
  99. /** Bundle layers concatenated — the part below the user layers on a live reload. */
  100. bundlePatches: PatchOptions[]
  101. /** The win32 shell platform layer (the base bundle's `windows.cordis.patch.yml`), between bundles and user layers. */
  102. windowsShellPatches: PatchOptions[]
  103. /** The home-level user layer (`$DSH_HOME/cordis.patch.yml`), applied after the profile's own. */
  104. homePatches: PatchOptions[]
  105. /** Layers above the user layers on a live reload: --patch overlays, flag patches, the telemetry switch. */
  106. overlayAndFlags: PatchOptions[]
  107. /**
  108. * id → row of the pre-flag composition (bundles + user layers + overlays),
  109. * for flag merges and row checks. Flag patches must not insert rows the
  110. * launcher consults here (they only override values and insert dev glue).
  111. */
  112. rows: ProfileRows
  113. }
  114. /** The full patch stack of one composed profile, in application order. */
  115. function allPatches(composed: ComposedProfile): PatchOptions[] {
  116. return [
  117. ...composed.bundlePatches,
  118. ...composed.windowsShellPatches,
  119. ...composed.profile.patches,
  120. ...composed.homePatches,
  121. ...composed.overlayAndFlags,
  122. ]
  123. }
  124. /**
  125. * Load `name` and compose its effective patch stack: bundle layers in
  126. * `dsh.profile.bundles` order, the win32 shell platform layer (when the host
  127. * is Windows), the profile's user layer, the home-level user layer
  128. * (`$DSH_HOME/cordis.patch.yml` — machine-local preferences that apply to
  129. * every profile, so it outranks the per-profile layer), `--patch` overlays,
  130. * then flag patches derived from the composed rows, then the telemetry
  131. * switch.
  132. * @param name - the profile name.
  133. * @param patchFiles - `--patch` overlay paths, in argv order.
  134. * @param deriveFlagPatches - launcher hook turning composed rows into flag patches.
  135. * @returns the profile, its patch layers, and the composed row index.
  136. */
  137. function composeProfile(
  138. name: string,
  139. patchFiles: readonly string[],
  140. deriveFlagPatches: (rows: ComposedProfile['rows']) => PatchOptions[] = () => [],
  141. ): ComposedProfile {
  142. const profile = prepareProfile(name)
  143. const homePatches = loadOptionalPatches(NAME, homePatchPath()) ?? []
  144. const overlays = patchFiles.flatMap(file => loadOverlayPatches(NAME, resolve(file)))
  145. const bundlePatches = profile.layers.flatMap(layer => layer.patches)
  146. const windowsShellPatches = resolveWindowsShellLayer(process.platform, profile.layers, NAME)?.patches ?? []
  147. const rows = new Map<string, { name?: string; config?: unknown }>()
  148. for (const row of composeEntries([bundlePatches, windowsShellPatches, profile.patches, homePatches, overlays])) {
  149. if (typeof row.id === 'string') rows.set(row.id, row)
  150. }
  151. const overlayAndFlags = [...overlays, ...deriveFlagPatches(rows)]
  152. // The agent-preset roots are an assembly fact of every dsh launcher, not a
  153. // patch author's choice: the shipped set sits beside this app's config and
  154. // the user's own under the Harness home. Resolved per boot ($DSH_HOME may
  155. // differ per run) and only patched when the composed tree actually mounts
  156. // the roster — a one-shot `dsh run` composes agents from the same roster
  157. // `dsh web` offers.
  158. if (rows.has('agent-presets')) {
  159. overlayAndFlags.push({
  160. id: 'agent-presets',
  161. config: {
  162. ...(rows.get('agent-presets')?.config ?? {}) as Record<string, unknown>,
  163. roots: [
  164. { path: SHIPPED_PRESET_ROOT, trust: 'system' },
  165. { path: dshHomePath(USER_PRESET_DIR), trust: 'user' },
  166. ],
  167. },
  168. })
  169. }
  170. const telemetryPatch = resolveTelemetryPatch(process.env.DSH_TELEMETRY_DISABLED, rows.has(TELEMETRY_ROW_ID))
  171. if (telemetryPatch !== undefined) overlayAndFlags.push(telemetryPatch)
  172. return { profile, bundlePatches, windowsShellPatches, homePatches, overlayAndFlags, rows }
  173. }
  174. /** Options for {@link runProfile}. */
  175. export interface RunProfileOptions {
  176. /** The profile name to boot. */
  177. profile: string
  178. /** `--patch` overlay paths, in argv order. */
  179. patchFiles: readonly string[]
  180. /** Launcher hook turning the pre-flag composed rows into flag patches (the web alias's flag family). */
  181. deriveFlagPatches?: (rows: ProfileRows) => PatchOptions[]
  182. /** `dsh run` task text; requires the composition to mount the headless runner row. */
  183. task?: string
  184. /** Surface setup registered after Loader installation and before any config-tree entry mounts. */
  185. prepare?: (ctx: Context, rows: ProfileRows) => Promise<void> | void
  186. /** This run's frozen environment snapshot, provided to the tree before any entry mounts. */
  187. environment: EnvironmentSnapshot
  188. }
  189. /** Re-throw setup failures unless this invocation's signal already owns shutdown. */
  190. function suppressSignalShutdownError(signal: AbortSignal, error: unknown): void {
  191. if (!signal.aborted) throw error
  192. }
  193. /**
  194. * Boot one profile invocation end to end and leave process lifetime to the
  195. * mounted plugins (or to the one-shot runner when `task` is present).
  196. * @param options - profile name, overlays, flag patches, and the optional task.
  197. * @returns the settled root context and the shutdown controller.
  198. */
  199. export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Context; shutdown: ProcessShutdown }> {
  200. const composed = composeProfile(options.profile, options.patchFiles, options.deriveFlagPatches)
  201. if (options.task !== undefined) {
  202. if (!composed.rows.has(HEADLESS_ROW_ID)) {
  203. throw new Error(
  204. `dsh: profile ${JSON.stringify(options.profile)} takes no task — its composition mounts no "${HEADLESS_ROW_ID}" row `
  205. + '(the headless profile does)',
  206. )
  207. }
  208. composed.overlayAndFlags.push({ id: HEADLESS_ROW_ID, config: { task: options.task } })
  209. } else if (composed.rows.has(HEADLESS_ROW_ID)) {
  210. // The inverse misuse: a one-shot composition booted without its task
  211. // would otherwise die in the runner row's schema with a raw "required"
  212. // error naming no fix.
  213. throw new Error(
  214. `dsh: profile ${JSON.stringify(options.profile)} mounts the one-shot runner and needs a task: `
  215. + `dsh run --profile ${options.profile} "<task>"`,
  216. )
  217. }
  218. const app: { current?: Context } = {}
  219. const shutdown = createProcessShutdown(async () => { await app.current?.fiber.dispose() })
  220. const signalShutdown = new AbortController()
  221. const interrupt = (code: number): void => {
  222. signalShutdown.abort()
  223. shutdown.interrupt(code)
  224. }
  225. // Signals own teardown throughout the startup window, not only after boot()
  226. // settles: an inserted entry point can publish readiness before sibling rows
  227. // finish mounting.
  228. process.on('SIGTERM', () => { interrupt(options.task === undefined ? 0 : 143) })
  229. process.on('SIGINT', () => { interrupt(130) })
  230. installFailLoud(NAME, process, async () => {
  231. await app.current?.fiber.dispose()
  232. })
  233. const rootConfig = join(composed.profile.dir, PROFILE_ROOT_FILENAME)
  234. // Recomposition for the live user layers: bundle layers below, overlays
  235. // and flag patches above, so a user edit can never displace them. BOTH
  236. // user files are re-read per generation (the HMR watcher hands us only the
  237. // changed file's patches, which one of the reads duplicates — fresh reads
  238. // keep the two watchers from stitching in each other's stale copy).
  239. // Fresh clones per generation: the include pushes `insert` rows into the
  240. // mounted tree BY REFERENCE and later id-targeted patches mutate those
  241. // objects in place. Reusing one parsed patch object across applications
  242. // would bake a user override into the bundle's in-memory insert row, so
  243. // removing the override could never revert the row to the bundle default.
  244. const composeLive = (): PatchOptions[] => structuredClone([
  245. ...composed.bundlePatches,
  246. ...composed.windowsShellPatches,
  247. ...loadOptionalPatches(NAME, composed.profile.patchPath) ?? [],
  248. ...loadOptionalPatches(NAME, homePatchPath()) ?? [],
  249. ...composed.overlayAndFlags,
  250. ])
  251. // One-shot runs exit through the runner; watching would only hold the
  252. // process open after its exit request.
  253. const watchProfilePatch = options.task === undefined
  254. // Cloned for the same insert-aliasing reason as composeLive: the boot
  255. // application must not mutate the objects later reloads recompose from.
  256. const ctx = await boot(NAME, rootConfig, structuredClone(allPatches(composed)), async (hostCtx) => {
  257. app.current = hostCtx
  258. // Before any config-tree entry mounts, so a plugin that resolves a
  259. // user-facing value at construction already sees this run's layers.
  260. hostCtx.provide(DSH_ENVIRONMENT_KEY, options.environment)
  261. if (options.task !== undefined) {
  262. const io: HeadlessIo = {
  263. stdout: process.stdout,
  264. stderr: process.stderr,
  265. exit: (code) => { void shutdown.shutdown(code) },
  266. }
  267. hostCtx.provide('headlessIo', io)
  268. }
  269. await options.prepare?.(hostCtx, composed.rows)
  270. })
  271. app.current = ctx
  272. // A surface can dispose the whole tree while startup or this post-boot
  273. // watcher setup is still in flight. Loader presence and fiber state own
  274. // liveness; the local signal fact distinguishes that expected exit race
  275. // from a real HMR error.
  276. if (watchProfilePatch
  277. && !signalShutdown.signal.aborted
  278. && ctx.fiber.state === FiberState.ACTIVE
  279. && ctx.get('loader') !== undefined) {
  280. try {
  281. // Config-only HMR for the live profile patch layer: the web bundle
  282. // disables the shared module-reload `hmr` row (its reload lifecycle is
  283. // untested), so when the composition leaves no HMR service, mount a
  284. // watch-only instance with no module roots — cordis.patch.yml edits stay
  285. // live on every long-lived surface. A silent skip would break the
  286. // documented hot-reload contract. HMR injects the timer service, which a
  287. // bare custom profile may not mount either.
  288. if (ctx.get('hmr') === undefined) {
  289. if (ctx.get('timer') === undefined) {
  290. await ctx.loader.create({ name: '@deepseek-ai/cordis-plugin-timer' })
  291. }
  292. await ctx.loader.create({ name: '@deepseek-ai/cordis-plugin-hmr', config: { root: [] } })
  293. }
  294. await watchUserPatches(ctx, {
  295. binName: NAME,
  296. filename: composed.profile.patchPath,
  297. compose: composeLive,
  298. })
  299. await watchUserPatches(ctx, {
  300. binName: NAME,
  301. filename: homePatchPath(),
  302. compose: composeLive,
  303. })
  304. } catch (error) {
  305. suppressSignalShutdownError(signalShutdown.signal, error)
  306. }
  307. }
  308. return { ctx, shutdown }
  309. }