app-cli-entry.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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 { 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 } from '@deepseek-ai/dsh-app-boot'
  20. import { resolveDshHome } 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 shipped cordis.yml. */
  94. configPath: string
  95. /** Whether to append the HMR row (the whole prod/dev difference; web surface only). */
  96. dev: boolean
  97. /** --host when explicitly passed; undefined keeps the yml engineering default. */
  98. host?: string
  99. /**
  100. * Listen port override onto the webserver row. Web passes the --port flag
  101. * value; headless passes 0 (an OS-assigned port, so parallel `dsh -p` runs
  102. * never collide — and the printed URL still opens the live session in a
  103. * browser).
  104. */
  105. port?: number
  106. /** Parent directory for name-created Workspaces; undefined uses the gateway's cwd fallback. */
  107. workspaceRoot?: string
  108. /** Extra authorities for the /api browser-trust fence (`host` or `host:port`), appended to the derived LAN IP literals. */
  109. trustedHosts?: string[]
  110. }
  111. /**
  112. * Boot driver for the config-tree dsh surfaces (web and headless share the
  113. * one composition; the surfaces differ only in constructor facts): holds only
  114. * what exists independently of (and prior to) cordis — argv facts, the
  115. * composed patch set, and finally the root ctx.
  116. */
  117. export class AppCLIEntry {
  118. /** The root context, set by {@link run}. */
  119. ctx!: Context
  120. /**
  121. * LAN IPv4 addresses sampled once at patch composition — the exact snapshot
  122. * the /api trust fence was configured with. Display reads this instead of
  123. * re-sampling, so the advertised LAN URL can never name an address the
  124. * fence rejects. Empty unless the effective bind is all-interfaces.
  125. */
  126. lanAddresses: readonly string[] = []
  127. private patches: PatchOptions[] = []
  128. constructor(private readonly options: AppCLIEntryOptions) {}
  129. /**
  130. * Run the boot chain: layered env → patch composition → Loader include
  131. * boot (dev row before await) → fail-loud triple.
  132. * @returns the settled root context and the listening port.
  133. */
  134. async run(): Promise<{ ctx: Context; port: number }> {
  135. this.loadEnvLayers()
  136. this.composePatches()
  137. await this.bootTree()
  138. this.assertBoot()
  139. const port = this.ctx.get('httpServer')?.port
  140. /* v8 ignore next -- the sweep above guarantees an ACTIVE webserver row */
  141. if (port === undefined) throw new Error('dsh: httpServer service missing after settled boot')
  142. return { ctx: this.ctx, port }
  143. }
  144. /** Layered .env: ambient > cwd (bin already loaded) > $DSH_HOME (loadEnvFile never overrides). */
  145. private loadEnvLayers(): void {
  146. loadEnv('dsh', resolveDshHome())
  147. }
  148. /**
  149. * Compose the patch set from the non-yml config sources: computed
  150. * engineering defaults (the global session root), profile json (user
  151. * config, overriding those defaults), CLI flags, and the resolved frontend
  152. * dist. Patches replace a row's config wholesale, so each patched row's yml
  153. * static values are re-read here (bypass parse) and merged under the overrides.
  154. */
  155. private composePatches(): void {
  156. const rows = this.parseYmlRows()
  157. const overrides = new Map<string, Record<string, unknown>>()
  158. const put = (entryId: string, key: string, value: unknown): void => {
  159. const bag = overrides.get(entryId) ?? {}
  160. bag[key] = value
  161. overrides.set(entryId, bag)
  162. }
  163. // Source 0: computed engineering defaults. The session store defaults to
  164. // a global dir under the Harness home ($DSH_HOME, else ~/.dsh) so history
  165. // is shared across every cwd, not a project-local ./.sessions. The profile
  166. // (Source 1) overwrites this same field via last-write-wins in put().
  167. put('session-persistence-jsonl', 'root', join(resolveDshHome(), 'sessions'))
  168. // Source 1: profile json (missing file = empty; unmapped key = loud).
  169. for (const [key, value] of Object.entries(this.readProfile())) {
  170. const mapping = PROFILE_MAPPINGS.find(m => m.jsonPath === key)
  171. if (mapping === undefined) {
  172. throw new Error(`dsh: profile key "${key}" has no mapping (known: ${PROFILE_MAPPINGS.map(m => m.jsonPath).join(', ')})`)
  173. }
  174. put(mapping.entryId, mapping.configKey, value)
  175. }
  176. // Source 2: CLI flags (field set disjoint from the json mappings).
  177. if (this.options.host !== undefined) put('webserver', 'host', this.options.host)
  178. if (this.options.port !== undefined) put('webserver', 'port', this.options.port)
  179. if (this.options.workspaceRoot !== undefined) put('api-gateway', 'workspaceRoot', this.options.workspaceRoot)
  180. // Source 2b: authorities for the /api browser-trust fence (rationale on
  181. // resolveLanTrust).
  182. const ymlHost = (rows.get('webserver')?.config as { host?: string } | undefined)?.host
  183. const { lanAddresses, trustedHosts } = resolveLanTrust(this.options.host ?? ymlHost, this.options.trustedHosts ?? [])
  184. this.lanAddresses = lanAddresses
  185. if (trustedHosts.length > 0) put('connection', 'trustedHosts', trustedHosts)
  186. // Source 3: the frontend dist — an assembly fact of this app, never yml
  187. // user config. Workspace knowledge stays here.
  188. put('webserver', 'distIndex', this.resolveDistIndex())
  189. this.patches = [...overrides.entries()].map(([id, bag]) => {
  190. const yml = rows.get(id)
  191. if (yml === undefined) throw new Error(`dsh: patch target row "${id}" not found in ${this.options.configPath}`)
  192. return { id, config: { ...(yml.config ?? {}) as Record<string, unknown>, ...bag } }
  193. })
  194. }
  195. /** Loader include boot; the dev HMR row mounts before await so the fail-loud triple covers it. */
  196. private async bootTree(): Promise<void> {
  197. const ctx = new Context()
  198. ctx.baseUrl = pathToFileURL(join(resolve(this.options.configPath), '..')).href + '/'
  199. await ctx.plugin(Loader)
  200. ctx.loader.builtins.include = Include
  201. await ctx.loader.create({
  202. name: 'cordis:include',
  203. config: {
  204. path: pathToFileURL(resolve(this.options.configPath)).href,
  205. ...this.patches.length > 0 ? { patches: this.patches } : {},
  206. },
  207. })
  208. if (this.options.dev) {
  209. await ctx.loader.create({ name: '@deepseek-ai/dsh-client-hmr' })
  210. }
  211. this.ctx = ctx
  212. await ctx.loader.await()
  213. }
  214. /**
  215. * Fail-loud triple: assertEntriesLoaded catches import failures,
  216. * installFailLoud catches late apply rejections, and the all-ACTIVE sweep
  217. * below catches PENDING fibers (cordis inject waiting has no timeout).
  218. */
  219. private assertBoot(): void {
  220. installFailLoud('dsh')
  221. assertEntriesLoaded(this.ctx, 'dsh')
  222. const failures: string[] = []
  223. for (const entry of this.ctx.loader.entries()) {
  224. if (entry.fiber === undefined || entry.disabled) continue
  225. const state = entry.fiber.state
  226. if (state === FIBER_ACTIVE) continue
  227. if (state === FIBER_PENDING) {
  228. const missing = Object.keys(entry.fiber.inject).filter(service => this.ctx.get(service) === undefined)
  229. failures.push(`${entry.options.name}: pending (waiting for service${missing.length === 1 ? '' : 's'}: ${missing.join(', ') || 'unknown'})`)
  230. } else {
  231. failures.push(`${entry.options.name}: fiber state ${String(state)}`)
  232. }
  233. }
  234. if (failures.length > 0) {
  235. throw new Error(`dsh: ${String(failures.length)} entr${failures.length === 1 ? 'y' : 'ies'} did not activate\n${failures.join('\n')}`)
  236. }
  237. }
  238. /** Bypass parse of the shipped yml (id → row) for patch-merge inputs; Loader still reads the file itself. */
  239. private parseYmlRows(): Map<string, { config?: unknown }> {
  240. const doc = yaml.load(readFileSync(this.options.configPath, 'utf8'), { schema: includeYamlSchema })
  241. if (!Array.isArray(doc)) throw new Error(`dsh: ${this.options.configPath} is not a top-level entry list`)
  242. const rows = new Map<string, { config?: unknown }>()
  243. for (const row of doc as { id?: string; config?: unknown }[]) {
  244. if (typeof row.id === 'string') rows.set(row.id, row)
  245. }
  246. return rows
  247. }
  248. /** Profile json under cwd; read-only — never created here, absent = no user config. */
  249. private readProfile(): Record<string, unknown> {
  250. let raw: string
  251. try {
  252. raw = readFileSync(join(process.cwd(), PROFILE_DIR, PROFILE_FILE), 'utf8')
  253. } catch (error) {
  254. if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}
  255. throw error
  256. }
  257. const parsed: unknown = JSON.parse(raw)
  258. if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
  259. throw new Error(`dsh: ${PROFILE_DIR}/${PROFILE_FILE} must hold a JSON object`)
  260. }
  261. return parsed as Record<string, unknown>
  262. }
  263. /** Dist location is workspace knowledge of this app: resolved through the frontend package exports, not configured. */
  264. private resolveDistIndex(): string {
  265. const require = createRequire(import.meta.url)
  266. try {
  267. return require.resolve('@deepseek-ai/dsh-frontend/dist/index.html')
  268. } catch {
  269. throw new Error('dsh: frontend dist not built; run pnpm --filter @deepseek-ai/dsh-frontend build first')
  270. }
  271. }
  272. }