app-cli-entry.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. /**
  2. * AppCLIEntry — the pre-cordis boot glue the config-tree dsh surfaces share
  3. * (`dsh web` and `dsh -p` boot the one composition; TUI migrates later).
  4. * Everything here is what must exist before the Loader runs: layered env,
  5. * the patch composition over the shipped cordis.yml (profile json + CLI
  6. * flags + the resolved frontend dist), and the fail-loud triple after the
  7. * tree settles.
  8. */
  9. import { readFileSync } from 'node:fs'
  10. import { createRequire } from 'node:module'
  11. import { join, resolve } from 'node:path'
  12. import { pathToFileURL } from 'node:url'
  13. import { Context } from 'cordis'
  14. import type { FiberState } from 'cordis'
  15. import Loader from '@cordisjs/plugin-loader'
  16. import Include, { type PatchOptions } from '@cordisjs/plugin-include'
  17. import yaml from 'js-yaml'
  18. import { assertEntriesLoaded, installFailLoud, loadEnv } from '@deepseek-ai/dsh-app-boot'
  19. import { resolveDshHome } from '@deepseek-ai/dsh-paths'
  20. // Empty type import carries the httpServer Context merge for the port read below.
  21. import type {} from '@deepseek-ai/dsh-host-webserver'
  22. /** Profile file under the invoking directory (read-only this round; never created — see the design's profile ruling). */
  23. const PROFILE_DIR = '.dsh-tmp-profile'
  24. const PROFILE_FILE = 'config.json'
  25. /** One profile-json key mapped onto a yml row's config field. */
  26. interface ProfileMapping {
  27. jsonPath: string
  28. entryId: string
  29. configKey: string
  30. }
  31. /**
  32. * The static profile→row mapping table. json is user config and wins over the
  33. * yml engineering default per field; a json key absent from this table fails
  34. * loud (a typo silently ignored would read as "setting has no effect").
  35. * Developers extend deployments by adding rows here.
  36. */
  37. const PROFILE_MAPPINGS: ProfileMapping[] = [
  38. { jsonPath: 'provider', entryId: 'api-gateway', configKey: 'provider' },
  39. { jsonPath: 'model', entryId: 'api-gateway', configKey: 'model' },
  40. { jsonPath: 'persistenceRoot', entryId: 'session-persistence-jsonl', configKey: 'root' },
  41. ]
  42. // The include's YAML dialect: `!!js` scalars become expression nodes the
  43. // Loader evaluates at entry activation. The bypass parse below must accept
  44. // them (and passing one through a patch unchanged is legal).
  45. const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
  46. kind: 'scalar',
  47. resolve: data => typeof data === 'string',
  48. construct: data => ({ __jsExpr: String(data) }),
  49. })
  50. const includeYamlSchema = yaml.JSON_SCHEMA.extend(jsExprType)
  51. /**
  52. * Value mirror of cordis's `FiberState` const enum members the sweep needs
  53. * (a const enum has no runtime object to import; same rationale as the
  54. * client-side mirror in dsh-client-web).
  55. */
  56. const FIBER_ACTIVE = 2 as FiberState.ACTIVE
  57. const FIBER_PENDING = 0 as FiberState.PENDING
  58. /** Constructor facts for one dsh invocation over the shared composition (argv already parsed by the surface bin). */
  59. export interface AppCLIEntryOptions {
  60. /** Absolute path of the shipped cordis.yml. */
  61. configPath: string
  62. /** Whether to append the HMR row (the whole prod/dev difference; web surface only). */
  63. dev: boolean
  64. /** --host when explicitly passed; undefined keeps the yml engineering default. */
  65. host?: string
  66. /**
  67. * Listen port override onto the webserver row. Web passes the --port flag
  68. * value; headless passes 0 (an OS-assigned port, so parallel `dsh -p` runs
  69. * never collide — and the printed URL still opens the live session in a
  70. * browser).
  71. */
  72. port?: number
  73. /** Parent directory for name-created Workspaces; undefined uses the gateway's cwd fallback. */
  74. workspaceRoot?: string
  75. }
  76. /**
  77. * Boot driver for the config-tree dsh surfaces (web and headless share the
  78. * one composition; the surfaces differ only in constructor facts): holds only
  79. * what exists independently of (and prior to) cordis — argv facts, the
  80. * composed patch set, and finally the root ctx.
  81. */
  82. export class AppCLIEntry {
  83. /** The root context, set by {@link run}. */
  84. ctx!: Context
  85. private patches: PatchOptions[] = []
  86. constructor(private readonly options: AppCLIEntryOptions) {}
  87. /**
  88. * Run the boot chain: layered env → patch composition → Loader include
  89. * boot (dev row before await) → fail-loud triple.
  90. * @returns the settled root context and the listening port.
  91. */
  92. async run(): Promise<{ ctx: Context; port: number }> {
  93. this.loadEnvLayers()
  94. this.composePatches()
  95. await this.bootTree()
  96. this.assertBoot()
  97. const port = this.ctx.get('httpServer')?.port
  98. /* v8 ignore next -- the sweep above guarantees an ACTIVE webserver row */
  99. if (port === undefined) throw new Error('dsh: httpServer service missing after settled boot')
  100. return { ctx: this.ctx, port }
  101. }
  102. /** Layered .env: ambient > cwd (bin already loaded) > $DSH_HOME (loadEnvFile never overrides). */
  103. private loadEnvLayers(): void {
  104. loadEnv('dsh', resolveDshHome())
  105. }
  106. /**
  107. * Compose the patch set from the three non-yml config sources: profile
  108. * json (user config), CLI flags, and the resolved frontend dist. Patches
  109. * replace a row's config wholesale, so each patched row's yml static
  110. * values are re-read here (bypass parse) and merged under the overrides.
  111. */
  112. private composePatches(): void {
  113. const rows = this.parseYmlRows()
  114. const overrides = new Map<string, Record<string, unknown>>()
  115. const put = (entryId: string, key: string, value: unknown): void => {
  116. const bag = overrides.get(entryId) ?? {}
  117. bag[key] = value
  118. overrides.set(entryId, bag)
  119. }
  120. // Source 1: profile json (missing file = empty; unmapped key = loud).
  121. for (const [key, value] of Object.entries(this.readProfile())) {
  122. const mapping = PROFILE_MAPPINGS.find(m => m.jsonPath === key)
  123. if (mapping === undefined) {
  124. throw new Error(`dsh: profile key "${key}" has no mapping (known: ${PROFILE_MAPPINGS.map(m => m.jsonPath).join(', ')})`)
  125. }
  126. put(mapping.entryId, mapping.configKey, value)
  127. }
  128. // Source 2: CLI flags (field set disjoint from the json mappings).
  129. if (this.options.host !== undefined) put('webserver', 'host', this.options.host)
  130. if (this.options.port !== undefined) put('webserver', 'port', this.options.port)
  131. if (this.options.workspaceRoot !== undefined) put('api-gateway', 'workspaceRoot', this.options.workspaceRoot)
  132. // Source 3: the frontend dist — an assembly fact of this app, never yml
  133. // user config. Workspace knowledge stays here.
  134. put('webserver', 'distIndex', this.resolveDistIndex())
  135. this.patches = [...overrides.entries()].map(([id, bag]) => {
  136. const yml = rows.get(id)
  137. if (yml === undefined) throw new Error(`dsh: patch target row "${id}" not found in ${this.options.configPath}`)
  138. return { id, config: { ...(yml.config ?? {}) as Record<string, unknown>, ...bag } }
  139. })
  140. }
  141. /** Loader include boot; the dev HMR row mounts before await so the fail-loud triple covers it. */
  142. private async bootTree(): Promise<void> {
  143. const ctx = new Context()
  144. ctx.baseUrl = pathToFileURL(join(resolve(this.options.configPath), '..')).href + '/'
  145. await ctx.plugin(Loader)
  146. ctx.loader.builtins.include = Include
  147. await ctx.loader.create({
  148. name: 'cordis:include',
  149. config: {
  150. path: pathToFileURL(resolve(this.options.configPath)).href,
  151. ...this.patches.length > 0 ? { patches: this.patches } : {},
  152. },
  153. })
  154. if (this.options.dev) {
  155. await ctx.loader.create({ name: '@deepseek-ai/dsh-client-hmr' })
  156. }
  157. this.ctx = ctx
  158. await ctx.loader.await()
  159. }
  160. /**
  161. * Fail-loud triple: assertEntriesLoaded catches import failures,
  162. * installFailLoud catches late apply rejections, and the all-ACTIVE sweep
  163. * below catches PENDING fibers (cordis inject waiting has no timeout).
  164. */
  165. private assertBoot(): void {
  166. installFailLoud('dsh')
  167. assertEntriesLoaded(this.ctx, 'dsh')
  168. const failures: string[] = []
  169. for (const entry of this.ctx.loader.entries()) {
  170. if (entry.fiber === undefined || entry.disabled) continue
  171. const state = entry.fiber.state
  172. if (state === FIBER_ACTIVE) continue
  173. if (state === FIBER_PENDING) {
  174. const missing = Object.keys(entry.fiber.inject).filter(service => this.ctx.get(service) === undefined)
  175. failures.push(`${entry.options.name}: pending (waiting for service${missing.length === 1 ? '' : 's'}: ${missing.join(', ') || 'unknown'})`)
  176. } else {
  177. failures.push(`${entry.options.name}: fiber state ${String(state)}`)
  178. }
  179. }
  180. if (failures.length > 0) {
  181. throw new Error(`dsh: ${String(failures.length)} entr${failures.length === 1 ? 'y' : 'ies'} did not activate\n${failures.join('\n')}`)
  182. }
  183. }
  184. /** Bypass parse of the shipped yml (id → row) for patch-merge inputs; Loader still reads the file itself. */
  185. private parseYmlRows(): Map<string, { config?: unknown }> {
  186. const doc = yaml.load(readFileSync(this.options.configPath, 'utf8'), { schema: includeYamlSchema })
  187. if (!Array.isArray(doc)) throw new Error(`dsh: ${this.options.configPath} is not a top-level entry list`)
  188. const rows = new Map<string, { config?: unknown }>()
  189. for (const row of doc as { id?: string; config?: unknown }[]) {
  190. if (typeof row.id === 'string') rows.set(row.id, row)
  191. }
  192. return rows
  193. }
  194. /** Profile json under cwd; read-only — never created here, absent = no user config. */
  195. private readProfile(): Record<string, unknown> {
  196. let raw: string
  197. try {
  198. raw = readFileSync(join(process.cwd(), PROFILE_DIR, PROFILE_FILE), 'utf8')
  199. } catch (error) {
  200. if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}
  201. throw error
  202. }
  203. const parsed: unknown = JSON.parse(raw)
  204. if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
  205. throw new Error(`dsh: ${PROFILE_DIR}/${PROFILE_FILE} must hold a JSON object`)
  206. }
  207. return parsed as Record<string, unknown>
  208. }
  209. /** Dist location is workspace knowledge of this app: resolved through the frontend package exports, not configured. */
  210. private resolveDistIndex(): string {
  211. const require = createRequire(import.meta.url)
  212. try {
  213. return require.resolve('@deepseek-ai/dsh-frontend/dist/index.html')
  214. } catch {
  215. throw new Error('dsh: frontend dist not built; run pnpm --filter @deepseek-ai/dsh-frontend build first')
  216. }
  217. }
  218. }