index.ts 14 KB

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