profile-boot.ts 13 KB

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