refactor(cmdline): make command providers ordinary

This commit is contained in:
Turtle
2026-08-10 21:49:11 +08:00
parent 668bdb3d8e
commit 09e2d2ddc1
46 changed files with 400 additions and 742 deletions

View File

@@ -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/boot/cmdline/README.md
README.md: a1512ae3357f06cd4de6347ea5ec2197fea40a90
README.zh.md: e27060db433e5c234febb28d6c120d75f82072cc
README.md: 98335e901bdf8fe33e14c1ad4c1a320d77f30c96
README.zh.md: 28ea749943c60089c6b4725cb61e121f82aa0114

View File

@@ -13,30 +13,28 @@ A launcher calls `provideCmdline(ctx, host)` before any tree entry mounts, which
An embedding host with no command line provides an empty list; that is the honest answer, not a missing value.
## Startup rows, and the service their app reads
## Ordinary providers and injected config
An app reads those arguments from its **startup row** — a Loader row and plugin that inject `cmdlineArgs` and calls `runStartup(ctx, service, program, plan)`:
Any app plugin may inject `cmdlineArgs`, parse it, and publish an ordinary app-owned service. `parseCmdline(ctx, program, plan)` is only a commander adapter; the caller owns the returned value and service:
```ts ignore
export const name = 'web-startup'
export const inject = ['cmdlineArgs']
export function apply(ctx: Context): void {
runStartup(ctx, 'webStartup', webCommand(), planWebStartup)
const values = parseCmdline(ctx, webCommand(), planWebStartup)
if (values !== undefined) ctx.provide('webStartup', values)
}
```
The Loader-row injection is also its discovery declaration, so no bundle manifest field is needed:
Its Loader row carries no launcher marker or special kind:
```yaml
- id: web-startup
name: '@deepseek-ai/dsh-web-app/startup'
inject: [cmdlineArgs]
```
The launcher uses that injection only to reject arguments for a composition with no command-line owner, and to reject a composition with multiple owners. Loader mounts the composition once and holds each row until its own injections are active.
Every row the app configures from flags then reads what the startup row resolved, naming the key it takes and the value it falls back to:
Every row configured from those values uses ordinary service injection and direct lazy config access:
```yaml
- id: webserver
@@ -47,9 +45,7 @@ Every row the app configures from flags then reads what the startup row resolved
port: !!js ctx.webStartup.port ?? 3080
```
`runStartup` parses the arguments, asks `plan` for the values, and provides them as the service. On `--help`, `--version`, a parse error, or a `program.error(...)` from the plan, it writes commander's text and requests exit — nothing is provided, so rows that depend on the startup service never activate.
`plan` receives the startup context and the options of every row that injects the service, for a value that has to take the composition into account. Include still holds nested expressions raw at this point, so a plan that needs a composed fallback can interpolate the relevant row config against the pre-service startup context; the `/api` fence authorities are the shipped example.
`parseCmdline` parses the immutable arguments and asks `plan` for the app-owned value. On `--help`, `--version`, a parse error, or a `program.error(...)` from the plan, it writes commander's text, requests exit, and returns `undefined`; the provider publishes nothing, so dependent rows never activate.
### How injection orders config
@@ -57,9 +53,9 @@ Loader defers a row's `!!js` interpolation until that row's declared injections
`enableRow(ctx, id)` turns on a row a bundle ships disabled because only some invocations want it (`dsh web --dev` and its client-plugin reload chain). The activation is an in-memory override: it does not rewrite the row's configured `disabled` value and survives config reapplication for that mounted entry. Loader applies the enabled row's ordinary injection ordering.
### One command line, one owner
### Shared immutable arguments
A composition has exactly one command-line owner. An app that layers over another one disables the underlying startup row and provides every startup service its retained rows inject.
`get()` does not consume or mutate argv. Multiple plugins can parse the same snapshot and independently provide services. The launcher does not inspect the composition for a command-line owner; a profile with no reader simply ignores its app arguments.
An out-of-tree plugin brings its own commander copy, so commander's control-flow errors are detected structurally rather than by class identity; an identity check would rethrow a printed help as a fatal load failure.
@@ -74,5 +70,5 @@ None; this package neither assembles nor sends a provider request.
## Known Limitations and Deferred Work
- **Launcher flags must precede app arguments.** The split is positional: the first token the launcher does not recognize starts the inner arguments, so `--patch` placed after an app flag belongs to the app. The launcher's parser consumes one `--`, so an app argument that must survive as a literal `--` needs `-- --`.
- **A startup service has no declared owner.** Reading rows name it and a `cmdlineArgs` consumer provides it; nothing links those two injections statically, so a bundle that ships reading rows without its startup row fails at settlement (pending entries naming the service) rather than at load.
- **An app-owned service has no statically declared provider.** Consumer rows name it through ordinary injection; a bundle that omits its provider fails at settlement with pending entries naming the service rather than at load.
- **A user patch that replaces a row's whole `config` drops its expressions.** A flag beats the value written beside it, not a literal a user wrote in place of the expression; keeping the expression is what keeps the flag winning.

View File

@@ -13,30 +13,28 @@ dsh 启动器交给它所引导应用的那条命令行。启动器只解析属
没有命令行的嵌入宿主提供空列表;这是诚实的答案,而不是缺失的值。
## 启动行,以及它的应用所读取的服务
## 普通提供方与注入配置
应用从自己的**启动行**读取这些参数:这是一个在 Loader 行与插件中都注入 `cmdlineArgs`,并调用 `runStartup(ctx, service, program, plan)` 的插件
任何应用插件都可以注入 `cmdlineArgs`、解析它,再发布一个普通的应用自有服务。`parseCmdline(ctx, program, plan)` 只适配 commander返回值与服务都归调用方持有
```ts ignore
export const name = 'web-startup'
export const inject = ['cmdlineArgs']
export function apply(ctx: Context): void {
runStartup(ctx, 'webStartup', webCommand(), planWebStartup)
const values = parseCmdline(ctx, webCommand(), planWebStartup)
if (values !== undefined) ctx.provide('webStartup', values)
}
```
Loader 行的注入同时也是发现声明,因此无需组合包 manifest 字段
它的 Loader 行不携带启动器标记,也没有特殊类型
```yaml
- id: web-startup
name: '@deepseek-ai/dsh-web-app/startup'
inject: [cmdlineArgs]
```
启动器只用该注入来拒绝那些没有命令行所有者却带有应用参数的组合以及拒绝存在多个所有者的组合。Loader 只挂载一次整套组合,并让每一行等待自身的注入激活。
应用用 flag 配置的每一行随后读取启动行解析出的取值,各自点名自己取用的键,以及回退时使用的值:
所有由这些取值配置的行都使用普通服务注入,并在惰性配置中直接访问该服务:
```yaml
- id: webserver
@@ -47,9 +45,7 @@ Loader 行的注入同时也是发现声明,因此无需组合包 manifest 字
port: !!js ctx.webStartup.port ?? 3080
```
`runStartup` 解析参数,向 `plan` 索取取值,并把它们作为服务提供出去。遇到 `--help`、`--version`、解析错误,或 `plan` 发出的 `program.error(...)` 时,它输出 commander 文本请求退出:什么也不会被提供,因此依赖启动服务的行不会激活。
`plan` 会收到启动上下文,以及所有注入该服务的行的选项,用于那些必须顾及组合本身的取值。此时 Include 仍保留着嵌套表达式的原始形态,因此需要组合回退值的 plan 可以基于服务提供前的启动上下文插值相关行配置;随附的例子是 `/api` 栅栏 authority。
`parseCmdline` 解析不可变参数,向 `plan` 索取应用自有取值。遇到 `--help`、`--version`、解析错误,或 `plan` 发出的 `program.error(...)` 时,它输出 commander 文本请求退出并返回 `undefined`;提供方什么也不发布,因此依赖行不会激活。
### 注入如何排列配置求值
@@ -57,9 +53,9 @@ Loader 会把一行的 `!!js` 插值推迟到该行声明的注入全部激活
`enableRow(ctx, id)` 打开某个组合包以禁用状态交付、只有部分调用才需要的行(`dsh web --dev` 及其客户端插件重载链路)。该激活是内存中的覆盖:它不会改写行所配置的 `disabled` 值并会在已挂载条目的配置重新应用后继续生效。Loader 会对启用后的行应用普通的注入顺序。
### 一条命令行,一个所有者
### 共享不可变参数
一套组合有且只有一个命令行所有者。叠加在另一应用之上的应用会禁用下层的启动行,并提供保留下来的各行所注入的全部启动服务
`get()` 不会消费或修改 argv。多个插件可以解析同一份快照并分别提供服务。启动器不会检查组合中的命令行所有者没有读取方的 profile 只会忽略自己的应用参数
树外插件会带来自己的一份 commander 副本,因此 commander 的控制流错误按结构识别,而不是按类身份识别;按身份判断会把已经打印出来的 help 重新抛成致命的加载失败。
@@ -74,5 +70,5 @@ Loader 会把一行的 `!!js` 插值推迟到该行声明的注入全部激活
## 已知限制与延期工作
- **启动器的 flag 必须写在应用参数之前**:切分按位置进行,启动器不认识的第一个 token 就是内层参数的起点,因此写在某个应用 flag 之后的 `--patch` 属于应用。启动器的解析器会消耗掉一个 `--`,因此必须以字面量 `--` 存活到应用的参数需要写成 `-- --`。
- **启动服务没有声明所有者**:读取行点名它,由 `cmdlineArgs` 消费方提供它;这两种注入之间没有静态关联,因此交付了读取行却缺少对应启动行的组合包会在结算时失败(出现指向该服务的待处理条目),而不是在加载时失败。
- **应用自有服务没有静态声明的提供方**:消费行通过普通注入点名它;缺少提供方的组合包会在结算时失败,由待处理条目点名该服务,而不是在加载时失败。
- **用户 patch 若整体替换某行的 `config`,会连同其中的表达式一起丢掉**flag 胜过的是表达式旁写着的那个值,而不是用户用字面量替换掉表达式之后的结果;保留表达式才能保留 flag 的优先级。

View File

@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-cmdline",
"description": "Command-line handoff between a dsh launcher and app bundles: cmdlineArgs exposes inner arguments, while injected startup rows parse them into app-owned runtime services",
"description": "Immutable command-line handoff from a dsh launcher to any app plugin that injects cmdlineArgs",
"version": "0.0.1",
"private": true,
"type": "module",
@@ -24,9 +24,6 @@
"lib/types/**/*.d.ts"
],
"license": "BSD-3-Clause",
"dependencies": {
"commander": "^15.0.0"
},
"peerDependencies": {
"@deepseek-ai/cordis-plugin-loader": "^1.0.0-rc.5",
"@deepseek-ai/dsh-invariants": "^0.0.1",
@@ -35,6 +32,7 @@
"devDependencies": {
"@deepseek-ai/cordis-plugin-include": "workspace:^",
"@deepseek-ai/cordis-plugin-loader": "workspace:^",
"commander": "^15.0.0",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/cordis": "^4.0.0-rc.7"
}

View File

@@ -7,22 +7,17 @@
* {@link CmdlineArgs} service, so an app owns its flag family, its `--help`
* text, and its parse errors instead of the launcher knowing them.
*
* An app consumes those arguments from a **startup plugin**: a row that
* injects `cmdlineArgs` and calls {@link runStartup}. What that plugin resolves
* becomes its own service, and the rows it configures read the values from
* there — `port: !!js ctx.webStartup.port ?? 3080` — so a flag beats
* the value written beside it. Nothing is handed back to the launcher.
*
* Loader delays each row's config interpolation until its declared injections
* are active. A startup row consumes `cmdlineArgs`, provides the app's resolved
* values, and thereby activates only the rows that depend on those values.
* Any app plugin can inject `cmdlineArgs` and call {@link parseCmdline}. A
* provider may publish the parsed values as its own service, and ordinary rows
* can inject that service and read it from lazily resolved config —
* `port: !!js ctx.webStartup.port ?? 3080` — so a flag beats the value written
* beside it. No row has launcher-level command-line status.
* @module @deepseek-ai/dsh-cmdline
*/
import type { Command } from 'commander'
import type { Context } from 'cordis'
import type { Entry, EntryOptions } from '@cordisjs/plugin-loader'
// Empty type import carries the loader Context merge used to walk the tree.
// Empty type import carries the Loader Context merge used by enableRow.
import type {} from '@cordisjs/plugin-loader'
/**
@@ -72,44 +67,11 @@ export interface CmdlineHost {
* @param host - the invocation's arguments and its exit request.
*/
export function provideCmdline(ctx: Context, host: CmdlineHost): void {
const snapshot = [...host.args]
const snapshot: readonly string[] = Object.freeze([...host.args])
ctx.provide('cmdlineArgs', { get: () => snapshot })
ctx.provide('appExit', host.exit)
}
/**
* Detect whether an active row consumes the launcher's command line.
*
* The Loader-row injection is the declaration: an active row that names
* `cmdlineArgs` owns startup for this composition. No bundle manifest field or
* plugin import is needed, so an out-of-tree app adds its command line by
* adding the same injection its startup plugin already requires.
* @param rows - the composed Loader rows.
* @returns whether this composition has a command-line owner.
* @throws when more than one active row claims the command line.
*/
export function hasCmdlineConsumer(rows: readonly EntryOptions[]): boolean {
const consumers: string[] = []
const visit = (entries: readonly EntryOptions[], ancestorDisabled = false, prefix = ''): void => {
for (const row of entries) {
const id = prefix + row.id
// Loader group containers stay active when disabled, but their children
// inherit that disabled state.
const active = row.group === true || (!ancestorDisabled && row.disabled !== true)
if (active && waitsForAny(row.inject, ['cmdlineArgs'])) consumers.push(id)
if (row.group === true && Array.isArray(row.config)) {
visit(row.config, ancestorDisabled || row.disabled === true, `${id}:`)
}
}
}
visit(rows)
if (consumers.length > 1) {
const ids = consumers.map(id => JSON.stringify(id)).join(', ')
throw new Error(`dsh-cmdline: multiple active rows inject cmdlineArgs (${ids}); disable all but one startup row`)
}
return consumers.length === 1
}
/** The process streams commander output is written to; production writes to the process. */
export const internals: { stdout: { write(chunk: string): unknown }; stderr: { write(chunk: string): unknown } } = {
stdout: process.stdout,
@@ -117,58 +79,36 @@ export const internals: { stdout: { write(chunk: string): unknown }; stderr: { w
}
/**
* Resolve this invocation into the values the app's rows read.
*
* Runs after a successful parse, with the waiting rows' composed options
* available for a value that has to take the composition into account (the
* `/api` fence authorities are the shipped example). Call `program.error(...)`
* to reject the invocation with a usage message instead of throwing.
* Resolve parsed arguments into an app-owned value. Call
* `program.error(...)` to reject the invocation with a usage message instead
* of throwing.
* @param program - the parsed commander program.
* @param rows - the waiting rows' composed options, in tree order.
* @param ctx - the startup row's context, for resolving composed fallbacks before the service exists.
* @returns the service value the app's rows read; `undefined` keys let a row's
* own fallback stand.
* @param ctx - the plugin context that received the command line.
* @returns the value an ordinary provider plugin may publish.
*/
export type StartupPlan<T = unknown> = (program: Command, rows: readonly EntryOptions[], ctx: Context) => T
export type CmdlinePlan<T = unknown> = (program: Command, ctx: Context) => T
/**
* Run one app's startup: parse the invocation's inner arguments with the app's
* own commander program and provide the resolved values as `service`. The
* Loader then activates the rows that were waiting for the provided service.
* Parse the launcher's immutable argument snapshot with an app's commander
* program. The caller decides whether and how to publish the returned value;
* this helper has no Loader-row or service ownership semantics.
*
* The rows read their values from the service, so nothing is written into
* their config from here: a row asks for `ctx.<service>.<key>` and
* falls back to the value written beside it, which is why a flag wins. Loader
* resolves a row's config only after its injections are active. A live
* recomposition reads the service that remains active, so editing a user patch
* cannot reset an invocation value.
*
* Help, version, and rejected arguments are terminal for the process: the text
* is written, the service is never provided, dependent rows stay pending, and
* `ctx.appExit` is requested.
*
* A custom app that layers over another one disables the underlying startup
* row and names every startup service its retained rows inject, because a
* composition has exactly one command-line owner.
* @param ctx - plugin context carrying `cmdlineArgs`, `appExit`, and the Loader.
* @param services - the service name, or names, this startup row provides.
* Help, version, and rejected arguments are terminal for the process: commander
* writes the text, the helper requests `ctx.appExit`, and it returns
* `undefined` so the caller publishes nothing.
* @param ctx - plugin context carrying `cmdlineArgs` and `appExit`.
* @param program - the app's commander program, with its flags and description already declared.
* @param plan - this invocation's resolved values; omitted provides an empty value.
* @returns the resolved values, or `undefined` when the app asked to exit
* instead (help, version, or arguments it rejected).
* @throws when the launcher provided no command line, or when a named service
* is injected by no row.
* @param plan - this invocation's resolved value; omitted returns an empty object.
* @returns the resolved value, or `undefined` when the app asked to exit.
* @throws when the launcher did not provide the command line and exit request.
*/
export function runStartup<T>(
export function parseCmdline<T>(
ctx: Context,
services: string | readonly string[],
program: Command,
plan: StartupPlan<T> = (() => ({}) as T),
plan: CmdlinePlan<T> = (() => ({}) as T),
): T | undefined {
const names = typeof services === 'string' ? [services] : services
// Read through the global service store, not the property proxy: these are
// optional host values, and a row that injects only `cmdlineArgs` may not
// read the others as declared injections.
// Read through the global service store, not the property proxy: appExit is
// an optional host value and the plugin only needs to inject cmdlineArgs.
const args = ctx.get('cmdlineArgs')
const exit = ctx.get('appExit')
if (args === undefined || exit === undefined) {
@@ -180,26 +120,17 @@ export function runStartup<T>(
writeOut: text => void internals.stdout.write(text),
writeErr: text => void internals.stderr.write(text),
})
let values: T
try {
program.parse(args.get(), { from: 'user' })
// An app can dispose the whole tree while this row is still parsing (an
// early SIGTERM, or another app exiting). There is then nothing to resolve
// and nothing to start, and the check below would blame the bundle for a
// tree that simply went away.
if (ctx.get('loader') === undefined) return undefined
values = plan(program, waitingRows(ctx, names), ctx)
return plan(program, ctx)
} catch (error) {
// exitOverride turns help, version, a parse error, and a plan's own
// program.error() into a CommanderError; commander has already written the
// text through the output configured above. With no startup service,
// dependent rows remain pending and the app stays unstarted.
// text through the output configured above.
if (!isCommanderError(error)) throw error
exit(error.exitCode)
return undefined
}
for (const service of names) ctx.provide(service, values)
return values
}
/**
@@ -224,34 +155,6 @@ export async function enableRow(ctx: Context, id: string): Promise<void> {
await entry.enableRuntime()
}
/**
* The composed options of every row waiting on one of `services`, in tree order.
* @param ctx - plugin context whose Loader tree carries the rows.
* @param services - the startup service names.
* @returns the waiting rows' options.
* @throws when a service is injected by no row, which means the bundle patch
* and its startup plugin disagree.
*/
function waitingRows(ctx: Context, services: readonly string[]): EntryOptions[] {
for (const service of services) {
if (waitingEntries(ctx, [service]).length === 0) {
throw new Error(`${service}: no row injects this startup service — the bundle patch must set "inject: [${service}]" on every row this app configures`)
}
}
return waitingEntries(ctx, services).map(entry => entry.options)
}
/**
* The Loader entries waiting on any of `services`.
* @param ctx - plugin context whose Loader tree carries the rows.
* @param services - the startup service names.
* @returns the waiting entries in tree order.
*/
function waitingEntries(ctx: Context, services: readonly string[]): Entry[] {
// Called only after runStartup established the tree is still live.
return [...ctx.loader.entries()].filter(entry => waitsForAny(entry.options.inject, services))
}
/**
* Whether a thrown value is commander's own control-flow error (help, version,
* a parse error, or `program.error`).
@@ -269,17 +172,3 @@ function isCommanderError(error: unknown): error is { code: string; exitCode: nu
return typeof candidate.code === 'string' && candidate.code.startsWith('commander.')
&& typeof candidate.exitCode === 'number'
}
/**
* Whether a row's `inject` declaration names any of `services`.
* @param inject - the row's `inject` value: the array form, the object form, or absent.
* @param services - the startup service names.
* @returns true when the row waits for one of them.
*/
function waitsForAny(inject: EntryOptions['inject'], services: readonly string[]): boolean {
if (inject === undefined || inject === null) return false
// The array form lists service names; the object form maps each name to its
// intercept config. Both name the service as a key of the same shape.
const declared = Array.isArray(inject) ? inject : Object.keys(inject)
return services.some(service => declared.includes(service))
}

View File

@@ -14,14 +14,10 @@ export const name = 'cmdline-invariant'
export const inject = ['invariants']
/**
* No runtime invariant: the owned relation is "no row is left waiting for a
* startup service", which is a property of the whole tree at Loader
* settlement, and the invariant service carries no settlement signal to
* evaluate it at. Observing it from the entry stream would fire while startup
* is still parsing, when every waiting row is legitimately still waiting. The
* launcher's post-settlement audit (`assertEntriesActivated`) already reports
* a startup service that was never provided as a pending entry naming it, and
* the built-bin e2e asserts the apps boot with flag values applied.
* No runtime invariant: `cmdlineArgs` is an immutable launcher fact that any
* number of ordinary plugins may read. App-owned providers and consumers use
* normal Cordis service injection, whose missing dependencies are already
* reported by Loader settlement.
*/
const install: InvariantInstaller = () => {}

View File

@@ -15,7 +15,7 @@ import Include from '@cordisjs/plugin-include'
import type { PatchOptions } from '@cordisjs/plugin-include'
import { afterEach, describe, expect, it } from 'vitest'
import {
enableRow, hasCmdlineConsumer, internals, provideCmdline, runStartup, type StartupPlan,
enableRow, internals, parseCmdline, provideCmdline, type CmdlinePlan,
} from '../src/index.ts'
/** Every value one boot of the fixture tree observed. */
@@ -26,7 +26,7 @@ interface Observed {
out: string
}
/** A booted fixture tree: what it observed, and its root for direct startup calls. */
/** A booted fixture tree: what it observed, and its root for direct parser calls. */
interface Fixture {
observed: Observed
ctx: Context
@@ -46,7 +46,7 @@ function demoCommand(): Command {
}
/** The fixture app's plan: the resolved values its rows read. */
const demoPlan: StartupPlan<{ port?: number }> = (program) => {
const demoPlan: CmdlinePlan<{ port?: number }> = (program) => {
const port = program.opts<{ port?: string }>().port
if (port === undefined) return {}
if (!/^\d+$/.test(port)) program.error(`error: --port must be a number, got ${JSON.stringify(port)}`)
@@ -65,8 +65,8 @@ const expression = (source: string): unknown => ({ __jsExpr: source })
*/
async function bootFixture(
args: string[],
plan: StartupPlan = demoPlan,
options: { objectInject?: boolean; withoutStartup?: boolean } = {},
plan: CmdlinePlan = demoPlan,
options: { objectInject?: boolean; withoutProvider?: boolean } = {},
): Promise<Fixture> {
const dir = mkdtempSync(join(tmpdir(), 'dsh-cmdline-'))
const observed: Observed = { exits: [], out: '' }
@@ -81,28 +81,31 @@ export function apply(ctx, config) { globalThis.__observed.started = config }
writeFileSync(join(dir, 'startup.mjs'), `
export const name = 'demo-startup'
export const inject = ['cmdlineArgs']
export function apply(ctx) { return globalThis.__runStartup(ctx) }
export function apply(ctx) { return globalThis.__provideDemoArgs(ctx) }
`)
writeFileSync(join(dir, 'cordis.yml'), '[]\n')
const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
internals.stdout = observing
internals.stderr = observing
const globals = globalThis as unknown as { __observed: Observed; __runStartup: (ctx: Context) => void }
const globals = globalThis as unknown as { __observed: Observed; __provideDemoArgs: (ctx: Context) => void }
globals.__observed = observed
globals.__runStartup = (ctx: Context) => { runStartup(ctx, 'demoStartup', demoCommand(), plan) }
globals.__provideDemoArgs = (ctx: Context) => {
const values = parseCmdline(ctx, demoCommand(), plan)
if (values !== undefined) ctx.provide('demoStartup', values)
}
// The composition, exactly as a profile delivers one: include patches whose
// config carries `!!js` expressions.
const composition: PatchOptions[] = [{
insert: [
...options.withoutStartup === true
...options.withoutProvider === true
? []
: [{ id: 'demo-startup', name: pathToFileURL(join(dir, 'startup.mjs')).href, inject: ['cmdlineArgs'] }],
: [{ id: 'demo-startup', name: pathToFileURL(join(dir, 'startup.mjs')).href }],
{
id: 'reader',
name: pathToFileURL(join(dir, 'reader.mjs')).href,
inject: options.objectInject === true ? { demoStartup: { required: true } } : ['demoStartup'],
config: { port: expression('ctx.demoStartup?.port ?? 3080') },
config: { port: expression('ctx.demoStartup.port ?? 3080') },
},
],
}]
@@ -119,55 +122,7 @@ export function apply(ctx) { return globalThis.__runStartup(ctx) }
return { observed, ctx }
}
describe('hasCmdlineConsumer', () => {
it('recognizes active array and object injections', () => {
expect(hasCmdlineConsumer([
{ id: 'ordinary', name: 'ordinary' },
{ id: 'disabled-startup', name: 'disabled-startup', inject: ['cmdlineArgs'], disabled: true },
{ id: 'tui-startup', name: 'tui-startup', inject: { cmdlineArgs: { required: true } } },
])).toBe(true)
expect(hasCmdlineConsumer([
{ id: 'ordinary', name: 'ordinary' },
{ id: 'disabled-startup', name: 'disabled-startup', inject: ['cmdlineArgs'], disabled: true },
])).toBe(false)
expect(() => hasCmdlineConsumer([
{ id: 'web-startup', name: 'web-startup', inject: ['cmdlineArgs'] },
{ id: 'tui-startup', name: 'tui-startup', inject: ['cmdlineArgs'] },
])).toThrow('multiple active rows inject cmdlineArgs ("web-startup", "tui-startup")')
})
it('walks nested groups and ignores consumers disabled by an ancestor', () => {
expect(hasCmdlineConsumer([{
id: 'app',
name: 'cordis:group',
group: true,
config: [{ id: 'startup', name: 'startup', inject: ['cmdlineArgs'] }],
}])).toBe(true)
expect(hasCmdlineConsumer([{
id: 'app',
name: 'cordis:group',
group: true,
disabled: true,
config: [{ id: 'startup', name: 'startup', inject: ['cmdlineArgs'] }],
}])).toBe(false)
expect(() => hasCmdlineConsumer([
{
id: 'first',
name: 'cordis:group',
group: true,
config: [{ id: 'startup', name: 'startup', inject: ['cmdlineArgs'] }],
},
{
id: 'second',
name: 'cordis:group',
group: true,
config: [{ id: 'startup', name: 'startup', inject: ['cmdlineArgs'] }],
},
])).toThrow('multiple active rows inject cmdlineArgs ("first:startup", "second:startup")')
})
})
describe('runStartup', () => {
describe('parseCmdline', () => {
it('lets a row read the flag value the app resolved', async () => {
const { observed } = await bootFixture(['--port', '8080'])
expect(observed.started).toEqual({ port: 8080 })
@@ -179,7 +134,7 @@ describe('runStartup', () => {
expect(observed.started).toEqual({ port: 3080 })
})
it('recognizes the Loader object form of a startup-service injection', async () => {
it('recognizes the Loader object form of a provider-service injection', async () => {
const { observed } = await bootFixture(['--port', '8080'], demoPlan, { objectInject: true })
expect(observed.started).toEqual({ port: 8080 })
})
@@ -199,32 +154,24 @@ describe('runStartup', () => {
})
it('rethrows a plan failure that is not commander asking to exit', async () => {
const { ctx } = await bootFixture([], demoPlan, { withoutStartup: true })
const plan: StartupPlan = () => { throw new Error('plan exploded') }
expect(() => { runStartup(ctx, 'demoStartup', demoCommand(), plan) }).toThrow('plan exploded')
const { ctx } = await bootFixture([], demoPlan, { withoutProvider: true })
const plan: CmdlinePlan = () => { throw new Error('plan exploded') }
expect(() => { parseCmdline(ctx, demoCommand(), plan) }).toThrow('plan exploded')
})
it('rethrows a thrown value that is not an object at all', async () => {
const { ctx } = await bootFixture([], demoPlan, { withoutStartup: true })
const plan: StartupPlan = () => {
const { ctx } = await bootFixture([], demoPlan, { withoutProvider: true })
const plan: CmdlinePlan = () => {
const thrown: unknown = 'plan threw a string'
throw thrown
}
expect(() => { runStartup(ctx, 'demoStartup', demoCommand(), plan) }).toThrow('plan threw a string')
expect(() => { parseCmdline(ctx, demoCommand(), plan) }).toThrow('plan threw a string')
})
it('fails loud when no row injects the service the app provides', async () => {
// The bundle patch and its startup row disagree; a silent no-op would leave
// every row of the app on its fallbacks with no explanation.
const { ctx } = await bootFixture([], demoPlan, { withoutStartup: true })
expect(() => { runStartup(ctx, 'absentStartup', demoCommand()) })
.toThrow('absentStartup: no row injects this startup service')
})
it('accepts a service-name list when the app declares no plan', async () => {
const { ctx } = await bootFixture([], demoPlan, { withoutStartup: true })
runStartup(ctx, ['demoStartup'], demoCommand())
expect(ctx.get('demoStartup')).toEqual({})
it('returns values without inspecting Loader rows or owning a service', async () => {
const { ctx } = await bootFixture([], demoPlan, { withoutProvider: true })
expect(parseCmdline(ctx, demoCommand())).toEqual({})
expect(ctx.get('demoStartup')).toBeUndefined()
})
})
@@ -302,19 +249,17 @@ describe('provideCmdline', () => {
expect(ctx.cmdlineArgs?.get()).toEqual(['--resume', 'abc'])
})
it('fails loud when a startup row runs without the launcher values', () => {
it('fails loud when a parser runs without the launcher values', () => {
const ctx = new Context()
expect(() => { runStartup(ctx, 'demoStartup', demoCommand()) })
expect(() => { parseCmdline(ctx, demoCommand()) })
.toThrow('the launcher must provide ctx.cmdlineArgs and ctx.appExit')
})
it('resolves nothing when the tree was disposed while the startup row parsed', () => {
// An early SIGTERM takes the Loader with it; there is nothing left to
// configure, and the bundle did nothing wrong.
const exits: number[] = []
it('lets multiple parsers read the same immutable snapshot', () => {
const ctx = new Context()
provideCmdline(ctx, { args: [], exit: code => void exits.push(code) })
expect(() => { runStartup(ctx, 'demoStartup', demoCommand()) }).not.toThrow()
expect(exits).toEqual([])
provideCmdline(ctx, { args: ['--port', '8080'], exit: () => {} })
expect(parseCmdline(ctx, demoCommand(), demoPlan)).toEqual({ port: 8080 })
expect(parseCmdline(ctx, demoCommand(), demoPlan)).toEqual({ port: 8080 })
expect(Object.isFrozen(ctx.cmdlineArgs?.get())).toBe(true)
})
})

View File

@@ -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

View File

@@ -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

View File

@@ -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 激活前被拒绝
## 模型体验

View File

@@ -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]

View File

@@ -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

View File

@@ -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)
}

View File

@@ -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')
})
})

View File

@@ -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

View File

@@ -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

View File

@@ -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 之上的同级表层,不挂载本组合包。
## 模型体验

View File

@@ -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'

View File

@@ -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)})`}`)
}

View File

@@ -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)
}

View File

@@ -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')
})
})

View File

@@ -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'] })
})
})

View File

@@ -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')