refactor(cmdline): make command providers ordinary
This commit is contained in:
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/bundle/headless/README.md
|
||||
README.md: 459d0f32788265d43e75922067da3c03d054f444
|
||||
README.zh.md: e3ca9d13512e3a13ac71c5cda650fca958609062
|
||||
README.md: 31a4894dbb191d2244371ca7272339e96e253053
|
||||
README.zh.md: 6e8d28f10071fbab175c4f14f1aaa9618b8f598a
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
The dsh one-shot bundle. [`cordis.patch.yml`](cordis.patch.yml) rides directly over [`dsh-base`](../base/README.md): it supplies the coding persona and tool mode, disables HMR, mounts Code Mode's worker as a core execution capability, and inserts this package's `headless-runner` plugin (config `{task}`, resolved from the injected startup service). It mounts no Host, HTTP server, Web runtime, or browser plugin.
|
||||
The dsh one-shot bundle. [`cordis.patch.yml`](cordis.patch.yml) rides directly over [`dsh-base`](../base/README.md): it supplies the coding persona and tool mode, disables HMR, mounts Code Mode's worker as a core execution capability, and inserts this package's `headless-runner` plugin (config `{task}`, resolved from the injected `headlessStartup` provider). It mounts no Host, HTTP server, Web runtime, or browser plugin.
|
||||
|
||||
After the Loader settles, the runner reads the shared [`ctx.agentDefaultModel`](../../core/agent-default-model/README.md), creates one fresh persisted Agent through `ctx.agents`, submits the task as an ordinary user message, and waits for quiescence. It flushes the Session before folding the owned durable event interval, writes the last non-empty assistant text to stdout, and requests exit through the launcher-provided `ctx.headlessIo` host hook (final `turn/end` completed → 0, otherwise 1). A terminal `error` reason also writes its code and message to stderr; successful runs keep stderr empty. The process opens no listening port. The task text is this app's command line: the `headless-startup` row ([`src/startup.ts`](src/startup.ts)) reads it as the positional argument of `dsh --profile headless "task"` from `ctx.cmdlineArgs` ([`dsh-cmdline`](../../boot/cmdline/README.md)), prints the app's `--help`, and rejects an invocation with no task instead of letting the runner's schema fail.
|
||||
After the Loader settles, the runner reads the shared [`ctx.agentDefaultModel`](../../core/agent-default-model/README.md), creates one fresh persisted Agent through `ctx.agents`, submits the task as an ordinary user message, and waits for quiescence. It flushes the Session before folding the owned durable event interval, writes the last non-empty assistant text to stdout, and requests exit through the launcher-provided `ctx.headlessIo` host hook (final `turn/end` completed → 0, otherwise 1). A terminal `error` reason also writes its code and message to stderr; successful runs keep stderr empty. The process opens no listening port. The task text is this app's command line: the ordinary `headless-startup` provider ([`src/startup.ts`](src/startup.ts)) injects `ctx.cmdlineArgs` ([`dsh-cmdline`](../../boot/cmdline/README.md)), reads the positional argument of `dsh --profile headless "task"`, prints the app's `--help`, and provides `headlessStartup`; the runner injects that service and reads its task from lazy config. A missing or whitespace-only task is rejected before the runner activates.
|
||||
|
||||
## Model Experience
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
dsh 一次性任务组合包。[`cordis.patch.yml`](cordis.patch.yml) 直接叠加在 [`dsh-base`](../base/README.md) 之上:提供编码 persona 和工具模式、禁用 HMR(热模块替换)、将 Code Mode 的 worker 作为核心执行能力挂载,并插入本包的 `headless-runner` 插件(配置为 `{task}`,从注入的启动服务解析)。它不挂载任何 Host、HTTP server、Web runtime 或浏览器插件。
|
||||
dsh 一次性任务组合包。[`cordis.patch.yml`](cordis.patch.yml) 直接叠加在 [`dsh-base`](../base/README.md) 之上:提供编码 persona 和工具模式、禁用 HMR(热模块替换)、将 Code Mode 的 worker 作为核心执行能力挂载,并插入本包的 `headless-runner` 插件(配置为 `{task}`,从注入的 `headlessStartup` 提供方解析)。它不挂载任何 Host、HTTP server、Web runtime 或浏览器插件。
|
||||
|
||||
Loader 结算后,runner 读取共享的 [`ctx.agentDefaultModel`](../../core/agent-default-model/README.md),通过 `ctx.agents` 创建一个全新的持久化 Agent(智能体),将任务作为普通用户消息提交,并等待完全停稳。它对 Session 执行 flush 后再汇总自身持有的持久化事件区间,将最后一条非空 assistant 文本写入 stdout,再经启动器提供的 `ctx.headlessIo` 宿主钩子请求退出(最终 `turn/end` 完成 → 0,否则为 1)。最终 reason 为 `error` 时,还会将持久化的 code 与 message 写入 stderr;成功运行时 stderr 保持为空。进程不会打开监听端口。任务文本就是这个应用的命令行:`headless-startup` 行([`src/startup.ts`](src/startup.ts))从 `ctx.cmdlineArgs`([`dsh-cmdline`](../../boot/cmdline/README.md))把它读作 `dsh --profile headless "task"` 的位置参数,打印应用自己的 `--help`,并拒绝没有任务的调用,而不是让 runner 的 schema 失败。
|
||||
Loader 结算后,runner 读取共享的 [`ctx.agentDefaultModel`](../../core/agent-default-model/README.md),通过 `ctx.agents` 创建一个全新的持久化 Agent(智能体),将任务作为普通用户消息提交,并等待完全停稳。它对 Session 执行 flush 后再汇总自身持有的持久化事件区间,将最后一条非空 assistant 文本写入 stdout,再经启动器提供的 `ctx.headlessIo` 宿主钩子请求退出(最终 `turn/end` 完成 → 0,否则为 1)。最终 reason 为 `error` 时,还会将持久化的 code 与 message 写入 stderr;成功运行时 stderr 保持为空。进程不会打开监听端口。任务文本就是这个应用的命令行:普通 `headless-startup` 提供方([`src/startup.ts`](src/startup.ts))注入 `ctx.cmdlineArgs`([`dsh-cmdline`](../../boot/cmdline/README.md)),读取 `dsh --profile headless "task"` 的位置参数、打印应用自己的 `--help`,并提供 `headlessStartup`;runner 注入该服务,再从惰性配置中读取任务。缺失或只有空白的任务会在 runner 激活前被拒绝。
|
||||
|
||||
## 模型体验
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# The dsh-headless bundle patch: one-shot task mode directly over dsh-base.
|
||||
# It mounts no Host, HTTP server, Web runtime, or browser plugin. The startup
|
||||
# row injects `cmdlineArgs`, owns the task positional
|
||||
# (`dsh --profile headless "<task>"`) and this app's --help; the direct driver
|
||||
# creates an Agent through the core registry and prints its durable result.
|
||||
# It mounts no Host, HTTP server, Web runtime, or browser plugin. An ordinary
|
||||
# provider plugin injects `cmdlineArgs`, parses the task positional
|
||||
# (`dsh --profile headless "<task>"`) and this app's --help, then the direct
|
||||
# driver creates an Agent through the core registry and prints its durable result.
|
||||
|
||||
- id: system-prompt
|
||||
config:
|
||||
@@ -25,10 +25,8 @@
|
||||
|
||||
- id: headless-startup
|
||||
name: '@deepseek-ai/dsh-headless/startup'
|
||||
inject: [cmdlineArgs]
|
||||
|
||||
# Reads its task from the headlessStartup service after the startup row
|
||||
# resolves this app's command line.
|
||||
# Reads its task from the ordinary headlessStartup provider.
|
||||
- id: headless-runner
|
||||
name: '@deepseek-ai/dsh-headless'
|
||||
inject: [headlessStartup]
|
||||
|
||||
@@ -25,7 +25,7 @@ export const name = 'headless-runner'
|
||||
/** Core services required before the one-shot turn can start. */
|
||||
export const inject = ['agentDefaultModel', 'agents', 'sessions']
|
||||
|
||||
/** Plugin config: the task resolved from this app's injected startup service. */
|
||||
/** Plugin config: the task resolved from this app's injected provider service. */
|
||||
export interface Config {
|
||||
/** The prompt text for the single run. */
|
||||
task: string
|
||||
|
||||
@@ -1,16 +1,13 @@
|
||||
/**
|
||||
* The one-shot app's startup row: it owns the `dsh --profile headless` command
|
||||
* line — the task text is this command's positional argument — and its
|
||||
* `--help` text, then provides {@link HEADLESS_STARTUP_SERVICE} with the task
|
||||
* the user asked for. The runner waits for it, so a missing task is a usage
|
||||
* error printed by this command instead of a schema failure inside the runner.
|
||||
* The one-shot app's command-line provider: it parses the task positional and
|
||||
* `--help`, then publishes {@link HEADLESS_STARTUP_SERVICE}. The runner is an
|
||||
* ordinary consumer whose lazy config waits for that service.
|
||||
* @module @deepseek-ai/dsh-headless/startup
|
||||
*/
|
||||
|
||||
import { Command } from 'commander'
|
||||
import type { Context } from 'cordis'
|
||||
import type { EntryOptions } from '@cordisjs/plugin-loader'
|
||||
import { runStartup } from '@deepseek-ai/dsh-cmdline'
|
||||
import { parseCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
|
||||
/** Stable Cordis plugin name. */
|
||||
export const name = 'headless-startup'
|
||||
@@ -18,12 +15,9 @@ export const name = 'headless-startup'
|
||||
/** Services required before the task can be resolved. */
|
||||
export const inject = ['cmdlineArgs']
|
||||
|
||||
/** The service this row provides and the one-shot runner row reads. */
|
||||
/** Service provided by this plugin and injected by the one-shot runner. */
|
||||
export const HEADLESS_STARTUP_SERVICE = 'headlessStartup'
|
||||
|
||||
/** The row that runs the task, and the only reason this app has a command line. */
|
||||
const RUNNER_ROW_ID = 'headless-runner'
|
||||
|
||||
/** What the runner row reads from {@link HEADLESS_STARTUP_SERVICE}. */
|
||||
export interface HeadlessStartupValues {
|
||||
/** The task text this invocation asked for. */
|
||||
@@ -47,27 +41,22 @@ Examples:
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the parsed command line into the runner row's task.
|
||||
* Turn the parsed command line into the runner's task.
|
||||
* @param program - the parsed headless command.
|
||||
* @param rows - the rows waiting on this app's service, in tree order.
|
||||
* @returns the runner row's service value.
|
||||
* @throws when the composition has no runner row, which would otherwise accept
|
||||
* a task and silently run nothing.
|
||||
* @returns the runner's service value.
|
||||
*/
|
||||
function planHeadlessStartup(program: Command, rows: readonly EntryOptions[]): HeadlessStartupValues {
|
||||
function planHeadlessStartup(program: Command): HeadlessStartupValues {
|
||||
const task = program.args.join(' ')
|
||||
if (task === '') program.error('error: a task is required, for example: dsh --profile headless "run the tests"')
|
||||
if (!rows.some(row => row.id === RUNNER_ROW_ID)) {
|
||||
throw new Error(`headless-startup: the composition has no waiting "${RUNNER_ROW_ID}" row to run the task`)
|
||||
}
|
||||
if (task.trim() === '') program.error('error: a task is required, for example: dsh --profile headless "run the tests"')
|
||||
return { task }
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the task for the runner waiting on `headlessStartup`.
|
||||
* @param ctx - plugin context carrying the command line and the Loader.
|
||||
* @returns nothing once the runner is started, or once `--help` or a missing task requested exit.
|
||||
* Parse and provide the one-shot task as an ordinary Cordis service.
|
||||
* @param ctx - plugin context carrying the command line.
|
||||
* @returns nothing once the task is provided, or when the command requested exit.
|
||||
*/
|
||||
export function apply(ctx: Context): void {
|
||||
runStartup(ctx, HEADLESS_STARTUP_SERVICE, headlessCommand(), planHeadlessStartup)
|
||||
const values = parseCmdline(ctx, headlessCommand(), planHeadlessStartup)
|
||||
if (values !== undefined) ctx.provide(HEADLESS_STARTUP_SERVICE, values)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* The one-shot app's startup row over a real Loader tree: the task positional
|
||||
* becomes the injected runner config, while help and usage errors leave the
|
||||
* runner pending.
|
||||
* The one-shot app's ordinary command-line provider over a real Loader tree:
|
||||
* the task becomes injected runner config, while help and usage errors leave
|
||||
* the consumer pending.
|
||||
*/
|
||||
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs'
|
||||
@@ -31,15 +31,11 @@ afterEach(async () => {
|
||||
})
|
||||
|
||||
/**
|
||||
* Mount the real startup row over a runner stand-in.
|
||||
* Mount the real provider over a runner stand-in.
|
||||
* @param args - the invocation's inner arguments.
|
||||
* @param options - fixture knobs for invalid compositions.
|
||||
* @returns the resolved startup value and observed runner/process effects.
|
||||
* @returns the resolved service value and observed runner/process effects.
|
||||
*/
|
||||
async function bootStartup(
|
||||
args: string[],
|
||||
options: { withoutRunner?: boolean } = {},
|
||||
): Promise<{ task: HeadlessStartupValues | undefined; observed: Observed }> {
|
||||
async function bootStartup(args: string[]): Promise<{ task: HeadlessStartupValues | undefined; observed: Observed }> {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'dsh-headless-startup-'))
|
||||
const observed: Observed = { exits: [], out: '' }
|
||||
writeFileSync(join(dir, 'row.mjs'), 'export function apply(_ctx, config) { globalThis.__headlessStartupObserved.runnerConfig = config }\n')
|
||||
@@ -52,14 +48,13 @@ export const apply = ctx => globalThis.__headlessStartupApply(ctx)
|
||||
`)
|
||||
const rowUrl = pathToFileURL(join(dir, 'row.mjs')).href
|
||||
writeFileSync(join(dir, 'cordis.yml'), [
|
||||
options.withoutRunner === true ? '- id: displaced-runner' : '- id: headless-runner',
|
||||
'- id: headless-runner',
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${HEADLESS_STARTUP_SERVICE}]`,
|
||||
' config:',
|
||||
' task: !!js ctx.headlessStartup.task',
|
||||
'- id: headless-startup',
|
||||
` name: ${pathToFileURL(join(dir, 'startup.mjs')).href}`,
|
||||
' inject: [cmdlineArgs]',
|
||||
'',
|
||||
].join('\n'))
|
||||
const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
|
||||
@@ -85,7 +80,7 @@ export const apply = ctx => globalThis.__headlessStartupApply(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
describe('headless startup', () => {
|
||||
describe('headless command-line provider', () => {
|
||||
it('joins the task positional into the runner config', async () => {
|
||||
const { task, observed } = await bootStartup(['run', 'the', 'tests'])
|
||||
expect(task).toEqual({ task: 'run the tests' })
|
||||
@@ -93,8 +88,8 @@ describe('headless startup', () => {
|
||||
expect(observed.exits).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects an invocation with no task and leaves the runner pending', async () => {
|
||||
const { task, observed } = await bootStartup([])
|
||||
it.each([{ args: [] }, { args: [' '] }])('rejects an invocation with no non-whitespace task ($args)', async ({ args }) => {
|
||||
const { task, observed } = await bootStartup(args)
|
||||
expect(observed.out).toContain('a task is required')
|
||||
expect(task).toBeUndefined()
|
||||
expect(observed.runnerConfig).toBeUndefined()
|
||||
@@ -108,9 +103,4 @@ describe('headless startup', () => {
|
||||
expect(observed.runnerConfig).toBeUndefined()
|
||||
expect(observed.exits).toEqual([0])
|
||||
})
|
||||
|
||||
it('fails when the composition has no runner row', async () => {
|
||||
await expect(bootStartup(['task'], { withoutRunner: true }))
|
||||
.rejects.toThrow('the composition has no waiting "headless-runner" row')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,5 +2,5 @@
|
||||
# side as of the last confirmed-consistent state. Both languages carry equal authority;
|
||||
# after editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write packages/bundle/web-app/README.md
|
||||
README.md: e2cca9ddcca5690f36ce3e952a2814767acdad43
|
||||
README.zh.md: 321f7853c821f262a38b35530a4df8b2e18fff49
|
||||
README.md: b6fa225f5e0a0a079605a4fb9064b79287ab21cd
|
||||
README.zh.md: 68af959719b9bd146eddd143aa9d98400e65fa68
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
The dsh browser-surface bundle. [`cordis.patch.yml`](cordis.patch.yml) rides over [`dsh-base`](../base/README.md): it sets the coding persona, inserts the Web host rows (webserver, API gateway, workspace, projection cache, storage) and the browser plugin roster, and mounts this package's `web-runtime` glue plugin (config `{mode, printUrl, surfaceContext, lanAddresses}`). That plugin resolves the built frontend dist through `@deepseek-ai/dsh-frontend`'s exports, enables the optional HMR row before client-module discovery so the first development graph contains its reload receiver, mounts the [`frontend-static`](../../host/frontend-static/README.md) fallback owner, registers the harness-source and web-surface prompt sections plus the bash-visible `DSH_WEB_URL`/`DSH_WEB_MODE` runtime variables when `surfaceContext` is true, and prints the `dsh web:` URL line when `printUrl` is true, after its Loader tree settles so a sibling failure cannot announce a dead app. This bundle also owns the app command line: the `web-startup` row ([`src/startup.ts`](src/startup.ts)) parses `--host`, `--port`, `--dev`, and repeatable `--trusted-host` from `ctx.cmdlineArgs` ([`dsh-cmdline`](../../boot/cmdline/README.md)) and prints the app's `--help`. Every row it configures injects `webStartup`, so nothing binds a port before argument resolution and `dsh --profile web --help` starts no server. `mode` and `lanAddresses` resolve on every boot because they describe the invocation. [`dsh-headless`](../headless/README.md) is a sibling surface over the same base and does not mount this bundle.
|
||||
The dsh browser-surface bundle. [`cordis.patch.yml`](cordis.patch.yml) rides over [`dsh-base`](../base/README.md): it sets the coding persona, inserts the Web host rows (webserver, API gateway, workspace, projection cache, storage) and the browser plugin roster, and mounts this package's `web-runtime` glue plugin (config `{mode, printUrl, surfaceContext, trustedHosts}`). That plugin resolves the built frontend dist through `@deepseek-ai/dsh-frontend`'s exports, enables the optional HMR row before client-module discovery so the first development graph contains its reload receiver, samples bind-dependent LAN trust once, provides it as `webRuntime` to the browser-trust fence and client roster, mounts the [`frontend-static`](../../host/frontend-static/README.md) fallback owner, registers the harness-source and web-surface prompt sections plus the bash-visible `DSH_WEB_URL`/`DSH_WEB_MODE` runtime variables when `surfaceContext` is true, and prints the `dsh web:` URL line when `printUrl` is true, after its Loader tree settles so a sibling failure cannot announce a dead app. This bundle also owns the app command line: the ordinary `web-startup` provider ([`src/startup.ts`](src/startup.ts)) injects `ctx.cmdlineArgs` ([`dsh-cmdline`](../../boot/cmdline/README.md)), parses `--host`, `--port`, `--dev`, repeatable `--trusted-host`, and the app's `--help`, then provides `webStartup`. Flag-configured rows inject that service and read it directly from lazy config, so nothing binds a port before argument resolution and `dsh --profile web --help` starts no server. [`dsh-headless`](../headless/README.md) is a sibling surface over the same base and does not mount this bundle.
|
||||
|
||||
## Model Experience
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
dsh 浏览器表层组合包。[`cordis.patch.yml`](cordis.patch.yml) 叠加在 [`dsh-base`](../base/README.md) 之上:设置 coding persona,插入 Web 宿主行(webserver、API 网关、workspace、投影缓存、存储)与浏览器插件名录,并挂载本包的 `web-runtime` 粘合插件(配置为 `{mode, printUrl, surfaceContext, lanAddresses}`)。该插件通过 `@deepseek-ai/dsh-frontend` 的 exports 解析已构建的前端 dist,在客户端模块发现前启用可选的 HMR 行,确保首份开发模式图中包含它的重载接收端,挂载 [`frontend-static`](../../host/frontend-static/README.md) 回退席位所有者,在 `surfaceContext` 为 true 时注册 Harness 源码与 Web 表层提示词段落,以及 bash 可见的 `DSH_WEB_URL`/`DSH_WEB_MODE` 运行时变量,并在 `printUrl` 为 true 时等自身的 Loader 配置树结算后再打印 `dsh web:` URL 行,避免兄弟行失败时公告一个已失效的应用。本组合包还持有应用命令行:`web-startup` 行([`src/startup.ts`](src/startup.ts))从 `ctx.cmdlineArgs`([`dsh-cmdline`](../../boot/cmdline/README.md))解析 `--host`、`--port`、`--dev` 以及可重复的 `--trusted-host`,并打印应用自己的 `--help`。它所配置的每一行都注入 `webStartup`,因此在参数解析完成之前不会有任何东西绑定端口,`dsh --profile web --help` 也不会启动服务器。`mode` 与 `lanAddresses` 在每次 boot 时解析,因为它们描述的是本次调用。[`dsh-headless`](../headless/README.md) 是同一 base 之上的同级表层,不挂载本组合包。
|
||||
dsh 浏览器表层组合包。[`cordis.patch.yml`](cordis.patch.yml) 叠加在 [`dsh-base`](../base/README.md) 之上:设置 coding persona,插入 Web 宿主行(webserver、API 网关、workspace、投影缓存、存储)与浏览器插件名录,并挂载本包的 `web-runtime` 粘合插件(配置为 `{mode, printUrl, surfaceContext, trustedHosts}`)。该插件通过 `@deepseek-ai/dsh-frontend` 的 exports 解析已构建的前端 dist,在客户端模块发现前启用可选的 HMR 行,确保首份开发模式图中包含它的重载接收端,只采样一次依赖 bind 的 LAN 信任信息并将其作为 `webRuntime` 提供给浏览器信任栅栏和客户端名录,挂载 [`frontend-static`](../../host/frontend-static/README.md) 回退席位所有者,在 `surfaceContext` 为 true 时注册 Harness 源码与 Web 表层提示词段落,以及 bash 可见的 `DSH_WEB_URL`/`DSH_WEB_MODE` 运行时变量,并在 `printUrl` 为 true 时等自身的 Loader 配置树结算后再打印 `dsh web:` URL 行,避免兄弟行失败时公告一个已失效的应用。本组合包还持有应用命令行:普通 `web-startup` 提供方([`src/startup.ts`](src/startup.ts))注入 `ctx.cmdlineArgs`([`dsh-cmdline`](../../boot/cmdline/README.md)),解析 `--host`、`--port`、`--dev`、可重复的 `--trusted-host` 以及应用自己的 `--help`,再提供 `webStartup`。由 flag 配置的行会注入该服务,并在惰性配置中直接读取它,因此参数解析完成前不会有任何东西绑定端口,`dsh --profile web --help` 也不会启动服务器。[`dsh-headless`](../headless/README.md) 是同一 base 之上的同级表层,不挂载本组合包。
|
||||
|
||||
## 模型体验
|
||||
|
||||
|
||||
@@ -5,12 +5,11 @@
|
||||
# A patch replaces the targeted row's whole `config`, so each row below
|
||||
# restates every key it owns.
|
||||
#
|
||||
# Rows this app configures from flags read them from the `webStartup` service:
|
||||
# each names the key it takes and the value it falls back to, so a flag wins
|
||||
# over the value written beside it. The web-startup row injects `cmdlineArgs`
|
||||
# and provides `webStartup`; Loader delays dependent-row config interpolation
|
||||
# until that service is active. `dsh --profile web --help` provides no service,
|
||||
# so the server rows never activate.
|
||||
# The web-startup plugin injects `cmdlineArgs` and provides `webStartup` as an
|
||||
# ordinary Cordis service. Rows configured from flags inject that service, so
|
||||
# Loader resolves their expressions only after it exists. The web runtime then
|
||||
# provides bind-dependent `webRuntime` values to the trust fence and client
|
||||
# roster. `dsh --profile web --help` provides neither service, so no server binds.
|
||||
|
||||
# ── surface-specific values the base deliberately omits ─────────────────────
|
||||
|
||||
@@ -81,39 +80,39 @@
|
||||
- id: api-gateway
|
||||
name: '@deepseek-ai/dsh-host-apiproxy'
|
||||
|
||||
# This app's command-line startup row. It owns the web flag family and its
|
||||
# --help, and provides webStartup to the rows that inject it.
|
||||
# Ordinary provider for the parsed Web flags. Its plugin-level injection
|
||||
# waits for cmdlineArgs; no launcher metadata or special row kind is needed.
|
||||
- id: web-startup
|
||||
name: '@deepseek-ai/dsh-web-app/startup'
|
||||
inject: [cmdlineArgs]
|
||||
|
||||
# ── layer 2: transport/service ──────────────────────────────────────────────
|
||||
|
||||
# Plain route-registration carrier; host and port come from the app's
|
||||
# startup service, with these deployment fallbacks. The dist is served by
|
||||
# webStartup provider, with these deployment fallbacks. The dist is served by
|
||||
# the web-runtime row below through the fallback seat.
|
||||
- id: webserver
|
||||
name: '@deepseek-ai/dsh-host-webserver'
|
||||
inject: [webStartup]
|
||||
config:
|
||||
host: !!js ctx.get('webStartup')?.host ?? '127.0.0.1'
|
||||
port: !!js ctx.get('webStartup')?.port ?? 3080
|
||||
host: !!js ctx.webStartup.host ?? '127.0.0.1'
|
||||
port: !!js ctx.webStartup.port ?? 3080
|
||||
|
||||
# Web glue owned by this bundle: resolves the built frontend dist (an
|
||||
# assembly fact of dsh-web-app, never user config), mounts the
|
||||
# frontend-static fallback owner, registers the web-surface prompt
|
||||
# section and bash runtime variables, and prints the URL line. `dsh web`
|
||||
# patches mode/lanAddresses over these defaults. A complete agent-preset
|
||||
# section and bash runtime variables, and prints the URL line. The webStartup
|
||||
# provider supplies invocation-only values; after the server binds, this row
|
||||
# samples LAN trust once and provides `webRuntime`. A complete agent-preset
|
||||
# persona suppresses the prompt section for that agent while retaining
|
||||
# these host-owned shell variables.
|
||||
- id: web-runtime
|
||||
name: '@deepseek-ai/dsh-web-app'
|
||||
inject: [webStartup]
|
||||
config:
|
||||
mode: !!js ctx.get('webStartup')?.mode ?? 'production'
|
||||
mode: !!js ctx.webStartup.mode
|
||||
printUrl: true
|
||||
surfaceContext: true
|
||||
lanAddresses: !!js ctx.get('webStartup')?.lanAddresses ?? []
|
||||
trustedHosts: !!js ctx.webStartup.trustedHosts
|
||||
|
||||
# The client-plugin reload chain: a dev-only row this bundle ships off,
|
||||
# which the runtime row turns on before client discovery. It is a row rather
|
||||
@@ -133,18 +132,18 @@
|
||||
# (adopted as a plugin entry by the kernel, never fetched).
|
||||
- id: modules
|
||||
name: '@deepseek-ai/dsh-client-modules'
|
||||
inject: [webClientRoster]
|
||||
inject: [webRuntime]
|
||||
|
||||
# Owns both ends of the web transport: node half binds the gateway to the
|
||||
# webserver under /api; browser half is the fetch/SSE client.
|
||||
- id: connection
|
||||
name: '@deepseek-ai/dsh-client-connection'
|
||||
inject: [webStartup]
|
||||
inject: [webRuntime]
|
||||
config:
|
||||
# The LAN literals an all-interfaces bind derived plus the
|
||||
# --trusted-host extras. A deployment that configures its own fence
|
||||
# authorities adds them to this list.
|
||||
trustedHosts: !!js ctx.get('webStartup')?.trustedHosts ?? []
|
||||
# LAN literals derived from the active bind plus --trusted-host extras.
|
||||
# A deployment adding authorities keeps this expression and concatenates
|
||||
# its literals, for example: ['app.internal', ...ctx.webRuntime.trustedHosts].
|
||||
trustedHosts: !!js ctx.webRuntime.trustedHosts
|
||||
|
||||
- id: api-remotes
|
||||
name: '@deepseek-ai/dsh-api-remotes'
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
|
||||
import { createRequire } from 'node:module'
|
||||
import { networkInterfaces } from 'node:os'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
import z from '@deepseek-ai/schemastery'
|
||||
@@ -28,7 +29,9 @@ export const name = 'web-app'
|
||||
/** This dsh installation's root, from either this package's source or built entry. */
|
||||
const SOURCE_ROOT = fileURLToPath(new URL('../../../..', import.meta.url))
|
||||
const HMR_ROW_ID = 'client-hmr'
|
||||
const CLIENT_ROSTER_SERVICE = 'webClientRoster'
|
||||
|
||||
/** Runtime service that releases Web rows after bind-dependent values resolve. */
|
||||
const WEB_RUNTIME_SERVICE = 'webRuntime'
|
||||
|
||||
/** Services required before the web runtime can mount. */
|
||||
export const inject = ['httpServer']
|
||||
@@ -36,7 +39,7 @@ export const inject = ['httpServer']
|
||||
/** Web runtime mode: production, or development when the client-plugin HMR receiver is active. */
|
||||
export type WebMode = 'production' | 'development'
|
||||
|
||||
/** Plugin config: composed deployment settings plus per-invocation startup values. */
|
||||
/** Plugin config: composed deployment settings plus per-invocation command-line values. */
|
||||
export interface Config {
|
||||
/** Whether this process mounted the client-plugin HMR receiver (`dsh web --dev`). */
|
||||
mode: WebMode
|
||||
@@ -49,22 +52,25 @@ export interface Config {
|
||||
* orientation text would be false.
|
||||
*/
|
||||
surfaceContext: boolean
|
||||
/**
|
||||
* LAN IPv4 addresses sampled once by the app startup row when the effective bind
|
||||
* is all-interfaces — the exact snapshot the /api trust fence was
|
||||
* configured with, so the printed LAN URL can never name an address the
|
||||
* fence rejects. Empty on a loopback bind.
|
||||
*/
|
||||
lanAddresses: string[]
|
||||
/** Explicit `--trusted-host` authorities from this invocation. */
|
||||
trustedHosts: string[]
|
||||
}
|
||||
|
||||
export const Config: z<Config> = z.object({
|
||||
mode: z.union([z.const('production'), z.const('development')]).default('production'),
|
||||
printUrl: z.boolean().default(true),
|
||||
surfaceContext: z.boolean().default(true),
|
||||
lanAddresses: z.array(String).default([]),
|
||||
trustedHosts: z.array(String).default([]),
|
||||
})
|
||||
|
||||
/** Bind-dependent Web values shared by the trust fence and URL display. */
|
||||
export interface WebRuntimeValues {
|
||||
/** LAN IPv4 literals sampled once when the server binds all interfaces. */
|
||||
lanAddresses: string[]
|
||||
/** LAN literals followed by explicit invocation authorities. */
|
||||
trustedHosts: string[]
|
||||
}
|
||||
|
||||
/** Environment variable naming the canonical local URL of this Web GUI. */
|
||||
const DSH_WEB_URL = 'DSH_WEB_URL' as const
|
||||
/** Environment variable naming the Web runtime mode. */
|
||||
@@ -73,6 +79,27 @@ const DSH_WEB_MODE = 'DSH_WEB_MODE' as const
|
||||
// Display-only mirror of the webserver schema's loopback host: the address the
|
||||
// local URL always prints. Not a source of truth — the schema is.
|
||||
const LOOPBACK_HOST = '127.0.0.1'
|
||||
/** The webserver schema's all-interfaces bind literal. */
|
||||
const ALL_INTERFACES_HOST = '0.0.0.0'
|
||||
|
||||
/**
|
||||
* Resolve one LAN-trust snapshot from the active server bind.
|
||||
*
|
||||
* Derived entries are port-less IP literals: DNS rebinding needs an
|
||||
* attacker-controlled name, while an IP-literal Host is safe on any port and
|
||||
* an OS-assigned port is unknowable before bind.
|
||||
* @param bindHost - the active webserver bind host.
|
||||
* @param extra - explicit `--trusted-host` values, in argument order.
|
||||
* @returns the LAN display addresses and invocation-derived fence authorities.
|
||||
*/
|
||||
export function resolveLanTrust(bindHost: string, extra: readonly string[]): WebRuntimeValues {
|
||||
const lanAddresses = bindHost === ALL_INTERFACES_HOST
|
||||
? Object.values(networkInterfaces()).flat()
|
||||
.filter((iface): iface is NonNullable<typeof iface> => iface !== undefined && iface.family === 'IPv4' && !iface.internal)
|
||||
.map(iface => iface.address)
|
||||
: []
|
||||
return { lanAddresses, trustedHosts: [...lanAddresses, ...extra] }
|
||||
}
|
||||
|
||||
/** Model-visible orientation and acceptance boundary for sessions created through `dsh web`. */
|
||||
function webSurfacePrompt(webUrl: string, mode: WebMode): string {
|
||||
@@ -124,8 +151,10 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
||||
// fiber. Otherwise its first browser graph omits the reload receiver, which
|
||||
// cannot use that receiver to discover itself later.
|
||||
if (config.mode === 'development') await enableRow(ctx, HMR_ROW_ID)
|
||||
// Release client discovery only after the optional row has a pending fiber.
|
||||
ctx.provide(CLIENT_ROSTER_SERVICE, true)
|
||||
const runtime = resolveLanTrust(ctx.httpServer.host, config.trustedHosts)
|
||||
// Release dependent rows only after the optional row has a pending fiber and
|
||||
// bind-dependent trust has been sampled once.
|
||||
ctx.provide(WEB_RUNTIME_SERVICE, runtime)
|
||||
ctx.plugin(FrontendStatic, { distIndex: internals.resolveDistIndex() })
|
||||
if (config.surfaceContext) {
|
||||
ctx.inject(['systemPrompt'], (promptCtx) => {
|
||||
@@ -153,9 +182,8 @@ export async function apply(ctx: Context, config: Config): Promise<void> {
|
||||
// sibling rows (the /api route owner) are still mounting. Await Loader
|
||||
// settlement first; a hand-built tree without a Loader prints at once.
|
||||
const printUrl = (): void => {
|
||||
// The startup row's boot-time LAN snapshot, not a fresh sample: the printed
|
||||
// LAN URL must name an address the /api trust fence was configured with.
|
||||
const lanCandidate = config.lanAddresses[0]
|
||||
// Reuse the exact LAN snapshot provided to the /api trust fence.
|
||||
const lanCandidate = runtime.lanAddresses[0]
|
||||
const port = ctx.httpServer.port
|
||||
console.log(`dsh web: ${localWebUrl(ctx)}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${String(port)})`}`)
|
||||
}
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
/**
|
||||
* The web app's startup row: it owns the `dsh --profile web` flag family
|
||||
* (`--host`, `--port`, `--dev`, `--trusted-host`) and its `--help` text,
|
||||
* turns those flags into changes on the rows that inject
|
||||
* {@link WEB_STARTUP_SERVICE}, and then provides it. Until it does, no
|
||||
* flag-configured web row starts, so `dsh --profile web --help` prints this
|
||||
* command's help and the server never binds.
|
||||
* The web app's command-line provider: it parses the `dsh --profile web` flag
|
||||
* family (`--host`, `--port`, `--dev`, `--trusted-host`) and its `--help`
|
||||
* text, then provides the immutable values as {@link WEB_STARTUP_SERVICE}.
|
||||
* Ordinary rows inject that service before reading it from lazy config.
|
||||
* @module @deepseek-ai/dsh-web-app/startup
|
||||
*/
|
||||
|
||||
import { networkInterfaces } from 'node:os'
|
||||
import { Command } from 'commander'
|
||||
import type { Context } from 'cordis'
|
||||
import { interpolate, type EntryOptions } from '@cordisjs/plugin-loader'
|
||||
import { runStartup } from '@deepseek-ai/dsh-cmdline'
|
||||
import { parseCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
|
||||
/** Stable Cordis plugin name. */
|
||||
export const name = 'web-startup'
|
||||
@@ -20,11 +16,7 @@ export const name = 'web-startup'
|
||||
/** Services required before the flags can be resolved. */
|
||||
export const inject = ['cmdlineArgs']
|
||||
|
||||
/**
|
||||
* The service this row provides and every flag-configured web row reads. The
|
||||
* rows are listed in this bundle's `cordis.patch.yml`, where each names the key
|
||||
* it takes from here and the value it falls back to.
|
||||
*/
|
||||
/** Service provided by this ordinary plugin and injected by flag-configured rows. */
|
||||
export const WEB_STARTUP_SERVICE = 'webStartup'
|
||||
|
||||
/** What the web rows read from {@link WEB_STARTUP_SERVICE}. */
|
||||
@@ -35,63 +27,8 @@ export interface WebStartupValues {
|
||||
port?: number
|
||||
/** Web runtime mode; `--dev` selects development, which also mounts the client-plugin reload chain. */
|
||||
mode: 'production' | 'development'
|
||||
/**
|
||||
* The `/api` fence authorities for this invocation: the LAN literals an
|
||||
* all-interfaces bind derived, plus the `--trusted-host` extras, over what
|
||||
* the composition already configured.
|
||||
*/
|
||||
/** Explicit `--trusted-host` authorities, in argument order. */
|
||||
trustedHosts: string[]
|
||||
/** The LAN literals the fence was configured with, for display. */
|
||||
lanAddresses: string[]
|
||||
}
|
||||
|
||||
/** The webserver schema's all-interfaces bind literal: only this bind derives LAN authorities. */
|
||||
const ALL_INTERFACES_HOST = '0.0.0.0'
|
||||
|
||||
/**
|
||||
* Read the deployment trust list before its row mounts and validates config.
|
||||
* @param config - the connection row's config resolved before `webStartup` exists.
|
||||
* @returns its configured authorities, or an empty list when absent.
|
||||
* @throws when the file-backed config is not an array of strings.
|
||||
*/
|
||||
function configuredTrustedHosts(config: unknown): string[] {
|
||||
const value = (config as { trustedHosts?: unknown } | undefined)?.trustedHosts
|
||||
if (value === undefined) return []
|
||||
const valid = Array.isArray(value) && value.every((entry: unknown) => typeof entry === 'string')
|
||||
if (!valid) throw new Error('web-startup: the composed connection trustedHosts must be an array of strings')
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-internal IPv4 interface addresses of this machine — the IP-literal
|
||||
* authorities an all-interfaces bind is reachable by on the LAN.
|
||||
* @returns the addresses in interface order (possibly empty).
|
||||
*/
|
||||
function lanIPv4Addresses(): string[] {
|
||||
return Object.values(networkInterfaces()).flat()
|
||||
.filter((iface): iface is NonNullable<typeof iface> => iface !== undefined && iface.family === 'IPv4' && !iface.internal)
|
||||
.map(iface => iface.address)
|
||||
}
|
||||
|
||||
/**
|
||||
* One LAN-trust resolution for one invocation, sampled exactly once: the
|
||||
* machine's LAN IP literals when the effective bind is all-interfaces, and the
|
||||
* `trustedHosts` value built from them plus the explicit extras. The single
|
||||
* sample is deliberate — display must advertise only addresses the fence was
|
||||
* configured with, so the `web-runtime` row receives this same snapshot.
|
||||
* Derived entries are port-less IP literals: DNS rebinding needs an
|
||||
* attacker-controlled name, so an IP-literal Host is safe on any port, and the
|
||||
* bound port may be OS-assigned, unknowable before the server binds.
|
||||
* @param bindHost - the effective webserver bind host (the flag, else the composed row value).
|
||||
* @param extra - `--trusted-host` values, in argv order.
|
||||
* @returns the sampled LAN addresses and the connection row's `trustedHosts` value (each possibly empty).
|
||||
*/
|
||||
export function resolveLanTrust(
|
||||
bindHost: string | undefined,
|
||||
extra: readonly string[],
|
||||
): { lanAddresses: string[]; trustedHosts: string[] } {
|
||||
const lanAddresses = bindHost === ALL_INTERFACES_HOST ? lanIPv4Addresses() : []
|
||||
return { lanAddresses, trustedHosts: [...lanAddresses, ...extra] }
|
||||
}
|
||||
|
||||
/** The web flag family, as commander parsed it. */
|
||||
@@ -125,51 +62,29 @@ Examples:
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the parsed flags into the values the web rows read.
|
||||
* Turn the parsed flags into the value injected rows read.
|
||||
* @param program - the parsed web command.
|
||||
* @param rows - the waiting rows' composed options, in tree order.
|
||||
* @param ctx - the startup context used to resolve composed fallbacks before `webStartup` exists.
|
||||
* @returns the web rows' service value.
|
||||
* @returns this invocation's immutable Web options.
|
||||
*/
|
||||
function planWebStartup(program: Command, rows: readonly EntryOptions[], ctx: Context): WebStartupValues {
|
||||
function planWebStartup(program: Command): WebStartupValues {
|
||||
const options = program.opts<WebOptions>()
|
||||
if (options.port !== undefined && !/^\d+$/.test(options.port)) {
|
||||
program.error(`error: --port must be a number, got ${JSON.stringify(options.port)}`)
|
||||
}
|
||||
const row = (id: string): EntryOptions => {
|
||||
const found = rows.find(candidate => candidate.id === id)
|
||||
if (found === undefined) throw new Error(`web-startup: the web composition has no waiting ${JSON.stringify(id)} row to configure`)
|
||||
return found
|
||||
}
|
||||
const webserver = row('webserver')
|
||||
row('web-runtime')
|
||||
const connection = row('connection')
|
||||
// Include preserves nested row expressions until their own injections are
|
||||
// active. Resolve just the composed fields this startup plan needs against
|
||||
// the pre-service context, where their `ctx.get('webStartup')` fallback wins.
|
||||
const webserverConfig = interpolate(ctx, webserver.config) as { host?: string } | undefined
|
||||
const connectionConfig: unknown = interpolate(ctx, connection.config)
|
||||
const bindHost = options.host ?? webserverConfig?.host
|
||||
const sampled = resolveLanTrust(bindHost, options.trustedHost ?? [])
|
||||
// Preserve deployment authorities when invocation-derived LAN literals or
|
||||
// explicit extras become the runtime value read by the connection row.
|
||||
const composedTrusted = configuredTrustedHosts(connectionConfig)
|
||||
return {
|
||||
...options.host !== undefined && { host: options.host },
|
||||
...options.port !== undefined && { port: Number(options.port) },
|
||||
// mode and lanAddresses describe this invocation, never the deployment, so
|
||||
// they are resolved on every boot.
|
||||
mode: options.dev === true ? 'development' : 'production',
|
||||
trustedHosts: [...composedTrusted, ...sampled.trustedHosts],
|
||||
lanAddresses: sampled.lanAddresses,
|
||||
trustedHosts: options.trustedHost ?? [],
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the web flag family for rows waiting on `webStartup`.
|
||||
* @param ctx - plugin context carrying the command line and the Loader.
|
||||
* @returns nothing once the values are provided, or once `--help` requested exit.
|
||||
* Parse and provide the Web invocation as an ordinary Cordis service.
|
||||
* @param ctx - plugin context carrying the command line.
|
||||
* @returns nothing once values are provided, or when the command requested exit.
|
||||
*/
|
||||
export function apply(ctx: Context): void {
|
||||
runStartup(ctx, WEB_STARTUP_SERVICE, webCommand(), planWebStartup)
|
||||
const values = parseCmdline(ctx, webCommand(), planWebStartup)
|
||||
if (values !== undefined) ctx.provide(WEB_STARTUP_SERVICE, values)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/**
|
||||
* The web app's startup row over a REAL Loader tree: every flag lands in the
|
||||
* `webStartup` service the web rows read, the bind it reports comes from the
|
||||
* flag or from what the composition falls back to, `--help` resolves nothing,
|
||||
* and a rejected argument exits without resolving anything.
|
||||
* The Web command-line provider over a real Loader tree: its ordinary service
|
||||
* releases a consumer whose config reads `ctx.webStartup` directly.
|
||||
*/
|
||||
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs'
|
||||
@@ -13,21 +11,14 @@ import { Context } from 'cordis'
|
||||
import Loader from '@cordisjs/plugin-loader'
|
||||
import Include from '@cordisjs/plugin-include'
|
||||
import { internals, provideCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { apply, WEB_STARTUP_SERVICE, type WebStartupValues } from '../src/startup.ts'
|
||||
|
||||
vi.mock('node:os', async importOriginal => ({
|
||||
...await importOriginal<typeof import('node:os')>(),
|
||||
networkInterfaces: () => ({
|
||||
lo0: [{ family: 'IPv4', internal: true, address: '127.0.0.1' }],
|
||||
en0: [{ family: 'IPv4', internal: false, address: '192.168.1.5' }],
|
||||
}),
|
||||
}))
|
||||
|
||||
/** What one boot of the fixture tree observed. */
|
||||
/** What one fixture boot observed. */
|
||||
interface Observed {
|
||||
exits: number[]
|
||||
out: string
|
||||
readerConfig?: unknown
|
||||
}
|
||||
|
||||
const disposers: (() => Promise<void>)[] = []
|
||||
@@ -39,67 +30,48 @@ afterEach(async () => {
|
||||
})
|
||||
|
||||
/**
|
||||
* Mount the real startup row over a stand-in for the `webserver` row whose
|
||||
* composed bind it reads before the dependent rows activate.
|
||||
* Mount the real provider and a consumer using injection-ordered config.
|
||||
* @param args - the invocation's inner arguments.
|
||||
* @param webserverConfig - the composed `webserver` row config, or `null` to omit the row.
|
||||
* @param trustedHosts - authorities the composed connection row already carries, or `null` when it carries none.
|
||||
* @returns the resolved service value (absent when the app requested exit) and what the boot observed.
|
||||
* @returns the service value and observed consumer/process effects.
|
||||
*/
|
||||
async function bootStartup(
|
||||
args: string[],
|
||||
webserverConfig: Record<string, unknown> | null = { host: '127.0.0.1', port: 3080 },
|
||||
trustedHosts: unknown = [],
|
||||
): Promise<{ values: WebStartupValues | undefined; observed: Observed; ctx: Context }> {
|
||||
async function bootProvider(args: string[]): Promise<{
|
||||
values: WebStartupValues | undefined
|
||||
observed: Observed
|
||||
}> {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'dsh-web-startup-'))
|
||||
const observed: Observed = { exits: [], out: '' }
|
||||
writeFileSync(join(dir, 'row.mjs'), 'export function apply() {}\n')
|
||||
// The Loader imports a row through Node's own resolver, which cannot resolve
|
||||
// this workspace's sources; the row delegates to the real plugin the test
|
||||
// imported through the source-plane path mapping.
|
||||
writeFileSync(join(dir, 'startup.mjs'), `
|
||||
writeFileSync(join(dir, 'reader.mjs'), `
|
||||
export function apply(_ctx, config) { globalThis.__webStartupObserved.readerConfig = config }
|
||||
`)
|
||||
// Node imports the fixture row outside Vite's source resolver, so delegate
|
||||
// to the source-plane plugin already imported by this test.
|
||||
writeFileSync(join(dir, 'provider.mjs'), `
|
||||
export const name = 'web-startup'
|
||||
export const inject = ['cmdlineArgs']
|
||||
export const apply = ctx => globalThis.__webStartupApply(ctx)
|
||||
`)
|
||||
const rowUrl = pathToFileURL(join(dir, 'row.mjs')).href
|
||||
writeFileSync(join(dir, 'cordis.yml'), [
|
||||
...webserverConfig === null ? [] : [
|
||||
'- id: webserver',
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${WEB_STARTUP_SERVICE}]`,
|
||||
' disabled: true',
|
||||
' config:',
|
||||
...Object.entries(webserverConfig).map(([key, value]) => ` ${key}: !!js ctx.get('${WEB_STARTUP_SERVICE}')?.${key} ?? ${JSON.stringify(value)}`),
|
||||
],
|
||||
'- id: connection',
|
||||
` name: ${rowUrl}`,
|
||||
'- id: reader',
|
||||
` name: ${pathToFileURL(join(dir, 'reader.mjs')).href}`,
|
||||
` inject: [${WEB_STARTUP_SERVICE}]`,
|
||||
' disabled: true',
|
||||
...trustedHosts === null ? [] : [
|
||||
' config:',
|
||||
` trustedHosts: !!js ctx.get('${WEB_STARTUP_SERVICE}')?.trustedHosts ?? ${JSON.stringify(trustedHosts)}`,
|
||||
],
|
||||
// A second reader keeps the composition honest when the webserver row is
|
||||
// the one under test: the service must still have someone to serve.
|
||||
'- id: web-runtime',
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${WEB_STARTUP_SERVICE}]`,
|
||||
' disabled: true',
|
||||
// The reload chain this bundle ships off, which `--dev` turns on.
|
||||
'- id: client-hmr',
|
||||
` name: ${rowUrl}`,
|
||||
` inject: [${WEB_STARTUP_SERVICE}]`,
|
||||
' disabled: true',
|
||||
'- id: web-startup',
|
||||
` name: ${pathToFileURL(join(dir, 'startup.mjs')).href}`,
|
||||
' inject: [cmdlineArgs]',
|
||||
' config:',
|
||||
" host: !!js ctx.webStartup.host ?? '127.0.0.1'",
|
||||
' port: !!js ctx.webStartup.port ?? 3080',
|
||||
' mode: !!js ctx.webStartup.mode',
|
||||
' trustedHosts: !!js ctx.webStartup.trustedHosts',
|
||||
'- id: provider',
|
||||
` name: ${pathToFileURL(join(dir, 'provider.mjs')).href}`,
|
||||
'',
|
||||
].join('\n'))
|
||||
const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
|
||||
internals.stdout = observing
|
||||
internals.stderr = observing
|
||||
;(globalThis as unknown as { __webStartupApply: typeof apply }).__webStartupApply = apply
|
||||
const globals = globalThis as unknown as {
|
||||
__webStartupApply: typeof apply
|
||||
__webStartupObserved: Observed
|
||||
}
|
||||
globals.__webStartupApply = apply
|
||||
globals.__webStartupObserved = observed
|
||||
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(Loader)
|
||||
@@ -108,89 +80,56 @@ export const apply = ctx => globalThis.__webStartupApply(ctx)
|
||||
await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(join(dir, 'cordis.yml')).href } })
|
||||
await ctx.loader.await()
|
||||
disposers.push(async () => { await ctx.fiber.dispose() })
|
||||
return { values: ctx.get(WEB_STARTUP_SERVICE) as WebStartupValues | undefined, observed, ctx }
|
||||
return {
|
||||
values: ctx.get(WEB_STARTUP_SERVICE) as WebStartupValues | undefined,
|
||||
observed,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
describe('web startup', () => {
|
||||
it('resolves each flag into the value its row reads', async () => {
|
||||
const { values } = await bootStartup(['--port', '8080'])
|
||||
describe('web command-line provider', () => {
|
||||
it('publishes each flag and releases direct service expressions', async () => {
|
||||
const { values, observed } = await bootProvider([
|
||||
'--host', '0.0.0.0',
|
||||
'--port', '8080',
|
||||
'--dev',
|
||||
'--trusted-host', 'lab.internal', 'lab-2.internal',
|
||||
'--trusted-host', '10.0.0.9',
|
||||
])
|
||||
expect(values).toEqual({
|
||||
host: '0.0.0.0',
|
||||
port: 8080,
|
||||
mode: 'development',
|
||||
trustedHosts: ['lab.internal', 'lab-2.internal', '10.0.0.9'],
|
||||
})
|
||||
expect(observed.readerConfig).toEqual(values)
|
||||
expect(observed.exits).toEqual([])
|
||||
})
|
||||
|
||||
it('leaves deployment values to each consumer when flags omit them', async () => {
|
||||
const { values, observed } = await bootProvider([])
|
||||
expect(values).toEqual({ mode: 'production', trustedHosts: [] })
|
||||
expect(observed.readerConfig).toEqual({
|
||||
host: '127.0.0.1',
|
||||
port: 3080,
|
||||
mode: 'production',
|
||||
trustedHosts: [],
|
||||
lanAddresses: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('names no value for a flag the invocation left out, so each row keeps its own', async () => {
|
||||
const { values } = await bootStartup([])
|
||||
expect(values).toEqual({ mode: 'production', trustedHosts: [], lanAddresses: [] })
|
||||
expect(values).not.toHaveProperty('host')
|
||||
expect(values).not.toHaveProperty('port')
|
||||
})
|
||||
|
||||
it('adds LAN literals and explicit extras after the composed fence authorities', async () => {
|
||||
const { values } = await bootStartup(
|
||||
['--host', '0.0.0.0', '--trusted-host', 'lab.internal', 'lab-2.internal', '--trusted-host', '10.0.0.9'],
|
||||
{ host: '127.0.0.1', port: 3080 },
|
||||
['profile.internal'],
|
||||
)
|
||||
expect(values?.trustedHosts).toEqual([
|
||||
'profile.internal', '192.168.1.5', 'lab.internal', 'lab-2.internal', '10.0.0.9',
|
||||
])
|
||||
// Display gets the same single sample the fence was configured with.
|
||||
expect(values?.lanAddresses).toEqual(['192.168.1.5'])
|
||||
})
|
||||
|
||||
it('starts from an empty trust list when the composed connection row names none', async () => {
|
||||
const { values } = await bootStartup(
|
||||
['--trusted-host', 'lab.internal'],
|
||||
{ host: '127.0.0.1', port: 3080 },
|
||||
null,
|
||||
)
|
||||
expect(values?.trustedHosts).toEqual(['lab.internal'])
|
||||
})
|
||||
|
||||
it.each([
|
||||
'profile.internal',
|
||||
['profile.internal', 1],
|
||||
])('rejects an invalid composed trust list before transforming it (%j)', async (trustedHosts) => {
|
||||
await expect(bootStartup([], { host: '127.0.0.1', port: 3080 }, trustedHosts))
|
||||
.rejects.toThrow('the composed connection trustedHosts must be an array of strings')
|
||||
})
|
||||
|
||||
it('reads the composed bind when no flag names one, so a configured 0.0.0.0 still derives them', async () => {
|
||||
const { values } = await bootStartup([], { host: '0.0.0.0', port: 3080 })
|
||||
expect(values?.lanAddresses).toEqual(['192.168.1.5'])
|
||||
})
|
||||
|
||||
it('reports the development mode for --dev, which the web runtime reads', async () => {
|
||||
const { values } = await bootStartup(['--dev'])
|
||||
// The runtime row turns the reload chain on after its host dependencies
|
||||
// activate; this row only reports the mode.
|
||||
expect(values?.mode).toBe('development')
|
||||
})
|
||||
|
||||
it('prints its own help and resolves nothing', async () => {
|
||||
const { values, observed } = await bootStartup(['--help'])
|
||||
it('prints its own help and leaves the consumer pending', async () => {
|
||||
const { values, observed } = await bootProvider(['--help'])
|
||||
expect(observed.out).toContain('dsh --profile web')
|
||||
expect(observed.out).toContain('--trusted-host')
|
||||
expect(values).toBeUndefined()
|
||||
expect(observed.readerConfig).toBeUndefined()
|
||||
expect(observed.exits).toEqual([0])
|
||||
})
|
||||
|
||||
it('rejects a non-numeric port before anything binds', async () => {
|
||||
const { values, observed } = await bootStartup(['--port', 'abc'])
|
||||
it('rejects a non-numeric port before the consumer activates', async () => {
|
||||
const { values, observed } = await bootProvider(['--port', 'abc'])
|
||||
expect(observed.out).toContain('--port must be a number')
|
||||
expect(values).toBeUndefined()
|
||||
expect(observed.readerConfig).toBeUndefined()
|
||||
expect(observed.exits).toEqual([1])
|
||||
})
|
||||
|
||||
it('fails the boot when the composition lost the row whose bind it reads', async () => {
|
||||
// The bundle patch and this startup row must agree on the row set; a
|
||||
// missing row would otherwise silently drop the flag that targets it.
|
||||
await expect(bootStartup([], null))
|
||||
.rejects.toThrow('the web composition has no waiting "webserver" row to configure')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Single-sample LAN-trust resolution for the /api browser-trust fence (`resolveLanTrust`). */
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { resolveLanTrust } from '../src/startup.ts'
|
||||
import { resolveLanTrust } from '../src/index.ts'
|
||||
|
||||
vi.mock('node:os', () => ({
|
||||
networkInterfaces: () => ({
|
||||
@@ -26,8 +26,9 @@ describe('resolveLanTrust', () => {
|
||||
expect(trustedHosts).toEqual(['192.168.1.5', '10.0.0.7', 'harness.internal:3080'])
|
||||
})
|
||||
|
||||
it('derives nothing for a loopback or unresolved bind — extras alone stand, no LAN URL to print', () => {
|
||||
it('derives nothing for a loopback bind — extras alone stand, no LAN URL to print', () => {
|
||||
expect(resolveLanTrust('127.0.0.1', [])).toEqual({ lanAddresses: [], trustedHosts: [] })
|
||||
expect(resolveLanTrust(undefined, ['lab.internal'])).toEqual({ lanAddresses: [], trustedHosts: ['lab.internal'] })
|
||||
expect(resolveLanTrust('127.0.0.1', ['lab.internal']))
|
||||
.toEqual({ lanAddresses: [], trustedHosts: ['lab.internal'] })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* Web runtime glue behavior: dist resolution through the bundle's own hook,
|
||||
* the frontend-static child claiming the fallback seat, the web-surface
|
||||
* prompt section and bash runtime variables, and URL-line printing with the
|
||||
* app startup row's LAN snapshot.
|
||||
* runtime's bind-dependent LAN snapshot.
|
||||
*/
|
||||
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
|
||||
@@ -14,6 +14,14 @@ import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import type { HttpServerService } from '@deepseek-ai/dsh-host-webserver'
|
||||
import { apply, Config, internals } from '../src/index.ts'
|
||||
|
||||
vi.mock('node:os', async importOriginal => ({
|
||||
...await importOriginal<typeof import('node:os')>(),
|
||||
networkInterfaces: () => ({
|
||||
lo0: [{ family: 'IPv4', internal: true, address: '127.0.0.1' }],
|
||||
en0: [{ family: 'IPv4', internal: false, address: '192.168.1.5' }],
|
||||
}),
|
||||
}))
|
||||
|
||||
let dist: string | undefined
|
||||
|
||||
afterEach(() => {
|
||||
@@ -36,9 +44,10 @@ function stageDist(): string {
|
||||
}
|
||||
|
||||
/** A fake httpServer capturing the fallback seat and index taps. */
|
||||
function fakeHttpServer(): { server: HttpServerService; seat: () => unknown } {
|
||||
function fakeHttpServer(host: '127.0.0.1' | '0.0.0.0' = '127.0.0.1'): { server: HttpServerService; seat: () => unknown } {
|
||||
let fallback: unknown
|
||||
const server = {
|
||||
host,
|
||||
port: 4567,
|
||||
registerFallback: (handler: unknown) => {
|
||||
fallback = handler
|
||||
@@ -72,7 +81,7 @@ describe('web-app runtime glue', () => {
|
||||
it('mounts dist serving, prompt section, bash variables, and prints the URL with the LAN snapshot', async () => {
|
||||
stageDist()
|
||||
const ctx = new Context()
|
||||
const { server, seat } = fakeHttpServer()
|
||||
const { server, seat } = fakeHttpServer('0.0.0.0')
|
||||
ctx.provide('httpServer', server)
|
||||
const contributions: BashContribution[] = []
|
||||
ctx.provide('bashEnv', {
|
||||
@@ -83,14 +92,17 @@ describe('web-app runtime glue', () => {
|
||||
} as never)
|
||||
const enabledRows = provideHmrRow(ctx)
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
await apply(ctx, new Config({ mode: 'development', printUrl: true, surfaceContext: true, lanAddresses: ['192.168.1.5'] }))
|
||||
await apply(ctx, new Config({ mode: 'development', printUrl: true, surfaceContext: true, trustedHosts: ['lab.internal'] }))
|
||||
await ctx.plugin(SystemPrompt, { persona: '' })
|
||||
// Settle the injected registrations.
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
|
||||
expect(seat()).toBeDefined() // frontend-static claimed the fallback
|
||||
expect(enabledRows).toEqual(['client-hmr'])
|
||||
expect(ctx.get('webClientRoster')).toBe(true)
|
||||
expect(ctx.get('webRuntime')).toEqual({
|
||||
lanAddresses: ['192.168.1.5'],
|
||||
trustedHosts: ['192.168.1.5', 'lab.internal'],
|
||||
})
|
||||
expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567 (LAN: http://192.168.1.5:4567)')
|
||||
const assembly = await ctx.systemPrompt.assemble()
|
||||
expect(assembly.sections.find(entry => entry.name === 'harness:source')?.text).toContain('DeepSeek Harness implementation checkout')
|
||||
@@ -107,7 +119,7 @@ describe('web-app runtime glue', () => {
|
||||
const ctx = new Context()
|
||||
ctx.provide('httpServer', fakeHttpServer().server)
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: true, lanAddresses: [] }))
|
||||
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: true, trustedHosts: [] }))
|
||||
await ctx.plugin(SystemPrompt, { persona: '' })
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(log).not.toHaveBeenCalled()
|
||||
@@ -128,7 +140,7 @@ describe('web-app runtime glue', () => {
|
||||
return () => {}
|
||||
},
|
||||
} as never)
|
||||
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: false, lanAddresses: [] }))
|
||||
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: false, trustedHosts: [] }))
|
||||
await ctx.plugin(SystemPrompt, { persona: '' })
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
const assembly = await ctx.systemPrompt.assemble()
|
||||
@@ -143,7 +155,7 @@ describe('web-app runtime glue', () => {
|
||||
const ctx = new Context()
|
||||
ctx.provide('httpServer', fakeHttpServer().server)
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
await apply(ctx, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
|
||||
await apply(ctx, new Config({ mode: 'production', printUrl: true, surfaceContext: true, trustedHosts: [] }))
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(log).toHaveBeenCalledWith('dsh web: http://127.0.0.1:4567')
|
||||
await ctx.fiber.dispose()
|
||||
@@ -159,7 +171,7 @@ describe('web-app runtime glue', () => {
|
||||
const settlement = new Promise<void>((resolve) => { release = resolve })
|
||||
provideHmrRow(settled, () => settlement)
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
await apply(settled, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
|
||||
await apply(settled, new Config({ mode: 'production', printUrl: true, surfaceContext: true, trustedHosts: [] }))
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(log).not.toHaveBeenCalled()
|
||||
release!()
|
||||
@@ -173,7 +185,7 @@ describe('web-app runtime glue', () => {
|
||||
const failed = new Context()
|
||||
failed.provide('httpServer', fakeHttpServer().server)
|
||||
provideHmrRow(failed, async () => { throw new Error('boot failed') })
|
||||
await apply(failed, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
|
||||
await apply(failed, new Config({ mode: 'production', printUrl: true, surfaceContext: true, trustedHosts: [] }))
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
expect(log).not.toHaveBeenCalled()
|
||||
await failed.fiber.dispose()
|
||||
@@ -189,7 +201,7 @@ describe('web-app runtime glue', () => {
|
||||
let releaseTorn: () => void
|
||||
const tornSettlement = new Promise<void>((resolve) => { releaseTorn = resolve })
|
||||
provideHmrRow(torn, () => tornSettlement)
|
||||
await apply(torn, new Config({ mode: 'production', printUrl: true, surfaceContext: true, lanAddresses: [] }))
|
||||
await apply(torn, new Config({ mode: 'production', printUrl: true, surfaceContext: true, trustedHosts: [] }))
|
||||
await child.dispose() // the httpServer service goes away
|
||||
releaseTorn!()
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
@@ -205,7 +217,7 @@ describe('web-app runtime glue', () => {
|
||||
const { server } = fakeHttpServer()
|
||||
Object.defineProperty(server, 'port', { get: () => undefined })
|
||||
ctx.provide('httpServer', server)
|
||||
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: true, lanAddresses: [] }))
|
||||
await apply(ctx, new Config({ mode: 'production', printUrl: false, surfaceContext: true, trustedHosts: [] }))
|
||||
await ctx.plugin(SystemPrompt, { persona: '' })
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
await expect(ctx.systemPrompt.assemble()).rejects.toThrow('httpServer service missing')
|
||||
|
||||
Reference in New Issue
Block a user