index.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. /**
  2. * @deepseek-ai/dsh-web-app — the browser-surface bundle's runtime glue plugin
  3. * plus the bundle patch (`cordis.patch.yml`, declared by the `dsh.bundle.patch`
  4. * manifest field). The plugin owns what used to be launcher code: it resolves
  5. * the built frontend dist (workspace knowledge of this bundle, never user
  6. * config), mounts the `frontend-static` fallback owner over it, registers the
  7. * web-surface prompt section and the bash-visible web runtime variables, and
  8. * prints the URL line when configured to. Flag-derived values (`mode`,
  9. * `lanAddresses`, `printUrl`) arrive as launcher patches over this row.
  10. * @module @deepseek-ai/dsh-web-app
  11. */
  12. import { createRequire } from 'node:module'
  13. import type { Context } from 'cordis'
  14. import z from 'schemastery'
  15. import * as FrontendStatic from '@deepseek-ai/dsh-frontend-static'
  16. import type {} from '@cordisjs/plugin-loader'
  17. import type {} from '@deepseek-ai/dsh-host-webserver'
  18. import type {} from '@deepseek-ai/dsh-system-prompt'
  19. import type {} from '@deepseek-ai/dsh-bash-env'
  20. /** Stable Cordis plugin name. */
  21. export const name = 'web-app'
  22. /** Services required before the web runtime can mount. */
  23. export const inject = ['httpServer']
  24. /** Web runtime mode: production, or development when the client-plugin HMR receiver is active. */
  25. export type WebMode = 'production' | 'development'
  26. /** Plugin config: the surface facts the launcher patches over this bundle's defaults. */
  27. export interface Config {
  28. /** Whether this process mounted the client-plugin HMR receiver (`dsh web --dev`). */
  29. mode: WebMode
  30. /** Print the URL line on activation; a headless layer over this bundle turns it off. */
  31. printUrl: boolean
  32. /**
  33. * Register the model-visible surface context (the `app:web-surface` prompt
  34. * section and the `DSH_WEB_URL`/`DSH_WEB_MODE` bash variables). A one-shot
  35. * layer turns it off: its user is not interacting through the GUI, so the
  36. * orientation text would be false.
  37. */
  38. surfaceContext: boolean
  39. /**
  40. * LAN IPv4 addresses sampled once by the launcher when the effective bind
  41. * is all-interfaces — the exact snapshot the /api trust fence was
  42. * configured with, so the printed LAN URL can never name an address the
  43. * fence rejects. Empty on a loopback bind.
  44. */
  45. lanAddresses: string[]
  46. }
  47. export const Config: z<Config> = z.object({
  48. mode: z.union([z.const('production'), z.const('development')]).default('production'),
  49. printUrl: z.boolean().default(true),
  50. surfaceContext: z.boolean().default(true),
  51. lanAddresses: z.array(String).default([]),
  52. })
  53. /** Environment variable naming the canonical local URL of this Web GUI. */
  54. const DSH_WEB_URL = 'DSH_WEB_URL' as const
  55. /** Environment variable naming the Web runtime mode. */
  56. const DSH_WEB_MODE = 'DSH_WEB_MODE' as const
  57. // Display-only mirror of the webserver schema's loopback host: the address the
  58. // local URL always prints. Not a source of truth — the schema is.
  59. const LOOPBACK_HOST = '127.0.0.1'
  60. /** Model-visible orientation and acceptance boundary for sessions created through `dsh web`. */
  61. function webSurfacePrompt(webUrl: string, mode: WebMode): string {
  62. const updateContract = mode === 'development'
  63. ? 'This Web process was launched with `dsh web --dev`, so its client-plugin HMR receiver is active. '
  64. + '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. '
  65. + 'Client-plugin changes then reload automatically, while apps/web shell and other plain-package changes still require a rebuild and page refresh. '
  66. : '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. '
  67. + '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. '
  68. return `You are interacting with the user through the DeepSeek Harness Web GUI at ${webUrl}. `
  69. + 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. '
  70. + 'The browser provides no implicit DOM, route, or screenshot context. '
  71. + updateContract
  72. + 'Starting another server does not update this GUI. '
  73. + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. '
  74. + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background task and verify its exact URL.'
  75. }
  76. /** Resolve the canonical loopback URL from the active Web server. */
  77. function localWebUrl(ctx: Context): string {
  78. const port = ctx.get('httpServer')?.port
  79. if (port === undefined) throw new Error('web-app: httpServer service missing while resolving Web runtime')
  80. return `http://${LOOPBACK_HOST}:${String(port)}`
  81. }
  82. /** Dist location is workspace knowledge of this bundle: resolved through the frontend package exports, not configured. */
  83. function resolveDistIndex(): string {
  84. const require = createRequire(import.meta.url)
  85. try {
  86. return require.resolve('@deepseek-ai/dsh-frontend/dist/index.html')
  87. } catch {
  88. /* v8 ignore next 2 -- reachable only on a checkout without a built dist; the test tree builds it */
  89. throw new Error('web-app: frontend dist not built; run pnpm run build from the repository root first')
  90. }
  91. }
  92. /** Test seam: hosts with no built frontend dist substitute the resolver; production never touches this. */
  93. export const internals: { resolveDistIndex: () => string } = { resolveDistIndex }
  94. /**
  95. * Mount the Web runtime: dist serving, surface prompt, bash runtime
  96. * variables, and the URL line.
  97. * @param ctx - plugin context carrying the httpServer service.
  98. * @param config - validated {@link Config}.
  99. */
  100. export function apply(ctx: Context, config: Config): void {
  101. ctx.plugin(FrontendStatic, { distIndex: internals.resolveDistIndex() })
  102. if (config.surfaceContext) {
  103. ctx.inject(['systemPrompt'], (promptCtx) => {
  104. promptCtx.systemPrompt.section({
  105. name: 'app:web-surface',
  106. order: -98,
  107. text: () => webSurfacePrompt(localWebUrl(promptCtx), config.mode),
  108. })
  109. })
  110. ctx.inject(['bashEnv'], (runtimeCtx) => {
  111. runtimeCtx.bashEnv.register({
  112. name: 'web-runtime',
  113. variables: {
  114. [DSH_WEB_URL]: { description: 'Canonical local URL of the DeepSeek Harness Web GUI serving this session.' },
  115. [DSH_WEB_MODE]: { description: 'Web runtime mode: production, or development when the client-plugin HMR receiver is active.' },
  116. },
  117. resolve: () => ({ [DSH_WEB_URL]: localWebUrl(runtimeCtx), [DSH_WEB_MODE]: config.mode }),
  118. })
  119. })
  120. }
  121. if (config.printUrl) {
  122. // The URL line is a readiness signal: supervisors (and the keyless CLI
  123. // smoke) RPC as soon as they observe it, so it must not print while
  124. // sibling rows (the /api route owner) are still mounting. Await Loader
  125. // settlement first; a hand-built tree without a Loader prints at once.
  126. const printUrl = (): void => {
  127. // The launcher's boot-time LAN snapshot, not a fresh sample: the printed
  128. // LAN URL must name an address the /api trust fence was configured with.
  129. const lanCandidate = config.lanAddresses[0]
  130. const port = ctx.httpServer.port
  131. console.log(`dsh web: ${localWebUrl(ctx)}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${String(port)})`}`)
  132. }
  133. const loader = ctx.get('loader')
  134. if (loader === undefined) printUrl()
  135. else {
  136. void loader.await().then(() => {
  137. // The tree can be disposed while settlement was in flight (early
  138. // SIGTERM); a URL line for a dead server would only mislead, and
  139. // reading the torn-down port would turn a clean shutdown into a crash.
  140. if (ctx.get('httpServer') !== undefined) printUrl()
  141. })
  142. }
  143. }
  144. }