index.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 the browser-surface glue: 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. * harness-source and web-surface prompt sections, the bash-visible web runtime
  8. * variables, and the URL line. App command-line values arrive through the
  9. * `webStartup` service expressions in the bundle patch.
  10. * @module @deepseek-ai/dsh-web-app
  11. */
  12. import { createRequire } from 'node:module'
  13. import { networkInterfaces } from 'node:os'
  14. import { fileURLToPath } from 'node:url'
  15. import type { Context } from '@deepseek-ai/cordis'
  16. import z from '@deepseek-ai/schemastery'
  17. import { addHarnessSourceSection } from '@deepseek-ai/dsh-app-boot'
  18. import { enableRow } from '@deepseek-ai/dsh-cmdline'
  19. import * as FrontendStatic from '@deepseek-ai/dsh-frontend-static'
  20. import type {} from '@deepseek-ai/cordis-plugin-loader'
  21. import type {} from '@deepseek-ai/dsh-host-webserver'
  22. import type {} from '@deepseek-ai/dsh-system-prompt'
  23. import type {} from '@deepseek-ai/dsh-bash-env'
  24. /** Stable Cordis plugin name. */
  25. export const name = 'web-app'
  26. /** This dsh installation's root, from either this package's source or built entry. */
  27. const SOURCE_ROOT = fileURLToPath(new URL('../../../..', import.meta.url))
  28. const HMR_ROW_ID = 'client-hmr'
  29. /** Runtime service that releases Web rows after bind-dependent values resolve. */
  30. const WEB_RUNTIME_SERVICE = 'webRuntime'
  31. /** Services required before the web runtime can mount. */
  32. export const inject = ['httpServer']
  33. /** Web runtime mode: production, or development when the client-plugin HMR receiver is active. */
  34. export type WebMode = 'production' | 'development'
  35. /** Plugin config: composed deployment settings plus per-invocation command-line values. */
  36. export interface Config {
  37. /** Whether this process mounted the client-plugin HMR receiver (`dsh web --dev`). */
  38. mode: WebMode
  39. /** Print the URL line on activation; a non-interactive layer can turn it off. */
  40. printUrl: boolean
  41. /**
  42. * Register the model-visible surface context (the `app:web-surface` prompt
  43. * section and the `DSH_WEB_URL`/`DSH_WEB_MODE` bash variables). A one-shot
  44. * non-interactive layer can turn it off when its user is not in the GUI, so the
  45. * orientation text would be false.
  46. */
  47. surfaceContext: boolean
  48. /** Explicit `--trusted-host` authorities from this invocation. */
  49. trustedHosts: string[]
  50. }
  51. export const Config: z<Config> = z.object({
  52. mode: z.union([z.const('production'), z.const('development')]).default('production'),
  53. printUrl: z.boolean().default(true),
  54. surfaceContext: z.boolean().default(true),
  55. trustedHosts: z.array(String).default([]),
  56. })
  57. /** Bind-dependent Web values shared by the trust fence and URL display. */
  58. export interface WebRuntimeValues {
  59. /** LAN IPv4 literals sampled once when the server binds all interfaces. */
  60. lanAddresses: string[]
  61. /** LAN literals followed by explicit invocation authorities. */
  62. trustedHosts: string[]
  63. }
  64. /** Environment variable naming the canonical local URL of this Web GUI. */
  65. const DSH_WEB_URL = 'DSH_WEB_URL' as const
  66. /** Environment variable naming the Web runtime mode. */
  67. const DSH_WEB_MODE = 'DSH_WEB_MODE' as const
  68. // Display-only mirror of the webserver schema's loopback host: the address the
  69. // local URL always prints. Not a source of truth — the schema is.
  70. const LOOPBACK_HOST = '127.0.0.1'
  71. /** The webserver schema's all-interfaces bind literal. */
  72. const ALL_INTERFACES_HOST = '0.0.0.0'
  73. /**
  74. * Resolve one LAN-trust snapshot from the active server bind.
  75. *
  76. * Derived entries are port-less IP literals: DNS rebinding needs an
  77. * attacker-controlled name, while an IP-literal Host is safe on any port and
  78. * an OS-assigned port is unknowable before bind.
  79. * @param bindHost - the active webserver bind host.
  80. * @param extra - explicit `--trusted-host` values, in argument order.
  81. * @returns the LAN display addresses and invocation-derived fence authorities.
  82. */
  83. export function resolveLanTrust(bindHost: string, extra: readonly string[]): WebRuntimeValues {
  84. const lanAddresses = bindHost === ALL_INTERFACES_HOST
  85. ? Object.values(networkInterfaces()).flat()
  86. .filter((iface): iface is NonNullable<typeof iface> => iface !== undefined && iface.family === 'IPv4' && !iface.internal)
  87. .map(iface => iface.address)
  88. : []
  89. return { lanAddresses, trustedHosts: [...lanAddresses, ...extra] }
  90. }
  91. /** Model-visible orientation and acceptance boundary for sessions created through `dsh web`. */
  92. function webSurfacePrompt(webUrl: string, mode: WebMode): string {
  93. const updateContract = mode === 'development'
  94. ? 'This Web process was launched with `dsh web --dev`, so its client-plugin HMR receiver is active. '
  95. + '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. '
  96. + 'Client-plugin changes then reload automatically, while apps/web shell and other plain-package changes still require a rebuild and page refresh. '
  97. : '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. '
  98. + '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. '
  99. return `You are interacting with the user through the DeepSeek Harness Web GUI at ${webUrl}. `
  100. + 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. '
  101. + 'The browser provides no implicit DOM, route, or screenshot context. '
  102. + updateContract
  103. + 'Starting another server does not update this GUI. '
  104. + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. '
  105. + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background task and verify its exact URL.'
  106. }
  107. /** Resolve the canonical loopback URL from the active Web server. */
  108. function localWebUrl(ctx: Context): string {
  109. const port = ctx.get('httpServer')?.port
  110. if (port === undefined) throw new Error('web-app: httpServer service missing while resolving Web runtime')
  111. return `http://${LOOPBACK_HOST}:${String(port)}`
  112. }
  113. /** Dist location is workspace knowledge of this bundle: resolved through the frontend package exports, not configured. */
  114. function resolveDistIndex(): string {
  115. const require = createRequire(import.meta.url)
  116. try {
  117. return require.resolve('@deepseek-ai/dsh-frontend/dist/index.html')
  118. } catch {
  119. /* v8 ignore next 2 -- reachable only on a checkout without a built dist; the test tree builds it */
  120. throw new Error('web-app: frontend dist not built; run pnpm run build from the repository root first')
  121. }
  122. }
  123. /** Test hook: hosts with no built frontend dist substitute the resolver; production never touches this. */
  124. export const internals: { resolveDistIndex: () => string } = { resolveDistIndex }
  125. /**
  126. * Mount the Web runtime: dist serving, surface prompt, bash runtime
  127. * variables, and the URL line.
  128. * @param ctx - plugin context carrying the httpServer service.
  129. * @param config - validated {@link Config}.
  130. * @returns nothing once the invocation's client roster and runtime contributions are registered.
  131. */
  132. export async function apply(ctx: Context, config: Config): Promise<void> {
  133. // Client discovery must start after the optional HMR row has a pending
  134. // fiber. Otherwise its first browser graph omits the reload receiver, which
  135. // cannot use that receiver to discover itself later.
  136. if (config.mode === 'development') await enableRow(ctx, HMR_ROW_ID)
  137. const runtime = resolveLanTrust(ctx.httpServer.host, config.trustedHosts)
  138. // Release dependent rows only after the optional row has a pending fiber and
  139. // bind-dependent trust has been sampled once.
  140. ctx.provide(WEB_RUNTIME_SERVICE, runtime)
  141. ctx.plugin(FrontendStatic, { distIndex: internals.resolveDistIndex() })
  142. if (config.surfaceContext) {
  143. ctx.inject(['systemPrompt'], (promptCtx) => {
  144. addHarnessSourceSection(promptCtx, SOURCE_ROOT)
  145. promptCtx.systemPrompt.section({
  146. name: 'app:web-surface',
  147. order: -98,
  148. text: () => webSurfacePrompt(localWebUrl(promptCtx), config.mode),
  149. })
  150. })
  151. ctx.inject(['bashEnv'], (runtimeCtx) => {
  152. runtimeCtx.bashEnv.register({
  153. name: 'web-runtime',
  154. variables: {
  155. [DSH_WEB_URL]: { description: 'Canonical local URL of the DeepSeek Harness Web GUI serving this session.' },
  156. [DSH_WEB_MODE]: { description: 'Web runtime mode: production, or development when the client-plugin HMR receiver is active.' },
  157. },
  158. resolve: () => ({ [DSH_WEB_URL]: localWebUrl(runtimeCtx), [DSH_WEB_MODE]: config.mode }),
  159. })
  160. })
  161. }
  162. if (config.printUrl) {
  163. // The URL line is a readiness signal: supervisors (and the keyless CLI
  164. // smoke) RPC as soon as they observe it, so it must not print while
  165. // sibling rows (the /api route owner) are still mounting. Await Loader
  166. // settlement first; a hand-built tree without a Loader prints at once.
  167. const printUrl = (): void => {
  168. // Reuse the exact LAN snapshot provided to the /api trust fence.
  169. const lanCandidate = runtime.lanAddresses[0]
  170. const port = ctx.httpServer.port
  171. console.log(`dsh web: ${localWebUrl(ctx)}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${String(port)})`}`)
  172. }
  173. // This row's own activation can precede a sibling failure. The app owns
  174. // readiness by waiting for its Loader tree, or prints at once in a
  175. // hand-built context without Loader.
  176. const settled = ctx.get('loader')?.await()
  177. if (settled === undefined) printUrl()
  178. else {
  179. void settled.then(() => {
  180. // The tree can be disposed while the boot was in flight (early
  181. // SIGTERM); a URL line for a dead server would only mislead, and
  182. // reading the torn-down port would turn a clean shutdown into a crash.
  183. if (ctx.get('httpServer') !== undefined) printUrl()
  184. // Loader reports a failed boot; this row only stays quiet.
  185. }, () => {})
  186. }
  187. }
  188. }