web.ts 7.1 KB

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