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 .agents/notes/implemented/architecture/2026-08-06-app-owned-command-line.md
|
||||
2026-08-06-app-owned-command-line.md: 3dae1cb209ae9083ac6ab6616a140b6f129bc931
|
||||
2026-08-06-app-owned-command-line.zh.md: 81750eec8a78a811dd90454d88fa8ed1611dcce6
|
||||
2026-08-06-app-owned-command-line.md: 4a05cac5ed7f44fb55c2d4498bf28a43befdb073
|
||||
2026-08-06-app-owned-command-line.zh.md: 86a37f416d17c4615152b29d73f171803f24c4c3
|
||||
@@ -12,9 +12,9 @@ After profiles, compositions were installable but their command lines were not.
|
||||
|
||||
The launcher parses only what it owns — `--profile`, `--patch`, the config dumps — and hands **everything after its own flags** to the booted tree verbatim. The split is positional: the first token the launcher does not recognize starts the app's arguments (commander's `passThroughOptions` + `allowUnknownOption` + `helpOption(false)`). A bare `dsh -h`, which has no app to hand the flag to, still prints the launcher's own help.
|
||||
|
||||
The new `@deepseek-ai/dsh-cmdline` package owns the handoff. A launcher calls `provideCmdline(ctx, host)` before any entry mounts, providing `ctx.cmdlineArgs` (whose whole interface is `get(): readonly string[]`) and `ctx.appExit`. An app consumes them from its **startup row**. Both the Loader row and plugin inject `cmdlineArgs`; the plugin calls `runStartup(ctx, service, program, plan)` with its own commander program and provides what it resolved as its own service. The Loader-row injection is also the launcher's discovery declaration; there is no parallel bundle-manifest field. Before boot, the launcher rejects nonempty app arguments with no active declaration and any composition with multiple active declarations. The rows the app configures inject that service and read it from their own config expressions (`port: !!js ctx.webStartup.port ?? 3080`), so a flag beats the value written beside it and nothing is written back into any row.
|
||||
The new `@deepseek-ai/dsh-cmdline` package owns the handoff. A launcher calls `provideCmdline(ctx, host)` before any entry mounts, providing `ctx.cmdlineArgs` (whose whole interface is `get(): readonly string[]`) and `ctx.appExit`. Any ordinary app plugin may inject `cmdlineArgs`, call `parseCmdline(ctx, program, plan)` with its own commander program, and provide the returned value as an app-owned service. Its Loader row carries no launcher marker or special kind, and the launcher does not inspect the composition for an owner. Multiple plugins may read the same immutable snapshot; a profile with no reader ignores its app arguments. Rows configured from a provider inject its service and read direct lazy config expressions (`port: !!js ctx.webStartup.port ?? 3080`), so a flag beats the value written beside it and nothing is written back into any row.
|
||||
|
||||
The boot mounts the composition once. Cordis holds each row until its injections are active; Loader then interpolates that row's `!!js` against the injection-ready plugin context immediately before activation. Include keeps nested row expressions raw until their target row reaches this point. `--help` provides no startup service, so dependent rows never activate, and a live patch reload interpolates again against the service that remains active, so a served port cannot be silently reset.
|
||||
The boot mounts the composition once. Cordis holds each row until its injections are active; Loader then interpolates that row's `!!js` against the injection-ready plugin context immediately before activation. Include keeps nested row expressions raw until their target row reaches this point. `--help` leaves the provider's service absent, so dependent rows never activate, and a live patch reload interpolates again against the service that remains active, so a served port cannot be silently reset.
|
||||
|
||||
The shipped apps moved their flags into their bundles: `dsh-web-app` owns the Web family (and enables the `client-hmr` row it now ships disabled, for `--dev`), and `dsh-headless` owns the task positional and rejects a missing task as a usage error. `apps/cli/src/web.ts` is gone; `runProfile` no longer knows any flag-target row id. Out of tree, turtle-ui gained `--resume <session>` / `--session <id>` the same way, which is the design's real validation: an installed plugin added a flag with no launcher change.
|
||||
|
||||
@@ -36,16 +36,16 @@ This leaves dependency ordering in Cordis activation and Loader interpolation, w
|
||||
- **Writing the resolved values into each row** (a config update per row, plus a patch layer handed back to the launcher so a reload could not undo it): it worked, but it meant patches travelling from an app to the launcher and back, two mechanisms for one fact, and a recycle whose correctness depended on Loader restart internals. The maintainer rejected the round trip; the service the rows read replaced all of it.
|
||||
- **Releasing rows by clearing their `inject`**: it worked in isolation and failed on the real web tree, because clearing `inject` is exactly what loses the plugin's static injections. The failure is silent until a plugin reads a service it declared.
|
||||
- **Launcher-managed two-pass mounting**: it can make a provider active before readers are applied, but duplicates the composition, makes ordering a launcher concern, and conceals the Loader defect that nested expressions were evaluated in the include context rather than the target row's injected context.
|
||||
- **The launcher running each bundle's startup function before boot** (no cordis involvement): strictly earlier than "boot, then help", but it makes app startup a second plugin protocol outside the tree. Using a `cmdlineArgs`-injected startup row keeps one protocol: it is an ordinary row, dumpable and patchable, and a layering bundle disables it like any other.
|
||||
- **Both apps parsing the same argv** (a custom composition combines Web and one-shot startup rows): two parsers cannot both own `-h`. A composition has exactly one command-line owner, so a layering bundle disables the startup row it absorbs and provides every startup service its retained rows inject.
|
||||
- **The launcher running each bundle's command function before boot** (no Cordis involvement): strictly earlier than "boot, then help", but it makes app startup a second plugin protocol outside the tree. An ordinary `cmdlineArgs`-injected provider keeps one protocol and remains dumpable and patchable.
|
||||
- **A launcher-enforced command-line owner**: rejecting zero or multiple readers would arbitrate overlaps such as `-h`, but `get()` is an immutable read and normal composition may need several app-owned services. Plugins therefore share the snapshot and own any parser interaction through ordinary composition.
|
||||
- **`instanceof CommanderError`**: an out-of-tree plugin brings its own commander copy, so the class identity differs and a printed `--help` was rethrown as a fatal load failure. Commander's control-flow errors are detected structurally instead.
|
||||
|
||||
## Consequences
|
||||
|
||||
- An app's flags, help text, and usage errors live with the rows they configure; adding a flag to an installed plugin needs no launcher change.
|
||||
- The launcher still recognizes the headless runner for one-shot process lifetime and the telemetry row for its environment switch; neither path interprets app arguments.
|
||||
- `--help` leaves every row that depends on a startup service pending and requests bounded exit; unrelated rows may activate concurrently before teardown. A profile with no active row injecting `cmdlineArgs` rejects nonempty app arguments before mounting instead of ignoring them.
|
||||
- A startup service has no statically declared owner: a bundle shipping reading rows without its startup row fails at settlement with pending entries naming the service, not at load.
|
||||
- `--help` leaves every row that depends on the provider's service pending and requests bounded exit; unrelated rows may activate concurrently before teardown.
|
||||
- An app-owned service has no statically declared provider: a bundle shipping consumer rows without that provider fails at settlement with pending entries naming the service, not at load.
|
||||
- A user patch that replaces a row's whole `config` drops its expressions, and with them the flag's precedence for that row.
|
||||
- Launcher flags must precede app arguments; a first app argument equal to `web` or `plugin` selects that subcommand instead, `-V`/`--version` remains launcher-owned before that boundary, and the launcher's parser consumes one `--`, so a literal `--` for the app needs `-- --`.
|
||||
- `--dump-config` never runs a startup row, so it prints the composition before any app argument is resolved and rejects an invocation that carries app arguments.
|
||||
- `--dump-config` never runs app command-line providers, so it prints the composition before any app argument is resolved and rejects an invocation that carries app arguments.
|
||||
@@ -12,9 +12,9 @@ profile 落地之后,组合可以安装,命令行却不能。`apps/cli` 仍
|
||||
|
||||
启动器只解析属于自己的部分(`--profile`、`--patch`、配置 dump),并把**自己 flag 之后的一切**原样交给引导起来的配置树。切分按位置进行:启动器不认识的第一个 token 就是应用参数的起点(依靠 commander 的 `passThroughOptions` + `allowUnknownOption` + `helpOption(false)`)。裸的 `dsh -h` 没有可交付的应用,仍然打印启动器自己的 help。
|
||||
|
||||
新包 `@deepseek-ai/dsh-cmdline` 持有这次交接。启动器在任何条目挂载之前调用 `provideCmdline(ctx, host)`,提供 `ctx.cmdlineArgs`(其全部接口就是 `get(): readonly string[]`)与 `ctx.appExit`。应用从自己的**启动行**消费它们。Loader 行与插件都注入 `cmdlineArgs`;插件以自己的 commander program 调用 `runStartup(ctx, service, program, plan)`,再把解析结果作为自己的服务提供出去。Loader 行的注入同时也是启动器的发现声明,不再需要一份平行的组合包 manifest 字段。启动器会在 boot 前拒绝没有活跃声明却带有非空应用参数的调用,也会拒绝存在多个活跃声明的组合。应用所配置的行注入该服务,再从各自的配置表达式中读取它(`port: !!js ctx.webStartup.port ?? 3080`),因此 flag 胜过写在它旁边的值,也没有任何东西被写回任何一行。
|
||||
新包 `@deepseek-ai/dsh-cmdline` 持有这次交接。启动器在任何条目挂载之前调用 `provideCmdline(ctx, host)`,提供 `ctx.cmdlineArgs`(其全部接口就是 `get(): readonly string[]`)与 `ctx.appExit`。任何普通应用插件都可以注入 `cmdlineArgs`,用自己的 commander program 调用 `parseCmdline(ctx, program, plan)`,再把返回值作为应用自有服务提供出去。它的 Loader 行不携带启动器标记或特殊类型,启动器也不会检查组合中的所有者。多个插件可以读取同一份不可变快照;没有读取方的 profile 会忽略自己的应用参数。由提供方配置的行注入其服务,并在惰性配置表达式中直接读取它(`port: !!js ctx.webStartup.port ?? 3080`),因此 flag 胜过写在它旁边的值,也没有任何东西被写回任何一行。
|
||||
|
||||
boot 只挂载一次整套组合。Cordis 让每一行等待其注入激活;Loader 随后在激活前一刻,基于已注入就绪的插件上下文插值该行的 `!!js`。Include 会保留嵌套的行表达式,直到目标行到达这一时点。`--help` 不提供启动服务,因此依赖行永不激活;活动 patch 重载会针对仍然在线的服务再次插值,所以已经服务中的端口不会被悄悄重置。
|
||||
boot 只挂载一次整套组合。Cordis 让每一行等待其注入激活;Loader 随后在激活前一刻,基于已注入就绪的插件上下文插值该行的 `!!js`。Include 会保留嵌套的行表达式,直到目标行到达这一时点。`--help` 会让提供方服务保持缺失,因此依赖行永不激活;活动 patch 重载会针对仍然在线的服务再次插值,所以已经服务中的端口不会被悄悄重置。
|
||||
|
||||
已交付的各应用把自己的 flag 搬进了组合包:`dsh-web-app` 持有 Web 家族(并为 `--dev` 启用它如今以禁用状态交付的 `client-hmr` 行),`dsh-headless` 持有任务位置参数,缺少任务时按用法错误拒绝。`apps/cli/src/web.ts` 已删除;`runProfile` 不再知道任何 flag 目标行 id。在树外,turtle-ui 以同样的方式获得了 `--resume <session>` / `--session <id>`,这才是这套设计的真正验证:一个已安装的插件加上了一个 flag,启动器毫无改动。
|
||||
|
||||
@@ -36,16 +36,16 @@ boot 只挂载一次整套组合。Cordis 让每一行等待其注入激活;Lo
|
||||
- **把解析出的取值写进每一行**(逐行一次配置更新,外加交还给启动器的一层 patch,使重载无法撤销它):它能工作,但这意味着 patch 在应用与启动器之间来回传递、同一件事有两套机制,以及一套其正确性依赖 Loader 重启内部细节的回收重建。维护者否决了这次往返;供各行读取的服务取代了这一切。
|
||||
- **通过清空行的 `inject` 来放行**:孤立测试可行,在真实 web 树上失败,因为清空 `inject` 恰恰会丢失插件的静态注入。在插件真的去读它声明过的服务之前,这个失败是静默的。
|
||||
- **由启动器管理两趟挂载**:它可以让提供方先于读取行激活,但会重复组合、把顺序变成启动器职责,还掩盖了 Loader 的缺陷——嵌套表达式在 include 上下文而不是目标行的注入上下文中求值。
|
||||
- **由启动器在 boot 之前运行每个组合包的启动函数**(完全不经过 cordis):严格早于「先 boot 再 help」,但这会让应用启动成为配置树之外的第二套插件协议。使用注入 `cmdlineArgs` 的启动行则只保留一套协议:它就是一个普通的行,可 dump、可 patch,叠加的组合包也能像禁用其他行那样禁用它。
|
||||
- **两个应用解析同一份 argv**(自定义组合同时包含 Web 与一次性启动行):两个解析器不可能同时持有 `-h`。一套组合有且只有一个命令行所有者,因此叠加的组合包要禁用被吸收的启动行,并提供保留下来的各行所注入的全部启动服务。
|
||||
- **由启动器在 boot 之前运行每个组合包的命令函数**(完全不经过 Cordis):严格早于「先 boot 再 help」,但这会让应用启动成为配置树之外的第二套插件协议。使用注入 `cmdlineArgs` 的普通提供方只保留一套协议,并且仍可 dump、可 patch。
|
||||
- **由启动器强制指定命令行所有者**:拒绝零个或多个读取方可以裁决 `-h` 等重叠项,但 `get()` 是不可变读取,普通组合也可能需要多个应用自有服务。因此插件共享该快照,并通过普通组合持有各自解析器的交互。
|
||||
- **`instanceof CommanderError`**:树外插件会带来自己的一份 commander 副本,类身份因此不同,已经打印出来的 `--help` 会被重新抛成致命的加载失败。改为按结构识别 commander 的控制流错误。
|
||||
|
||||
## 后果
|
||||
|
||||
- 应用的 flag、help 文本和用法错误与它们所配置的行放在一起;给已安装的插件加一个 flag 不需要改动启动器。
|
||||
- 启动器仍会识别 headless runner 以管理一次性进程生命周期,并识别 telemetry 行以应用环境开关;两条路径都不解析应用参数。
|
||||
- `--help` 会让所有依赖启动服务的行保持待处理并请求有边界的退出;无关行可能在拆除前并发激活。没有注入 `cmdlineArgs` 的活跃行的 profile 会在挂载前拒绝非空应用参数,而不是忽略它们。
|
||||
- 启动服务没有静态声明的所有者:交付了读取行却缺少对应启动行的组合包会在结算时失败,报出指向该服务的待处理条目,而不是在加载时失败。
|
||||
- `--help` 会让所有依赖提供方服务的行保持待处理并请求有边界的退出;无关行可能在拆除前并发激活。
|
||||
- 应用自有服务没有静态声明的提供方:交付了消费行却缺少对应提供方的组合包会在结算时失败,报出指向该服务的待处理条目,而不是在加载时失败。
|
||||
- 用户 patch 若整体替换某行的 `config`,会连同其中的表达式一起丢掉,该行上 flag 的优先级也随之消失。
|
||||
- 启动器的 flag 必须写在应用参数之前;如果应用的第一个参数恰好等于 `web` 或 `plugin`,会选择对应的子命令;`-V`/`--version` 在该边界之前仍归启动器持有;而且启动器的解析器会消耗掉一个 `--`,因此要给应用传一个字面量 `--` 需要写成 `-- --`。
|
||||
- `--dump-config` 从不运行启动行,因此它在任何应用参数被解析之前打印组合,并拒绝携带应用参数的调用。
|
||||
- `--dump-config` 从不运行应用命令行提供方,因此它在任何应用参数被解析之前打印组合,并拒绝携带应用参数的调用。
|
||||
@@ -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 apps/cli/README.md
|
||||
README.md: 96c6932a1faf6f5ce9b64e0390e2a4b3dcb55fc4
|
||||
README.zh.md: ea80985a8f6ea43bcea45dfe169937388ab25df0
|
||||
README.md: 4fae5338a89ce12c2620e123530acf883ae9efff
|
||||
README.zh.md: a2d086b8ff12fb07f2446fc4162de09739bcdeab
|
||||
+1
-1
@@ -17,7 +17,7 @@ The invoking directory is the default workspace root. The `web` and `headless` p
|
||||
|
||||
## App arguments
|
||||
|
||||
The launcher parses only its own flags and hands everything after them to the booted profile, where that app's own startup row parses them ([`dsh-cmdline`](../../packages/boot/cmdline/README.md)). Launcher flags therefore come first, and the first token the launcher does not recognize starts the app's arguments:
|
||||
The launcher parses only its own flags and hands everything after them to the booted profile, where any injected app plugin may parse the shared immutable snapshot ([`dsh-cmdline`](../../packages/boot/cmdline/README.md)). Launcher flags therefore come first, and the first token the launcher does not recognize starts the app's arguments:
|
||||
|
||||
```sh
|
||||
dsh --profile web --port 8080 # --port belongs to the web app
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
|
||||
## 应用参数
|
||||
|
||||
启动器只解析属于自己的 flag,并把其后的一切交给启动起来的 profile,由该应用自己的启动行解析([`dsh-cmdline`](../../packages/boot/cmdline/README.md))。因此启动器的 flag 必须写在前面,而启动器不认识的第一个 token 就是应用参数的起点:
|
||||
启动器只解析属于自己的 flag,并把其后的一切交给启动起来的 profile,任何注入它的应用插件都可以解析这份共享的不可变快照([`dsh-cmdline`](../../packages/boot/cmdline/README.md))。因此启动器的 flag 必须写在前面,而启动器不认识的第一个 token 就是应用参数的起点:
|
||||
|
||||
```sh
|
||||
dsh --profile web --port 8080 # --port belongs to the web app
|
||||
|
||||
@@ -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 apps/cli/reference/README.md
|
||||
README.md: f28d77ccba7380426df2dd1769e33be0f7256d27
|
||||
README.zh.md: 3d8fbae31780c00f05384a1e4010fda2b6ce3246
|
||||
README.md: fd0647347312051a1814a5e3464b34032ae70dfc
|
||||
README.zh.md: afe4b9ba5651e962288ffebbe7c095ad20bcc617
|
||||
@@ -14,11 +14,11 @@ The `web` and `headless` profiles auto-initialize from shipped templates on firs
|
||||
|
||||
### App arguments
|
||||
|
||||
The launcher's flags come first and end at the first token it does not recognize; everything from there on is handed to the booted profile verbatim through `ctx.cmdlineArgs`, where that app's own startup row parses it ([`dsh-cmdline`](../../../packages/boot/cmdline/README.md)). `dsh --profile web --port 8080` therefore reaches the web app's `--port`, `dsh --profile web --help` prints that app's help and boots nothing, and `dsh --help` (no profile to hand it to) prints the launcher's own. `-V`/`--version` prints the launcher's version when it appears before the app-argument boundary.
|
||||
The launcher's flags come first and end at the first token it does not recognize; everything from there on is handed to the booted profile verbatim through `ctx.cmdlineArgs`, where any injected app plugin may parse it ([`dsh-cmdline`](../../../packages/boot/cmdline/README.md)). `dsh --profile web --port 8080` therefore reaches the web app's `--port`, `dsh --profile web --help` prints that app's help and boots nothing, and `dsh --help` (no profile to hand it to) prints the launcher's own. `-V`/`--version` prints the launcher's version when it appears before the app-argument boundary.
|
||||
|
||||
A composition mounts once. A Loader row that injects `cmdlineArgs` parses this app's arguments and provides what it resolved as a service; each row configured from flags injects that service, and Loader waits for it before evaluating the row's config (`port: !!js ctx.webStartup.port ?? 3080`). A flag therefore beats the value written beside it. This precedence requires the row to retain that expression; a user patch that replaces the whole `config` with literals removes the runtime read. Help and rejected arguments request exit — nonzero for a rejection, 0 for help — without activating rows that depend on the startup service. A live `cordis.patch.yml` edit re-evaluates expressions against services that are still up, so it cannot reset a served port.
|
||||
A composition mounts once. An ordinary plugin injects `cmdlineArgs`, parses this app's arguments, and provides what it resolved as a service; each row configured from flags injects that service, and Loader waits for it before evaluating the row's config (`port: !!js ctx.webStartup.port ?? 3080`). A flag therefore beats the value written beside it. This precedence requires the row to retain that expression; a user patch that replaces the whole `config` with literals removes the runtime read. Help and rejected arguments request exit — nonzero for a rejection, 0 for help — without activating rows that depend on the provider's service. A live `cordis.patch.yml` edit re-evaluates expressions against services that are still up, so it cannot reset a served port.
|
||||
|
||||
Launcher flags must come before app arguments, and the launcher's parser consumes one `--`: an app argument that must arrive as a literal `--` needs `-- --`. A first app argument equal to `web` or `plugin` selects that subcommand instead. A profile with no active row injecting `cmdlineArgs` accepts no app arguments; it rejects them before mounting any row instead of silently ignoring them. A composition with multiple active rows injecting `cmdlineArgs` is always rejected because two parsers cannot own the same command line.
|
||||
Launcher flags must come before app arguments, and the launcher's parser consumes one `--`: an app argument that must arrive as a literal `--` needs `-- --`. A first app argument equal to `web` or `plugin` selects that subcommand instead. `ctx.cmdlineArgs.get()` is a shared immutable read: multiple plugins may parse the same snapshot, while a profile with no reader ignores its app arguments.
|
||||
|
||||
The shipped apps own these command lines:
|
||||
|
||||
@@ -36,7 +36,7 @@ dsh --profile web --dump-default-config
|
||||
dsh --profile web --patch ./extra.yml --dump-config
|
||||
```
|
||||
|
||||
`--dump-default-config` prints only the bundle layers; `--dump-config` adds the profile's `cordis.patch.yml`, the home-level `$DSH_HOME/cordis.patch.yml`, and `--patch` overlays. Both print comments naming the file that supplied each row and every overlay that changed it; `!!js` expressions remain unevaluated, and unmatched patch targets are reported on stderr. A dump never runs an app's startup row, so it shows the composed tree before any app argument is resolved and rejects an invocation that carries app arguments.
|
||||
`--dump-default-config` prints only the bundle layers; `--dump-config` adds the profile's `cordis.patch.yml`, the home-level `$DSH_HOME/cordis.patch.yml`, and `--patch` overlays. Both print comments naming the file that supplied each row and every overlay that changed it; `!!js` expressions remain unevaluated, and unmatched patch targets are reported on stderr. A dump never runs app command-line providers, so it shows the composed tree before any app argument is resolved and rejects an invocation that carries app arguments.
|
||||
|
||||
## Plugin management
|
||||
|
||||
@@ -52,7 +52,7 @@ Git-hosted plugins that ship sources build during install through their `prepare
|
||||
|
||||
## Web alias
|
||||
|
||||
`dsh web` is a hardcoded alias for `--profile web`; the flags after it belong to the web app, which owns them in its bundle's startup row. `--host` and `--port` override the composed values of the rows that carry them, repeatable `--trusted-host` adds authorities over the composed fence configuration, and `--dev` switches the web-runtime row to development mode and enables the client-plugin HMR receiver the bundle ships disabled; it expects a separate `pnpm run dev:web` watcher for no-refresh client bundle updates.
|
||||
`dsh web` is a hardcoded alias for `--profile web`; the flags after it belong to the web app, whose ordinary bundle provider parses them. `--host` and `--port` override the composed values of the rows that carry them, repeatable `--trusted-host` contributes invocation authorities through `ctx.webRuntime.trustedHosts` (a deployment expression concatenates its own authorities), and `--dev` switches the web-runtime row to development mode and enables the client-plugin HMR receiver the bundle ships disabled; it expects a separate `pnpm run dev:web` watcher for no-refresh client bundle updates.
|
||||
|
||||
```sh
|
||||
dsh web
|
||||
|
||||
@@ -14,11 +14,11 @@
|
||||
|
||||
### 应用参数
|
||||
|
||||
启动器自己的 flag 写在最前面,并在它不认识的第一个 token 处结束;从那里开始的一切都通过 `ctx.cmdlineArgs` 原样交给启动起来的 profile,由该应用自己的启动行解析([`dsh-cmdline`](../../../packages/boot/cmdline/README.md))。因此 `dsh --profile web --port 8080` 到达的是 web 应用的 `--port`,`dsh --profile web --help` 打印的是该应用的 help 且什么也不启动,而 `dsh --help`(没有可以交付的 profile)打印的是启动器自己的 help。`-V`/`--version` 写在应用参数边界之前时会打印启动器的版本。
|
||||
启动器自己的 flag 写在最前面,并在它不认识的第一个 token 处结束;从那里开始的一切都通过 `ctx.cmdlineArgs` 原样交给启动起来的 profile,任何注入它的应用插件都可以解析([`dsh-cmdline`](../../../packages/boot/cmdline/README.md))。因此 `dsh --profile web --port 8080` 到达的是 web 应用的 `--port`,`dsh --profile web --help` 打印的是该应用的 help 且什么也不启动,而 `dsh --help`(没有可以交付的 profile)打印的是启动器自己的 help。`-V`/`--version` 写在应用参数边界之前时会打印启动器的版本。
|
||||
|
||||
一套组合只挂载一次。注入 `cmdlineArgs` 的 Loader 行解析本应用的参数,并把结果作为服务提供出去;由 flag 配置的每一行都会注入该服务,Loader 会等服务激活后再求值该行配置(`port: !!js ctx.webStartup.port ?? 3080`),因此 flag 胜过写在它旁边的值。该优先级要求配置行保留这一表达式;若用户 patch 用字面量替换整份 `config`,运行时读取也会随之消失。help 和被拒绝的参数会请求退出——拒绝时以非零状态,help 时以 0——且不会激活依赖启动服务的行。在线编辑 `cordis.patch.yml` 会针对仍然在线的服务重新求值表达式,因此不会重置已在服务的端口。
|
||||
一套组合只挂载一次。普通插件注入 `cmdlineArgs`、解析本应用参数,并把结果作为服务提供出去;由 flag 配置的每一行都会注入该服务,Loader 会等服务激活后再求值该行配置(`port: !!js ctx.webStartup.port ?? 3080`),因此 flag 胜过写在它旁边的值。该优先级要求配置行保留这一表达式;若用户 patch 用字面量替换整份 `config`,运行时读取也会随之消失。help 和被拒绝的参数会请求退出——拒绝时以非零状态,help 时以 0——且不会激活依赖提供方服务的行。在线编辑 `cordis.patch.yml` 会针对仍然在线的服务重新求值表达式,因此不会重置已在服务的端口。
|
||||
|
||||
启动器的 flag 必须写在应用参数之前,且启动器的解析器会消耗掉一个 `--`:必须以字面量 `--` 送达应用的参数需要写成 `-- --`。如果应用的第一个参数恰好等于 `web` 或 `plugin`,会选择对应的子命令。若 profile 中没有注入 `cmdlineArgs` 的活跃行,该 profile 不接受应用参数;启动器会在挂载任何行之前拒绝这些参数,而不是静默忽略。若组合中有多个注入 `cmdlineArgs` 的活跃行,启动器总会拒绝该组合,因为两个解析器不能共同持有同一条命令行。
|
||||
启动器的 flag 必须写在应用参数之前,且启动器的解析器会消耗掉一个 `--`:必须以字面量 `--` 送达应用的参数需要写成 `-- --`。如果应用的第一个参数恰好等于 `web` 或 `plugin`,会选择对应的子命令。`ctx.cmdlineArgs.get()` 是共享的不可变读取:多个插件可以解析同一份快照,没有读取方的 profile 则会忽略自己的应用参数。
|
||||
|
||||
随附的各应用持有这些命令行:
|
||||
|
||||
@@ -36,7 +36,7 @@ dsh --profile web --dump-default-config
|
||||
dsh --profile web --patch ./extra.yml --dump-config
|
||||
```
|
||||
|
||||
`--dump-default-config` 只打印组合包各层;`--dump-config` 额外加上 profile 的 `cordis.patch.yml`、home 级的 `$DSH_HOME/cordis.patch.yml` 和 `--patch` overlay。两者都会打印注释,标明每行由哪个文件提供,以及哪些 overlay 修改过它;`!!js` 表达式保持未求值,找不到目标的 patch 会报告到 stderr。dump 从不运行应用的启动行,因此它展示的是任何应用参数被解析之前的组合配置树,并拒绝携带应用参数的调用。
|
||||
`--dump-default-config` 只打印组合包各层;`--dump-config` 额外加上 profile 的 `cordis.patch.yml`、home 级的 `$DSH_HOME/cordis.patch.yml` 和 `--patch` overlay。两者都会打印注释,标明每行由哪个文件提供,以及哪些 overlay 修改过它;`!!js` 表达式保持未求值,找不到目标的 patch 会报告到 stderr。dump 从不运行应用命令行提供方,因此它展示的是任何应用参数被解析之前的组合配置树,并拒绝携带应用参数的调用。
|
||||
|
||||
## 插件管理
|
||||
|
||||
@@ -52,7 +52,7 @@ Git 托管、随附源码的插件在安装期间通过其 `prepare` 脚本构
|
||||
|
||||
## Web 别名
|
||||
|
||||
`dsh web` 是 `--profile web` 的硬编码别名;写在它之后的 flag 属于 web 应用,由该应用在其组合包的启动行中持有。`--host` 和 `--port` 覆盖承载它们的那些行的组合取值,可重复的 `--trusted-host` 在组合出的围栏配置之上追加 authority,`--dev` 把 web-runtime 行切换到开发模式并启用组合包以禁用状态交付的客户端插件 HMR(热模块替换)接收器;若要无刷新更新客户端 bundle,还需单独运行 `pnpm run dev:web` watcher。
|
||||
`dsh web` 是 `--profile web` 的硬编码别名;写在它之后的 flag 属于 web 应用,由组合包中的普通提供方解析。`--host` 和 `--port` 覆盖承载它们的那些行的组合取值,可重复的 `--trusted-host` 通过 `ctx.webRuntime.trustedHosts` 提供本次调用的 authority(部署表达式会拼接自己的 authority),`--dev` 把 web-runtime 行切换到开发模式并启用组合包以禁用状态交付的客户端插件 HMR(热模块替换)接收器;若要无刷新更新客户端 bundle,还需单独运行 `pnpm run dev:web` watcher。
|
||||
|
||||
```sh
|
||||
dsh web
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
*
|
||||
* The launcher parses only what it owns — which profile to boot, which extra
|
||||
* patch overlays to apply, and the config dumps — and hands **everything after
|
||||
* its own flags** to the booted tree verbatim, where the booted app's startup row
|
||||
* parses its own flag family and prints its own `--help` (see
|
||||
* its own flags** to the booted tree verbatim, where injected app plugins parse
|
||||
* their own flag families and print their own `--help` (see
|
||||
* `@deepseek-ai/dsh-cmdline`). Launcher flags therefore come first: the first
|
||||
* token this parser does not recognize starts the inner arguments, so
|
||||
* `dsh --profile tui --resume abc` boots the tui profile with `--resume abc`,
|
||||
@@ -23,7 +23,7 @@ interface ProfileInvocation {
|
||||
profile: string
|
||||
/** Extra patch-list overlays applied after the profile's own layer, in argv order. */
|
||||
patches: string[]
|
||||
/** Everything after the launcher's own flags, verbatim, for the booted app's startup row. */
|
||||
/** Everything after the launcher's own flags, verbatim, for injected app plugins. */
|
||||
args: string[]
|
||||
}
|
||||
|
||||
@@ -89,8 +89,8 @@ function resolveBoot(program: Command, profile: string, options: BootOptions, ar
|
||||
if (options.dumpConfig === true && options.dumpDefaultConfig === true) {
|
||||
program.error('error: --dump-config and --dump-default-config are mutually exclusive')
|
||||
}
|
||||
// The dump is boot-free: it never runs the app's startup row, so it cannot
|
||||
// show what that app's flags would decide, and printing a tree that differs
|
||||
// The dump is boot-free: it never runs app command-line providers, so it
|
||||
// cannot show what those flags would decide, and printing a tree that differs
|
||||
// from the same invocation's boot would mislead.
|
||||
if (args.length > 0) {
|
||||
program.error(`error: config dumps take no app arguments, got ${args.map(argument => JSON.stringify(argument)).join(' ')}`)
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
* live, and wire fail-loud plus bounded shutdown.
|
||||
*
|
||||
* App flags are not the launcher's business: the invocation's inner arguments
|
||||
* are provided to the tree through `ctx.cmdlineArgs`, and the booted app's
|
||||
* startup row parses them and configures its own rows.
|
||||
* are provided to the tree through `ctx.cmdlineArgs`, where any injected app
|
||||
* plugin may read the same immutable snapshot.
|
||||
* @module @deepseek-ai/dsh/profile-boot
|
||||
*/
|
||||
|
||||
@@ -37,7 +37,7 @@ const SHIPPED_PRESET_ROOT = fileURLToPath(new URL('../config/agent-presets/', im
|
||||
/** Harness-home directory holding locally authored agent presets. */
|
||||
const USER_PRESET_DIR = '.agent-presets'
|
||||
import { DSH_ENVIRONMENT_KEY, type EnvironmentSnapshot } from '@deepseek-ai/dsh-environment'
|
||||
import { hasCmdlineConsumer, provideCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
import { provideCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
import type { HeadlessIo } from '@deepseek-ai/dsh-headless'
|
||||
import { createProcessShutdown, type ProcessShutdown } from './process-shutdown.ts'
|
||||
import { resolveWindowsShellLayer } from './windows-shell.ts'
|
||||
@@ -206,12 +206,6 @@ function suppressSignalShutdownError(signal: AbortSignal, error: unknown): void
|
||||
*/
|
||||
export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Context; shutdown: ProcessShutdown }> {
|
||||
const composed = composeProfile(options.profile, options.patchFiles)
|
||||
if (!hasCmdlineConsumer([...composed.rows.values()]) && options.args.length > 0) {
|
||||
throw new Error(
|
||||
`${NAME}: profile ${JSON.stringify(options.profile)} takes no app arguments because no active row injects cmdlineArgs; `
|
||||
+ `got ${options.args.map(argument => JSON.stringify(argument)).join(' ')}`,
|
||||
)
|
||||
}
|
||||
// A one-shot composition ends by itself, which changes what a signal means
|
||||
// and makes watching the user's patch layer pointless.
|
||||
const headlessRow = composed.rows.get(HEADLESS_ROW_ID)
|
||||
@@ -225,8 +219,7 @@ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Con
|
||||
shutdown.interrupt(code)
|
||||
}
|
||||
// Signals own teardown throughout the startup window, not only after boot()
|
||||
// settles: an inserted startup row can publish readiness before sibling rows
|
||||
// finish mounting.
|
||||
// settles: an inserted provider can publish before sibling rows finish mounting.
|
||||
process.on('SIGTERM', () => { interrupt(oneShot ? 143 : 0) })
|
||||
process.on('SIGINT', () => { interrupt(130) })
|
||||
installFailLoud(NAME, process, async () => {
|
||||
@@ -235,9 +228,9 @@ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Con
|
||||
|
||||
const rootConfig = join(composed.profile.dir, PROFILE_ROOT_FILENAME)
|
||||
// Recomposition for the live user layers: bundle layers below, overlays
|
||||
// above, so a user edit can never displace them. What an app's startup row
|
||||
// resolved is not in here at all — it lives in that row's own service, which
|
||||
// survives a recomposition. BOTH
|
||||
// above, so a user edit can never displace them. Parsed app arguments are
|
||||
// not in here at all — they live in app-provided services that survive a
|
||||
// recomposition. BOTH
|
||||
// user files are re-read per generation (the HMR watcher hands us only the
|
||||
// changed file's patches, which one of the reads duplicates — fresh reads
|
||||
// keep the two watchers from stitching in each other's stale copy).
|
||||
@@ -263,9 +256,8 @@ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Con
|
||||
// Before any config-tree entry mounts, so plugins resolve all launch-time
|
||||
// environment values from the same immutable provenance snapshot.
|
||||
hostCtx.provide(DSH_ENVIRONMENT_KEY, options.environment)
|
||||
// The command line is a launcher fact every app reads the same way: its
|
||||
// own arguments, and the bounded exit its startup row requests after
|
||||
// printing help or rejecting them.
|
||||
// The command line and bounded exit request are launcher facts available
|
||||
// to every app plugin that injects the argument snapshot.
|
||||
provideCmdline(hostCtx, {
|
||||
args: options.args,
|
||||
exit: code => void shutdown.shutdown(code),
|
||||
@@ -280,8 +272,8 @@ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Con
|
||||
}
|
||||
})
|
||||
app.current = ctx
|
||||
// A surface can dispose the whole tree while startup or this post-boot
|
||||
// watcher setup is still in flight. Loader presence and fiber state own
|
||||
// A surface can dispose the whole tree while boot or this post-boot watcher
|
||||
// setup is still in flight. Loader presence and fiber state own
|
||||
// liveness; the local signal fact distinguishes that expected exit race
|
||||
// from a real HMR error.
|
||||
if (watchProfilePatch
|
||||
|
||||
@@ -87,8 +87,8 @@ describe('parseDshArgs', () => {
|
||||
expect(exitCode(['web', '--dump-config', '--dump-default-config'])).toBe(1)
|
||||
expect(exitCode(['web', '--dump-default-config', '--patch', 'w.yml'])).toBe(1)
|
||||
expect(exitCode(['web', '--patch='])).toBe(1)
|
||||
// A dump never runs the app's startup row, so it cannot show what that
|
||||
// app's own flags would decide; printing a tree that differs from the same
|
||||
// A dump never runs app command-line providers, so it cannot show what
|
||||
// those flags would decide; printing a tree that differs from the same
|
||||
// invocation's boot would mislead.
|
||||
expect(exitCode(['web', '--dump-config', '--port', '8080'])).toBe(1)
|
||||
expect(exitCode(['--profile', 'web', '--dump-config', '-h'])).toBe(1)
|
||||
|
||||
@@ -128,8 +128,8 @@ function createProfileLifecycleFixture(): ProfileLifecycleFixture {
|
||||
return { home, ready, settled, disposed, interrupt }
|
||||
}
|
||||
|
||||
function startProfileLifecycle(fixture: ProfileLifecycleFixture) {
|
||||
return execa(process.execPath, [dshBin, '--profile', 'lifecycle'], {
|
||||
function startProfileLifecycle(fixture: ProfileLifecycleFixture, args: readonly string[] = []) {
|
||||
return execa(process.execPath, [dshBin, '--profile', 'lifecycle', ...args], {
|
||||
cwd: fixture.home,
|
||||
input: '',
|
||||
reject: false,
|
||||
@@ -203,9 +203,9 @@ interface StartupFixture {
|
||||
}
|
||||
|
||||
/**
|
||||
* A custom profile whose bundle owns a command line: a startup row whose
|
||||
* `cmdlineArgs` injection identifies it to the launcher, and a row that reads
|
||||
* what it resolved through a `!!js` config expression. Both plugin modules resolve
|
||||
* A custom profile whose ordinary provider plugin injects `cmdlineArgs`, plus
|
||||
* a row that reads its app-owned service through a `!!js` config expression.
|
||||
* Both plugin modules resolve
|
||||
* `@deepseek-ai/dsh-cmdline` and `commander` through the profile module
|
||||
* fallback, exactly as an installed out-of-tree bundle does.
|
||||
*/
|
||||
@@ -219,12 +219,13 @@ function createStartupFixture(): StartupFixture {
|
||||
mkdirSync(bundleDir, { recursive: true })
|
||||
writeFileSync(join(bundleDir, 'startup.mjs'), [
|
||||
"import { Command } from 'commander'",
|
||||
"import { runStartup } from '@deepseek-ai/dsh-cmdline'",
|
||||
"import { parseCmdline } from '@deepseek-ai/dsh-cmdline'",
|
||||
"export const name = 'fixture-startup'",
|
||||
"export const inject = ['cmdlineArgs']",
|
||||
'export function apply(ctx) {',
|
||||
" const program = new Command().name('fixture').option('--generation <value>', 'echoed generation')",
|
||||
" return runStartup(ctx, 'fixtureStartup', program, parsed => ({ generation: parsed.opts().generation }))",
|
||||
' const values = parseCmdline(ctx, program, parsed => ({ generation: parsed.opts().generation }))',
|
||||
' if (values !== undefined) ctx.provide(\'fixtureStartup\', values)',
|
||||
'}',
|
||||
'',
|
||||
].join('\n'))
|
||||
@@ -260,11 +261,10 @@ function createStartupFixture(): StartupFixture {
|
||||
` name: ${pathToFileURL(join(bundleDir, 'waiting.mjs')).href}`,
|
||||
' inject: [fixtureStartup]',
|
||||
' config:',
|
||||
// The flag the startup row resolved wins over the value written beside it.
|
||||
" generation: !!js ctx.get('fixtureStartup')?.generation ?? 'bundle-default'",
|
||||
// Lazy interpolation runs only after the provider's service is injected.
|
||||
" generation: !!js ctx.fixtureStartup.generation ?? 'bundle-default'",
|
||||
' - id: fixture-startup',
|
||||
` name: ${pathToFileURL(join(bundleDir, 'startup.mjs')).href}`,
|
||||
' inject: [cmdlineArgs]',
|
||||
' - id: reload-witness',
|
||||
` name: ${pathToFileURL(join(bundleDir, 'witness.mjs')).href}`,
|
||||
'',
|
||||
@@ -466,21 +466,9 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)',
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
it('rejects arguments when no active row injects the profile command line', async () => {
|
||||
it('lets a profile without a parser ignore app arguments and dispose on a startup-time signal', async () => {
|
||||
const fixture = createProfileLifecycleFixture()
|
||||
try {
|
||||
const result = await runBuiltBin(['--profile', 'lifecycle', '--help'], { DSH_HOME: fixture.home })
|
||||
expect(result.code).toBe(1)
|
||||
expect(result.stderr).toContain('takes no app arguments because no active row injects cmdlineArgs')
|
||||
expect(existsSync(fixture.ready)).toBe(false)
|
||||
} finally {
|
||||
rmSync(fixture.home, { recursive: true, force: true })
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
it('applies a custom profile bundle and disposes it on a startup-time signal', async () => {
|
||||
const fixture = createProfileLifecycleFixture()
|
||||
const child = startProfileLifecycle(fixture)
|
||||
const child = startProfileLifecycle(fixture, ['--unclaimed'])
|
||||
try {
|
||||
await waitForFile(fixture.ready)
|
||||
requestProfileShutdown(child, fixture)
|
||||
@@ -551,8 +539,8 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)',
|
||||
const child = startStartupProfile(fixture, ['--generation', 'flagged'])
|
||||
try {
|
||||
await waitForFile(fixture.ready)
|
||||
// The waiting row started once, already carrying the flag value: the
|
||||
// launcher never saw --generation, and the app resolved it first.
|
||||
// The consumer started once, already carrying the flag value: the
|
||||
// launcher never saw --generation, and the app provider resolved it first.
|
||||
expect(readFileSync(fixture.echo, 'utf8')).toBe('flagged')
|
||||
requestProfileShutdown(child, fixture)
|
||||
expect((await child).exitCode).toBe(0)
|
||||
@@ -562,7 +550,7 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)',
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
it('starts a waiting row on its composed value when the invocation carries no app arguments', async () => {
|
||||
it('starts a consumer on its composed value when the invocation carries no app arguments', async () => {
|
||||
const fixture = createStartupFixture()
|
||||
const child = startStartupProfile(fixture, [])
|
||||
try {
|
||||
@@ -577,7 +565,7 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)',
|
||||
}, 30_000)
|
||||
|
||||
it('keeps the app arguments across a user patch reload', async () => {
|
||||
// A live edit recomposes every row while the startup service remains
|
||||
// A live edit recomposes every row while the provider service remains
|
||||
// active, so each config expression reads the same invocation value (a
|
||||
// served port does not move back to its composed fallback).
|
||||
const fixture = createStartupFixture()
|
||||
|
||||
@@ -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 docs/config-catalog.md
|
||||
config-catalog.md: 64e65e93b165ede2ac6c8fa399b9ce461938b939
|
||||
config-catalog.zh.md: 9f4a7ab071d68cfaf8ae3ea42458babfee67c9fd
|
||||
config-catalog.md: 0813c9e1f1d761b69180bc919d0629e10c7661bc
|
||||
config-catalog.zh.md: cda44f7904196fe2bf401fed2dc5b5e8b28ccf1c
|
||||
+5
-10
@@ -572,7 +572,7 @@ Source: [`packages/goal/goal/src/index.ts:116`](../packages/goal/goal/src/index.
|
||||
Requires: `agentDefaultModel` · `agents` · `sessions`
|
||||
|
||||
```ts config-catalog
|
||||
/** 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
|
||||
@@ -2520,7 +2520,7 @@ Source: [`packages/web/web/src/index.ts:55`](../packages/web/web/src/index.ts)
|
||||
Requires: `httpServer`
|
||||
|
||||
```ts config-catalog
|
||||
/** 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
|
||||
@@ -2533,20 +2533,15 @@ 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[]
|
||||
}
|
||||
|
||||
/** Web runtime mode: production, or development when the client-plugin HMR receiver is active. */
|
||||
export type WebMode = 'production' | 'development'
|
||||
```
|
||||
|
||||
Source: [`packages/bundle/web-app/src/index.ts:40`](../packages/bundle/web-app/src/index.ts)
|
||||
Source: [`packages/bundle/web-app/src/index.ts:43`](../packages/bundle/web-app/src/index.ts)
|
||||
|
||||
## `@deepseek-ai/dsh-web-fetch-local`
|
||||
|
||||
|
||||
@@ -574,7 +574,7 @@ export interface Config {
|
||||
需要:`agentDefaultModel` · `agents` · `sessions`
|
||||
|
||||
```ts config-catalog
|
||||
/** 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
|
||||
@@ -2521,7 +2521,7 @@ export interface WebServiceConfig {
|
||||
需要:`httpServer`
|
||||
|
||||
```ts config-catalog
|
||||
/** 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
|
||||
@@ -2534,20 +2534,15 @@ 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[]
|
||||
}
|
||||
|
||||
/** Web runtime mode: production, or development when the client-plugin HMR receiver is active. */
|
||||
export type WebMode = 'production' | 'development'
|
||||
```
|
||||
|
||||
来源:[`packages/bundle/web-app/src/index.ts:40`](../packages/bundle/web-app/src/index.ts)
|
||||
来源:[`packages/bundle/web-app/src/index.ts:43`](../packages/bundle/web-app/src/index.ts)
|
||||
|
||||
## `@deepseek-ai/dsh-web-fetch-local`
|
||||
|
||||
|
||||
@@ -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 docs/user/develop/basic/publish.md
|
||||
publish.md: 04520b0fb7d30c716e3c87761bd38f0c25824739
|
||||
publish.zh.md: 7b0e0141dc0522bb5ec356aa8cba1618c9517f09
|
||||
publish.md: 8437c7ea5c4cb966f9f3d68977949c78986ec9a5
|
||||
publish.zh.md: 4409dbfda060a84b316029d87ec985209cfa286a
|
||||
@@ -99,7 +99,7 @@ The effective configuration composes over an empty root by applying, in order:
|
||||
3. The home-level `$DSH_HOME/cordis.patch.yml` — machine-local preferences shared by every profile.
|
||||
4. Each `--patch <path>` overlay, in argv order.
|
||||
|
||||
App arguments are not another patch layer. A surface bundle can resolve them through a startup service, described below.
|
||||
App arguments are not another patch layer. A surface bundle can resolve them through an ordinary app-owned service, described below.
|
||||
|
||||
Later layers win per row, and a patch replaces a row's entire `config` value rather than deep-merging keys. Two consequences for bundle authors:
|
||||
|
||||
@@ -110,17 +110,16 @@ In-box bundle names always resolve from the dsh installation itself; pnpm manage
|
||||
|
||||
## Give a surface bundle its own command line
|
||||
|
||||
A bundle that defines a runnable app marks its startup row through the injection it already requires:
|
||||
A bundle that defines a runnable app mounts an ordinary provider plugin:
|
||||
|
||||
```yaml
|
||||
- id: hello-startup
|
||||
name: 'dsh-hello-plugin/startup'
|
||||
inject: [cmdlineArgs]
|
||||
```
|
||||
|
||||
That row calls `runStartup` from [`@deepseek-ai/dsh-cmdline`](../../../../packages/boot/cmdline/README.md) with the app's own commander program. The launcher hands it every argument after the launcher flags, so app-specific flags need no launcher change. Loader mounts the composition once, waits for each row's injections, and only then evaluates that row's `!!js` config against its injected context.
|
||||
The plugin exports `inject = ['cmdlineArgs']`, calls `parseCmdline` from [`@deepseek-ai/dsh-cmdline`](../../../../packages/boot/cmdline/README.md) with its own commander program, and provides the returned value as its app-owned service. The launcher hands every plugin the same immutable arguments after launcher flags, so app-specific flags need no launcher change and multiple plugins may parse the snapshot. The Loader row needs no launcher marker or special kind.
|
||||
|
||||
Rows configured by those arguments inject the startup service and read it from their own `!!js` options, with the deployment value beside it as the fallback:
|
||||
Rows configured by those arguments inject the provider's service and read it from their own `!!js` options, with the deployment value beside it as the fallback:
|
||||
|
||||
```yaml
|
||||
- id: my-app
|
||||
@@ -130,7 +129,7 @@ Rows configured by those arguments inject the startup service and read it from t
|
||||
port: !!js ctx.myAppStartup.port ?? 8080
|
||||
```
|
||||
|
||||
On `--help`, the service is not provided, so those rows never activate. An app layered over another app disables the lower startup row, because one composition has one command-line owner.
|
||||
On `--help`, the provider publishes no service, so those rows never activate. Loader mounts the composition once, waits for each row's ordinary injections, and only then evaluates that row's `!!js` config against its injected context.
|
||||
|
||||
## Installing from GitHub: the build-script catch
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ dsh --profile demo
|
||||
3. home 级的 `$DSH_HOME/cordis.patch.yml`——各 profile 共享的机器本地偏好。
|
||||
4. 每个 `--patch <path>` overlay,按 argv 顺序。
|
||||
|
||||
应用参数不是另一层 patch。表层组合包可以通过下文所述的启动服务解析它们。
|
||||
应用参数不是另一层 patch。表层组合包可以通过下文所述的普通应用自有服务解析它们。
|
||||
|
||||
后应用的层按行胜出,且 patch 会替换目标行的整个 `config` 值,而不是深度合并各键。这给组合包作者带来两个推论:
|
||||
|
||||
@@ -110,17 +110,16 @@ dsh --profile demo
|
||||
|
||||
## 让表层组合包持有自己的命令行
|
||||
|
||||
定义了可运行应用的组合包可以通过启动行本来就需要的注入来标记它:
|
||||
定义了可运行应用的组合包挂载一个普通提供方插件:
|
||||
|
||||
```yaml
|
||||
- id: hello-startup
|
||||
name: 'dsh-hello-plugin/startup'
|
||||
inject: [cmdlineArgs]
|
||||
```
|
||||
|
||||
该行使用应用自己的 commander program 调用 [`@deepseek-ai/dsh-cmdline`](../../../../packages/boot/cmdline/README.md) 中的 `runStartup`。启动器把自身 flag 之后的所有参数交给它,因此添加应用专属 flag 无需修改启动器。Loader 只挂载一次组合,等待每一行的注入,再基于其已注入的上下文求值该行的 `!!js` 配置。
|
||||
该插件导出 `inject = ['cmdlineArgs']`,使用自己的 commander program 调用 [`@deepseek-ai/dsh-cmdline`](../../../../packages/boot/cmdline/README.md) 中的 `parseCmdline`,再把返回值作为应用自有服务提供出去。启动器把自身 flag 之后的同一份不可变参数交给每个插件,因此添加应用专属 flag 无需修改启动器,多个插件也可以解析该快照。Loader 行不需要启动器标记或特殊类型。
|
||||
|
||||
受这些参数配置的行会注入启动服务,并在自己的 `!!js` 选项中读取它,同时把部署取值写在旁边作为回退:
|
||||
受这些参数配置的行会注入提供方服务,并在自己的 `!!js` 选项中读取它,同时把部署取值写在旁边作为回退:
|
||||
|
||||
```yaml
|
||||
- id: my-app
|
||||
@@ -130,7 +129,7 @@ dsh --profile demo
|
||||
port: !!js ctx.myAppStartup.port ?? 8080
|
||||
```
|
||||
|
||||
遇到 `--help` 时,该服务不会被提供,所以这些行不会激活。叠加在另一应用之上的应用会禁用下层启动行,因为一套组合只能有一个命令行所有者。
|
||||
遇到 `--help` 时,提供方不会发布该服务,所以这些行不会激活。Loader 只挂载一次组合,等待每一行的普通注入,再基于其已注入的上下文求值该行的 `!!js` 配置。
|
||||
|
||||
## 从 GitHub 安装:构建脚本这道坎
|
||||
|
||||
|
||||
@@ -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 docs/user/guide/config.md
|
||||
config.md: 7a8492d45fc3710958853b8498f90f5a19b62f4a
|
||||
config.zh.md: 62a1693a13cdd4b2428085187b73b69d429cde6e
|
||||
config.md: 1d3ad5ce36d4b360ba5156b6be28a6caae4a23d4
|
||||
config.zh.md: 7f8bfaa77066f2976a5667e3ac402814a7afdf96
|
||||
@@ -51,7 +51,7 @@ Cordis starts sibling entries concurrently. A plugin declares required services
|
||||
|
||||
## CLI patch layers
|
||||
|
||||
`dsh --profile <name>` composes the profile's bundle patch layers (its manifest's `dsh.profile.bundles` list, in order) over an empty root, then the profile's own `~/.dsh/profiles/<name>/cordis.patch.yml`, the home-level `$DSH_HOME/cordis.patch.yml`, and each `--patch <path>` overlay. Later layers win per row. App flags are not another patch layer: the bundle's `cmdlineArgs`-injected startup row resolves them into a service, and rows that retain a `!!js` read of that service give the invocation value precedence.
|
||||
`dsh --profile <name>` composes the profile's bundle patch layers (its manifest's `dsh.profile.bundles` list, in order) over an empty root, then the profile's own `~/.dsh/profiles/<name>/cordis.patch.yml`, the home-level `$DSH_HOME/cordis.patch.yml`, and each `--patch <path>` overlay. Later layers win per row. App flags are not another patch layer: an ordinary bundle plugin injects `cmdlineArgs` and provides parsed values as its own service, while rows that inject and retain a `!!js` read of that service give the invocation value precedence.
|
||||
|
||||
A patch replaces a row's entire `config` value; it does not deep-merge keys. For example, patching `llm-deepseek` with only `config: { thinking: disabled }` also removes that row's configured `apiKey` and `baseURL`, so restate every key the row must retain.
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ Cordis 会并发启动同级配置项。插件通过 `inject` 声明必需服务
|
||||
|
||||
## CLI 补丁层
|
||||
|
||||
`dsh --profile <name>` 按该 profile 的 manifest(元数据清单)中 `dsh.profile.bundles` 列表的顺序,在空根之上组合各组合包补丁层,随后依次应用该 profile 自己的 `~/.dsh/profiles/<name>/cordis.patch.yml`、home 级的 `$DSH_HOME/cordis.patch.yml` 与每个 `--patch <path>` overlay。同一行以较后的层为准。应用 flag 并不是另一层 patch:组合包中注入 `cmdlineArgs` 的启动行把它们解析成服务,而保留了读取该服务的 `!!js` 表达式的行会让本次调用的取值优先。
|
||||
`dsh --profile <name>` 按该 profile 的 manifest(元数据清单)中 `dsh.profile.bundles` 列表的顺序,在空根之上组合各组合包补丁层,随后依次应用该 profile 自己的 `~/.dsh/profiles/<name>/cordis.patch.yml`、home 级的 `$DSH_HOME/cordis.patch.yml` 与每个 `--patch <path>` overlay。同一行以较后的层为准。应用 flag 并不是另一层 patch:组合包中的普通插件注入 `cmdlineArgs`,再把解析值作为自身服务提供;注入该服务并保留其 `!!js` 读取的行会让本次调用的取值优先。
|
||||
|
||||
补丁会替换目标行的整个 `config` 值,而不是深度合并各个键。例如,只用 `config: { thinking: disabled }` 修补 `llm-deepseek`,也会移除该行原有的 `apiKey` 与 `baseURL`;因此必须重新写出该行需要保留的全部键。
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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.
|
||||
@@ -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 的优先级。
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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 = () => {}
|
||||
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -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')
|
||||
|
||||
Generated
+3
-4
@@ -1185,10 +1185,6 @@ importers:
|
||||
version: 4.0.9
|
||||
|
||||
packages/boot/cmdline:
|
||||
dependencies:
|
||||
commander:
|
||||
specifier: ^15.0.0
|
||||
version: 15.0.0
|
||||
devDependencies:
|
||||
'@deepseek-ai/cordis':
|
||||
specifier: ^4.0.0-rc.7
|
||||
@@ -1202,6 +1198,9 @@ importers:
|
||||
'@deepseek-ai/dsh-invariants':
|
||||
specifier: workspace:^
|
||||
version: link:../../support/invariants
|
||||
commander:
|
||||
specifier: ^15.0.0
|
||||
version: 15.0.0
|
||||
|
||||
packages/bundle/base:
|
||||
dependencies:
|
||||
|
||||
Reference in New Issue
Block a user