index.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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, the process-token URL line, and the default-browser handoff. The
  9. * model and shell retain the clean URL. App command-line values arrive through
  10. * the `webStartup` service expressions in the bundle patch.
  11. * @module @deepseek-ai/dsh-web-app
  12. */
  13. import { spawn, type ChildProcess } from 'node:child_process'
  14. import { createRequire } from 'node:module'
  15. import { dirname, join } from 'node:path'
  16. import { networkInterfaces } from 'node:os'
  17. import { fileURLToPath } from 'node:url'
  18. import type { Context } from '@deepseek-ai/cordis'
  19. import z from '@deepseek-ai/schemastery'
  20. import { addHarnessSourceSection } from '@deepseek-ai/dsh-app-boot'
  21. import type {} from '@deepseek-ai/dsh-client-connection'
  22. import * as FrontendStatic from '@deepseek-ai/dsh-host-frontend-static'
  23. import { launchedThroughSsh, launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
  24. import { scrubbedParentEnv } from '@deepseek-ai/dsh-subprocess'
  25. import type {} from '@deepseek-ai/cordis-plugin-loader'
  26. import type {} from '@deepseek-ai/dsh-host-webserver'
  27. import type {} from '@deepseek-ai/dsh-shell-env'
  28. /** Stable Cordis plugin name. */
  29. export const name = 'web-app'
  30. /** This dsh installation's root, from either this package's source or built entry. */
  31. const SOURCE_ROOT = fileURLToPath(new URL('../../../..', import.meta.url))
  32. const ANNOUNCED_ROOTS = new WeakSet<Context>()
  33. /** Runtime service that releases Web rows after bind-dependent values resolve. */
  34. const WEB_RUNTIME_SERVICE = 'webRuntime'
  35. /** Services required before the web runtime can mount. */
  36. export const inject = ['webServer']
  37. /** Plugin config: composed deployment settings plus per-invocation command-line values. */
  38. export interface Config {
  39. /** Permit default-browser handoff after the Loader tree settles; an SSH launch suppresses it. */
  40. openBrowser: boolean
  41. /** Print the URL line on activation; a non-interactive layer can turn it off. */
  42. printUrl: boolean
  43. /**
  44. * Register the model-visible surface context (the `app:web-surface` prompt
  45. * section and the `DSH_WEB_URL` bash variable). A one-shot non-interactive
  46. * layer can turn it off when its user is not in the GUI, so the
  47. * orientation text would be false.
  48. */
  49. surfaceContext: boolean
  50. /** Explicit `--trusted-host` authorities from this invocation. */
  51. trustedHosts: string[]
  52. }
  53. export const Config: z<Config> = z.object({
  54. openBrowser: z.boolean().default(true),
  55. printUrl: z.boolean().default(true),
  56. surfaceContext: z.boolean().default(true),
  57. trustedHosts: z.array(String).default([]),
  58. })
  59. /** Bind-dependent Web values shared by the trust fence and URL display. */
  60. export interface WebRuntimeValues {
  61. /** LAN IPv4 literals sampled once when the server binds all interfaces. */
  62. lanAddresses: string[]
  63. /** LAN literals followed by explicit invocation authorities. */
  64. trustedHosts: string[]
  65. }
  66. /** Environment variable naming the canonical local URL of this Web GUI. */
  67. const DSH_WEB_URL = 'DSH_WEB_URL' 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. const BROWSER_OPENER_MODULE = import.meta.resolve('open')
  74. const BROWSER_OPENER_PROGRAM = `
  75. try {
  76. const { default: open } = await import(${JSON.stringify(BROWSER_OPENER_MODULE)})
  77. const launcher = await open(process.argv[1])
  78. if (process.platform === 'win32') {
  79. // open resolves at PowerShell spawn; keep it referenced until that launcher hands the URL to Windows.
  80. const code = launcher.exitCode ?? await new Promise((resolve, reject) => {
  81. function onError(error) {
  82. launcher.off('close', onClose)
  83. reject(error)
  84. }
  85. function onClose(code) {
  86. launcher.off('error', onError)
  87. resolve(code)
  88. }
  89. launcher.ref()
  90. launcher.once('error', onError)
  91. launcher.once('close', onClose)
  92. })
  93. if (code !== 0) throw new Error('browser operating-system launcher exited with code ' + String(code))
  94. }
  95. process.exitCode = 0
  96. } catch (error) {
  97. // The parent turns this exit into the manual-URL warning.
  98. console.error(error)
  99. process.exitCode = 1
  100. }
  101. `
  102. /**
  103. * Resolve one LAN-trust snapshot from the active server bind.
  104. *
  105. * Derived entries are port-less IP literals: DNS rebinding needs an
  106. * attacker-controlled name, while an IP-literal Host is safe on any port and
  107. * an OS-assigned port is unknowable before bind.
  108. * @param bindHost - the active webserver bind host.
  109. * @param extra - explicit `--trusted-host` values, in argument order.
  110. * @returns the LAN display addresses and invocation-derived fence authorities.
  111. */
  112. export function resolveLanTrust(bindHost: string, extra: readonly string[]): WebRuntimeValues {
  113. const lanAddresses = bindHost === ALL_INTERFACES_HOST
  114. ? Object.values(networkInterfaces()).flat()
  115. .filter((iface): iface is NonNullable<typeof iface> => iface !== undefined && iface.family === 'IPv4' && !iface.internal)
  116. .map(iface => iface.address)
  117. : []
  118. return { lanAddresses, trustedHosts: [...lanAddresses, ...extra] }
  119. }
  120. /** Model-visible orientation and acceptance boundary for sessions created through `dsh web`. */
  121. function webSurfacePrompt(webUrl: string): string {
  122. const updateContract = 'The client-plugin HMR receiver is active, but client-plugin changes reload without a refresh only while '
  123. + '`pnpm run dev:web` is also running from this same checkout to rebuild their bundles; verify that watcher before promising automatic updates. '
  124. + '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. '
  125. return `You are interacting with the user through the DeepSeek Harness Web GUI at ${webUrl}. `
  126. + 'When the user refers to "this page", "this GUI", or "this app" without naming another target, they mean this GUI. '
  127. + 'The browser provides no implicit DOM, route, or screenshot context. '
  128. + updateContract
  129. + 'Starting another server does not update this GUI. '
  130. + 'The apps/web Vite entry builds the shell but is not a standalone application because only dsh web injects window.__DSH_BOOT__. '
  131. + 'Do not start a replacement server unless the user asks; if one is needed, use a managed background job and verify its exact URL.'
  132. }
  133. /** Resolve the canonical loopback URL from the active Web server. */
  134. function localWebUrl(ctx: Context): string {
  135. const port = ctx.get('webServer')?.port
  136. if (port === undefined) throw new Error('web-app: webServer service missing while resolving Web runtime')
  137. return `http://${LOOPBACK_HOST}:${String(port)}`
  138. }
  139. /**
  140. * Dist location is workspace knowledge of this bundle: anchored on the
  141. * frontend package manifest, not configured. Existence is a request-time
  142. * concern — the fallback owner reads files per request, so a composition
  143. * whose page never reaches the fallback seat (the static worker preview
  144. * ships its own page and carries no dist) boots without one.
  145. */
  146. function resolveDistIndex(): string {
  147. const require = createRequire(import.meta.url)
  148. try {
  149. return join(dirname(require.resolve('@deepseek-ai/dsh-web-frontend/package.json')), 'dist', 'index.html')
  150. } catch {
  151. /* v8 ignore next 2 -- reachable only when the frontend package is absent from the checkout */
  152. throw new Error('web-app: @deepseek-ai/dsh-web-frontend is not resolvable from this composition')
  153. }
  154. }
  155. /** Start the maintained platform opener without forwarding Harness credentials. */
  156. function spawnBrowserLauncher(url: string): ChildProcess {
  157. return spawn(process.execPath, [
  158. '--input-type=module',
  159. '--eval', BROWSER_OPENER_PROGRAM,
  160. '--', url,
  161. ], {
  162. env: scrubbedParentEnv(),
  163. stdio: ['ignore', 'inherit', 'pipe'],
  164. })
  165. }
  166. /** Hand one URL to the operating system's default browser. */
  167. async function openBrowser(url: string): Promise<void> {
  168. const launcher = spawnBrowserLauncher(url)
  169. let launcherStderr = ''
  170. launcher.stderr?.setEncoding('utf8')
  171. launcher.stderr?.on('data', (chunk: string) => { launcherStderr += chunk })
  172. await new Promise<void>((resolve, reject) => {
  173. function onError(error: Error): void {
  174. launcher.off('close', onClose)
  175. reject(error)
  176. }
  177. function onClose(code: number | null): void {
  178. launcher.off('error', onError)
  179. if (code !== 0) {
  180. const firstLine = launcherStderr.trim().split(/\r?\n/u)[0]
  181. const reason = firstLine === undefined || firstLine === ''
  182. ? `browser launcher exited with code ${String(code)}`
  183. : firstLine.replace(/^(?:[A-Za-z]*Error):\s*/u, '')
  184. reject(new Error(reason))
  185. return
  186. }
  187. if (launcherStderr !== '') process.stderr.write(launcherStderr)
  188. resolve()
  189. }
  190. launcher.once('error', onError)
  191. launcher.once('close', onClose)
  192. })
  193. }
  194. /** Test hooks for the built dist and native browser handoff; production never mutates them. */
  195. export const internals: {
  196. resolveDistIndex: () => string
  197. openBrowser: (url: string) => Promise<void>
  198. } = { resolveDistIndex, openBrowser }
  199. /**
  200. * Mount the Web runtime: dist serving, surface prompt, the bash runtime
  201. * variable, the URL line, and the default-browser handoff.
  202. * @param ctx - plugin context carrying the webServer service.
  203. * @param config - validated {@link Config}.
  204. */
  205. export function apply(ctx: Context, config: Config): void {
  206. const runtime = resolveLanTrust(ctx.webServer.host, config.trustedHosts)
  207. // The loopback URL belongs to this host. Under SSH, the operator reaches it
  208. // through a local forwarding address that this process cannot derive.
  209. const handoffBrowser = config.openBrowser && !launchedThroughSsh(launchEnvironmentOf(ctx))
  210. // Release dependent rows only after bind-dependent trust has been sampled once.
  211. ctx.provide(WEB_RUNTIME_SERVICE, runtime)
  212. ctx.plugin(FrontendStatic, { distIndex: internals.resolveDistIndex() })
  213. if (config.surfaceContext) {
  214. ctx.inject(['systemPrompt'], (promptCtx) => {
  215. addHarnessSourceSection(promptCtx, SOURCE_ROOT)
  216. promptCtx.systemPrompt.section({
  217. name: 'app:web-surface',
  218. order: promptCtx.systemPrompt.getSectionOrder('WEB_SURFACE'),
  219. text: () => webSurfacePrompt(localWebUrl(promptCtx)),
  220. })
  221. })
  222. ctx.inject(['shellEnv'], (runtimeCtx) => {
  223. runtimeCtx.shellEnv.register({
  224. name: 'web-runtime',
  225. variables: {
  226. [DSH_WEB_URL]: { description: 'Canonical local URL of the DeepSeek Harness Web GUI serving this session.' },
  227. },
  228. resolve: () => ({ [DSH_WEB_URL]: localWebUrl(runtimeCtx) }),
  229. })
  230. })
  231. }
  232. if (config.printUrl || handoffBrowser) {
  233. ctx.inject(['connection'], (connectionCtx) => {
  234. // The URL line and browser handoff are readiness signals: supervisors RPC
  235. // as soon as they observe the line, while a browser requests the page as
  236. // soon as it opens. Neither may run while sibling rows such as the /api
  237. // route owner are still mounting. Await Loader settlement first; a
  238. // hand-built tree without a Loader is already the complete tree.
  239. const announceReady = (): void => {
  240. if (ANNOUNCED_ROOTS.has(connectionCtx.root)) return
  241. const webUrl = localWebUrl(connectionCtx)
  242. const authenticatedUrl = connectionCtx.connection.authenticatedUrl(webUrl)
  243. // Reuse the exact LAN snapshot provided to the /api trust fence.
  244. const lanCandidate = runtime.lanAddresses[0]
  245. const port = connectionCtx.webServer.port
  246. const lanUrl = lanCandidate === undefined
  247. ? undefined
  248. : connectionCtx.connection.authenticatedUrl(`http://${lanCandidate}:${String(port)}`)
  249. ANNOUNCED_ROOTS.add(connectionCtx.root)
  250. if (config.printUrl) {
  251. console.log(`dsh web: ${authenticatedUrl}${lanUrl === undefined ? '' : ` (LAN: ${lanUrl})`}`)
  252. }
  253. if (handoffBrowser) {
  254. console.log('dsh web: opening the default browser; pass --no-open to disable')
  255. void internals.openBrowser(authenticatedUrl).catch((error: unknown) => {
  256. const reason = error instanceof Error ? error.message : String(error)
  257. console.error(`web-app: could not open the default browser because ${reason}; use the dsh web URL printed at startup`)
  258. })
  259. }
  260. }
  261. // This row's own activation can precede a sibling failure. The app owns
  262. // readiness by waiting for its Loader tree, or announces at once in a
  263. // hand-built tree without Loader.
  264. const settled = connectionCtx.get('loader')?.await()
  265. if (settled === undefined) announceReady()
  266. else {
  267. void settled.then(() => {
  268. // The tree can be disposed while the boot was in flight (early
  269. // SIGTERM); a URL line or browser tab for a dead server would only
  270. // mislead, and reading torn-down services would turn a clean shutdown
  271. // into a crash.
  272. if (connectionCtx.get('webServer') !== undefined
  273. && connectionCtx.get('connection') !== undefined) announceReady()
  274. // Loader reports a failed boot; this row only stays quiet.
  275. }, () => {})
  276. }
  277. })
  278. }
  279. }