@knyazevai/dsh 0.1.4 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Knyazev AI
3
+ Copyright (c) 2026 DeepSeek
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,22 @@
1
+ # Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
2
+ # section, a hash of its English and Chinese blocks outside code blocks and generated regions.
3
+ # After editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write apps/cli/README.md
5
+ /knyazevai-dsh:
6
+ en: 7f209ab22bae6892
7
+ zh: 0beec262978f532c
8
+ /knyazevai-dsh/entry-modes:
9
+ en: a1e035a813554366
10
+ zh: b87053214afe71b6
11
+ /knyazevai-dsh/app-arguments:
12
+ en: cc03e6b75206661b
13
+ zh: 99e41f4143198352
14
+ /knyazevai-dsh/profiles:
15
+ en: fbbccefed0aa4bf7
16
+ zh: 74876aced6ad2f0a
17
+ /knyazevai-dsh/optional-overlays:
18
+ en: 3a40ddc44e55f79c
19
+ zh: 8d3949132e1ef93c
20
+ /knyazevai-dsh/development:
21
+ en: 87b16c6ce185903d
22
+ zh: b83991dd89607c22
package/README.md CHANGED
@@ -1,113 +1,64 @@
1
- # @knyazevai/dsh
1
+ # `@knyazevai/dsh`
2
2
 
3
- Плагин [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness): провайдер **Knyazev AI**, модели Flash / Kimi / MiniMax, thinking и effort `off / high / max`. После установки выбран **Flash max** — в Models остаётся только ключ.
3
+ English | [中文](README.zh.md)
4
4
 
5
- ## Установка
5
+ The `dsh` command is the sole supported Node application launcher: profiles are ordered stacks of plugin-bundle patch layers under the user's own overrides. SDK and ACP are profiles, not separate public bins. The Python runtime wheel packages this same command; the SDK defaults to `sdk`, and the minimal example selects `sdk-minimal`. [`src/args.ts`](src/args.ts) owns the command grammar, and [`src/bin.ts`](src/bin.ts) loads only the selected runner. Invalid commands, options from another mode, and fatal configuration or boot failures exit nonzero.
6
6
 
7
- Нужны [Node.js](https://nodejs.org/) и [pnpm](https://pnpm.io/).
7
+ ## Entry modes
8
8
 
9
- Профили DSH — pnpm workspace, поэтому нужен `-w`.
10
-
11
- ```sh
12
- npx @deepseek-ai/dsh plugin --profile web add -w @knyazevai/dsh
13
- npx @deepseek-ai/dsh web
14
- ```
9
+ | Command | Purpose |
10
+ |---|---|
11
+ | `dsh <name>` / `dsh --profile <name>` | Boot the named profile under `$DSH_HOME/profiles/<name>`. |
12
+ | `dsh --profile <name> --from-default-profile <template>` | Replace a custom profile with a fresh copy of a shipped template, then boot it. |
13
+ | `dsh --profile acp` | Serve automation clients over ACP stdio until disconnect. |
14
+ | `dsh --profile headless "job"` | Run one fresh persisted session, print the final answer, and exit. |
15
+ | `dsh --profile sdk` | Serve SDK clients over JSON-RPC stdio until shutdown or disconnect. |
16
+ | `dsh --profile sdk-minimal` | Serve SDK clients with the standalone minimal agent tree. |
17
+ | `dsh web` | Boot the Web profile. |
18
+ | `dsh plugin --profile <name> <pnpm args>` | Manage a profile's plugins by forwarding to pnpm in the profile directory. |
15
19
 
16
- Пока пакет не на npm — ставь с GitHub:
20
+ The invoking directory is the default workspace root. The `web`, `headless`, `sdk`, `sdk-minimal`, and `acp` profiles auto-initialize on first use from shipped templates. Create or reset another profile at a non-shipped name with `--from-default-profile`, or initialize a base-backed profile through `dsh plugin`. The `desktop` name is reserved for the Electron-owned profile, so the CLI rejects boot and config-dump requests for it. The npm CLI also rejects its plugin-management requests; the [Desktop-installed command](../desktop/README.md#bundled-command-runtime) can manage the initialized Desktop profile using that installation’s runtime.
17
21
 
18
- ```sh
19
- npx @deepseek-ai/dsh plugin --profile web add -w git+https://github.com/knyazev741/knyazevai-dsh.git
20
- ```
22
+ ## App arguments
21
23
 
22
- Локально из клона:
24
+ 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)). The first token the launcher does not recognize starts the app's arguments:
23
25
 
24
26
  ```sh
25
- npx @deepseek-ai/dsh plugin --profile web add -w .
27
+ dsh --profile web --port 8080 # --port belongs to the web app
28
+ dsh --profile tui --resume <id> # example, assuming the tui profile is installed; --resume belongs to the terminal app
29
+ dsh --profile headless "run the tests"
30
+ dsh --profile web --help # the web app's flags, not the launcher's
31
+ dsh --help # the launcher's own help
26
32
  ```
27
33
 
28
- Для headless то же с `--profile headless`.
29
-
30
- ## После установки
31
-
32
- Новые сессии сразу идут на **Knyazev AI / DeepSeek V4 Flash** с effort **max**. Kimi и MiniMax уже в пикере, сабагенты на том же маршруте.
34
+ <a id="profiles"></a>
35
+ ## Profiles
33
36
 
34
- Ключ в пакет не входит. Если `KNYAZEV_AI_API_KEY` ещё не в окружении — открой Harness → Models → **Knyazev AI** и вставь `kn_live_…` из [кабинета](https://knyazevai.work). Модели выбирать не нужно.
37
+ A profile directory holds a `package.json` (out-of-tree plugin dependencies plus the profile manifest `dsh.profile` with its ordered `bundles` list) and a `cordis.patch.yml` (the user's own patch layer). `dsh-hmr`, when enabled in YAML, watches the profile manifest and both profile and home patch files, then recomposes all layers through one serialized reload. Without HMR, changes apply on restart. Edits arriving during watcher registration use the same nonfatal reload reporting as later edits. [Plugin Manager](../../packages/boot/plugin-manager/README.md) shares package operations and the profile write lock with `dsh plugin`; package updates retain disabled bundle selections. CLI package commands inherit authentication variables and terminal descriptors, including interactive build approval; service calls retain their scrubbed environment and captured diagnostics.
35
38
 
36
- Не копируй YAML руками и не дублируй провайдер в `settings.yaml`. Пакет кладёт маршрут и дефолт в composition; ключ живёт в credentials. Сохранённый выбор в `settings.yaml` по-прежнему перекрывает composition.
39
+ Installation and profile startup enforce the declared `engines.dsh` range, or DSH peer ranges when it is absent, against the same runtime version shown by `dsh --version`. Incompatible plugins require an explicitly acknowledged exact-version exemption. The [plugin manager's compatibility reference](../../packages/boot/plugin-manager/README.md#version-compatibility-and-exemptions) documents `version-exemptions`, `allow-version`, `revoke-version`, persistence, and risks.
37
40
 
38
- ## Полная сборка с фиксом компактинга
41
+ The tree composes over an empty root:
42
+ - each bundle's patch in `dsh.profile.bundles` order
43
+ - then the profile's `cordis.patch.yml`, then the home-level `$DSH_HOME/cordis.patch.yml`
44
+ - then `--patch` overlays
39
45
 
40
- Обычная установка по имени использует официальный релиз DeepSeek Harness, в котором bounded-компактинг для огромных контекстов (400k) ещё не вышел. Если он нужен (большие сессии сжимаются по кусочкам, а не падают по `pi-ai stream idle timeout`) — запусти харнесс из форка с этим фиксом + плагин:
46
+ Bundles named in `dsh.profile.bundles` resolve from the dsh installation first (`@knyazevai/dsh-base`, `@knyazevai/dsh-web-app`, `@knyazevai/dsh-headless`, `@knyazevai/dsh-sdk-app`, `@knyazevai/dsh-sdk-minimal`, `@knyazevai/dsh-acp-app`), then from the profile's own `node_modules`, where pnpm installs out-of-tree plugins.
41
47
 
42
- ```sh
43
- git clone https://github.com/knyazev741/deepseek-harness
44
- cd deepseek-harness
45
- pnpm install
46
- pnpm run build
47
- pnpm dsh plugin --profile fork-web add -w @knyazevai/dsh@0.1.4
48
- pnpm dsh web
49
- ```
50
-
51
- Фикс `maxSummarizationInputTokens` — код харнесса, он есть только в этой сборке; плагин несёт его конфиг (только для `knyazev-ai`).
52
-
53
- **Как форк держится свежим по upstream (автоматически, с AI-ревью).** В форке есть два воркфлоу:
54
- - `upstream-sync.yml` — раз в час тянет официальный `deepseek-ai/deepseek-harness` master в ветку-ПР `sync/upstream-master` (конфликты решаются в пользу форка);
55
- - `upstream-review.yml` — на каждом таком ПР гоняет sanity-гейты (typecheck + тесты) и прогоняет многоходовой headless-агент Knyazev (`knyazev-ai/deepseek-v4-flash`), который ревьюит дифф и отдаёт вердикт `{safe, summary, risks}`. Авто-мёрж ПР делается **только при вердикте safe**; risky остаётся человеку. Никогда ничего не деплоит.
48
+ Use `--dump-default-config` and `--dump-config` to inspect the composed tree without booting it. `--dump-config-schema` imports the composed tree's declared plugin schemas and prints JSON Schema for entries and patches instead of configuration values; read the [schema-dump safety and scope](reference/README.md#config-schema-dump) before inspecting untrusted plugins.
56
49
 
57
- Для ревью в настройках репозитория форка нужен секрет `KNYAZEV_AI_API_KEY` (тот же ключ маршрута knyazev-ai).
50
+ The [CLI behavior reference](reference/README.md) owns exact layer precedence, flags, shutdown behavior, deployment defaults, and source execution. The [startup and reload failure table](../../packages/boot/app-boot/README.md#startup-and-reload-failures) compares optional and required plugin failures with configuration HMR.
58
51
 
59
- Для человека обновление сводится к `git pull` в клоне + `pnpm install && pnpm run build` — сами изменения upstream уже засинканы и отревьюены на стороне форка.
60
-
61
- Пока этот фикс не в официальном релизе, обычная установка по имени compaction-фикса не даёт — только запуск из форка.
62
-
63
- ## Что ставится
64
-
65
- | Поле | Значение |
66
- |---|---|
67
- | Provider | `knyazev-ai` |
68
- | Endpoint | `https://knyazevai.work/v1` |
69
- | Models | `deepseek-v4-flash`, `kimi-2.6`, `minimax-2.7` |
70
- | Thinking | qwen / `enable_thinking` |
71
- | Effort | `off`, `high`, `max` (Flash и Kimi) |
52
+ ## Optional overlays
72
53
 
73
- MiniMax без пикера effort: модель не отдаёт reasoning отдельным полем.
54
+ `config/examples/` ships opt-in overlays for GitHub review webhooks, memory MCP servers, and runtime Cordis tools. They are never part of a default profile; the [user guides](../../docs/user/guide/index.md) and [developer practice guides](../../docs/user/develop/practice/index.md) own setup and safety instructions.
74
55
 
75
- Дефолт Harness после установки: `knyazev-ai` / `deepseek-v4-flash`, effort `max`. Сабагенты (`subagent`, `subagent_fork`) на том же маршруте.
56
+ ## Development
76
57
 
77
- ## Обновление / снятие
58
+ Production runs require built package and frontend artifacts. From the repository root, run `pnpm run build` separately, then use `pnpm dsh <args...>` to run the TypeScript entry and forward every argument; the [source-execution reference](reference/README.md#source-execution) owns the module-resolution contract.
78
59
 
79
- ```sh
80
- npx @deepseek-ai/dsh plugin --profile web update
81
- npx @deepseek-ai/dsh plugin --profile web remove -w @knyazevai/dsh
82
- ```
83
-
84
- ## Релиз (публикация в npm)
85
-
86
- Пакет публикуется автоматически: GitHub Actions прогоняет тесты и на пуш тега `v<версия>` выкладывает `@knyazevai/dsh` в npm.
87
-
88
- Один раз настрой доступ:
89
-
90
- 1. В npm (Account → Access Tokens) создай токен уровня **Automation** (без двухфакторки).
91
- 2. На GitHub в репо → Settings → Secrets and variables → Actions добавь секрет `NPM_TOKEN` с этим токеном.
92
- 3. `publishConfig.access: public` уже стоит в `package.json`.
93
-
94
- Дальше на каждый новый релиз:
95
-
96
- ```sh
97
- npm version patch # поднимает версию: patch | minor | major
98
- git push origin main
99
- git push origin v0.1.1 # пуш тега запускает тесты + публикацию
100
- ```
101
-
102
- Тесты перед публикацией идут сами (`prepublishOnly` в `package.json`).
103
-
104
- Установка **по имени** — на любой машине:
105
-
106
- ```sh
107
- npx @deepseek-ai/dsh plugin --profile web add -w @knyazevai/dsh
108
- npx @deepseek-ai/dsh web
109
- ```
60
+ The `@knyazevai/dsh/profile-boot` export provides the shared profile lifecycle to the Desktop host. A resolved application profile supplies its own installation anchor for runtime package resolution while retaining the Harness home patch, proxy environment, telemetry switch, patch reload, and bounded shutdown.
110
61
 
111
- ## Docs
62
+ Packaged installations call the same `runCli()` entry with their package-manager executable. The Desktop carrier also enables plugin operations for its initialized profile; npm launches omit these options. Installation-owned package environments apply only to plugin package operations; the invoking directory, ordinary profile selection, and agent-shell PATH retain their CLI meanings.
112
63
 
113
- https://knyazevai.work/docs
64
+ The [Web failure matrix](tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts) runs the built CLI through startup failures and native configuration HMR with `awaitWriteFinish` enabled in `test:expected`. It verifies authenticated HTTP responses, diagnostics, recovery, process exits, and disposal without model API calls; the [startup acceptance](tests/profiles/web/tests/web-best-effort-startup.expected.e2e.ts) also covers the shipped required Web dependencies and port conflicts.
package/README.zh.md ADDED
@@ -0,0 +1,64 @@
1
+ # `@knyazevai/dsh`
2
+
3
+ [English](README.md) | 中文
4
+
5
+ `dsh` 是唯一受支持的 Node 应用启动器;profile 由多个插件组合包 patch 层按顺序叠加而成,其上再应用用户自己的覆盖配置。SDK 与 ACP(Agent Client Protocol)都是 profile,而不是独立的公开可执行命令。Python 运行时 wheel 包中也包含同一个命令;SDK 默认使用 `sdk`,极简示例选择 `sdk-minimal`。[`src/args.ts`](src/args.ts) 负责命令语法,[`src/bin.ts`](src/bin.ts) 只加载选中的运行器。无效命令、来自其他模式的选项,以及致命的配置或启动错误都会以非零状态退出。
6
+
7
+ ## 入口模式
8
+
9
+ | 命令 | 用途 |
10
+ |---|---|
11
+ | `dsh <name>` / `dsh --profile <name>` | 启动位于 `$DSH_HOME/profiles/<name>` 的指定 profile。 |
12
+ | `dsh --profile <name> --from-default-profile <template>` | 用随附模板的全新副本替换自定义 profile,然后启动它。 |
13
+ | `dsh --profile acp` | 通过 ACP stdio 为自动化客户端提供服务,直至断开连接。 |
14
+ | `dsh --profile headless "job"` | 运行一个全新的持久化会话,打印最终答案并退出。 |
15
+ | `dsh --profile sdk` | 通过 JSON-RPC stdio 为 SDK 客户端提供服务,直至关闭或断开连接。 |
16
+ | `dsh --profile sdk-minimal` | 以独立极简 agent(智能体)配置树为 SDK 客户端提供服务。 |
17
+ | `dsh web` | 启动 Web profile。 |
18
+ | `dsh plugin --profile <name> <pnpm args>` | 通过在 profile 目录中转发给 pnpm 来管理该 profile 的插件。 |
19
+
20
+ 运行命令时所在的目录将作为默认 workspace 根目录。`web`、`headless`、`sdk`、`sdk-minimal` 和 `acp` profile 在首次使用时会从随附模板自动初始化。使用 `--from-default-profile` 可以基于这些模板之一,在非内置名称处创建或重置其他 profile;通过 `dsh plugin` 则可以初始化一个以 base 为基础的 profile。`desktop` 名称保留给 Electron 持有的 profile,因此 CLI(命令行界面)会拒绝针对它的启动和配置 dump 请求。npm CLI 也会拒绝其插件管理请求;[Desktop 内置命令](../desktop/README.zh.md#bundled-command-runtime)可以使用该安装的运行时管理已初始化的 Desktop profile。
21
+
22
+ ## 应用参数
23
+
24
+ 启动器只解析自身的 flag,并将其后的所有内容交给已启动的 profile;注入该 profile 的任意应用插件都可以解析这份共享的不可变快照([`dsh-cmdline`](../../packages/boot/cmdline/README.zh.md))。启动器无法识别的第一个 token 标志着应用参数的开始:
25
+
26
+ ```sh
27
+ dsh --profile web --port 8080 # --port belongs to the web app
28
+ dsh --profile tui --resume <id> # example, assuming the tui profile is installed; --resume belongs to the terminal app
29
+ dsh --profile headless "run the tests"
30
+ dsh --profile web --help # the web app's flags, not the launcher's
31
+ dsh --help # the launcher's own help
32
+ ```
33
+
34
+ <a id="profiles"></a>
35
+ ## Profile
36
+
37
+ profile 目录包含一个 `package.json`,其中记录树外插件依赖,以及 profile manifest(元数据清单)`dsh.profile`、其中按顺序排列的 `bundles` 列表;还包含一个 `cordis.patch.yml`,其中保存用户自己的 patch 层。在 YAML 中启用的 `dsh-hmr` 监视 profile manifest、profile 与 home 级 patch 文件,再通过统一串行重载重新组合所有层。未启用 HMR 时,更改在重启后生效。监听器注册期间发生的编辑与后续编辑使用相同的非致命重载错误报告。[插件管理器](../../packages/boot/plugin-manager/README.zh.md) 与 `dsh plugin` 共享包操作和 profile 写锁;更新依赖会保留已停用的组合包选择。CLI 包操作继承认证环境和终端描述符,支持交互式构建批准;service 调用保留清理后的环境并捕获诊断。
38
+
39
+ 安装和 profile 启动会按声明的 `engines.dsh` 范围(未声明时按 DSH peer 范围),检查与 `dsh --version` 显示值相同的运行时版本。不兼容插件需要用户明确确认精确版本豁免。[插件管理器的兼容性参考](../../packages/boot/plugin-manager/README.zh.md#version-compatibility-and-exemptions)说明 `version-exemptions`、`allow-version`、`revoke-version`、持久化规则与风险。
40
+
41
+ 配置树以空根为起点,依次叠加以下配置层:
42
+ - `dsh.profile.bundles` 中各组合包的 patch
43
+ - profile 自身的 `cordis.patch.yml`,然后是 home 级的 `$DSH_HOME/cordis.patch.yml`
44
+ - `--patch` 指定的覆盖层
45
+
46
+ `dsh.profile.bundles` 中列出的组合包先从 dsh 安装目录解析(`@knyazevai/dsh-base`、`@knyazevai/dsh-web-app`、`@knyazevai/dsh-headless`、`@knyazevai/dsh-sdk-app`、`@knyazevai/dsh-sdk-minimal`、`@knyazevai/dsh-acp-app`),再从 profile 自身的 `node_modules` 解析;pnpm 会将树外插件安装到该目录。
47
+
48
+ 使用 `--dump-default-config` 和 `--dump-config` 可在不启动的情况下检查组合后的配置树。`--dump-config-schema` 会导入组合树中插件声明的 schema,并打印描述 entry 与 patch 的 JSON Schema,而不是配置值;检查不受信任的插件前,请阅读 [schema dump 的安全性与范围](reference/README.zh.md#config-schema-dump)。
49
+
50
+ 层的确切优先级、flag、关闭行为、部署默认值和源码执行方式,以 [CLI 行为参考](reference/README.zh.md)为准。[启动与重载失败表](../../packages/boot/app-boot/README.zh.md#startup-and-reload-failures)对比 optional、required 插件启动失败与配置 HMR 的行为。
51
+
52
+ ## 可选覆盖层
53
+
54
+ `config/examples/` 交付 GitHub 评审 webhook、记忆 MCP 服务器与运行时 Cordis 工具的可选覆盖层。它们绝不属于默认 profile;设置与安全说明由[用户指南](../../docs/user/guide/index.zh.md)和[开发实战指南](../../docs/user/develop/practice/index.zh.md)负责。
55
+
56
+ ## 开发
57
+
58
+ 生产运行需要已构建的包与前端产物。请在仓库根目录单独运行 `pnpm run build`,然后使用 `pnpm dsh <args...>` 运行 TypeScript 入口并转发所有参数;模块解析约定以[源码执行参考](reference/README.zh.md#source-execution)为准。
59
+
60
+ `@knyazevai/dsh/profile-boot` 导出向 Desktop Host 提供共享 profile 生命周期。已解析的应用 profile 为运行时包解析指定自己的安装锚点,同时沿用 Harness home patch、代理环境、遥测开关、patch 热重载和有界关闭。
61
+
62
+ 打包安装通过同一个 `runCli()` 入口传入包管理器可执行文件。Desktop 载体还会启用其已初始化 profile 的插件操作;npm 启动不传入这些选项。安装包提供的包管理环境仅用于插件包操作;调用目录、普通 profile 选择与 agent shell 的 PATH 保留 CLI 语义。
63
+
64
+ [Web 失败矩阵](tests/profiles/web/tests/web-failure-matrix.expected.e2e.ts)在 `test:expected` 中通过构建后的 CLI 验证启动失败与启用 `awaitWriteFinish` 的原生配置 HMR。它不调用模型 API,而是检查经过认证的 HTTP 响应、诊断、恢复、进程退出与 dispose;[启动验收测试](tests/profiles/web/tests/web-best-effort-startup.expected.e2e.ts)还覆盖随附 Web 的必需依赖与端口冲突。
package/bin.mjs ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+
3
+ // A workspace install must run the checkout's source launcher; an npm install
4
+ // outside the repository must run the packaged build.
5
+
6
+ import { existsSync, realpathSync } from 'node:fs'
7
+ import { dirname, join, resolve } from 'node:path'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { spawnSync } from 'node:child_process'
10
+
11
+ const packageRoot = dirname(realpathSync(fileURLToPath(import.meta.url)))
12
+ const repositoryRoot = resolve(packageRoot, '../..')
13
+ const repositoryEntry = join(repositoryRoot, 'scripts/repo-dsh.ts')
14
+ const inRepository = existsSync(repositoryEntry) && existsSync(join(repositoryRoot, 'pnpm-workspace.yaml'))
15
+ const args = inRepository
16
+ ? ['--import', 'tsx/esm', repositoryEntry, ...process.argv.slice(2)]
17
+ : [join(packageRoot, 'lib/bin.js'), ...process.argv.slice(2)]
18
+ const result = spawnSync(process.execPath, args, { env: process.env, stdio: 'inherit' })
19
+
20
+ if (result.error !== undefined) {
21
+ process.stderr.write(`dsh: could not start Node: ${result.error.message}\n`)
22
+ process.exit(1)
23
+ }
24
+
25
+ process.exit(result.status ?? 1)
package/lib/bin.js ADDED
@@ -0,0 +1,260 @@
1
+ #!/usr/bin/env node
2
+ import { StartupError, getDshRuntimeVersion, loadLayeredEnv } from "@knyazevai/dsh-app-boot";
3
+ import { resolveDshHome } from "@knyazevai/dsh-home-paths";
4
+ import { Command, CommanderError, InvalidArgumentError } from "commander";
5
+ import { randomUUID } from "node:crypto";
6
+ import { mkdir, writeFile } from "node:fs/promises";
7
+ import { join } from "node:path";
8
+ import { inspect } from "node:util";
9
+ //#region lib/types/args.js
10
+ /**
11
+ * Commander adapter for the `dsh` command line.
12
+ *
13
+ * The launcher parses only what it owns — which profile to boot, which extra
14
+ * patch overlays to apply, and the config dumps — and hands **everything after
15
+ * its own flags** to the booted tree verbatim, where injected app plugins parse
16
+ * their own flag families and print their own `--help` (see
17
+ * `@knyazevai/dsh-cmdline`). Launcher flags therefore come first: the first
18
+ * token this parser does not recognize starts the inner arguments, so
19
+ * `dsh --profile tui --resume abc` boots the tui profile with `--resume abc`,
20
+ * and `dsh --profile web -h` prints the web app's help, not this one's.
21
+ *
22
+ * `dsh <name>` abbreviates `dsh --profile <name>`; `plugin` manages a profile's
23
+ * plugin dependencies by forwarding to pnpm.
24
+ * @module @knyazevai/dsh/args
25
+ */
26
+ /**
27
+ * Repeatable single-value collector: `--patch a.yml --patch b.yml`. Never
28
+ * variadic — a variadic `--patch` would swallow the inner arguments.
29
+ */
30
+ const collect = (value, previous = []) => [...previous, value];
31
+ function selectProfile(value, previous) {
32
+ if (previous !== void 0) throw new InvalidArgumentError("select a profile only once");
33
+ return value;
34
+ }
35
+ function rejectElectronProfile(program, profile) {
36
+ if (profile.toLowerCase() === "desktop") program.error("error: profile \"desktop\" is managed exclusively by the Electron application");
37
+ }
38
+ /** The launcher's own help text; each app prints its own. */
39
+ const HELP_EXAMPLES = `
40
+ Examples:
41
+ dsh web boot the web profile (same as: dsh --profile web)
42
+ dsh rescue --from-default-profile web
43
+ recreate rescue from the shipped web template, then boot it
44
+ dsh headless "run the tests" answer one task, print the result, and exit
45
+ dsh tui --patch ./extra.yml boot a custom profile with one extra overlay
46
+ dsh tui --resume <session> arguments after the launcher flags reach the app
47
+ dsh web --help the web app's own flags and help
48
+ dsh plugin --profile tui add <package> install a plugin into the tui profile
49
+ `;
50
+ /**
51
+ * Resolve a boot or dump invocation from the launcher flags and the leftover
52
+ * inner arguments.
53
+ * @param program - the command whose options were parsed.
54
+ * @param profile - the profile these flags boot.
55
+ * @param options - the launcher flags commander collected.
56
+ * @param args - the leftover arguments, in argv order.
57
+ * @returns the resolved invocation.
58
+ */
59
+ function resolveBoot(program, profile, options, args) {
60
+ const patches = options.patch ?? [];
61
+ if (patches.includes("")) program.error("error: --patch needs a path");
62
+ if (options.fromDefaultProfile === "") program.error("error: --from-default-profile needs a name");
63
+ const dumps = [
64
+ options.dumpConfig,
65
+ options.dumpDefaultConfig,
66
+ options.dumpConfigSchema
67
+ ].filter(Boolean);
68
+ if (dumps.length === 0) return {
69
+ mode: "profile",
70
+ profile,
71
+ fromDefaultProfile: options.fromDefaultProfile,
72
+ patches,
73
+ args
74
+ };
75
+ if (dumps.length > 1) program.error("error: --dump-config, --dump-default-config, and --dump-config-schema are mutually exclusive");
76
+ if (args.length > 0) program.error(`error: config dumps take no app arguments, got ${args.map((argument) => JSON.stringify(argument)).join(" ")}`);
77
+ if (options.dumpConfigSchema === true) return {
78
+ mode: "dump-config-schema",
79
+ profile,
80
+ fromDefaultProfile: options.fromDefaultProfile,
81
+ patches
82
+ };
83
+ const defaultOnly = options.dumpDefaultConfig === true;
84
+ if (defaultOnly && patches.length > 0) program.error("error: --dump-default-config prints the bundle layers and takes no --patch");
85
+ return {
86
+ mode: "dump-config",
87
+ profile,
88
+ fromDefaultProfile: options.fromDefaultProfile,
89
+ defaultOnly,
90
+ patches
91
+ };
92
+ }
93
+ /**
94
+ * Resolve argv into one invocation, or print and exit for help, version, or an
95
+ * error.
96
+ * @param argv - arguments after the Node binary and script.
97
+ * @param version - version string printed by `--version`.
98
+ * @param manageDesktopProfile - permit Desktop's installed carrier to manage its reserved profile's plugins.
99
+ * @returns the resolved invocation.
100
+ */
101
+ function parseDshArgs(argv, version, manageDesktopProfile = false) {
102
+ const first = argv[0];
103
+ const webProfile = process.env.DSH_REPOSITORY_WEB_PROFILE ?? "fork-web";
104
+ if (webProfile === "") throw new Error("DSH_REPOSITORY_WEB_PROFILE needs a profile name");
105
+ let resolved;
106
+ const program = new Command();
107
+ program.name("dsh").version(version, "-V, --version", "output the version number").usage("[--profile] <name> [options] [app-args...]\n dsh plugin --profile <name> <pnpm-args...>").description("dsh: boot a DeepSeek Harness profile — an ordered stack of plugin-bundle patch layers under your own overrides.").addHelpText("after", HELP_EXAMPLES).exitOverride().helpOption(false).helpCommand(false).allowUnknownOption().passThroughOptions().enablePositionalOptions().argument("[args...]", "arguments for the booted profile's app (see: dsh --profile <name> --help)").option("--profile <name>", "the profile under $DSH_HOME/profiles to boot", selectProfile).option("--from-default-profile <name>", "replace a custom profile with a fresh copy of a shipped profile template").option("--patch <path>", "extra patch-list overlay applied after the profile layer (repeatable)", collect).option("--dump-config", "print the composed profile tree and exit").option("--dump-config-schema", "print JSON Schema for profile entries and patches without mounting").option("--dump-default-config", "print the profile tree without its user layer or --patch overlays and exit").action((args, options) => {
108
+ if (options.profile === void 0) {
109
+ if (args.some((argument) => argument === "-h" || argument === "--help")) program.help();
110
+ program.error("error: --profile <name> is required");
111
+ }
112
+ const profile = options.profile;
113
+ if (profile === "") program.error("error: --profile needs a name");
114
+ rejectElectronProfile(program, profile);
115
+ resolved = resolveBoot(program, profile, options, args);
116
+ });
117
+ if (first === "plugin") {
118
+ const plugin = program.command("plugin").description("manage a profile's plugins by forwarding the remaining arguments to pnpm in the profile directory");
119
+ plugin.helpOption("-h, --help", "show this help").passThroughOptions().requiredOption("--profile <name>", "the profile whose plugins to manage (initialized on first use)", selectProfile).allowUnknownOption().argument("[args...]", "pnpm arguments, forwarded verbatim (add <pkg>, remove <pkg>, why <pkg>, ...)").action((args, options) => {
120
+ if (options.profile === "") program.error("error: --profile needs a name");
121
+ if (!manageDesktopProfile) rejectElectronProfile(plugin, options.profile);
122
+ if (args.length === 0) program.error("error: plugin needs pnpm arguments to forward (e.g. add <package>)");
123
+ resolved = {
124
+ mode: "plugin",
125
+ profile: options.profile.toLowerCase() === "desktop" ? "desktop" : options.profile,
126
+ args
127
+ };
128
+ });
129
+ }
130
+ try {
131
+ const expanded = first !== void 0 && !first.startsWith("-") && first !== "plugin" ? [
132
+ "--profile",
133
+ first === "web" ? webProfile : first,
134
+ ...argv.slice(1)
135
+ ] : argv;
136
+ program.parse(expanded, { from: "user" });
137
+ } catch (error) {
138
+ return process.exit(error instanceof CommanderError ? error.exitCode : 1);
139
+ }
140
+ /* v8 ignore next -- an action resolves or Commander throws */
141
+ if (resolved === void 0) throw new Error("dsh: no invocation resolved");
142
+ return resolved;
143
+ }
144
+ //#endregion
145
+ //#region lib/types/startup-diagnostics.js
146
+ /** Save original startup diagnostics while keeping the terminal report concise. */
147
+ /** Wait for stderr to finish the write before the failed process exits. */
148
+ function writeStderr(text) {
149
+ return new Promise((resolve, reject) => {
150
+ process.stderr.write(text, (error) => {
151
+ if (error) reject(error);
152
+ else resolve();
153
+ });
154
+ });
155
+ }
156
+ /**
157
+ * Print the startup summary and save a private, uniquely named report under DSH_HOME/logs.
158
+ * Failed writes print the complete report to stderr instead of claiming a saved path.
159
+ * @param error - startup audit failure retaining plugin metadata and original errors.
160
+ * @param context - resolved Harness home, application version, and selected profile.
161
+ * @param write - terminal output sink; awaited before returning, defaults to stderr.
162
+ * @returns after saving or printing the report and completing terminal writes.
163
+ */
164
+ async function reportStartupFailure(error, context, write = writeStderr) {
165
+ const now = (/* @__PURE__ */ new Date()).toISOString();
166
+ const report = "WARNING: Raw diagnostics may contain configuration or credential values from plugin errors. Review before sharing.\n\n" + inspect({
167
+ timestamp: now,
168
+ dshVersion: context.version,
169
+ nodeVersion: process.version,
170
+ platform: process.platform,
171
+ arch: process.arch,
172
+ profile: context.profile,
173
+ error
174
+ }, {
175
+ depth: null,
176
+ maxArrayLength: null,
177
+ maxStringLength: null,
178
+ showHidden: true,
179
+ customInspect: false,
180
+ getters: false,
181
+ colors: false
182
+ }) + "\n";
183
+ await write(`${error.message}\n`);
184
+ const logDir = join(context.home, "logs");
185
+ const logPath = join(logDir, `startup-${now.replaceAll(":", "-")}-${randomUUID()}.log`);
186
+ try {
187
+ await mkdir(logDir, {
188
+ recursive: true,
189
+ mode: 448
190
+ });
191
+ await writeFile(logPath, report, {
192
+ flag: "wx",
193
+ mode: 384
194
+ });
195
+ } catch (writeError) {
196
+ await write(`\ndsh: warning: could not write startup diagnostics: ${String(writeError)}\nFull diagnostics:\n${report}`);
197
+ return;
198
+ }
199
+ await write(`\nFull diagnostics: ${logPath}\n`);
200
+ }
201
+ //#endregion
202
+ //#region lib/types/bin.js
203
+ /**
204
+ * Command-line entry for dsh.
205
+ * @module @knyazevai/dsh/bin
206
+ */
207
+ /* v8 ignore file -- built-bin acceptance exercises this self-executing dispatch. */
208
+ /**
209
+ * Run the public dsh command-line interface.
210
+ * @param options - Package runtime and Desktop profile access supplied by the installation.
211
+ * @returns a promise that settles when the selected command mode finishes.
212
+ */
213
+ async function runCli(options = {}) {
214
+ const version = getDshRuntimeVersion();
215
+ const { manageDesktopProfile, ...profileOptions } = options;
216
+ const invocation = parseDshArgs(process.argv.slice(2), version, manageDesktopProfile);
217
+ switch (invocation.mode) {
218
+ case "profile": {
219
+ const { runProfile } = await import("./profile-boot.js");
220
+ try {
221
+ await runProfile({
222
+ environment: loadLayeredEnv("dsh"),
223
+ profile: invocation.profile,
224
+ fromDefaultProfile: invocation.fromDefaultProfile,
225
+ patchFiles: invocation.patches,
226
+ args: invocation.args,
227
+ ...profileOptions
228
+ });
229
+ } catch (error) {
230
+ if (!(error instanceof StartupError)) throw error;
231
+ await reportStartupFailure(error, {
232
+ home: resolveDshHome(),
233
+ version,
234
+ profile: invocation.profile
235
+ });
236
+ process.exit(1);
237
+ }
238
+ break;
239
+ }
240
+ case "plugin": {
241
+ const { runPlugin } = await import("./plugin-CjFov5EZ.js");
242
+ process.exit(await runPlugin(invocation.profile, invocation.args, options.packageManager));
243
+ break;
244
+ }
245
+ case "dump-config": {
246
+ const { runDumpConfig } = await import("./dump-config-Cxlnwi7L.js");
247
+ runDumpConfig(invocation.profile, invocation.defaultOnly, invocation.patches, invocation.fromDefaultProfile);
248
+ break;
249
+ }
250
+ case "dump-config-schema": {
251
+ const { runDumpConfigSchema } = await import("./dump-config-schema-CzGcS3DG.js");
252
+ await runDumpConfigSchema(invocation.profile, invocation.patches, invocation.fromDefaultProfile);
253
+ break;
254
+ }
255
+ default: throw new Error(`dsh: unhandled invocation mode ${JSON.stringify(invocation)}`);
256
+ }
257
+ }
258
+ if (import.meta.main) await runCli();
259
+ //#endregion
260
+ export { runCli };
@@ -0,0 +1,2 @@
1
+ import { n as runDumpConfig } from "./dump-config-DC1v_CSl.js";
2
+ export { runDumpConfig };
@@ -0,0 +1,64 @@
1
+ import { a as prepareProfile, n as PROFILE_ROOT_FILENAME, r as homePatchPath } from "./profile-boot-B44a52oE.js";
2
+ import { loadOptionalPatches, loadOverlayPatches, renderConfigDump } from "@knyazevai/dsh-app-boot";
3
+ import { join, resolve } from "node:path";
4
+ import { existsSync } from "node:fs";
5
+ //#region lib/types/dump-config.js
6
+ /**
7
+ * Config-dump entry for `dsh --profile <name> --dump-config`: compose the
8
+ * profile's patch layers through the include plugin's patch algorithm without
9
+ * booting or evaluating `!!js`, with one source layer per bundle, the
10
+ * profile's own patch file, and each `--patch` overlay.
11
+ * @module @knyazevai/dsh/dump-config
12
+ */
13
+ const NAME = "dsh";
14
+ /* v8 ignore start -- built-bin acceptance drives this boot-free dispatch */
15
+ /**
16
+ * Print a profile composition with comments naming each source file and patch layer.
17
+ * @param profile - the profile name.
18
+ * @param defaultOnly - omit the profile's user layer and `--patch` overlays
19
+ * (the recovery diagnostic for a broken `cordis.patch.yml`, which is then
20
+ * never parsed).
21
+ * @param patches - `--patch` overlay paths, in argv order.
22
+ * @param fromDefaultProfile - shipped template that replaces the profile before loading it.
23
+ */
24
+ function runDumpConfig(profile, defaultOnly, patches, fromDefaultProfile) {
25
+ const loaded = prepareProfile(profile, !defaultOnly, fromDefaultProfile);
26
+ const layers = collectConfigDumpLayers(loaded, defaultOnly, patches);
27
+ process.stdout.write(renderConfigDump(NAME, join(loaded.dir, PROFILE_ROOT_FILENAME), layers));
28
+ }
29
+ /**
30
+ * Read dump layers in bundle, profile, home, then argv order without composing them.
31
+ * @param loaded - prepared profile and parsed bundle and profile patches.
32
+ * @param defaultOnly - omit profile, home, and argv layers without reading their files.
33
+ * @param patches - overlay paths relative to the invoking directory, in argv order.
34
+ * @returns the labeled layers shared by YAML and schema dumps.
35
+ */
36
+ function collectConfigDumpLayers(loaded, defaultOnly, patches) {
37
+ const layers = loaded.layers.map((layer) => ({
38
+ label: layer.packageName,
39
+ patches: layer.patches
40
+ }));
41
+ if (!defaultOnly) {
42
+ if (existsSync(loaded.patchPath)) layers.push({
43
+ label: loaded.patchPath,
44
+ patches: loaded.patches
45
+ });
46
+ const homePatchFile = homePatchPath();
47
+ const homePatches = loadOptionalPatches(NAME, homePatchFile);
48
+ if (homePatches !== void 0) layers.push({
49
+ label: homePatchFile,
50
+ patches: homePatches
51
+ });
52
+ for (const file of patches) {
53
+ const absolute = resolve(file);
54
+ layers.push({
55
+ label: absolute,
56
+ patches: loadOverlayPatches(NAME, absolute)
57
+ });
58
+ }
59
+ }
60
+ return layers;
61
+ }
62
+ /* v8 ignore stop */
63
+ //#endregion
64
+ export { runDumpConfig as n, collectConfigDumpLayers as t };