web.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. /**
  2. * `dsh web` — thin bin over the config-tree boot: run AppCLIEntry with the
  3. * already-parsed host/port/dev, print the URL line, wire signals. All
  4. * composition lives in the shared base plus Web overlay; all boot glue lives in AppCLIEntry. Host and
  5. * port are unvalidated pass-through overrides — the `dsh-host-webserver` schema
  6. * gates them at boot.
  7. */
  8. import { fileURLToPath } from 'node:url'
  9. import type { Context } from 'cordis'
  10. import { addHarnessSourceSection, resolveConfigPath } from '@deepseek-ai/dsh-app-boot'
  11. import type {} from '@deepseek-ai/dsh-host-webserver'
  12. import type {} from '@deepseek-ai/dsh-system-prompt'
  13. import type {} from '@deepseek-ai/dsh-tool-bash'
  14. import { AppCLIEntry } from './app-cli-entry.ts'
  15. // The shared core every `dsh` surface mounts, plus this surface's overlay over it.
  16. const BASE_CONFIG = fileURLToPath(new URL('../config/base.cordis.yml', import.meta.url))
  17. const WEB_OVERLAY = fileURLToPath(new URL('../config/web.cordis.yml', import.meta.url))
  18. const SOURCE_ROOT = fileURLToPath(new URL('../../..', import.meta.url))
  19. const DSH_WEB_URL = 'DSH_WEB_URL' as const
  20. const DSH_WEB_MODE = 'DSH_WEB_MODE' as const
  21. type WebMode = 'production' | 'development'
  22. // Display-only mirror of the webserver schema's loopback host: the address the
  23. // local URL always prints. Not a source of truth — the schema is.
  24. const LOOPBACK_HOST = '127.0.0.1'
  25. /** Model-visible orientation and acceptance boundary for sessions created through `dsh web`. */
  26. function webSurfacePrompt(webUrl: string, mode: WebMode): string {
  27. const updateContract = mode === 'development'
  28. ? 'This Web process was launched with `dsh web --dev`, so its client-plugin HMR receiver is active. '
  29. + 'No-refresh updates occur only when `pnpm run dev:web` is also running from this same checkout to rebuild client-plugin bundles; verify that watcher before promising automatic updates. '
  30. + 'Client-plugin changes then reload automatically, while apps/web shell and other plain-package changes still require a rebuild and page refresh. '
  31. : 'This Web process was launched without `--dev`, so HMR is inactive: rebuild the affected Web artifacts and verify this existing URL after a page refresh. '
  32. + 'If the user wants no-refresh client-plugin updates, explain that this GUI must be restarted with `dsh web --dev` and `pnpm run dev:web` must also run from this same checkout; do not present either command alone as sufficient. '
  33. return `You are interacting with the user through the DeepSeek Harness Web GUI at ${webUrl}. `
  34. + 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. '
  35. + 'The browser provides no implicit DOM, route, or screenshot context. '
  36. + updateContract
  37. + 'Starting another server does not update this GUI. '
  38. + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. '
  39. + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background task and verify its exact URL.'
  40. }
  41. /** Resolve the canonical loopback URL from the active Web server. */
  42. function localWebUrl(ctx: Context): string {
  43. const port = ctx.get('httpServer')?.port
  44. if (port === undefined) throw new Error('dsh web: httpServer service missing while resolving Web runtime')
  45. return `http://${LOOPBACK_HOST}:${String(port)}`
  46. }
  47. /**
  48. * Register the launcher-owned prompt and shell runtime context before the
  49. * shared config tree mounts. The earlier injections install the prompt
  50. * sections and managed Bash contributor when their owning services activate;
  51. * dynamic values read the bound server only when consumed.
  52. * @param ctx - Web root context with Loader installed but no config tree mounted.
  53. * @param sourceRoot - absolute checkout root resolved from the launcher module.
  54. * @param mode - whether this process mounted the client-plugin HMR receiver.
  55. */
  56. export function prepareWebRuntimeContext(ctx: Context, sourceRoot: string, mode: WebMode): void {
  57. ctx.inject(['systemPrompt'], (promptCtx) => {
  58. addHarnessSourceSection(promptCtx, sourceRoot)
  59. promptCtx.systemPrompt.section({
  60. name: 'app:web-surface',
  61. order: -98,
  62. text: () => webSurfacePrompt(localWebUrl(promptCtx), mode),
  63. })
  64. })
  65. ctx.inject(['bashEnv'], (runtimeCtx) => {
  66. runtimeCtx.bashEnv.register({
  67. name: 'web-runtime',
  68. variables: {
  69. [DSH_WEB_URL]: { description: 'Canonical local URL of the DeepSeek Harness Web GUI serving this session.' },
  70. [DSH_WEB_MODE]: { description: 'Web runtime mode: production, or development when the client-plugin HMR receiver is active.' },
  71. },
  72. resolve: () => ({ [DSH_WEB_URL]: localWebUrl(runtimeCtx), [DSH_WEB_MODE]: mode }),
  73. })
  74. })
  75. }
  76. /**
  77. * Fail a settled Web boot whose composition omitted the managed Bash environment registry.
  78. * @param ctx - settled Web application context.
  79. */
  80. export function assertWebRuntimeContext(ctx: Context): void {
  81. if (ctx.get('bashEnv') === undefined) throw new Error('dsh web: bashEnv service missing after settled boot')
  82. }
  83. /**
  84. * Serve the browser UI from the shipped config tree. `host`/`port` are passed
  85. * through only when the flag was given; absent, the shipped Web overlay value stands.
  86. * @param host - the bind host, or `undefined` to keep the config default.
  87. * @param port - the listen port (`0` requests an OS-assigned port), or `undefined` to keep the config default.
  88. * @param dev - mount the client HMR receiver; `pnpm run dev:web` separately rebuilds watched plugin bundles.
  89. * @param workspaceRoot - parent directory for name-created workspaces, or `undefined` for the gateway's cwd fallback.
  90. * @param trustedHosts - extra authorities for the /api browser-trust fence, or `undefined` for the derived LAN literals alone.
  91. * @param config - an overlay of loader patches applied over the shipped web
  92. * composition instead of `$DSH_HOME/config.yaml`, or `undefined` to use the
  93. * personal overlay; already parsed from `--config`.
  94. */
  95. export async function runWeb(
  96. host: string | undefined,
  97. port: number | undefined,
  98. dev: boolean,
  99. workspaceRoot: string | undefined,
  100. trustedHosts: string[] | undefined,
  101. config?: string,
  102. ): Promise<void> {
  103. const mode: WebMode = dev ? 'development' : 'production'
  104. const entry = new AppCLIEntry({
  105. configPath: BASE_CONFIG,
  106. overlayPath: WEB_OVERLAY,
  107. ...config !== undefined && { extraOverlayPath: resolveConfigPath(config, undefined) },
  108. dev,
  109. prepare: (ctx) => { prepareWebRuntimeContext(ctx, SOURCE_ROOT, mode) },
  110. ...host !== undefined && { host },
  111. ...port !== undefined && { port },
  112. ...workspaceRoot !== undefined && { workspaceRoot },
  113. ...trustedHosts !== undefined && { trustedHosts },
  114. })
  115. const { ctx, port: boundPort } = await entry.run()
  116. assertWebRuntimeContext(ctx)
  117. const resolvedLocalWebUrl = localWebUrl(ctx)
  118. let exiting = false
  119. const shutdown = (code: number): void => {
  120. if (exiting) return
  121. exiting = true
  122. void Promise.resolve(ctx.fiber.dispose()).finally(() => { process.exit(code) })
  123. }
  124. // Install shutdown handling before publishing readiness: supervisors may
  125. // send a signal as soon as they observe the URL line.
  126. process.on('SIGTERM', () => { shutdown(0) })
  127. process.on('SIGINT', () => { shutdown(130) })
  128. // The entry's boot-time snapshot, not a fresh sample: the printed LAN URL
  129. // must name an address the /api trust fence was configured with.
  130. const lanCandidate = entry.lanAddresses[0]
  131. console.log(`dsh web: ${resolvedLocalWebUrl}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${boundPort})`}`)
  132. }