profile-boot.ts 14 KB

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