profile-boot.ts 17 KB

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