app-cli-entry.ts 16 KB

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