index.ts 13 KB

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