app-cli-entry.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /**
  2. * AppCLIEntry — the pre-cordis boot glue the config-tree dsh surfaces share
  3. * for the Web/headless surface.
  4. * Everything here is what must exist before the Loader runs: layered env,
  5. * the patch composition over the shipped base and surface overlay (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 { networkInterfaces } from 'node:os'
  12. import { join, resolve } from 'node:path'
  13. import { pathToFileURL } from 'node:url'
  14. import { Context } from 'cordis'
  15. import type { FiberState } from 'cordis'
  16. import Loader from '@cordisjs/plugin-loader'
  17. import Include, { type PatchOptions } from '@cordisjs/plugin-include'
  18. import yaml from 'js-yaml'
  19. import { assertEntriesLoaded, installFailLoud, loadEnv, loadOverlayPatches, loadPersonalPatches } from '@deepseek-ai/dsh-app-boot'
  20. import { resolveDshHome, resolveSessionsRoot } from '@deepseek-ai/dsh-paths'
  21. // Empty type import carries the httpServer Context merge for the port read below.
  22. import type {} from '@deepseek-ai/dsh-host-webserver'
  23. /** Profile file under the invoking directory (read-only this round; never created — see the design's profile ruling). */
  24. const PROFILE_DIR = '.dsh-tmp-profile'
  25. const PROFILE_FILE = 'config.json'
  26. /** The webserver schema's all-interfaces bind literal: gates LAN-authority derivation here and the printed LAN URL in web.ts. */
  27. const ALL_INTERFACES_HOST = '0.0.0.0'
  28. /**
  29. * Non-internal IPv4 interface addresses of this machine — the IP-literal
  30. * authorities an all-interfaces bind is reachable by on the LAN.
  31. * @returns the addresses in interface order (possibly empty).
  32. */
  33. function lanIPv4Addresses(): string[] {
  34. return Object.values(networkInterfaces()).flat()
  35. .filter((iface): iface is NonNullable<typeof iface> => iface !== undefined && iface.family === 'IPv4' && !iface.internal)
  36. .map(iface => iface.address)
  37. }
  38. /**
  39. * One LAN-trust resolution for one invocation, sampled exactly once: the
  40. * machine's LAN IP literals when the effective bind is all-interfaces, and
  41. * the `trustedHosts` value built from them plus the explicit extras. The
  42. * single sample is deliberate — display must advertise only addresses the
  43. * fence was configured with, so both read this snapshot. Derived entries are
  44. * port-less IP literals: DNS rebinding needs an attacker-controlled name, so
  45. * an IP-literal Host is safe on any port, and the bound port may be
  46. * OS-assigned, unknowable pre-boot.
  47. * @param bindHost - the effective webserver bind host (CLI flag, else the yml default).
  48. * @param extra - `--trusted-host` values, in argv order.
  49. * @returns the sampled LAN addresses and the connection row's `trustedHosts` value (each possibly empty).
  50. */
  51. export function resolveLanTrust(
  52. bindHost: string | undefined,
  53. extra: readonly string[],
  54. ): { lanAddresses: string[]; trustedHosts: string[] } {
  55. const lanAddresses = bindHost === ALL_INTERFACES_HOST ? lanIPv4Addresses() : []
  56. return { lanAddresses, trustedHosts: [...lanAddresses, ...extra] }
  57. }
  58. /** One profile-json key mapped onto a yml row's config field. */
  59. interface ProfileMapping {
  60. jsonPath: string
  61. entryId: string
  62. configKey: string
  63. }
  64. /**
  65. * The static profile→row mapping table. json is user config and wins over the
  66. * yml engineering default per field; a json key absent from this table fails
  67. * loud (a typo silently ignored would read as "setting has no effect").
  68. * Developers extend deployments by adding rows here.
  69. */
  70. const PROFILE_MAPPINGS: ProfileMapping[] = [
  71. { jsonPath: 'provider', entryId: 'api-gateway', configKey: 'provider' },
  72. { jsonPath: 'model', entryId: 'api-gateway', configKey: 'model' },
  73. { jsonPath: 'persistenceRoot', entryId: 'session-persistence-jsonl', configKey: 'root' },
  74. ]
  75. // The include's YAML dialect: `!!js` scalars become expression nodes the
  76. // Loader evaluates at entry activation. The bypass parse below must accept
  77. // them (and passing one through a patch unchanged is legal).
  78. const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
  79. kind: 'scalar',
  80. resolve: data => typeof data === 'string',
  81. construct: data => ({ __jsExpr: String(data) }),
  82. })
  83. const includeYamlSchema = yaml.JSON_SCHEMA.extend(jsExprType)
  84. /**
  85. * Value mirror of cordis's `FiberState` const enum members the sweep needs
  86. * (a const enum has no runtime object to import; same rationale as the
  87. * client-side mirror in dsh-client-web).
  88. */
  89. const FIBER_ACTIVE = 2 as FiberState.ACTIVE
  90. const FIBER_PENDING = 0 as FiberState.PENDING
  91. /** Constructor facts for one dsh invocation over the shared composition (argv already parsed by the surface bin). */
  92. export interface AppCLIEntryOptions {
  93. /** Absolute path of the shared base config the Loader includes. */
  94. configPath: string
  95. /**
  96. * Absolute path of this surface's overlay: a patch list applied over
  97. * {@link configPath} before this entry's own profile/flag patches. Its rows
  98. * are also merge inputs, so a flag override preserves the overlay's other
  99. * fields on the same row.
  100. */
  101. overlayPath: string
  102. /**
  103. * Optional explicit overlay applied after {@link overlayPath} and before
  104. * this entry's own profile/flag patches. When absent, the personal
  105. * `$DSH_HOME/config.yaml` overlay is applied instead.
  106. */
  107. extraOverlayPath?: string
  108. /** Whether to append the HMR row (the whole prod/dev difference; web surface only). */
  109. dev: boolean
  110. /** --host when explicitly passed; undefined keeps the yml engineering default. */
  111. host?: string
  112. /**
  113. * Listen port override onto the webserver row. Web passes the --port flag
  114. * value; headless passes 0 (an OS-assigned port, so parallel `dsh -p` runs
  115. * never collide — and the printed URL still opens the live session in a
  116. * browser).
  117. */
  118. port?: number
  119. /** Parent directory for name-created Workspaces; undefined uses the gateway's cwd fallback. */
  120. workspaceRoot?: string
  121. /** Extra authorities for the /api browser-trust fence (`host` or `host:port`), appended to the derived LAN IP literals. */
  122. trustedHosts?: string[]
  123. }
  124. /**
  125. * Boot driver for the config-tree dsh surfaces (web and headless share the
  126. * one composition; the surfaces differ only in constructor facts): holds only
  127. * what exists independently of (and prior to) cordis — argv facts, the
  128. * composed patch set, and finally the root ctx.
  129. */
  130. export class AppCLIEntry {
  131. /** The root context, set by {@link run}. */
  132. ctx!: Context
  133. /**
  134. * LAN IPv4 addresses sampled once at patch composition — the exact snapshot
  135. * the /api trust fence was configured with. Display reads this instead of
  136. * re-sampling, so the advertised LAN URL can never name an address the
  137. * fence rejects. Empty unless the effective bind is all-interfaces.
  138. */
  139. lanAddresses: readonly string[] = []
  140. private patches: PatchOptions[] = []
  141. constructor(private readonly options: AppCLIEntryOptions) {}
  142. /**
  143. * Run the boot chain: layered env → patch composition → Loader include
  144. * boot (dev row before await) → fail-loud triple.
  145. * @returns the settled root context and the listening port.
  146. */
  147. async run(): Promise<{ ctx: Context; port: number }> {
  148. this.loadEnvLayers()
  149. this.composePatches()
  150. await this.bootTree()
  151. this.assertBoot()
  152. const port = this.ctx.get('httpServer')?.port
  153. /* v8 ignore next -- the sweep above guarantees an ACTIVE webserver row */
  154. if (port === undefined) throw new Error('dsh: httpServer service missing after settled boot')
  155. return { ctx: this.ctx, port }
  156. }
  157. /** Layered .env: ambient > cwd (bin already loaded) > $DSH_HOME (loadEnvFile never overrides). */
  158. private loadEnvLayers(): void {
  159. loadEnv('dsh', resolveDshHome())
  160. }
  161. /**
  162. * Compose the patch set from the non-yml config sources: computed
  163. * engineering defaults (the global session root), profile json (user
  164. * config, overriding those defaults), CLI flags, and the resolved frontend
  165. * dist. Patches replace a row's config wholesale, so each patched row's yml
  166. * static values are re-read here (bypass parse) and merged under the overrides.
  167. */
  168. private composePatches(): void {
  169. const rows = this.parseYmlRows()
  170. const overrides = new Map<string, Record<string, unknown>>()
  171. const put = (entryId: string, key: string, value: unknown): void => {
  172. const bag = overrides.get(entryId) ?? {}
  173. bag[key] = value
  174. overrides.set(entryId, bag)
  175. }
  176. // Source 0: computed engineering defaults. The session store is the one
  177. // shared root every dsh surface resolves, so history follows the user across
  178. // working directories instead of splitting per project. The profile
  179. // (Source 1) overwrites this same field via last-write-wins in put().
  180. put('session-persistence-jsonl', 'root', resolveSessionsRoot())
  181. // Source 1: profile json (missing file = empty; unmapped key = loud).
  182. for (const [key, value] of Object.entries(this.readProfile())) {
  183. const mapping = PROFILE_MAPPINGS.find(m => m.jsonPath === key)
  184. if (mapping === undefined) {
  185. throw new Error(`dsh: profile key "${key}" has no mapping (known: ${PROFILE_MAPPINGS.map(m => m.jsonPath).join(', ')})`)
  186. }
  187. put(mapping.entryId, mapping.configKey, value)
  188. }
  189. // Source 2: CLI flags (field set disjoint from the json mappings).
  190. if (this.options.host !== undefined) put('webserver', 'host', this.options.host)
  191. if (this.options.port !== undefined) put('webserver', 'port', this.options.port)
  192. if (this.options.workspaceRoot !== undefined) put('api-gateway', 'workspaceRoot', this.options.workspaceRoot)
  193. // Source 2b: authorities for the /api browser-trust fence (rationale on
  194. // resolveLanTrust).
  195. const ymlHost = (rows.get('webserver')?.config as { host?: string } | undefined)?.host
  196. const { lanAddresses, trustedHosts } = resolveLanTrust(this.options.host ?? ymlHost, this.options.trustedHosts ?? [])
  197. this.lanAddresses = lanAddresses
  198. if (trustedHosts.length > 0) put('connection', 'trustedHosts', trustedHosts)
  199. // Source 3: the frontend dist — an assembly fact of this app, never yml
  200. // user config. Workspace knowledge stays here.
  201. put('webserver', 'distIndex', this.resolveDistIndex())
  202. this.patches = [...overrides.entries()].map(([id, bag]) => {
  203. const yml = rows.get(id)
  204. if (yml === undefined) throw new Error(`dsh: patch target row "${id}" not found in ${this.options.configPath}`)
  205. return { id, config: { ...(yml.config ?? {}) as Record<string, unknown>, ...bag } }
  206. })
  207. }
  208. /** Loader include boot; the dev HMR row mounts before await so the fail-loud triple covers it. */
  209. private async bootTree(): Promise<void> {
  210. const ctx = new Context()
  211. ctx.baseUrl = pathToFileURL(join(resolve(this.options.configPath), '..')).href + '/'
  212. await ctx.plugin(Loader)
  213. ctx.loader.builtins.include = Include
  214. // One include of the shared base with every overlay as a sibling patch
  215. // list: patches never cross an include boundary, so nesting them would
  216. // silently stop reaching base rows. The surface overlay applies first, then
  217. // this entry's profile-json and CLI-flag patches, which therefore win.
  218. const patches = [
  219. ...loadOverlayPatches('dsh', this.options.overlayPath),
  220. ...this.options.extraOverlayPath === undefined
  221. ? loadPersonalPatches('dsh') ?? []
  222. : loadOverlayPatches('dsh', this.options.extraOverlayPath),
  223. ...this.patches,
  224. ]
  225. await ctx.loader.create({
  226. name: 'cordis:include',
  227. config: {
  228. path: pathToFileURL(resolve(this.options.configPath)).href,
  229. ...patches.length > 0 ? { patches } : {},
  230. },
  231. })
  232. if (this.options.dev) {
  233. await ctx.loader.create({ name: '@deepseek-ai/dsh-client-hmr' })
  234. }
  235. this.ctx = ctx
  236. await ctx.loader.await()
  237. }
  238. /**
  239. * Fail-loud triple: assertEntriesLoaded catches import failures,
  240. * installFailLoud catches late apply rejections, and the all-ACTIVE sweep
  241. * below catches PENDING fibers (cordis inject waiting has no timeout).
  242. */
  243. private assertBoot(): void {
  244. installFailLoud('dsh')
  245. assertEntriesLoaded(this.ctx, 'dsh')
  246. const failures: string[] = []
  247. for (const entry of this.ctx.loader.entries()) {
  248. if (entry.fiber === undefined || entry.disabled) continue
  249. const state = entry.fiber.state
  250. if (state === FIBER_ACTIVE) continue
  251. if (state === FIBER_PENDING) {
  252. const missing = Object.keys(entry.fiber.inject).filter(service => this.ctx.get(service) === undefined)
  253. failures.push(`${entry.options.name}: pending (waiting for service${missing.length === 1 ? '' : 's'}: ${missing.join(', ') || 'unknown'})`)
  254. } else {
  255. failures.push(`${entry.options.name}: fiber state ${String(state)}`)
  256. }
  257. }
  258. if (failures.length > 0) {
  259. throw new Error(`dsh: ${String(failures.length)} entr${failures.length === 1 ? 'y' : 'ies'} did not activate\n${failures.join('\n')}`)
  260. }
  261. }
  262. /**
  263. * Bypass parse of the base and this surface's overlay (id → row) for
  264. * patch-merge inputs; the Loader still reads both files itself. The overlay
  265. * wins per row, matching the order its patches are applied in, and its
  266. * `insert` rows are indexed too because a flag may target one of them.
  267. */
  268. private parseYmlRows(): Map<string, { config?: unknown }> {
  269. const rows = new Map<string, { config?: unknown }>()
  270. const files = [this.options.configPath, this.options.overlayPath]
  271. if (this.options.extraOverlayPath !== undefined) files.push(this.options.extraOverlayPath)
  272. for (const file of files) {
  273. for (const row of this.parseRowList(file)) {
  274. if (typeof row.id === 'string') rows.set(row.id, row)
  275. for (const inserted of row.insert ?? []) {
  276. if (typeof inserted.id === 'string') rows.set(inserted.id, inserted)
  277. }
  278. }
  279. }
  280. return rows
  281. }
  282. /**
  283. * Parse one entry or patch list, rejecting anything that is not a top-level
  284. * array so a malformed file fails here rather than at row lookup.
  285. * @param file - absolute path of the config or overlay file.
  286. * @returns the parsed top-level entries.
  287. */
  288. private parseRowList(file: string): { id?: string; config?: unknown; insert?: { id?: string; config?: unknown }[] }[] {
  289. const doc = yaml.load(readFileSync(file, 'utf8'), { schema: includeYamlSchema })
  290. if (!Array.isArray(doc)) throw new Error(`dsh: ${file} is not a top-level entry list`)
  291. return doc as { id?: string; config?: unknown; insert?: { id?: string; config?: unknown }[] }[]
  292. }
  293. /** Profile json under cwd; read-only — never created here, absent = no user config. */
  294. private readProfile(): Record<string, unknown> {
  295. let raw: string
  296. try {
  297. raw = readFileSync(join(process.cwd(), PROFILE_DIR, PROFILE_FILE), 'utf8')
  298. } catch (error) {
  299. if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}
  300. throw error
  301. }
  302. const parsed: unknown = JSON.parse(raw)
  303. if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
  304. throw new Error(`dsh: ${PROFILE_DIR}/${PROFILE_FILE} must hold a JSON object`)
  305. }
  306. return parsed as Record<string, unknown>
  307. }
  308. /** Dist location is workspace knowledge of this app: resolved through the frontend package exports, not configured. */
  309. private resolveDistIndex(): string {
  310. const require = createRequire(import.meta.url)
  311. try {
  312. return require.resolve('@deepseek-ai/dsh-frontend/dist/index.html')
  313. } catch {
  314. throw new Error('dsh: frontend dist not built; run pnpm --filter @deepseek-ai/dsh-frontend build first')
  315. }
  316. }
  317. }