profile-boot.ts 18 KB

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