index.ts 14 KB

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