profile-boot.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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
  4. * own `cordis.patch.yml`, `--patch` overlays, the telemetry switch), mount the
  5. * tree over the profile's empty root config, apply its selected patch-reload
  6. * lifecycle, and wire fail-loud plus bounded shutdown.
  7. *
  8. * App flags are not the launcher's business: the invocation's inner arguments
  9. * are provided to the tree through `ctx.cmdlineArgs`, where any injected app
  10. * plugin may read the same immutable snapshot.
  11. * @module @deepseek-ai/dsh/profile-boot
  12. */
  13. import { writeFileSync } from 'node:fs'
  14. import { join, resolve } from 'node:path'
  15. import { fileURLToPath } from 'node:url'
  16. import { FiberState, type Context } from '@deepseek-ai/cordis'
  17. import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  18. import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
  19. import {
  20. boot,
  21. composeEntries,
  22. healProfilesModuleFallback,
  23. installFailLoud,
  24. loadOptionalPatches,
  25. loadOverlayPatches,
  26. loadProfile,
  27. PROFILE_PATCH_FILENAME,
  28. watchUserPatches,
  29. type Profile,
  30. } from '@deepseek-ai/dsh-app-boot'
  31. import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
  32. import { DSH_LAUNCH_ENVIRONMENT_KEY, type LaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
  33. import { provideCmdline, type AppReady } from '@deepseek-ai/dsh-cmdline'
  34. import { createProcessShutdown, type ProcessShutdown } from './process-shutdown.ts'
  35. const NAME = 'dsh'
  36. /** Launcher-owned readiness signal committed only after boot and host setup succeed. */
  37. function createAppReady(): { service: AppReady; commit(): void } {
  38. let ready = false
  39. const listeners = new Set<() => void>()
  40. return {
  41. service: {
  42. onReady(listener) {
  43. if (ready) {
  44. listener()
  45. return () => {}
  46. }
  47. listeners.add(listener)
  48. return () => { listeners.delete(listener) }
  49. },
  50. },
  51. commit() {
  52. if (ready) return
  53. ready = true
  54. for (const listener of [...listeners]) listener()
  55. listeners.clear()
  56. },
  57. }
  58. }
  59. /**
  60. * The home-level user patch layer (`$DSH_HOME/cordis.patch.yml`), applied
  61. * over every profile's own layer. Resolved per call, not at module load:
  62. * `$DSH_HOME` may be set by the test or launcher after import.
  63. * @returns the absolute patch-file path.
  64. */
  65. export function homePatchPath(): string {
  66. return join(resolveDshHome(), PROFILE_PATCH_FILENAME)
  67. }
  68. /** Absolute path of this dsh installation's package.json (both anchors: src/ and lib/ sit one level under apps/cli). */
  69. export const INSTALL_ANCHOR = fileURLToPath(new URL('../package.json', import.meta.url))
  70. /** The session-telemetry row id the DSH_TELEMETRY_DISABLED switch targets. */
  71. const TELEMETRY_ROW_ID = 'session-telemetry-otel'
  72. /** The empty root entry list every profile tree patches over. */
  73. const PROFILE_ROOT_CONFIG = `# dsh profile root — an empty entry list. The tree is composed as patches:
  74. # each bundle in package.json's dsh.profile.bundles, then cordis.patch.yml, then any
  75. # --patch overlays. Edit cordis.patch.yml, not this file.
  76. []
  77. `
  78. /** Root config filename inside a profile directory. */
  79. export const PROFILE_ROOT_FILENAME = 'cordis.yml'
  80. /**
  81. * Resolve the telemetry opt-out switch into its boot patch. ANY non-empty
  82. * value (including `'0'`/`'false'`) disables: a privacy switch prefers
  83. * off-by-mistake over on-by-mistake. A composition without the telemetry row
  84. * exports nothing, so the switch is then trivially satisfied and no patch is
  85. * generated — custom profiles need not mount telemetry to run with the
  86. * switch set.
  87. * @param disabledEnv - the raw `DSH_TELEMETRY_DISABLED` value (`undefined` when unset).
  88. * @param hasRow - whether the composition carries the telemetry row.
  89. * @returns the disable patch, or `undefined` when no hard-disable patch is required.
  90. */
  91. export function resolveTelemetryPatch(disabledEnv: string | undefined, hasRow: boolean): PatchOptions | undefined {
  92. if ((disabledEnv ?? '') === '' || !hasRow) return undefined
  93. return { id: TELEMETRY_ROW_ID, disabled: true }
  94. }
  95. /**
  96. * Load a resolved profile for `name` and (re)write the empty root config. The
  97. * root is always rewritten: the whole composition is patch layers, and the
  98. * vendored Loader's tree write-back (a plugin self-disposing persists the
  99. * current tree) can bake composed rows into this file — which would duplicate
  100. * every bundle insert on the next boot. The file exists on disk only because
  101. * the Loader needs a real include root to anchor `baseUrl` at the profile
  102. * directory (the config dump anchors on the same file, so both compose over
  103. * the identical base).
  104. * @param name - the profile name.
  105. * @param userLayer - `false` skips parsing `cordis.patch.yml` (the default dump).
  106. * @returns the loaded profile.
  107. */
  108. export function prepareProfile(name: string, userLayer = true): Profile {
  109. const profile = loadProfile(NAME, name, INSTALL_ANCHOR, undefined, { userLayer })
  110. writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG)
  111. return profile
  112. }
  113. /** One profile's patch layers, in application order. */
  114. interface ComposedProfile {
  115. profile: Profile
  116. /** Bundle layers concatenated — the part below the user layers on a live reload. */
  117. bundlePatches: PatchOptions[]
  118. /** The home-level user layer (`$DSH_HOME/cordis.patch.yml`), applied after the profile's own. */
  119. homePatches: PatchOptions[]
  120. /** Layers above the user layers on a live reload: `--patch` overlays and the telemetry switch. */
  121. overlays: PatchOptions[]
  122. }
  123. /** The full patch stack of one composed profile, in application order. */
  124. function allPatches(composed: ComposedProfile): PatchOptions[] {
  125. return [
  126. ...composed.bundlePatches,
  127. ...composed.profile.patches,
  128. ...composed.homePatches,
  129. ...composed.overlays,
  130. ]
  131. }
  132. /**
  133. * Load `name` and compose its effective patch stack: bundle layers in
  134. * `dsh.profile.bundles` order (a base-backed profile gets the base bundle's
  135. * platform-gated shell rows), the profile's user layer, the home-level user
  136. * layer (`$DSH_HOME/cordis.patch.yml` — machine-local preferences that apply
  137. * to every profile, so it outranks the per-profile layer), `--patch` overlays,
  138. * then the telemetry switch.
  139. * @param name - the profile name.
  140. * @param patchFiles - `--patch` overlay paths, in argv order.
  141. * @returns the profile and its patch layers.
  142. */
  143. async function composeProfile(
  144. name: string,
  145. patchFiles: readonly string[],
  146. ): Promise<ComposedProfile> {
  147. const profile = prepareProfile(name)
  148. await healProfilesModuleFallback({ installAnchor: INSTALL_ANCHOR, profile })
  149. const homePatches = loadOptionalPatches(NAME, homePatchPath()) ?? []
  150. const overlays = patchFiles.flatMap(file => loadOverlayPatches(NAME, resolve(file)))
  151. const bundlePatches = profile.layers.flatMap(layer => layer.patches)
  152. const rows = new Map<string, EntryOptions>()
  153. for (const row of composeEntries([bundlePatches, profile.patches, homePatches, overlays])) {
  154. if (typeof row.id === 'string') rows.set(row.id, row)
  155. }
  156. const composedOverlays = [...overlays]
  157. const telemetryPatch = resolveTelemetryPatch(process.env.DSH_TELEMETRY_DISABLED, rows.has(TELEMETRY_ROW_ID))
  158. if (telemetryPatch !== undefined) composedOverlays.push(telemetryPatch)
  159. return { profile, bundlePatches, homePatches, overlays: composedOverlays }
  160. }
  161. /** Options for {@link runProfile}. */
  162. export interface RunProfileOptions {
  163. /** This run's frozen environment snapshot, provided before any entry mounts. */
  164. environment: LaunchEnvironmentSnapshot
  165. /** The profile name to boot. */
  166. profile: string
  167. /** `--patch` overlay paths, in argv order. */
  168. patchFiles: readonly string[]
  169. /** The invocation's inner arguments, handed to the tree through `ctx.cmdlineArgs`. */
  170. args: readonly string[]
  171. }
  172. /**
  173. * Re-throw a watcher-setup failure unless a shutdown already owns the tree:
  174. * a signal aborted this invocation, or an app requested exit (`ctx.appExit`
  175. * from a fast one-shot) and the root's disposal rejected the in-flight setup
  176. * await. Either way the failure describes a tree that is exiting as asked,
  177. * not a broken watch.
  178. * @param ctx - the booted root context.
  179. * @param signal - this invocation's signal-shutdown fact.
  180. * @param error - the setup failure.
  181. */
  182. function suppressShutdownError(ctx: Context, signal: AbortSignal, error: unknown): void {
  183. if (signal.aborted) return
  184. if (ctx.fiber.state !== FiberState.ACTIVE || ctx.get('loader') === undefined) return
  185. throw error
  186. }
  187. /**
  188. * Boot one profile invocation end to end and leave process lifetime to the
  189. * mounted plugins (or to a one-shot runner the composition mounts).
  190. * @param options - environment snapshot, profile name, overlays, and the booted app's own arguments.
  191. * @returns the settled root context and the shutdown controller.
  192. */
  193. export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Context; shutdown: ProcessShutdown }> {
  194. const composed = await composeProfile(options.profile, options.patchFiles)
  195. const app: { current?: Context } = {}
  196. const appReady = createAppReady()
  197. const shutdown = createProcessShutdown(async () => { await app.current?.fiber.dispose() })
  198. const signalShutdown = new AbortController()
  199. const interrupt = (code: number): void => {
  200. signalShutdown.abort()
  201. shutdown.interrupt(code)
  202. }
  203. // Signals own teardown throughout the startup window, not only after boot()
  204. // settles: an inserted provider can publish before sibling rows finish mounting.
  205. // SIGTERM is a supervisor's ordinary stop request and exits 0 on every
  206. // surface — the launcher does not know whether the app considered its work
  207. // complete; SIGINT is a user interrupt and reports 130.
  208. process.on('SIGTERM', () => { interrupt(0) })
  209. process.on('SIGINT', () => { interrupt(130) })
  210. installFailLoud(NAME, process, async () => {
  211. await app.current?.fiber.dispose()
  212. })
  213. const rootConfig = join(composed.profile.dir, PROFILE_ROOT_FILENAME)
  214. // Recomposition for the live user layers: bundle layers below, overlays
  215. // above, so a user edit can never displace them. Parsed app arguments are
  216. // not in here at all — they live in app-provided services that survive a
  217. // recomposition. BOTH
  218. // user files are re-read per generation (the HMR watcher hands us only the
  219. // changed file's patches, which one of the reads duplicates — fresh reads
  220. // keep the two watchers from stitching in each other's stale copy).
  221. // Fresh clones per generation: the include pushes `insert` rows into the
  222. // mounted tree BY REFERENCE and later id-targeted patches mutate those
  223. // objects in place. Reusing one parsed patch object across applications
  224. // would bake a user override into the bundle's in-memory insert row, so
  225. // removing the override could never revert the row to the bundle default.
  226. const composeLive = (): PatchOptions[] => structuredClone([
  227. ...composed.bundlePatches,
  228. ...loadOptionalPatches(NAME, composed.profile.patchPath) ?? [],
  229. ...loadOptionalPatches(NAME, homePatchPath()) ?? [],
  230. ...composed.overlays,
  231. ])
  232. // Cloned for the same insert-aliasing reason as composeLive: the boot
  233. // application must not mutate the objects later reloads recompose from.
  234. const ctx = await boot(NAME, rootConfig, structuredClone(allPatches(composed)), (hostCtx) => {
  235. app.current = hostCtx
  236. // Before any config-tree entry mounts, so plugins resolve all launch-time
  237. // environment values from the same immutable provenance snapshot.
  238. hostCtx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, options.environment)
  239. // The command line and bounded exit request are launcher facts available
  240. // to every app plugin that injects the argument snapshot.
  241. provideCmdline(hostCtx, {
  242. args: options.args,
  243. exit: code => void shutdown.shutdown(code),
  244. ready: appReady.service,
  245. })
  246. })
  247. app.current = ctx
  248. // A live-reload profile can dispose the whole tree while post-boot watcher
  249. // setup is in flight — a signal or appExit. Loader presence and fiber state
  250. // own liveness; the initial check skips a tree that already exited, and the
  251. // catch below re-checks for an exit that landed mid-setup. Startup-frozen
  252. // profiles apply every user layer above but install no HMR fallback or watcher.
  253. if (composed.profile.patchReload === 'live'
  254. && !signalShutdown.signal.aborted
  255. && ctx.fiber.state === FiberState.ACTIVE
  256. && ctx.get('loader') !== undefined) {
  257. try {
  258. // Config-only HMR for the live profile patch layer: dsh-base disables
  259. // module reload by default, so when no profile explicitly enabled that
  260. // service, mount a watch-only instance with no module roots —
  261. // cordis.patch.yml edits stay live without replacing source modules. A
  262. // silent skip would break the documented reload contract. HMR injects
  263. // the timer service, which a bare custom profile may not mount either.
  264. if (ctx.get('hmr') === undefined) {
  265. if (ctx.get('timer') === undefined) {
  266. await ctx.loader.create({ name: '@deepseek-ai/cordis-plugin-timer' })
  267. }
  268. await ctx.loader.create({ name: '@deepseek-ai/cordis-plugin-hmr', config: { root: [] } })
  269. }
  270. await watchUserPatches(ctx, {
  271. binName: NAME,
  272. filename: composed.profile.patchPath,
  273. compose: composeLive,
  274. })
  275. await watchUserPatches(ctx, {
  276. binName: NAME,
  277. filename: homePatchPath(),
  278. compose: composeLive,
  279. })
  280. } catch (error) {
  281. suppressShutdownError(ctx, signalShutdown.signal, error)
  282. }
  283. }
  284. if (!signalShutdown.signal.aborted
  285. && ctx.fiber.state === FiberState.ACTIVE
  286. && ctx.get('loader') !== undefined) {
  287. appReady.commit()
  288. }
  289. return { ctx, shutdown }
  290. }