index.ts 8.8 KB

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