diff --git a/CHANGELOG.md b/CHANGELOG.md index 303c65643..c97b4274e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,23 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and [中文版](CHANGELOG.zh.md) · [README](README.md) · [Contributing](CONTRIBUTING.md) +## [2.14.0] - 2026-11-27 + +### Added + +- Inspect servers with `bl mcp get`, create, update or delete custom servers, and activate or deactivate official and custom servers in batches. Use `bl mcp tool search`, `list`, and `call` to find, list and invoke tools through OpenAPI. +- Search official and private workspace skills with `bl skill search`. Select cloud skills by `--code` and public OSS skills by `--name`. Choose an agent and user or project scope at installation time. For cloud skills, you can pin a version, preview update differences, or remove an installation offline. + +### Changed + +- `bl mcp list` now requires a standard Bailian API key and reports local agent registrations. **(BREAKING)** +- `bl skill list` and `bl skill update` now default to the cloud catalog. To keep using OSS, run `bl skill list --source oss` and `bl skill update --all`. **(BREAKING)** +- `bl mcp connect` and `bl skill add` activate inactive MCP services they need by default, which can incur charges. Preview the operation with `--dry-run`. To skip activation, use `--and-activate=false` for connections or `--with-mcp false` for skill installations. + +### Fixed + +- `bl mcp tools` now follows pagination so servers with multiple pages return their full tool list. + ## [2.13.0] - 2026-11-27 ### Added diff --git a/CHANGELOG.zh.md b/CHANGELOG.zh.md index 1376cce5b..6c5fbaaea 100644 --- a/CHANGELOG.zh.md +++ b/CHANGELOG.zh.md @@ -6,6 +6,23 @@ [English](CHANGELOG.md) · [README](README.zh.md) · [参与贡献](CONTRIBUTING.zh.md) +## [2.14.0] - 2026-11-27 + +### 新增 + +- `bl mcp get` 可查看 MCP 服务详情。自定义服务支持创建、更新和删除,官方及自定义服务支持批量启停。使用 `bl mcp tool search`、`list` 和 `call` 可通过 OpenAPI 搜索、列出和调用工具。 +- `bl skill search` 可搜索官方 Skill 和工作空间的私有 Skill。用 `--code` 指定云端 Skill,用 `--name` 指定公共 OSS Skill。安装时可选择 Agent 和用户或项目范围。云端 Skill 支持固定版本、预览更新差异和离线移除本地安装。 + +### 变更 + +- `bl mcp list` 改用普通百炼 API Key,结果包含本地 Agent 注册信息。**(BREAKING)** +- `bl skill list` 和 `bl skill update` 默认使用云端目录。原有 OSS 脚本请分别改用 `bl skill list --source oss` 和 `bl skill update --all`。**(BREAKING)** +- `bl mcp connect` 和 `bl skill add` 默认会开通所需的未启用 MCP 服务,可能产生费用。可用 `--dry-run` 预览。跳过自动开通时,连接 MCP 服务用 `--and-activate=false`,安装 Skill 用 `--with-mcp false`。 + +### 修复 + +- `bl mcp tools` 现在会读取后续分页,工具较多时也能列出完整清单。 + ## [2.13.0] - 2026-11-27 ### 新增 diff --git a/README.md b/README.md index 6d84cd754..b4b37860c 100644 --- a/README.md +++ b/README.md @@ -192,7 +192,7 @@ Synchronous Batch Chat is non-streaming; explicit realtime/international/Token P ### Console Login (OAuth, Recommended) -Required for console capability commands (model list, flow-agent list, MCP list, workspace, usage queries, rate-limit increases, direct console calls). It can create an ordinary API key when needed. Token Plan and other subscription plans cannot use `--console`; use the API Key login below. +Required for console capability commands (model list, flow-agent list, workspace, usage queries, rate-limit increases, direct console calls). It can create an ordinary API key when needed. Token Plan and other subscription plans cannot use `--console`; use the API Key login below. ```bash bl auth login --console @@ -218,6 +218,28 @@ Input must be one raw token (up to 64 KiB), not JSON or `Bearer ...`; interactiv ### API Key +MCP management and cloud Skill commands use the configured workspace ID to build the Beijing workspace endpoint. Set it once with `bl config set workspace_id `, or use `BAILIAN_WORKSPACE_ID` or `--workspace-id`. An explicit model base URL (flag, environment or profile) takes precedence. + +Search the cloud Skill catalog with a Bailian API key, for example `bl skill search --keyword pdf --type official`. Pass a returned `skill_code` to `bl skill get --code ` to see the latest version and local installation paths. Omit `--type` to include private skills in your workspace. `skill get` also reads MCP server codes from the latest package’s `mcp-config.json` by default. Use `--with-mcp false` to skip the package download. + +Install a search result with `bl skill add --code --agent cursor --scope project`. Add `--skill-version 1.0` to pin a version. `bl skill list --scope project` shows installation paths and states. Preview updates with `bl skill update --code --scope project --diff --dry-run` and omit `--dry-run` to apply. `bl skill remove --code --agent cursor --scope project` removes that local installation offline. + +When targeting a skill with `get`, `add`, `update` or `remove`, use either `--code` with its cloud OpenAPI code or `--name` with its public OSS registry name. For example, `bl skill add --name spark-video` installs one OSS skill. `bl skill add --all` installs the entire public OSS registry. Browse that registry with `bl skill list --source oss`. + +Skill commands check unpinned installations from the selected source and report available updates on stderr. The check reuses catalog reads and caches revisions for 24 hours. Removal uses the cache offline. Run `bl skill update` to update installed cloud skills, or `bl skill update --all` to update installed OSS skills. `bl skill update --name all` remains an alias for `bl skill update --all`. + +Installation activates inactive MCP dependencies by default, which may incur charges. Use `--dry-run` to preview the activation plan. To install only the Skill, pass `--with-mcp false`. + +Use an ordinary Bailian API key to list activated MCP servers (`bl mcp list`), inspect server details and tools (`bl mcp get --server `), and manage custom servers (`bl mcp create`, `update`, `delete`). Use `--dry-run` to preview changes. Deleting a custom server requires `bl mcp delete --server --yes`. + +Search for tools with a natural-language query, for example `bl mcp tool search --query "look up an order" --limit 5`. Recommendations can trigger OneKey activation. For a known server, use `bl mcp tool list --server ` to read its tools and input schemas through OpenAPI. Listing tools can also trigger OneKey activation. Both commands support a local `--dry-run` preview. To inspect tools through an MCP session, use `bl mcp tools --server ` with an optional `--url `. + +To call a tool through OpenAPI, run `bl mcp tool call --server --tool getOrder --arg orderId=A123`. Use `--dry-run` to preview the arguments. Calling a tool may activate a OneKey service. To call through an MCP session, use `bl mcp call --target .getOrder --arg orderId=A123`. Both commands apply `--json` first, then repeated `--arg` values, and finally `--query` as text. + +Use `bl mcp activate --server ` or `bl mcp deactivate --server ` for up to 30 distinct official or custom servers. Preview changes with `--dry-run`. OneKey activation may place an order. Stopping a custom server keeps its saved configuration. + +Use `bl mcp connect --server --transport streamable-http --agent cursor` to register the workspace endpoint. Connecting activates an inactive service by default. Use `--and-activate=false` to connect only to active services. Add `--scope project` from the project root for project-level registration. Agent config files and backups can contain your API key. `bl mcp disconnect --server --agent cursor` removes the matching local registration offline. Use the same scope for both commands. + To use an existing ordinary API key or a Token Plan subscription key, run the same command: ```bash diff --git a/README.zh.md b/README.zh.md index aa73c1db2..7fdad45c0 100644 --- a/README.zh.md +++ b/README.zh.md @@ -191,7 +191,7 @@ bl text chat --batch --model qwen-plus --message "你好" --timeout 3600 ### 控制台登录(OAuth,推荐) -控制台能力命令(模型列表、应用列表、MCP 列表、工作空间、用量查询、限流提额、控制台直调)需要使用此登录方式,并可在需要时创建普通 API Key。Token Plan 等订阅计划不能使用 `--console`,请使用下面的 API Key 登录方式。 +控制台能力命令(模型列表、应用列表、工作空间、用量查询、限流提额、控制台直调)需要使用此登录方式,并可在需要时创建普通 API Key。Token Plan 等订阅计划不能使用 `--console`,请使用下面的 API Key 登录方式。 ```bash bl auth login --console @@ -217,6 +217,28 @@ bl auth login --console --token-stdin --console-site international --console-reg ### API Key +MCP 管理命令和云端 Skill 命令会用工作空间 ID 自动拼接北京地域的专属域名。可用 `bl config set workspace_id ` 配置一次,也可通过 `BAILIAN_WORKSPACE_ID` 或 `--workspace-id` 指定。若已通过参数、环境变量或 Profile 设置模型 Base URL,则优先使用该地址。 + +使用百炼 API Key 查询云端 Skill,例如 `bl skill search --keyword pdf --type official`。用结果中的 `skill_code` 执行 `bl skill get --code `,可查看最新版本及本地安装路径。省略 `--type` 会同时检索官方 Skill 和当前工作空间的私有 Skill。`skill get` 默认读取最新版本包中 `mcp-config.json` 声明的 MCP 服务编码。只需元数据时,加 `--with-mcp false` 可跳过下载。 + +用 `bl skill add --code --agent cursor --scope project` 安装搜索到的 Skill。加 `--skill-version 1.0` 可固定版本。`bl skill list --scope project` 显示安装位置和状态。`bl skill update --code --scope project --diff --dry-run` 预览更新,去掉 `--dry-run` 后应用。`bl skill remove --code --agent cursor --scope project` 只移除该 Agent 的本地安装,可离线执行。 + +对指定 Skill 执行 `get`、`add`、`update`、`remove` 时,使用 `--code` 传入云端 OpenAPI 编码,或用 `--name` 传入公开 OSS Registry 名称,二者互斥。例如,`bl skill add --name spark-video` 安装一个公开 Skill,`bl skill add --all` 安装公开 OSS Registry 中的全部 Skill。用 `bl skill list --source oss` 查看公开目录。 + +运行 Skill 命令时,CLI 会检查当前来源中未固定版本的已安装项,并在 stderr 提示可用更新。检查会复用本次目录查询,版本信息缓存 24 小时;卸载时只读有效缓存。运行 `bl skill update` 更新已安装的云端 Skill,或用 `bl skill update --all` 更新已安装的 OSS Skill。原有写法 `bl skill update --name all` 与 `bl skill update --all` 等效。 + +安装时默认开通包内声明且尚未启用的 MCP 依赖,可能产生费用。使用 `--dry-run` 可预览开通计划。仅安装 Skill 可加 `--with-mcp false`。 + +使用百炼普通 API Key 即可列出已启用的 MCP 服务(`bl mcp list`)、查看服务详情和工具(`bl mcp get --server `),以及管理自定义服务(`bl mcp create`、`update`、`delete`)。可用 `--dry-run` 预览变更。删除自定义服务须执行 `bl mcp delete --server --yes`。 + +可用自然语言查找工具,例如 `bl mcp tool search --query "查询订单" --limit 5`。推荐请求可能触发 OneKey 服务开通。已知服务编码时,可用 `bl mcp tool list --server ` 通过 OpenAPI 查看工具和入参定义。查询工具也可能触发 OneKey 服务开通。两个命令都支持用 `--dry-run` 在本地预览。要通过真实 MCP 会话查看工具,可用 `bl mcp tools --server `,也可用 `--url ` 指定端点。 + +通过 OpenAPI 调用工具可用 `bl mcp tool call --server --tool getOrder --arg orderId=A123`。用 `--dry-run` 可预览参数。调用工具可能触发 OneKey 服务开通。通过 MCP 会话调用同一工具可用 `bl mcp call --target .getOrder --arg orderId=A123`。两个命令都先取 `--json`,再按顺序应用 `--arg`,最后用 `--query` 的文本覆盖同名参数。 + +使用 `bl mcp activate --server ` 或 `bl mcp deactivate --server ` 可批量开通或停用官方和自定义服务,去重后最多 30 个。用 `--dry-run` 可预览变更。开通 OneKey 服务可能下单。停用自定义服务会保留已保存的配置。 + +用 `bl mcp connect --server --transport streamable-http --agent cursor` 注册工作空间端点。接入时默认开通尚未启用的服务。用 `--and-activate=false` 可仅接入已启用的服务。项目级注册需在项目根目录加 `--scope project`。Agent 配置和备份可能含有 API Key。用 `bl mcp disconnect --server --agent cursor` 可离线移除相同作用域的本地托管注册。 + 使用已有的普通 API Key 或 Token Plan 订阅 Key,都执行同一条命令: ```bash diff --git a/docs/agents/auth-change.md b/docs/agents/auth-change.md index 35d576cfa..44565b8ee 100644 --- a/docs/agents/auth-change.md +++ b/docs/agents/auth-change.md @@ -29,6 +29,8 @@ defineCommand({ auth }) → runtime/authStage → ctx.client → command.run(ctx - `openapi` — 阿里云 OpenAPI 签名域,用 AccessKey ID/Secret 调用 Token Plan 等 OpenAPI - `none` — 本地命令、登录/配置类命令、无需 credential 的命令 +同一命令同时支持公开来源和鉴权来源时,可通过 `requiresApiKey(flags)` 声明何时解析 API Key。例如 Skill 的 OSS Registry 可匿名读取,云端目录使用当前 Profile 的百炼 API Key。`skill get/add/update/remove` 的 `--name` 选择公开 OSS Registry,`--code` 选择云端 OpenAPI。移除按所选来源筛选本地记录,可离线执行。`skill list` 默认查询云端,`--source oss` 列出公开目录。`skill add --all` 从 OSS 安装,`skill update --all` 匿名更新已安装的 OSS Skill。不带选择器的 `skill update` 默认走云端。OSS 安装检查包声明的 MCP 时,`requiresApiKey` 返回 `"optional"`,由 runtime 注入已配置的 API Key;无 MCP 依赖的包可匿名安装。 + ### 可选 console 副凭证 `auth: "apiKey"` 的命令可用 `optionalConsole: true` 声明 best-effort console 副凭证(例:`cmodel import` 提交前用 console 目录预检基础模型)。runtime 在注入 apiCred 后尽力 `resolveConsole`;解析失败静默跳过,**不得**让 apiKey 主流程失败。此类命令的 help 会额外展示 console 域 flag(`--console-region` / `--console-site` / `--console-switch-agent`),命令捕获 `client.console` 的 AUTH 错误后降级并 warning。纯 console 请求仍必须声明 `auth: "console"`。 diff --git a/docs/agents/skill-change.md b/docs/agents/skill-change.md index d73e7996d..4c96cba85 100644 --- a/docs/agents/skill-change.md +++ b/docs/agents/skill-change.md @@ -15,7 +15,7 @@ 2. **`bailian-protocol` 是共享协议 skill**,业务 skill 执行前应 Read 它 3. **不要**在 frontmatter 写 `companions`,也不要对外说「companions = 安装器硬依赖」 4. 子集安装:`bl skill add --name bailian-protocol,`;漏装 protocol 会导致相对路径 Read 失败 -5. **`bl skill add --all`:** 安装 registry 全量(含 `spark-video` 等非 bailian 技能);不要用 `--all` 做升级同步。首次 / 整包用 `bl skill init`。升级后自动同步以及 `bl update` 成功后用 `bl skill update`(只更新已安装,不装新 skill)。 +5. **OSS 批量安装与更新**:首次安装百炼整包用 `bl skill init`。`bl skill add --all` 安装公开 Registry 全量 Skill(含 `spark-video` 等非百炼 Skill)。升级后自动同步及 `bl update` 使用 `bl skill update --all` 更新已安装的 OSS Skill。 ## 概念图 @@ -38,7 +38,7 @@ bailian-gen bailian-finetune bailian-managed-agent bailian-web-search ### A. 分层边界 -- [ ] **整包装齐**:安装 / 缺 skill 文案主推 `bl skill init`;升级同步用 `bl skill update`(只更新已安装,不装新 skill);业务 skill **不**声明 `companions` +- [ ] **整包装齐**:安装 / 缺 skill 文案主推 `bl skill init`;升级同步用 `bl skill update --all`(只更新已安装,不装新 skill);业务 skill **不**声明 `companions` - [ ] **协议读取**:CRITICAL / references 可链 `../bailian-protocol/…`;若读不到 → 停止执行 `bl`,提示 `bl skill init` - [ ] **调用归因**:协议 `SKILL.md` 放 bash + PowerShell 的 agent / script 模板与协议样例;每个业务 skill **只留一条**填好的 agent 样例并链回协议;其余示例 / `assets/` / `reference/` 保持裸 `bl …`。Agent 当面 inline 套 agent 四变量;**抄进可复用脚本时改用 protocol `script` 模板**,并写明「样例仅当面 inline」。禁止为冒充 agent 而设变量,也禁止写入 shell profile / direnv / CI 全局环境 - [ ] **高风险确认**:统一由 `bailian-protocol` 定义;reference / leaf help 以 `risk: high` 明示风险,业务 skill 不得引导 Agent 自动补 `--yes`。遇到 exit code 7 / `requires_confirmation` 时停止执行并请求确认;目标或范围变化后重新确认 diff --git a/packages/bailian-kb-dsh/package.json b/packages/bailian-kb-dsh/package.json index 2f19e972d..6984a8563 100644 --- a/packages/bailian-kb-dsh/package.json +++ b/packages/bailian-kb-dsh/package.json @@ -1,6 +1,6 @@ { "name": "bailian-kb-dsh", - "version": "2.13.0", + "version": "2.14.0", "description": "Bailian knowledge-base tools for DeepSeek Harness: kb_search and kb_chat over the DashScope RAG API, plus the bl CLI management skill.", "keywords": [ "alibaba-cloud", diff --git a/packages/bailian-memo-dsh/package.json b/packages/bailian-memo-dsh/package.json index 35fecf617..9e4030ca3 100644 --- a/packages/bailian-memo-dsh/package.json +++ b/packages/bailian-memo-dsh/package.json @@ -1,6 +1,6 @@ { "name": "bailian-memo-dsh", - "version": "2.13.0", + "version": "2.14.0", "description": "Bailian personal memory for DeepSeek Harness: automatic recall, silent curation, and user-controlled remember/forget.", "keywords": [ "alibaba-cloud", diff --git a/packages/cli/README.md b/packages/cli/README.md index 6d84cd754..b4b37860c 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -192,7 +192,7 @@ Synchronous Batch Chat is non-streaming; explicit realtime/international/Token P ### Console Login (OAuth, Recommended) -Required for console capability commands (model list, flow-agent list, MCP list, workspace, usage queries, rate-limit increases, direct console calls). It can create an ordinary API key when needed. Token Plan and other subscription plans cannot use `--console`; use the API Key login below. +Required for console capability commands (model list, flow-agent list, workspace, usage queries, rate-limit increases, direct console calls). It can create an ordinary API key when needed. Token Plan and other subscription plans cannot use `--console`; use the API Key login below. ```bash bl auth login --console @@ -218,6 +218,28 @@ Input must be one raw token (up to 64 KiB), not JSON or `Bearer ...`; interactiv ### API Key +MCP management and cloud Skill commands use the configured workspace ID to build the Beijing workspace endpoint. Set it once with `bl config set workspace_id `, or use `BAILIAN_WORKSPACE_ID` or `--workspace-id`. An explicit model base URL (flag, environment or profile) takes precedence. + +Search the cloud Skill catalog with a Bailian API key, for example `bl skill search --keyword pdf --type official`. Pass a returned `skill_code` to `bl skill get --code ` to see the latest version and local installation paths. Omit `--type` to include private skills in your workspace. `skill get` also reads MCP server codes from the latest package’s `mcp-config.json` by default. Use `--with-mcp false` to skip the package download. + +Install a search result with `bl skill add --code --agent cursor --scope project`. Add `--skill-version 1.0` to pin a version. `bl skill list --scope project` shows installation paths and states. Preview updates with `bl skill update --code --scope project --diff --dry-run` and omit `--dry-run` to apply. `bl skill remove --code --agent cursor --scope project` removes that local installation offline. + +When targeting a skill with `get`, `add`, `update` or `remove`, use either `--code` with its cloud OpenAPI code or `--name` with its public OSS registry name. For example, `bl skill add --name spark-video` installs one OSS skill. `bl skill add --all` installs the entire public OSS registry. Browse that registry with `bl skill list --source oss`. + +Skill commands check unpinned installations from the selected source and report available updates on stderr. The check reuses catalog reads and caches revisions for 24 hours. Removal uses the cache offline. Run `bl skill update` to update installed cloud skills, or `bl skill update --all` to update installed OSS skills. `bl skill update --name all` remains an alias for `bl skill update --all`. + +Installation activates inactive MCP dependencies by default, which may incur charges. Use `--dry-run` to preview the activation plan. To install only the Skill, pass `--with-mcp false`. + +Use an ordinary Bailian API key to list activated MCP servers (`bl mcp list`), inspect server details and tools (`bl mcp get --server `), and manage custom servers (`bl mcp create`, `update`, `delete`). Use `--dry-run` to preview changes. Deleting a custom server requires `bl mcp delete --server --yes`. + +Search for tools with a natural-language query, for example `bl mcp tool search --query "look up an order" --limit 5`. Recommendations can trigger OneKey activation. For a known server, use `bl mcp tool list --server ` to read its tools and input schemas through OpenAPI. Listing tools can also trigger OneKey activation. Both commands support a local `--dry-run` preview. To inspect tools through an MCP session, use `bl mcp tools --server ` with an optional `--url `. + +To call a tool through OpenAPI, run `bl mcp tool call --server --tool getOrder --arg orderId=A123`. Use `--dry-run` to preview the arguments. Calling a tool may activate a OneKey service. To call through an MCP session, use `bl mcp call --target .getOrder --arg orderId=A123`. Both commands apply `--json` first, then repeated `--arg` values, and finally `--query` as text. + +Use `bl mcp activate --server ` or `bl mcp deactivate --server ` for up to 30 distinct official or custom servers. Preview changes with `--dry-run`. OneKey activation may place an order. Stopping a custom server keeps its saved configuration. + +Use `bl mcp connect --server --transport streamable-http --agent cursor` to register the workspace endpoint. Connecting activates an inactive service by default. Use `--and-activate=false` to connect only to active services. Add `--scope project` from the project root for project-level registration. Agent config files and backups can contain your API key. `bl mcp disconnect --server --agent cursor` removes the matching local registration offline. Use the same scope for both commands. + To use an existing ordinary API key or a Token Plan subscription key, run the same command: ```bash diff --git a/packages/cli/README.zh.md b/packages/cli/README.zh.md index aa73c1db2..7fdad45c0 100644 --- a/packages/cli/README.zh.md +++ b/packages/cli/README.zh.md @@ -191,7 +191,7 @@ bl text chat --batch --model qwen-plus --message "你好" --timeout 3600 ### 控制台登录(OAuth,推荐) -控制台能力命令(模型列表、应用列表、MCP 列表、工作空间、用量查询、限流提额、控制台直调)需要使用此登录方式,并可在需要时创建普通 API Key。Token Plan 等订阅计划不能使用 `--console`,请使用下面的 API Key 登录方式。 +控制台能力命令(模型列表、应用列表、工作空间、用量查询、限流提额、控制台直调)需要使用此登录方式,并可在需要时创建普通 API Key。Token Plan 等订阅计划不能使用 `--console`,请使用下面的 API Key 登录方式。 ```bash bl auth login --console @@ -217,6 +217,28 @@ bl auth login --console --token-stdin --console-site international --console-reg ### API Key +MCP 管理命令和云端 Skill 命令会用工作空间 ID 自动拼接北京地域的专属域名。可用 `bl config set workspace_id ` 配置一次,也可通过 `BAILIAN_WORKSPACE_ID` 或 `--workspace-id` 指定。若已通过参数、环境变量或 Profile 设置模型 Base URL,则优先使用该地址。 + +使用百炼 API Key 查询云端 Skill,例如 `bl skill search --keyword pdf --type official`。用结果中的 `skill_code` 执行 `bl skill get --code `,可查看最新版本及本地安装路径。省略 `--type` 会同时检索官方 Skill 和当前工作空间的私有 Skill。`skill get` 默认读取最新版本包中 `mcp-config.json` 声明的 MCP 服务编码。只需元数据时,加 `--with-mcp false` 可跳过下载。 + +用 `bl skill add --code --agent cursor --scope project` 安装搜索到的 Skill。加 `--skill-version 1.0` 可固定版本。`bl skill list --scope project` 显示安装位置和状态。`bl skill update --code --scope project --diff --dry-run` 预览更新,去掉 `--dry-run` 后应用。`bl skill remove --code --agent cursor --scope project` 只移除该 Agent 的本地安装,可离线执行。 + +对指定 Skill 执行 `get`、`add`、`update`、`remove` 时,使用 `--code` 传入云端 OpenAPI 编码,或用 `--name` 传入公开 OSS Registry 名称,二者互斥。例如,`bl skill add --name spark-video` 安装一个公开 Skill,`bl skill add --all` 安装公开 OSS Registry 中的全部 Skill。用 `bl skill list --source oss` 查看公开目录。 + +运行 Skill 命令时,CLI 会检查当前来源中未固定版本的已安装项,并在 stderr 提示可用更新。检查会复用本次目录查询,版本信息缓存 24 小时;卸载时只读有效缓存。运行 `bl skill update` 更新已安装的云端 Skill,或用 `bl skill update --all` 更新已安装的 OSS Skill。原有写法 `bl skill update --name all` 与 `bl skill update --all` 等效。 + +安装时默认开通包内声明且尚未启用的 MCP 依赖,可能产生费用。使用 `--dry-run` 可预览开通计划。仅安装 Skill 可加 `--with-mcp false`。 + +使用百炼普通 API Key 即可列出已启用的 MCP 服务(`bl mcp list`)、查看服务详情和工具(`bl mcp get --server `),以及管理自定义服务(`bl mcp create`、`update`、`delete`)。可用 `--dry-run` 预览变更。删除自定义服务须执行 `bl mcp delete --server --yes`。 + +可用自然语言查找工具,例如 `bl mcp tool search --query "查询订单" --limit 5`。推荐请求可能触发 OneKey 服务开通。已知服务编码时,可用 `bl mcp tool list --server ` 通过 OpenAPI 查看工具和入参定义。查询工具也可能触发 OneKey 服务开通。两个命令都支持用 `--dry-run` 在本地预览。要通过真实 MCP 会话查看工具,可用 `bl mcp tools --server `,也可用 `--url ` 指定端点。 + +通过 OpenAPI 调用工具可用 `bl mcp tool call --server --tool getOrder --arg orderId=A123`。用 `--dry-run` 可预览参数。调用工具可能触发 OneKey 服务开通。通过 MCP 会话调用同一工具可用 `bl mcp call --target .getOrder --arg orderId=A123`。两个命令都先取 `--json`,再按顺序应用 `--arg`,最后用 `--query` 的文本覆盖同名参数。 + +使用 `bl mcp activate --server ` 或 `bl mcp deactivate --server ` 可批量开通或停用官方和自定义服务,去重后最多 30 个。用 `--dry-run` 可预览变更。开通 OneKey 服务可能下单。停用自定义服务会保留已保存的配置。 + +用 `bl mcp connect --server --transport streamable-http --agent cursor` 注册工作空间端点。接入时默认开通尚未启用的服务。用 `--and-activate=false` 可仅接入已启用的服务。项目级注册需在项目根目录加 `--scope project`。Agent 配置和备份可能含有 API Key。用 `bl mcp disconnect --server --agent cursor` 可离线移除相同作用域的本地托管注册。 + 使用已有的普通 API Key 或 Token Plan 订阅 Key,都执行同一条命令: ```bash diff --git a/packages/cli/package.json b/packages/cli/package.json index 04f4fa48f..f9249ca2b 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli", - "version": "2.13.0", + "version": "2.14.0", "description": "CLI for Aliyun Model Studio (DashScope) AI Platform.", "keywords": [ "agent", diff --git a/packages/cli/postinstall.js b/packages/cli/postinstall.js index 60ce9638d..c8cb48706 100644 --- a/packages/cli/postinstall.js +++ b/packages/cli/postinstall.js @@ -454,6 +454,8 @@ async function main() { // 5. skill-lock.json record: wiki shares the same ledger as bl skill upsertSkillLock(WIKI_SKILL_NAME, { contentHash: entry.contentHash, + remoteId: entry.remoteId, + installedVersion: entry.version, ...(entry.publishedAt ? { publishedAt: entry.publishedAt } : {}), installedAt: new Date().toISOString(), sourceType: "oss", diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 6243f0498..a7bd65436 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -100,11 +100,20 @@ import { knowledgeCollectionGet, knowledgeDocImportOss, knowledgeDocImport, + mcpActivate, mcpCall, mcpConnect, + mcpCreate, + mcpDeactivate, + mcpDelete, mcpDisconnect, + mcpGet, mcpList, mcpTools, + mcpToolCall, + mcpToolList, + mcpToolSearch, + mcpUpdate, searchWeb, speechSynthesize, speechRecognize, @@ -282,6 +291,8 @@ import { pluginList, pluginRemove, skillAdd, + skillSearch, + skillGet, skillUpdate, skillRemove, skillList, @@ -505,11 +516,20 @@ export const commands: Record = { "knowledge file list": knowledgeFileList, "knowledge file get": knowledgeFileGet, "knowledge file delete": knowledgeFileDelete, + "mcp activate": mcpActivate, "mcp call": mcpCall, "mcp connect": mcpConnect, + "mcp create": mcpCreate, + "mcp deactivate": mcpDeactivate, + "mcp delete": mcpDelete, "mcp disconnect": mcpDisconnect, + "mcp get": mcpGet, "mcp list": mcpList, "mcp tools": mcpTools, + "mcp tool call": mcpToolCall, + "mcp tool list": mcpToolList, + "mcp tool search": mcpToolSearch, + "mcp update": mcpUpdate, "search web": searchWeb, "speech synthesize": speechSynthesize, "speech recognize": speechRecognize, @@ -687,6 +707,8 @@ export const commands: Record = { "plugin list": pluginList, "plugin remove": pluginRemove, "skill add": skillAdd, + "skill search": skillSearch, + "skill get": skillGet, "skill update": skillUpdate, "skill remove": skillRemove, "skill list": skillList, diff --git a/packages/cli/tests/e2e/aliyun-compat.e2e.test.ts b/packages/cli/tests/e2e/aliyun-compat.e2e.test.ts index 9020c5655..be6f0fe52 100644 --- a/packages/cli/tests/e2e/aliyun-compat.e2e.test.ts +++ b/packages/cli/tests/e2e/aliyun-compat.e2e.test.ts @@ -93,7 +93,7 @@ test("all command metadata preserves standalone wording and resolves hosted refe }; expect(JSON.parse(serialized.replaceAll("aliyun bl", "bl"))).toEqual(qualifiedStandalone); const skill = hosted.commands.find((command) => command.path.join(" ") === "bl skill init")!; - expect(JSON.stringify(skill.notes)).toContain("Equivalent to: `aliyun bl skill add --all`"); + expect(JSON.stringify(skill.notes)).toContain("`aliyun bl skill add --all`"); }); // Real subprocesses below verify the product entrypoint reads the inherited host marker. diff --git a/packages/cli/tests/e2e/knowledge-skill-registry.e2e.test.ts b/packages/cli/tests/e2e/knowledge-skill-registry.e2e.test.ts index 26ea934c8..9de137a4b 100644 --- a/packages/cli/tests/e2e/knowledge-skill-registry.e2e.test.ts +++ b/packages/cli/tests/e2e/knowledge-skill-registry.e2e.test.ts @@ -131,7 +131,7 @@ test("local registry delivers knowledge through init and subset add; update stay expect(initialized.skills.sort()).toEqual(["bailian-knowledge", "bailian-protocol"]); await run("subset", ["add", "--name", "bailian-protocol"]); const beforeUpdate = requests.length; - await run("subset", ["update"]); + await run("subset", ["update", "--all"]); expect(requests.slice(beforeUpdate)).toEqual(["/index.json"]); const updatedFiles = await skillFiles(join(root, "skills/bailian-protocol")); updatedFiles["revision.txt"] = Buffer.from("local registry updated revision\n"); @@ -140,7 +140,7 @@ test("local registry delivers knowledge through init and subset add; update stay resources.set("/bailian-protocol/skill.tar.br", updatedAsset.body); resources.set("/index.json", Buffer.from(JSON.stringify({ skills: entries }))); const beforeChangedUpdate = requests.length; - await run("subset", ["update"]); + await run("subset", ["update", "--all"]); expect(requests.slice(beforeChangedUpdate)).toEqual([ "/index.json", "/bailian-protocol/skill.tar.br", diff --git a/packages/commands/package.json b/packages/commands/package.json index 2cd29d96e..985baa15b 100644 --- a/packages/commands/package.json +++ b/packages/commands/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-commands", - "version": "2.13.0", + "version": "2.14.0", "description": "Command library for bailian-cli products (knowledge, memory, media, …). See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/commands/src/commands/config/agent/writers/utils.ts b/packages/commands/src/commands/config/agent/writers/utils.ts index 45e178988..aa8b32da0 100644 --- a/packages/commands/src/commands/config/agent/writers/utils.ts +++ b/packages/commands/src/commands/config/agent/writers/utils.ts @@ -1,5 +1,15 @@ import { dirname } from "path"; -import { existsSync, readFileSync, writeFileSync, mkdirSync, renameSync, copyFileSync } from "fs"; +import { randomUUID } from "node:crypto"; +import { + closeSync, + existsSync, + openSync, + readFileSync, + writeFileSync, + mkdirSync, + renameSync, + rmSync, +} from "fs"; import { BailianError, ExitCode, type LocalizedText } from "bailian-cli-core"; /** Parameters shared by every agent writer. */ @@ -128,25 +138,31 @@ export function readJsonc(path: string): Record { /** Atomically write `data` as pretty JSON with owner-only permissions. */ export function writeJsonAtomic(path: string, data: unknown): void { - mkdirSync(dirname(path), { recursive: true }); - const tmp = path + ".tmp"; - writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", { mode: 0o600 }); - renameSync(tmp, path); + writeTextAtomic(path, JSON.stringify(data, null, 2) + "\n"); } /** Atomically write raw text with owner-only permissions. */ export function writeTextAtomic(path: string, content: string): void { mkdirSync(dirname(path), { recursive: true }); - const tmp = path + ".tmp"; - writeFileSync(tmp, content, { mode: 0o600 }); - renameSync(tmp, path); + const tmp = `${path}.${randomUUID()}.tmp`; + const handle = openSync(tmp, "wx", 0o600); + try { + try { + writeFileSync(handle, content); + } finally { + closeSync(handle); + } + renameSync(tmp, path); + } finally { + rmSync(tmp, { force: true }); + } } -/** Copy an existing file to a timestamped `.bak.` sibling. No-op if absent. */ +/** Private backup. Multiple Agent updates in the same second keep separate copies. */ export function backup(path: string): void { if (!existsSync(path)) return; - const timestamp = Math.floor(Date.now() / 1000); - copyFileSync(path, `${path}.bak.${timestamp}`); + const name = `${path}.bak.${Date.now()}-${randomUUID()}`; + writeFileSync(name, readFileSync(path), { flag: "wx", mode: 0o600 }); } /** Whether a base URL targets the Anthropic-messages compatible endpoint. */ diff --git a/packages/commands/src/commands/knowledge/state-store.ts b/packages/commands/src/commands/knowledge/state-store.ts index 788f135ab..d538117df 100644 --- a/packages/commands/src/commands/knowledge/state-store.ts +++ b/packages/commands/src/commands/knowledge/state-store.ts @@ -1,6 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; import { mkdir, open, readFile, rename, rm } from "node:fs/promises"; -import { hostname } from "node:os"; import { basename, dirname, join } from "node:path"; import { BailianError, ExitCode, type LocalizedText } from "bailian-cli-core"; @@ -82,46 +81,4 @@ export async function writeStateFile(path: string, state: unknown): Promise( - path: string, - localize: Localize, - action: () => Promise, -): Promise { - const lockPath = `${path}.lock`; - const nonce = randomUUID(); - await mkdir(dirname(path), { recursive: true }); - const handle = await open(lockPath, "wx", 0o600).catch((error: unknown) => { - if (!hasCode(error, "EEXIST")) throw error; - throw new BailianError( - localize({ - "en-US": `State is locked: ${lockPath}. Verify that no other operation is running before removing the lock.`, - "zh-CN": `状态文件已锁定:${lockPath}。请确认没有其他操作正在运行,再移除锁文件。`, - }), - ExitCode.GENERAL, - ); - }); - try { - try { - await handle.writeFile( - JSON.stringify({ nonce, pid: process.pid, hostname: hostname() }), - "utf8", - ); - await handle.sync(); - } finally { - await handle.close(); - } - return await action(); - } finally { - // A missing, corrupt, or replaced lock is not ours to remove. Cleanup must - // not replace a service error with a secondary filesystem error. - try { - const current: unknown = JSON.parse(await readFile(lockPath, "utf8")); - if (current && typeof current === "object" && "nonce" in current && current.nonce === nonce) { - await rm(lockPath); - } - } catch { - // Retaining an uncertain lock is safer than allowing concurrent writes. - } - } -} +export { withStateLock } from "../shared/state-lock.ts"; diff --git a/packages/commands/src/commands/mcp/activate.ts b/packages/commands/src/commands/mcp/activate.ts new file mode 100644 index 000000000..835a2c97c --- /dev/null +++ b/packages/commands/src/commands/mcp/activate.ts @@ -0,0 +1,44 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineCommand } from "bailian-cli-core"; +import { + batchServerFlag, + prepareLifecycle, + runLifecycle, + validateServers, + type LifecyclePlan, +} from "./server-lifecycle.ts"; + +const flags = { + ...WORKSPACE_FLAG, + server: batchServerFlag, + noBrowser: { + type: "switch", + description: { + "en-US": "Print the console link without opening it when manual setup is required", + "zh-CN": "需要手动配置时只输出控制台链接", + }, + }, +} as const; + +export default defineCommand({ + description: { + "en-US": + "Activate official MCP servers or enable custom servers using their saved configuration", + "zh-CN": "开通官方 MCP 服务,或使用已保存的配置启用自定义服务", + }, + auth: "apiKey", + flags, + usageArgs: "--server [--no-browser] [--dry-run]", + exampleArgs: ["--server mcp-example,mcp-weather --dry-run", "--server mcp-example"], + notes: [ + { + "en-US": + "OneKey activation may place an order. ACTIVATING means the deployment is still in progress. Use mcp list to see servers once they are active.", + "zh-CN": + "开通 OneKey 服务可能下单。ACTIVATING 表示部署仍在进行。部署完成后可用 mcp list 查询已启用的服务。", + }, + ], + validate: (values) => validateServers(values.server), + prepare: (ctx) => prepareLifecycle(ctx, ctx.flags.server, "activate"), + run: (ctx) => runLifecycle(ctx, !ctx.flags.noBrowser), +}); diff --git a/packages/commands/src/commands/mcp/agent-config.ts b/packages/commands/src/commands/mcp/agent-config.ts index e198da49e..f8cdd5fc0 100644 --- a/packages/commands/src/commands/mcp/agent-config.ts +++ b/packages/commands/src/commands/mcp/agent-config.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; -import { existsSync, readFileSync, unlinkSync } from "node:fs"; -import { join } from "node:path"; -import { BailianError, ExitCode } from "bailian-cli-core"; +import { existsSync, readFileSync, realpathSync, unlinkSync } from "node:fs"; +import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; +import { BailianError, ExitCode, type LocalizedText } from "bailian-cli-core"; import { parse as parseToml, stringify as stringifyToml } from "smol-toml"; import yaml from "yaml"; import { getPiAgentDir } from "../config/agent/pi-home.ts"; @@ -37,6 +37,30 @@ const OPENCLAW_DIRS = [".openclaw", ".clawdbot", ".moltbot"] as const; export type NativeMcpAgent = (typeof MCP_AGENT_IDS)[number]; export type McpTransport = "streamable-http" | "sse"; +export type McpScope = "user" | "project"; + +const projectFiles: Partial> = { + codex: ".codex/config.toml", + "claude-code": ".mcp.json", + cursor: ".cursor/mcp.json", + qoder: ".qoder/settings.json", + "qwen-code": ".qwen/settings.json", + gemini: ".gemini/settings.json", + opencode: "opencode.json", + pi: ".pi/mcp.json", + workbuddy: ".workbuddy/mcp.json", +}; +export const projectAgents = MCP_AGENT_IDS.filter((agent) => projectFiles[agent]); + +export class McpRegistrationError extends BailianError { + constructor( + readonly reason: string, + readonly text: LocalizedText, + exitCode: ExitCode = ExitCode.GENERAL, + ) { + super(typeof text === "string" ? text : text["en-US"], exitCode); + } +} export interface McpConnectionSpec { name: string; @@ -59,6 +83,10 @@ interface ManagedRegistration { transport: McpTransport; endpoint: string; path: string; + scope?: McpScope; + projectRoot?: string | null; + configPath?: string; + configPaths?: string[]; fingerprint: string; cliVersion: string; updatedAt: string; @@ -80,7 +108,13 @@ interface AgentAdapter { buildEntry(spec: McpConnectionSpec): Record; } -interface ConnectOptions { +interface RegistrationOptions { + scope?: McpScope; + projectRoot?: string; + dryRun?: boolean; +} + +interface ConnectOptions extends RegistrationOptions { agents: NativeMcpAgent[]; spec: McpConnectionSpec; cliVersion: string; @@ -88,7 +122,7 @@ interface ConnectOptions { configDir: string; } -interface DisconnectOptions { +interface DisconnectOptions extends RegistrationOptions { agents: NativeMcpAgent[]; name: string; home: string; @@ -105,19 +139,23 @@ function isObject(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } +function invalidConfiguration(path: string) { + return new McpRegistrationError("INVALID_CONFIG", { + "en-US": `Invalid MCP configuration in ${path}. Correct the file before retrying.`, + "zh-CN": `${path} 中的 MCP 配置无效,请修正文件后重试。`, + }); +} + function parseObject(path: string, parser: (content: string) => unknown): Record { if (!existsSync(path)) return {}; + const content = readFileSync(path, "utf8"); try { - const parsed = parser(readFileSync(path, "utf8")); + const parsed = parser(content); if (!isObject(parsed)) throw new Error("root value is not an object"); return parsed; - } catch (error) { - throw new BailianError( - `Cannot update MCP configuration because ${path} is invalid.`, - ExitCode.GENERAL, - "Fix the existing configuration file and retry; it was not changed.", - { cause: error }, - ); + } catch { + // Parser errors may quote credentials from the source file. + throw invalidConfiguration(path); } } @@ -137,10 +175,10 @@ function serverMap(config: Record, key: string): Record): string | undefined { function parseDshPatch(path: string): Record { if (!existsSync(path)) return { [DSH_OTHER_PATCHES]: [], [DSH_SERVERS]: {} }; let parsed: unknown; + const content = readFileSync(path, "utf8"); try { - parsed = yaml.parse(readFileSync(path, "utf8")); - } catch (error) { - throw new BailianError( - `Cannot update MCP configuration because ${path} is invalid.`, - ExitCode.GENERAL, - "Fix the existing configuration file and retry; it was not changed.", - { cause: error }, - ); + parsed = yaml.parse(content); + } catch { + throw invalidConfiguration(path); } if (parsed === null || parsed === undefined) { return { [DSH_OTHER_PATCHES]: [], [DSH_SERVERS]: {} }; } if (!Array.isArray(parsed)) { - throw new BailianError( - `Cannot update MCP configuration because ${path} is invalid.`, - ExitCode.GENERAL, - "Fix the existing configuration file and retry; it was not changed.", - ); + throw invalidConfiguration(path); } const otherPatches: unknown[] = []; - const servers: Record = {}; + const servers: Record = Object.create(null); for (const item of parsed) { if (isObject(item) && Array.isArray(item.insert)) { const otherEntries: unknown[] = []; @@ -504,11 +538,124 @@ function fingerprint(value: unknown): string { return createHash("sha256").update(stableJson(value)).digest("hex"); } -function registrationKey(agent: NativeMcpAgent, name: string): string { +function registrationKey(agent: NativeMcpAgent, name: string, projectRoot?: string): string { + if (projectRoot) return JSON.stringify([agent, projectRoot, name]); return `${agent}:${name}`; } -function manifestPath(configDir: string): string { +function targetPaths( + agent: NativeMcpAgent, + home: string, + projectRoot?: string, + savedPaths?: string[], +): string[] { + if (!projectRoot) return adapterWritePaths(adapters[agent], home).map((path) => resolve(path)); + const file = projectFiles[agent]; + if (!file) + throw new McpRegistrationError("SCOPE_UNSUPPORTED", { + "en-US": `Project scope is unavailable for ${agent}.`, + "zh-CN": `${agent} 不支持项目级 MCP 配置。`, + }); + let files = [file]; + const accepted = [file]; + if (agent === "opencode") { + accepted.push("opencode.jsonc"); + if (existsSync(join(projectRoot, "opencode.jsonc"))) files = ["opencode.jsonc"]; + } + if (agent === "workbuddy") { + accepted.push(".mcp.json", "mcp.json"); + if (existsSync(join(home, ".codebuddy"))) { + if (!existsSync(join(home, ".workbuddy")) && !existsSync(join(home, ".workbuddy-ai"))) + files = []; + files.push( + !existsSync(join(projectRoot, ".mcp.json")) && existsSync(join(projectRoot, "mcp.json")) + ? "mcp.json" + : ".mcp.json", + ); + } + } + const paths = files.map((name) => join(projectRoot, name)); + if (Array.isArray(savedPaths)) { + for (const name of accepted) { + const candidate = join(projectRoot, name); + if (savedPaths.includes(candidate) && !paths.includes(candidate)) paths.push(candidate); + } + } + for (const path of paths) { + if (!existsSync(projectRoot)) continue; + let parent = path; + while (!existsSync(parent)) parent = dirname(parent); + const within = relative(realpathSync(projectRoot), realpathSync(parent)); + if (isAbsolute(within) || within === ".." || within.startsWith(".." + sep)) { + throw new McpRegistrationError("CONFIG_OUTSIDE_PROJECT", { + "en-US": `The Agent config resolves outside the project: ${path}.`, + "zh-CN": `Agent 配置路径指向项目以外的位置:${path}。`, + }); + } + } + return paths; +} + +function registrationTarget( + options: RegistrationOptions & { home: string }, + manifest: RegistrationManifest, + agent: NativeMcpAgent, + name: string, +) { + const projectRoot = + options.scope === "project" ? (options.projectRoot ?? process.cwd()) : undefined; + const key = registrationKey(agent, name, projectRoot); + const managed = manifest.registrations[key]; + const paths = targetPaths( + agent, + options.home, + projectRoot, + managed?.configPaths ?? (managed?.configPath ? [managed.configPath] : undefined), + ); + const ambiguous = () => + new McpRegistrationError("AMBIGUOUS_REGISTRATION", { + "en-US": `Cannot identify the configuration owned by the saved ${agent} registration for ${name}.`, + "zh-CN": `无法确定 ${agent} 中 ${name} 的托管记录对应哪份配置。`, + }); + if (!Object.hasOwn(manifest.registrations, key)) { + if ( + !projectRoot && + Object.values(manifest.registrations).some( + (record) => record && !record.scope && record.agent === agent && record.serverCode === name, + ) + ) + throw ambiguous(); + return { key, managed: undefined, paths, projectRoot }; + } + if ( + !managed || + managed.agent !== agent || + managed.name !== name || + managed.serverCode !== name || + !managed.fingerprint || + (managed.scope ?? "user") !== (options.scope ?? "user") || + (managed.projectRoot ?? undefined) !== projectRoot + ) + throw ambiguous(); + // Version-one records only stored the primary user path. Migrate only recognizable targets. + if (!managed.scope) { + if (!paths.includes(managed.path)) throw ambiguous(); + return { key, managed, paths, projectRoot }; + } + const recorded = managed.configPaths ?? [managed.configPath]; + if ( + !Array.isArray(recorded) || + !recorded.length || + !recorded.every((path): path is string => typeof path === "string" && isAbsolute(path)) || + recorded[0] !== managed.configPath || + (projectRoot && !recorded.every((path) => paths.includes(path))) + ) + throw ambiguous(); + // Keep managing recorded files when discovery changes; new WorkBuddy product folders can join on connect. + return { key, managed, paths: recorded, projectRoot }; +} + +export function manifestPath(configDir: string): string { return join(configDir, "mcp-registrations.json"); } @@ -517,14 +664,88 @@ function readManifest(configDir: string): RegistrationManifest { if (!existsSync(path)) return { version: 1, registrations: {} }; const parsed = parseJson(path); if (parsed.version !== 1 || !isObject(parsed.registrations)) { - throw new BailianError( - `Cannot update MCP registrations because ${path} has an unsupported format.`, - ExitCode.GENERAL, - ); + throw invalidConfiguration(path); } return parsed as unknown as RegistrationManifest; } +export function registeredMcpAgents(configDir: string, serverCode: string): NativeMcpAgent[] { + const { registrations } = readManifest(configDir); + const records = Object.values(registrations); + return MCP_AGENT_IDS.filter((agent) => + records.some((record) => record?.agent === agent && record.serverCode === serverCode), + ); +} + +/** Join managed registrations to the native entries still present on this machine. */ +export function connectedMcpPaths( + configDir: string, + home: string, + serverCodes: Set, + onUnreadable: (path: string) => void, +) { + type PathsByAgent = Partial>; + const connections = new Map(); + if (serverCodes.size === 0) return connections; + let manifest: RegistrationManifest; + try { + manifest = readManifest(configDir); + } catch { + onUnreadable(manifestPath(configDir)); + return connections; + } + const records = Object.values(manifest.registrations).filter( + (record) => record && serverCodes.has(record.serverCode), + ); + for (const agent of MCP_AGENT_IDS) { + const managed = records.filter((record) => record.agent === agent); + if (!managed.length) continue; + const adapter = adapters[agent]; + const recordsByPath = new Map(); + for (const record of managed) { + try { + const target = registrationTarget( + { home, scope: record.scope, projectRoot: record.projectRoot ?? undefined }, + manifest, + agent, + record.name, + ); + if (target.managed !== record) { + onUnreadable(manifestPath(configDir)); + continue; + } + for (const path of target.paths) { + if (!recordsByPath.has(path)) recordsByPath.set(path, []); + recordsByPath.get(path)!.push(record); + } + } catch { + onUnreadable(manifestPath(configDir)); + } + } + for (const [path, pathRecords] of recordsByPath) { + if (!existsSync(path)) continue; + let entries: Record; + try { + entries = adapter.getServers(adapter.parse(path)); + } catch { + onUnreadable(path); + continue; + } + for (const record of pathRecords) { + if ( + !Object.hasOwn(entries, record.name) || + fingerprint(entries[record.name]) !== record.fingerprint + ) + continue; + const paths = connections.get(record.serverCode) ?? {}; + (paths[agent] ??= []).push(path); + connections.set(record.serverCode, paths); + } + } + } + return connections; +} + function assertManagedEntry( existing: unknown, managed: ManagedRegistration | undefined, @@ -533,24 +754,23 @@ function assertManagedEntry( ): void { if (existing === undefined) return; if (!managed) { - throw new BailianError( - `MCP server "${name}" already exists in ${agent} and is not managed by bailian-cli.`, - ExitCode.GENERAL, - "Choose another server name or remove the existing entry yourself.", - ); + throw new McpRegistrationError("UNMANAGED_CONFLICT", { + "en-US": `MCP server "${name}" already exists in ${agent} and is not managed by bailian-cli.`, + "zh-CN": `${agent} 中已存在由其他方式管理的同名 MCP 服务“${name}”。`, + }); } if (fingerprint(existing) !== managed.fingerprint) { - throw new BailianError( - `MCP server "${name}" in ${agent} conflicts with the last bailian-cli registration.`, - ExitCode.GENERAL, - "The entry was changed after registration; resolve it manually before retrying.", - ); + throw new McpRegistrationError("MODIFIED_CONFLICT", { + "en-US": `MCP server "${name}" in ${agent} conflicts with the last bailian-cli registration.`, + "zh-CN": `${agent} 中的 MCP 服务“${name}”在注册后已被修改。`, + }); } } function restoreWrites(writes: PlannedWrite[]): void { for (const write of writes.reverse()) { try { + if (readFileSync(write.path, "utf8") !== write.content) continue; if (write.original === undefined) unlinkSync(write.path); else writeTextAtomic(write.path, write.original); } catch { @@ -567,6 +787,12 @@ function applyWrites( const completed: PlannedWrite[] = []; try { for (const write of writes) { + const current = existsSync(write.path) ? readFileSync(write.path, "utf8") : undefined; + if (current !== write.original) + throw new McpRegistrationError("MODIFIED_CONFLICT", { + "en-US": `The configuration changed during registration: ${write.path}.`, + "zh-CN": `注册期间配置文件发生变化:${write.path}。`, + }); backup(write.path); writeTextAtomic(write.path, write.content); completed.push(write); @@ -574,29 +800,33 @@ function applyWrites( writeJsonAtomic(manifestPath(configDir), manifest); } catch (error) { restoreWrites(completed); - throw new BailianError( - "Failed to update MCP Agent configuration.", - ExitCode.GENERAL, - undefined, - { - cause: error, - }, - ); + throw error; } } export function resolveMcpAgentTargets( target: NativeMcpAgent | "all", home: string, + registration?: { configDir: string; server: string; projectRoot?: string }, ): NativeMcpAgent[] { if (target !== "all") return [target]; - return MCP_AGENT_IDS.filter((agent) => adapters[agent].installed(home)); + const records = registration ? readManifest(registration.configDir).registrations : {}; + return MCP_AGENT_IDS.filter( + (agent) => + adapters[agent].installed(home) || + (registration && + Object.hasOwn( + records, + registrationKey(agent, registration.server, registration.projectRoot), + )), + ); } export function connectMcpAgents(options: ConnectOptions): McpAgentResult[] { const manifest = readManifest(options.configDir); const writes: PlannedWrite[] = []; const results: McpAgentResult[] = []; + let manifestChanged = false; for (const agent of options.agents) { const adapter = adapters[agent]; @@ -604,19 +834,30 @@ export function connectMcpAgents(options: ConnectOptions): McpAgentResult[] { throw unsupportedSseError(agent); } - const paths = adapterWritePaths(adapter, options.home); - const primaryPath = adapter.path(options.home); - const key = registrationKey(agent, options.spec.name); - const managed = manifest.registrations[key]; + const target = registrationTarget(options, manifest, agent, options.spec.name); + const { key, managed, projectRoot } = target; + const paths = + agent === "workbuddy" + ? [...new Set([...target.paths, ...targetPaths(agent, options.home, projectRoot)])] + : target.paths; + const primaryPath = paths[0]; const desired = adapter.buildEntry(options.spec); const desiredFingerprint = fingerprint(desired); let status: McpAgentResult["status"] | undefined; for (const path of paths) { + const original = existsSync(path) ? readFileSync(path, "utf8") : undefined; const config = adapter.parse(path); const servers = adapter.getServers(config); - const existing = servers[options.spec.name]; - assertManagedEntry(existing, managed, agent, options.spec.name); + const existing = Object.hasOwn(servers, options.spec.name) + ? servers[options.spec.name] + : undefined; + assertManagedEntry( + existing, + target.paths.includes(path) ? managed : undefined, + agent, + options.spec.name, + ); const pathStatus = existing === undefined ? "added" @@ -625,10 +866,15 @@ export function connectMcpAgents(options: ConnectOptions): McpAgentResult[] { : "updated"; status = mergeConnectStatus(status, pathStatus); if (pathStatus !== "unchanged") { - servers[options.spec.name] = desired; + Object.defineProperty(servers, options.spec.name, { + value: desired, + writable: true, + enumerable: true, + configurable: true, + }); writes.push({ path, - original: existsSync(path) ? readFileSync(path, "utf8") : undefined, + original, content: adapter.serialize(config), }); } @@ -636,7 +882,7 @@ export function connectMcpAgents(options: ConnectOptions): McpAgentResult[] { const resolvedStatus = status ?? "unchanged"; results.push({ agent, path: primaryPath, status: resolvedStatus }); - if (resolvedStatus !== "unchanged") { + if (resolvedStatus !== "unchanged" || !managed?.scope) { manifest.registrations[key] = { agent, name: options.spec.name, @@ -644,14 +890,18 @@ export function connectMcpAgents(options: ConnectOptions): McpAgentResult[] { transport: options.spec.transport, endpoint: options.spec.endpoint, path: primaryPath, + scope: options.scope ?? "user", + projectRoot: projectRoot ?? null, + configPath: primaryPath, + configPaths: paths, fingerprint: desiredFingerprint, cliVersion: options.cliVersion, updatedAt: new Date().toISOString(), }; + manifestChanged = true; } } - - if (writes.length > 0) applyWrites(writes, manifest, options.configDir); + if (!options.dryRun && manifestChanged) applyWrites(writes, manifest, options.configDir); return results; } @@ -663,28 +913,26 @@ export function disconnectMcpAgents(options: DisconnectOptions): McpAgentResult[ for (const agent of options.agents) { const adapter = adapters[agent]; - const primaryPath = adapter.path(options.home); - const key = registrationKey(agent, options.name); - const managed = manifest.registrations[key]; + const { key, managed, paths } = registrationTarget(options, manifest, agent, options.name); + const primaryPath = paths[0]; if (!managed) { results.push({ agent, path: primaryPath, status: "absent" }); continue; } let removed = false; - let sawExisting = false; - for (const path of adapterWritePaths(adapter, options.home)) { + for (const path of paths) { + const original = existsSync(path) ? readFileSync(path, "utf8") : undefined; const config = adapter.parse(path); const servers = adapter.getServers(config); - const existing = servers[options.name]; + const existing = Object.hasOwn(servers, options.name) ? servers[options.name] : undefined; if (existing === undefined) continue; - sawExisting = true; assertManagedEntry(existing, managed, agent, options.name); delete servers[options.name]; removed = true; writes.push({ path, - original: readFileSync(path, "utf8"), + original, content: adapter.serialize(config), }); } @@ -694,11 +942,11 @@ export function disconnectMcpAgents(options: DisconnectOptions): McpAgentResult[ results.push({ agent, path: primaryPath, - status: sawExisting && removed ? "removed" : "absent", + status: removed ? "removed" : "absent", }); } - if (writes.length > 0 || manifestChanged) { + if (!options.dryRun && (writes.length > 0 || manifestChanged)) { applyWrites(writes, manifest, options.configDir); } return results; diff --git a/packages/commands/src/commands/mcp/call-arguments.ts b/packages/commands/src/commands/mcp/call-arguments.ts new file mode 100644 index 000000000..4ad1f8fc1 --- /dev/null +++ b/packages/commands/src/commands/mcp/call-arguments.ts @@ -0,0 +1,104 @@ +import { + UsageError, + type CommandContext, + type FlagsDef, + type LocalizedText, + type ParsedFlags, +} from "bailian-cli-core"; + +export const argumentFlags = { + json: { + type: "string", + valueHint: "", + description: { + "en-US": "Base tool arguments as a JSON object", + "zh-CN": "工具参数的基础 JSON 对象", + }, + }, + arg: { + type: "array", + valueHint: "", + description: { + "en-US": + "Set a tool argument (repeatable). Values are parsed as JSON when possible and override --json.", + "zh-CN": "设置工具参数(可重复)。值优先按 JSON 解析,覆盖 --json 中的同名键。", + }, + }, + query: { + type: "string", + valueHint: "", + description: { + "en-US": "Set the query argument to this text after applying --json and --arg", + "zh-CN": "在 --json 和 --arg 合并后,将 query 参数设为此文本", + }, + }, +} satisfies FlagsDef; + +type ArgumentFlags = ParsedFlags; +type ParseResult = + | { params: Record; error?: never } + | { error: LocalizedText; params?: never }; + +function parseArguments(flags: ArgumentFlags): ParseResult { + // Business keys such as "__proto__" must be ordinary own properties. + const params: Record = Object.create(null); + if (flags.json !== undefined) { + let parsed: unknown; + try { + parsed = JSON.parse(flags.json); + } catch { + return { + error: { "en-US": "--json is not valid JSON.", "zh-CN": "--json 不是有效的 JSON。" }, + }; + } + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { + return { + error: { "en-US": "--json must decode to an object.", "zh-CN": "--json 须为 JSON 对象。" }, + }; + } + Object.assign(params, parsed); + } + for (const item of flags.arg ?? []) { + const separator = item.indexOf("="); + const key = item.slice(0, separator).trim(); + if (separator < 1 || !key) { + return { + error: { + "en-US": "--arg must be in K=V form with a nonblank key.", + "zh-CN": "--arg 须为 K=V 格式,键不能为空白。", + }, + }; + } + const value = item.slice(separator + 1); + try { + params[key] = JSON.parse(value); + } catch { + params[key] = value; + } + } + if (flags.query !== undefined) params.query = flags.query; + return { params }; +} + +export function validateArguments(flags: ArgumentFlags) { + return parseArguments(flags).error; +} + +export function toolArguments(flags: ArgumentFlags, localize: CommandContext["localize"]) { + const result = parseArguments(flags); + if (result.params === undefined) throw new UsageError(localize(result.error)); + return result.params; +} + +export function toolErrorMessage( + content: readonly { text?: string | null }[] | null, + localize: CommandContext["localize"], +): string { + const text = content + ?.map((item) => item.text) + .filter((value) => typeof value === "string" && value !== "") + .join("\n"); + return ( + text || localize({ "en-US": "The MCP tool reported an error.", "zh-CN": "MCP 工具执行出错。" }) + ); +} diff --git a/packages/commands/src/commands/mcp/call.ts b/packages/commands/src/commands/mcp/call.ts index b15ff278e..25d0c7575 100644 --- a/packages/commands/src/commands/mcp/call.ts +++ b/packages/commands/src/commands/mcp/call.ts @@ -1,126 +1,42 @@ -import { - defineCommand, - UsageError, - BailianError, - bailianMcpPath, - type FlagsDef, - type ParsedFlags, -} from "bailian-cli-core"; +import { defineCommand, BailianError, bailianMcpPath } from "bailian-cli-core"; import { rethrowWithMcpActivateHint } from "./activate-hint.ts"; +import { + argumentFlags, + toolArguments, + toolErrorMessage, + validateArguments, +} from "./call-arguments.ts"; +import { endpointFlag, validateEndpoint } from "./protocol-endpoint.ts"; -const CALL_FLAGS = { - target: { - type: "string", - valueHint: "", - description: { - "en-US": - "Server code and tool name joined by a dot, e.g. market-cmapi00073529.SmartStockSelection", - "zh-CN": "由点号连接的 Server Code 和工具名称,例如 market-cmapi00073529.SmartStockSelection", - }, - required: true, - }, - arg: { - type: "array", - valueHint: "", - description: { - "en-US": "Tool argument (repeatable). Values parsed as JSON if possible, else string.", - "zh-CN": "工具参数(可重复)。值会优先按 JSON 解析,否则作为字符串。", - }, - }, - json: { - type: "string", - valueHint: "", - description: { - "en-US": "Full arguments object as JSON; merged with --arg (arg wins).", - "zh-CN": "完整的 JSON 参数对象;与 --arg 合并(--arg 优先)。", - }, - }, - query: { - type: "string", - valueHint: "", - description: { - "en-US": "Shortcut for --arg query= (mirrors many DashScope MCP tools).", - "zh-CN": "--arg query= 的快捷方式(与许多 DashScope MCP 工具一致)。", - }, - }, - url: { - type: "string", - valueHint: "", - description: { - "en-US": - "Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL.", - "zh-CN": - "覆盖 MCP Endpoint URL(非百炼)。先尝试 Streamable HTTP,再在同一 URL 上回退到传统 SSE。", - }, - }, -} satisfies FlagsDef; -type CallFlags = ParsedFlags; - -function parseTarget(target: string): { serverCode: string; toolName: string } { - const dot = target.indexOf("."); - if (dot <= 0 || dot === target.length - 1) { - throw new UsageError(`target must be ., got "${target}".`); - } - return { serverCode: target.slice(0, dot), toolName: target.slice(dot + 1) }; -} - -function parseArgFlags(raw: string[]): Record { - const out: Record = {}; - for (const item of raw) { - const idx = item.indexOf("="); - if (idx <= 0) { - throw new UsageError(`--arg must be in K=V form, got: ${item}`); - } - const key = item.slice(0, idx).trim(); - const rawVal = item.slice(idx + 1); - try { - out[key] = JSON.parse(rawVal); - } catch { - out[key] = rawVal; - } - } - return out; -} - -function parseJsonArg(raw: string): Record { - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch (err) { - throw new UsageError(`--json is not valid JSON — ${(err as Error).message}`); - } - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) { - throw new UsageError("--json must decode to an object."); - } - return parsed as Record; -} - -function buildToolArgs(flags: CallFlags): Record { - const toolArgs = flags.json ? parseJsonArg(flags.json) : {}; - Object.assign(toolArgs, parseArgFlags(flags.arg ?? [])); - if (flags.query !== undefined) toolArgs.query = flags.query; - return toolArgs; -} - -function validateCallFlags(flags: CallFlags): string | undefined { - try { - parseTarget(flags.target); - buildToolArgs(flags); - } catch (err) { - if (err instanceof UsageError) return err.message; - throw err; - } - return undefined; +function parseTarget(target: string) { + const separator = target.indexOf("."); + return { + serverCode: separator < 0 ? "" : target.slice(0, separator), + toolName: target.slice(separator + 1), + }; } export default defineCommand({ description: { - "en-US": "Call a tool on an MCP server (tools/call)", - "zh-CN": "调用 MCP 服务器上的工具(tools/call)", + "en-US": "Open an MCP session and call a tool (tools/call)", + "zh-CN": "建立 MCP 会话并调用工具(tools/call)", }, auth: "apiKey", - usageArgs: "--target [--arg k=v ...] [--json '{...}'] [--url ]", - flags: CALL_FLAGS, + usageArgs: + "--target [--arg k=v ...] [--json '{...}'] [--query ] [--url ]", + flags: { + target: { + type: "string", + required: true, + valueHint: "", + description: { + "en-US": "Server code and tool name separated by the first dot", + "zh-CN": "用第一个点号分隔服务编码和工具名称", + }, + }, + ...argumentFlags, + url: endpointFlag, + }, exampleArgs: [ { "en-US": @@ -134,18 +50,25 @@ export default defineCommand({ }, "--target market-cmapi00073529.SmartFundSelection --arg riskLevel=R3 --arg minScale=10", ], - validate: validateCallFlags, + validate(flags) { + const target = parseTarget(flags.target); + if (!target.serverCode.trim() || !target.toolName.trim()) { + return { + "en-US": "--target must be ..", + "zh-CN": "--target 须为 .。", + }; + } + return validateEndpoint(flags.url) ?? validateArguments(flags); + }, async run(ctx) { const { settings, flags } = ctx; const { serverCode, toolName } = parseTarget(flags.target); - const toolArgs = buildToolArgs(flags); - - const previewUrl = flags.url || ctx.client.url(bailianMcpPath(serverCode)); + const toolArgs = toolArguments(flags, ctx.localize); if (settings.dryRun) { ctx.output.result({ server: serverCode, - url: previewUrl, + url: flags.url || ctx.client.baseUrl + bailianMcpPath(serverCode), tool: toolName, arguments: toolArgs, }); @@ -153,17 +76,11 @@ export default defineCommand({ } let client: { close?(): void } | undefined; + let result; try { const connected = await ctx.client.connectBailianMcp(serverCode, flags.url); client = connected.client; - const result = await connected.client.callTool(toolName, toolArgs); - - if (result.isError) { - const errText = result.content.map((contentItem) => contentItem.text || "").join("\n"); - throw new BailianError(`Tool error: ${errText}`); - } - - ctx.output.result(result); + result = await connected.client.callTool(toolName, toolArgs); } catch (error) { if (!flags.url) { rethrowWithMcpActivateHint(error, serverCode); @@ -172,5 +89,7 @@ export default defineCommand({ } finally { client?.close?.(); } + if (result.isError) throw new BailianError(toolErrorMessage(result.content, ctx.localize)); + ctx.output.result(result); }, }); diff --git a/packages/commands/src/commands/mcp/connect.ts b/packages/commands/src/commands/mcp/connect.ts index 66b02cd2a..4dcce85b0 100644 --- a/packages/commands/src/commands/mcp/connect.ts +++ b/packages/commands/src/commands/mcp/connect.ts @@ -1,138 +1,291 @@ -import { homedir } from "node:os"; +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { BailianError, defineCommand, formatCommand, type CommandContext } from "bailian-cli-core"; +import { withStateLock } from "../shared/state-lock.ts"; import { - BailianError, - ExitCode, - REGIONS, - bailianMcpPath, - bailianMcpSsePath, - defineCommand, - getConfigDir, - trackingHeaders, - type FlagsDef, -} from "bailian-cli-core"; -import { - MCP_AGENT_IDS, connectMcpAgents, - resolveMcpAgentTargets, + manifestPath, + McpRegistrationError, type McpTransport, type NativeMcpAgent, } from "./agent-config.ts"; +import { + projectCredentialNote, + registrationAttempt, + registrationFailure, + registrationFlags, + registrationLocation, + reportRegistrations, + type RegistrationOutcome, + type RegistrationResult, +} from "./registration.ts"; +import { planServerLifecycle, writeServer } from "./server-lifecycle.ts"; +import { validateServer } from "./server-management.ts"; +import { requestMcpServer } from "./server-response.ts"; -const AGENT_CHOICES = [...MCP_AGENT_IDS, "all"] as const; -const TRANSPORT_CHOICES = ["streamable-http", "sse"] as const; - -const FLAGS = { - server: { - type: "string", - valueHint: "", - description: { - "en-US": "Bailian MCP Server Code, such as TextGenerateImage", - "zh-CN": "百炼 MCP Server Code,例如 TextGenerateImage", - }, - required: true, - }, +const flags = { + ...WORKSPACE_FLAG, + ...registrationFlags, transport: { type: "string", - valueHint: "", - choices: TRANSPORT_CHOICES, + required: true, + choices: ["streamable-http", "sse"], + valueHint: "", description: { - "en-US": "MCP transport exposed by the server: streamable-http or sse", - "zh-CN": "服务端提供的 MCP 传输协议:streamable-http 或 sse", + "en-US": "Transport exposed by the service endpoint", + "zh-CN": "服务端点实际使用的传输协议", }, - required: true, }, - agent: { - type: "string", - valueHint: "", - choices: AGENT_CHOICES, + andActivate: { + type: "boolean", + implicitValue: true, + valueHint: "[true|false]", description: { - "en-US": `Target Agent: ${AGENT_CHOICES.join(", ")}`, - "zh-CN": `目标 Agent:${AGENT_CHOICES.join(", ")}`, + "en-US": + "Activate an inactive service before connecting (default true, activation may incur charges). Use --and-activate=false to connect only to active services.", + "zh-CN": + "接入前开通未启用的服务(默认 true,开通可能产生费用)。仅接入已启用的服务可用 --and-activate=false。", }, - required: true, }, -} satisfies FlagsDef; +} as const; +type Context = Pick< + CommandContext, + "client" | "identity" | "localize" | "flags" | "settings" +>; +type Location = ReturnType; +type Activation = Extract, { action: string }>; +interface Dependency { + endpoint?: string; + activation?: Activation; + status?: string | null; + problem?: { error: unknown; fields?: Partial }; +} + +function readyEndpoint(endpoint: string | null, transport: McpTransport): string { + if (!endpoint || !URL.canParse(endpoint)) + throw new McpRegistrationError("ENDPOINT_UNAVAILABLE", { + "en-US": "The active service did not return a usable MCP endpoint.", + "zh-CN": "已启用的服务未返回可用的 MCP 端点。", + }); + const url = new URL(endpoint); + if (url.protocol !== "https:" || url.username || url.password || url.hash || url.search) + throw new McpRegistrationError("ENDPOINT_UNAVAILABLE", { + "en-US": "Expected an HTTPS MCP endpoint without embedded credentials, query, or fragment.", + "zh-CN": "MCP 端点须使用 HTTPS,且不含嵌入凭证、查询参数或片段。", + }); + const suffix = transport === "sse" ? "/sse" : "/mcp"; + if (!url.pathname.replace(/\/$/, "").endsWith(suffix)) + throw new McpRegistrationError("TRANSPORT_MISMATCH", { + "en-US": `The service endpoint does not support the requested transport (${transport}).`, + "zh-CN": `服务端点与所选传输协议 ${transport} 不匹配。`, + }); + return endpoint; +} + +function pendingActivation() { + return new McpRegistrationError("SERVER_NOT_READY", { + "en-US": "Activation is still in progress. Run connect again when the service is active.", + "zh-CN": "服务仍在开通中,请在启用后重新执行 connect。", + }); +} + +async function connectionDependency(ctx: Context, allowActivation: boolean): Promise { + const { server, transport } = ctx.flags; + try { + const response = await requestMcpServer(ctx, "GET", server); + const status = response.detail.server_status; + if (status === "ACTIVATED") + return { status, endpoint: readyEndpoint(response.detail.endpoint, transport) }; + if (status === "ACTIVATING") return { status, problem: { error: pendingActivation() } }; + const step = planServerLifecycle(ctx, server, "activate", response); + if ("result" in step) return { status, problem: { error: step.error, fields: step.result } }; + if (!allowActivation) { + const command = formatCommand(ctx.identity, "mcp activate --server "); + return { + status, + problem: { + error: new McpRegistrationError("NOT_ACTIVATED", { + "en-US": `The service is inactive. Activate it first with ${command}.`, + "zh-CN": `服务尚未启用,请先执行 ${command}。`, + }), + }, + }; + } + return { status, activation: step }; + } catch (error) { + return { problem: { error } }; + } +} + +function connectTarget( + ctx: Context, + location: Location, + agent: NativeMcpAgent, + endpoint: string, + dryRun: boolean, +) { + return registrationAttempt( + ctx, + agent, + () => + connectMcpAgents({ + ...location, + agents: [agent], + dryRun, + cliVersion: ctx.identity.version, + spec: { + name: ctx.flags.server, + serverCode: ctx.flags.server, + transport: ctx.flags.transport, + endpoint, + headers: ctx.client.bailianMcpRegistrationHeaders(), + }, + })[0], + ); +} + +interface Prepared { + location: Location; + dependency: Dependency; + targets: RegistrationOutcome[]; +} + +async function finishConnection(ctx: Context, plan: Prepared) { + let { dependency, targets } = plan; + if (dependency.activation) { + targets = targets.map((target) => + target.error ? target : connectTarget(ctx, plan.location, target.result.agent, "", true), + ); + if (targets.some((target) => !target.error)) { + const activation = await writeServer(ctx, dependency.activation); + if (activation.error) + dependency = { problem: { error: activation.error, fields: activation.result } }; + else if (activation.result.server_status === "ACTIVATING") + dependency = { status: "ACTIVATING", problem: { error: pendingActivation() } }; + else dependency = await connectionDependency(ctx, false); + } + } + const { endpoint, problem } = dependency; + const outcomes = targets.map((target) => { + if (target.error) return target; + const agent = target.result.agent; + if (problem) return registrationFailure(ctx, agent, problem.error, problem.fields); + if (!endpoint) return registrationFailure(ctx, agent, pendingActivation()); + return connectTarget(ctx, plan.location, agent, endpoint, false); + }); + return { dependency, outcomes }; +} -export default defineCommand({ +export default defineCommand({ description: { - "en-US": "Register a Bailian MCP server in an Agent's native configuration", - "zh-CN": "将百炼 MCP 服务注册到 Agent 的原生配置中", + "en-US": "Connect a Bailian MCP service to native Agent configurations", + "zh-CN": "将百炼 MCP 服务接入 Agent 原生配置", }, auth: "apiKey", - usageArgs: "--server --transport --agent ", - flags: FLAGS, + flags, + usageArgs: + "--server --transport --agent [--scope ] [--and-activate[=true|false]] [--dry-run]", + exampleArgs: [ + "--server TextGenerateImage --transport streamable-http --agent cursor --dry-run", + "--server mcp-example --transport sse --agent claude-code --scope project --and-activate=false", + ], notes: [ + projectCredentialNote, { "en-US": - "This release registers the official China-site MCP endpoint; the model API --base-url does not change the MCP endpoint.", - "zh-CN": "本期固定注册中国站官方 MCP 地址;模型 API 的 --base-url 不会改变 MCP 地址。", - }, - { - "en-US": - "The resolved API key is written to the selected Agent's private local configuration. Existing unmanaged entries are never overwritten.", - "zh-CN": "解析出的 API Key 会写入所选 Agent 的本地私有配置;CLI 不会覆盖非其管理的同名条目。", - }, - { - "en-US": - "qoder, qoderwork, and qwenwork are independent products. qwenwork is QwenWork (千问办公); qoderwork is Qoder Work.", - "zh-CN": - "qoder、qoderwork、qwenwork 是彼此独立的产品。qwenwork 是千问办公(QwenWork);qoderwork 是 Qoder Work。", - }, - { - "en-US": - "workbuddy covers CodeBuddy / WorkBuddy. deepseek-harness is DeepSeek Harness and only accepts streamable-http.", - "zh-CN": - "workbuddy 覆盖 CodeBuddy / WorkBuddy。deepseek-harness 是 DeepSeek Harness,仅支持 streamable-http。", + "The service detail supplies the workspace endpoint. Each Agent is updated independently after its registration fingerprint is checked.", + "zh-CN": "使用服务详情返回的工作空间端点。逐个校验托管指纹并更新目标 Agent。", }, ], - exampleArgs: [ - "--server TextGenerateImage --transport streamable-http --agent cursor", - "--server VideoGenerate --transport sse --agent claude-code", - "--server TextGenerateImage --transport streamable-http --agent all", - ], + validate: (values) => validateServer(values.server), + async prepare(ctx) { + const location = registrationLocation(ctx.flags, ctx.localize); + // Check scope, transport and ownership before looking up or activating a service. + const inspected = location.agents.map((agent) => connectTarget(ctx, location, agent, "", true)); + const canConnect = inspected.some((target) => !target.error); + const dependency: Dependency = canConnect + ? await connectionDependency(ctx, ctx.flags.andActivate !== false) + : {}; + const targets = inspected.map((target) => + !target.error && dependency.endpoint + ? connectTarget(ctx, location, target.result.agent, dependency.endpoint, true) + : target, + ); + const previewTargets = targets.map(({ result, error }) => { + if (error) return result; + if (dependency.problem) + return registrationFailure( + ctx, + result.agent, + dependency.problem.error, + dependency.problem.fields, + ).result; + return { + agent: result.agent, + path: result.path, + action: dependency.activation ? "connect_after_activation" : result.action, + }; + }); + return { + data: { location, dependency, targets }, + preview: { + server: ctx.flags.server, + transport: ctx.flags.transport, + endpoint: dependency.endpoint ?? null, + agents: location.agents, + scope: location.scope, + project_root: location.projectRoot, + server_status: dependency.status, + activation: canConnect ? dependency.activation?.action : undefined, + targets: previewTargets, + header_names: Object.keys(ctx.client.bailianMcpRegistrationHeaders()), + }, + risk: null, + notices: [], + }; + }, async run(ctx) { - const { flags, settings } = ctx; - const transport = flags.transport as McpTransport; - const target = flags.agent as NativeMcpAgent | "all"; - const agents = resolveMcpAgentTargets(target, homedir()); - if (agents.length === 0) { + if (!ctx.prepared) throw new BailianError( - "No supported installed Agent was found for --agent all.", - ExitCode.USAGE, + ctx.localize({ "en-US": "Missing MCP connection plan.", "zh-CN": "缺少 MCP 接入计划。" }), ); + const plan = ctx.prepared; + const { location } = plan; + const canWrite = !plan.dependency.problem && plan.targets.some((target) => !target.error); + let completed; + try { + completed = canWrite + ? await withStateLock(manifestPath(location.configDir), ctx.localize, () => + finishConnection(ctx, plan), + ) + : await finishConnection(ctx, plan); + } catch (error) { + completed = { + dependency: plan.dependency, + outcomes: plan.targets.map((target) => + target.error ? target : registrationFailure(ctx, target.result.agent, error), + ), + }; } - - const endpointPath = - transport === "sse" ? bailianMcpSsePath(flags.server) : bailianMcpPath(flags.server); - const endpoint = `${REGIONS.cn}${endpointPath}`; - const channelHeaders = trackingHeaders(ctx.identity); - const headerNames = ["Authorization", ...Object.keys(channelHeaders)]; - - if (settings.dryRun) { - ctx.output.result({ - server: flags.server, - transport, - endpoint, - agents, - header_names: headerNames, - }); - return; - } - - const results = connectMcpAgents({ - agents, - spec: { - name: flags.server, - serverCode: flags.server, - transport, - endpoint, - headers: ctx.client.bailianMcpRegistrationHeaders(), + const { dependency, outcomes } = completed; + const serverArg = /^[\w.-]+$/.test(ctx.flags.server) ? ctx.flags.server : ""; + const nextStep = outcomes.some(({ error }) => !error) + ? formatCommand(ctx.identity, "mcp tools --server " + serverArg) + : undefined; + reportRegistrations( + ctx, + { + server: ctx.flags.server, + transport: ctx.flags.transport, + scope: location.scope, + project_root: location.projectRoot, + server_status: dependency.status, + endpoint: dependency.endpoint, + message: outcomes.some(({ result }) => result.status === "succeeded") + ? ctx.localize({ "en-US": "Agent configuration written.", "zh-CN": "Agent 配置已写入。" }) + : undefined, + next_step: nextStep, }, - cliVersion: ctx.identity.version, - home: homedir(), - configDir: getConfigDir(), - }); - - ctx.output.result({ server: flags.server, transport, endpoint, results }); + outcomes, + ); }, }); diff --git a/packages/commands/src/commands/mcp/create.ts b/packages/commands/src/commands/mcp/create.ts new file mode 100644 index 000000000..4b0a6f98c --- /dev/null +++ b/packages/commands/src/commands/mcp/create.ts @@ -0,0 +1,56 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineCommand } from "bailian-cli-core"; +import { + buildServerBody, + deploymentNote, + editableFlags, + executeServerWrite, + validateEdits, + type ServerWrite, +} from "./server-management.ts"; + +const flags = { + ...WORKSPACE_FLAG, + name: { ...editableFlags.name, required: true }, + description: { ...editableFlags.description, required: true }, + mcpType: { ...editableFlags.mcpType, required: true }, + mcpConfig: { ...editableFlags.mcpConfig, required: true }, +} as const; + +export default defineCommand({ + description: { + "en-US": "Create and deploy a custom MCP server", + "zh-CN": "创建并部署自定义 MCP 服务", + }, + auth: "apiKey", + notes: [deploymentNote], + flags, + usageArgs: + "--name --description --mcp-type --mcp-config [flags]", + exampleArgs: [ + { + "en-US": `--name weather --description "Weather lookup" --mcp-type http --mcp-config '{"url":"https://mcp.example.com/mcp"}' --dry-run`, + "zh-CN": `--name weather --description "天气查询" --mcp-type http --mcp-config '{"url":"https://mcp.example.com/mcp"}' --dry-run`, + }, + { + "en-US": `--name weather --description "Weather lookup" --mcp-type http --mcp-config ./weather.json`, + "zh-CN": `--name weather --description "天气查询" --mcp-type http --mcp-config ./weather.json`, + }, + ], + validate: validateEdits, + async prepare(ctx) { + const body = await buildServerBody(ctx.flags, ctx.localize); + return { + data: { method: "POST", body }, + preview: { + action: "create", + deploy: true, + server_name: body.server_name, + mcp_type: body.mcp_type, + }, + risk: null, + notices: [], + }; + }, + run: executeServerWrite, +}); diff --git a/packages/commands/src/commands/mcp/deactivate.ts b/packages/commands/src/commands/mcp/deactivate.ts new file mode 100644 index 000000000..e949a7b97 --- /dev/null +++ b/packages/commands/src/commands/mcp/deactivate.ts @@ -0,0 +1,36 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineCommand } from "bailian-cli-core"; +import { + batchServerFlag, + prepareLifecycle, + runLifecycle, + validateServers, + type LifecyclePlan, +} from "./server-lifecycle.ts"; + +const flags = { + ...WORKSPACE_FLAG, + server: batchServerFlag, +}; + +export default defineCommand({ + description: { + "en-US": "Deactivate official MCP servers or stop custom server deployments", + "zh-CN": "关闭官方 MCP 服务,或停用自定义服务的部署", + }, + auth: "apiKey", + flags, + usageArgs: "--server [--dry-run]", + exampleArgs: ["--server mcp-example,mcp-weather --dry-run", "--server mcp-example"], + notes: [ + { + "en-US": + "Stopping a server can interrupt callers. Stopping a custom server keeps its definition and saved configuration. The service may reject deactivation for OneKey servers.", + "zh-CN": + "停用服务可能中断调用。停用自定义服务后会保留服务定义和已保存的配置。OneKey 服务可能拒绝关闭。", + }, + ], + validate: (values) => validateServers(values.server), + prepare: (ctx) => prepareLifecycle(ctx, ctx.flags.server, "deactivate"), + run: (ctx) => runLifecycle(ctx, false), +}); diff --git a/packages/commands/src/commands/mcp/delete.ts b/packages/commands/src/commands/mcp/delete.ts new file mode 100644 index 000000000..cc658331f --- /dev/null +++ b/packages/commands/src/commands/mcp/delete.ts @@ -0,0 +1,60 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineCommand, getConfigDir, type CommandRisk } from "bailian-cli-core"; +import { registeredMcpAgents } from "./agent-config.ts"; +import { + executeServerWrite, + getCustomServer, + serverFlag, + validateServer, + type ServerWrite, +} from "./server-management.ts"; + +const flags = { + ...WORKSPACE_FLAG, + server: serverFlag, +}; +const risk = { + level: "high", + reason: "destructive", + message: { + "en-US": "Permanently delete this custom MCP server. This cannot be undone.", + "zh-CN": "将永久删除此自定义 MCP 服务,删除后无法恢复。", + }, +} satisfies CommandRisk; + +export default defineCommand({ + description: { + "en-US": "Permanently delete a custom MCP server", + "zh-CN": "永久删除自定义 MCP 服务", + }, + auth: "apiKey", + flags, + risk, + usageArgs: "--server [flags]", + exampleArgs: ["--server mcp-example --dry-run", "--server mcp-example --yes"], + notes: [ + { + "en-US": + "Deletion is irreversible. Use mcp disconnect to remove any local Agent registrations listed in the result.", + "zh-CN": "云端删除不可撤销。结果中列出的本地 Agent 注册可用 mcp disconnect 清理。", + }, + ], + validate: (values) => validateServer(values.server), + async prepare(ctx) { + const detail = await getCustomServer(ctx, ctx.flags.server); + const registeredAgents = registeredMcpAgents(getConfigDir(), ctx.flags.server); + return { + data: { method: "DELETE", server: ctx.flags.server, registeredAgents }, + preview: { + action: "delete", + server_code: detail.mcp_code, + server_name: detail.server_name, + server_status: detail.server_status, + connected_agents: registeredAgents, + }, + risk, + notices: [], + }; + }, + run: executeServerWrite, +}); diff --git a/packages/commands/src/commands/mcp/disconnect.ts b/packages/commands/src/commands/mcp/disconnect.ts index 75ac40b13..8607b410d 100644 --- a/packages/commands/src/commands/mcp/disconnect.ts +++ b/packages/commands/src/commands/mcp/disconnect.ts @@ -1,80 +1,75 @@ -import { homedir } from "node:os"; +import { existsSync } from "node:fs"; +import { defineCommand } from "bailian-cli-core"; +import { withStateLock } from "../shared/state-lock.ts"; +import { disconnectMcpAgents, manifestPath } from "./agent-config.ts"; import { - BailianError, - ExitCode, - defineCommand, - getConfigDir, - type FlagsDef, -} from "bailian-cli-core"; -import { - MCP_AGENT_IDS, - disconnectMcpAgents, - resolveMcpAgentTargets, - type NativeMcpAgent, -} from "./agent-config.ts"; - -const AGENT_CHOICES = [...MCP_AGENT_IDS, "all"] as const; - -const FLAGS = { - server: { - type: "string", - valueHint: "", - description: { - "en-US": "Bailian MCP Server Code used during connect", - "zh-CN": "connect 时使用的百炼 MCP Server Code", - }, - required: true, - }, - agent: { - type: "string", - valueHint: "", - choices: AGENT_CHOICES, - description: { - "en-US": `Target Agent: ${AGENT_CHOICES.join(", ")}`, - "zh-CN": `目标 Agent:${AGENT_CHOICES.join(", ")}`, - }, - required: true, - }, -} satisfies FlagsDef; + registrationAttempt, + registrationFailure, + registrationFlags, + registrationLocation, + reportRegistrations, +} from "./registration.ts"; +import { validateServer } from "./server-management.ts"; export default defineCommand({ description: { - "en-US": "Remove an unchanged MCP registration previously managed by bailian-cli", - "zh-CN": "移除此前由 bailian-cli 管理且未被修改的 MCP 注册", + "en-US": "Remove a managed MCP registration from local Agent configurations", + "zh-CN": "从本地 Agent 配置中移除托管的 MCP 注册", }, auth: "none", - usageArgs: "--server --agent ", - flags: FLAGS, + flags: registrationFlags, + usageArgs: "--server --agent [--scope ] [--dry-run]", notes: [ { - "en-US": "A registration changed after connect is left untouched and reported as a conflict.", - "zh-CN": "如果注册项在 connect 后被修改,CLI 会保留该配置并报告冲突。", + "en-US": + "Disconnect runs offline. Entries edited since registration are preserved and reported as conflicts.", + "zh-CN": "断开连接可离线执行。注册后被修改的条目会保留并报告冲突。", }, ], exampleArgs: [ - "--server TextGenerateImage --agent cursor", - "--server TextGenerateImage --agent all", + "--server mcp-example --agent cursor --scope project --dry-run", + "--server mcp-example --agent all", ], + validate: (values) => validateServer(values.server), async run(ctx) { - const { flags, settings } = ctx; - const target = flags.agent as NativeMcpAgent | "all"; - const agents = resolveMcpAgentTargets(target, homedir()); - if (agents.length === 0) { - throw new BailianError( - "No supported installed Agent was found for --agent all.", - ExitCode.USAGE, + const location = registrationLocation(ctx.flags, ctx.localize); + const metadata = { + server: ctx.flags.server, + scope: location.scope, + project_root: location.projectRoot, + }; + const inspect = (dryRun: boolean) => + location.agents.map((agent) => + registrationAttempt( + ctx, + agent, + () => + disconnectMcpAgents({ + ...location, + agents: [agent], + name: ctx.flags.server, + dryRun, + })[0], + ), ); - } - if (settings.dryRun) { - ctx.output.result({ server: flags.server, agents, action: "disconnect" }); + if (ctx.settings.dryRun) { + ctx.output.result({ + ...metadata, + action: "disconnect", + agents: location.agents, + targets: inspect(true).map(({ result }) => result), + }); return; } - const results = disconnectMcpAgents({ - agents, - name: flags.server, - home: homedir(), - configDir: getConfigDir(), - }); - ctx.output.result({ server: flags.server, results }); + const path = manifestPath(location.configDir); + let results; + try { + results = existsSync(path) + ? await withStateLock(path, ctx.localize, () => inspect(false)) + : inspect(true); + } catch (error) { + results = location.agents.map((agent) => registrationFailure(ctx, agent, error)); + } + reportRegistrations(ctx, metadata, results); }, }); diff --git a/packages/commands/src/commands/mcp/get.ts b/packages/commands/src/commands/mcp/get.ts new file mode 100644 index 000000000..111acff7d --- /dev/null +++ b/packages/commands/src/commands/mcp/get.ts @@ -0,0 +1,55 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { BailianError, defineCommand } from "bailian-cli-core"; +import { validateServer } from "./server-management.ts"; +import { requestMcpServer } from "./server-response.ts"; +import { listServerTools, toolServerFlag } from "./tool-response.ts"; + +const flags = { + ...WORKSPACE_FLAG, + server: toolServerFlag, +}; + +type ServerDetail = Awaited>["detail"]; +export default defineCommand({ + description: { + "en-US": "Get an MCP server's details and tool definitions", + "zh-CN": "查询 MCP 服务详情和工具定义", + }, + auth: "apiKey", + flags, + usageArgs: "--server [flags]", + exampleArgs: ["--server mcp-example", "--server mcp-example --dry-run"], + notes: [ + { + "en-US": + "Billing shows the reported mode, unit price and free quota, or null when unavailable. Dry-run retrieves only server details. Tool discovery may activate a OneKey service. If tool discovery fails, the detail result contains tools=null and the command exits with the error.", + "zh-CN": + "billing 展示服务端提供的计费模式、单价和免费额度,未提供时为 null。预览只读取服务详情。查询工具可能触发 OneKey 服务开通。工具查询失败时仍输出详情,tools 为 null,并返回错误退出码。", + }, + ], + validate: (values) => validateServer(values.server), + async prepare(ctx) { + const { detail } = await requestMcpServer(ctx, "GET", ctx.flags.server); + return { + data: detail, + preview: { ...detail, action: "list_tools" }, + risk: null, + notices: [], + }; + }, + async run(ctx) { + const detail = ctx.prepared; + if (!detail) + throw new BailianError( + ctx.localize({ "en-US": "Missing MCP server details.", "zh-CN": "缺少 MCP 服务详情。" }), + ); + let tools; + try { + tools = await listServerTools(ctx, detail.server_code); + } catch (error) { + ctx.output.result({ ...detail, tools: null }); + throw error; + } + ctx.output.result({ ...detail, tools }); + }, +}); diff --git a/packages/commands/src/commands/mcp/list.ts b/packages/commands/src/commands/mcp/list.ts index 86fc200d8..a9c97f7ed 100644 --- a/packages/commands/src/commands/mcp/list.ts +++ b/packages/commands/src/commands/mcp/list.ts @@ -1,116 +1,206 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { homedir } from "node:os"; import { - formatCommand, - defineCommand, - effectiveConsoleGatewayConfig, BailianError, + defineCommand, ExitCode, + getConfigDir, + mcpServersPath, } from "bailian-cli-core"; +import { connectedMcpPaths } from "./agent-config.ts"; +import { publicServer, requestMcpData, type ServerDto } from "./server-response.ts"; -const MCP_LIST_API = "zeldaEasy.broadscope-bailian.mcp-server.PageList"; - -interface ServerSummary { - code: string; - name: string; - description?: string; - type: string; - source?: string; - bizType?: string; - installType?: string; - streamable: boolean; +const SCAN_PAGE_SIZE = 100; +const MAX_CANDIDATES = 10_000; +interface ServerPage { + items: ServerDto[]; + total: number; + page_no?: number; + pageNo?: number; + page_size?: number; + pageSize?: number; } export default defineCommand({ description: { - "en-US": "List MCP servers activated under your Bailian account", - "zh-CN": "列出百炼账号下已激活的 MCP 服务器", + "en-US": "List activated MCP servers and their local Agent registrations", + "zh-CN": "列出已启用的 MCP 服务及其本地 Agent 注册", }, - auth: "console", - usageArgs: "[flags]", + auth: "apiKey", + usageArgs: "[--name ] [--type ] [--page ] [--page-size ]", flags: { + ...WORKSPACE_FLAG, name: { type: "string", valueHint: "", description: { "en-US": "Filter by server name (substring match)", - "zh-CN": "按服务器名称筛选(子字符串匹配)", + "zh-CN": "按服务名称子串筛选", }, }, type: { type: "string", - valueHint: "", + valueHint: "", description: { - "en-US": "Server type: OFFICIAL | PRIVATE (default: OFFICIAL)", - "zh-CN": "服务器类型:OFFICIAL | PRIVATE(默认:OFFICIAL)", + "en-US": "Ownership type (default official, case-insensitive)", + "zh-CN": "服务归属类型(默认 official,不区分大小写)", }, }, page: { type: "number", valueHint: "", - description: { "en-US": "Page number (default: 1)", "zh-CN": "页码(默认:1)" }, + description: { + "en-US": "Page of matching servers (default 1)", + "zh-CN": "筛选后的页码(默认 1)", + }, }, pageSize: { type: "number", valueHint: "", description: { - "en-US": "Results per page (default: 30)", - "zh-CN": "每页结果数(默认:30)", + "en-US": "Matching servers per page (1–100, default 30)", + "zh-CN": "每页服务数(1~100,默认 30)", }, }, }, - exampleArgs: ["", "--name finance", "--output json"], + notes: [ + { + "en-US": + "The CLI scans the selected type to compute the activated total before paging. connected_agents and config_paths report managed native entries whose fingerprints still match.", + "zh-CN": + "CLI 扫描所选类型,统计已启用且名称匹配的服务后分页。connected_agents 和 config_paths 列出仍与托管记录指纹匹配的本地 Agent 和配置路径。", + }, + ], + exampleArgs: ["", "--name finance", "--type private --page 2 --page-size 10"], + validate(flags) { + if ( + flags.type !== undefined && + !["OFFICIAL", "PRIVATE", "CUSTOMER"].includes(flags.type.toUpperCase()) + ) { + return { + "en-US": "--type must be official or private (CUSTOMER).", + "zh-CN": "--type 须为 official 或 private(CUSTOMER)。", + }; + } + const page = flags.page ?? 1; + const pageSize = flags.pageSize ?? 30; + if ( + !Number.isSafeInteger(page) || + page < 1 || + !Number.isSafeInteger(pageSize) || + pageSize < 1 || + pageSize > 100 || + page * pageSize > MAX_CANDIDATES + ) { + return { + "en-US": + "--page must be a positive integer, --page-size an integer from 1 to 100, and their product at most 10000.", + "zh-CN": "--page 须为正整数,--page-size 须为 1~100 的整数,两者乘积不能超过 10000。", + }; + } + }, async run(ctx) { - const { settings, identity, flags } = ctx; - const serverName = flags.name || ""; - const type = flags.type || "OFFICIAL"; - const pageNo = flags.page || 1; - const pageSize = flags.pageSize || 30; - - const data = { - reqDTO: { + const { flags } = ctx; + const page = flags.page ?? 1; + const pageSize = flags.pageSize ?? 30; + const type = (flags.type ?? "official").toUpperCase() === "OFFICIAL" ? "OFFICIAL" : "CUSTOMER"; + const name = flags.name ?? ""; + const listPath = `${mcpServersPath()}/list`; + if (ctx.settings.dryRun) { + ctx.output.result({ + method: "GET", + path: listPath, type, - displayTools: false, - activated: 1, - pageNo, - pageSize, - serverName, - }, - }; - - if (settings.dryRun) { - ctx.output.result({ api: MCP_LIST_API, data, ...effectiveConsoleGatewayConfig(settings) }); + name, + activated: true, + page, + page_size: pageSize, + scan_page_size: SCAN_PAGE_SIZE, + }); return; } - const result = (await ctx.client.console(MCP_LIST_API, data)) as Record; - - const dataField = (result?.data as Record | undefined) ?? {}; - if (dataField.success === false) { - const code = (dataField.errorCode as string | undefined) ?? "UnknownError"; - const msg = (dataField.errorMsg as string | undefined) ?? code; - const hint = - code === "BailianGateway.Login.NotLogined" - ? `Run \`${formatCommand(identity, "auth login --console")}\` to refresh your console session.` - : undefined; - throw new BailianError(`Console gateway: ${msg}`, ExitCode.AUTH, hint); + const offset = (page - 1) * pageSize; + const selected: ReturnType[] = []; + const needle = name.toLowerCase(); + let total = 0; + for (let scanPage = 1; ; scanPage++) { + const query = new URLSearchParams({ + type, + pageNo: String(scanPage), + pageSize: String(SCAN_PAGE_SIZE), + }); + const { data, requestId } = await requestMcpData(ctx, { + method: "GET", + path: `${listPath}?${query.toString()}`, + }); + if (data.total > MAX_CANDIDATES) + throw new BailianError( + ctx.localize({ + "en-US": + "The candidate list exceeds the API's 10000-record window. An accurate activated total is unavailable.", + "zh-CN": "候选服务超过接口的 10000 条分页上限,无法统计准确的已启用服务总数。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId } }, + ); + const scanned = (scanPage - 1) * SCAN_PAGE_SIZE; + if ( + !Number.isSafeInteger(data.total) || + data.total < 0 || + !Array.isArray(data.items) || + data.items.length !== Math.min(SCAN_PAGE_SIZE, Math.max(0, data.total - scanned)) || + (data.page_no ?? data.pageNo ?? scanPage) !== scanPage || + (data.page_size ?? data.pageSize ?? SCAN_PAGE_SIZE) !== SCAN_PAGE_SIZE + ) { + throw new BailianError( + ctx.localize({ + "en-US": "The MCP list response contains inconsistent pagination. Retry the list.", + "zh-CN": "MCP 列表响应的分页信息不一致,请重新查询。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId } }, + ); + } + for (const item of data.items) { + const detail = publicServer(ctx, item, requestId); + if (!detail.activated || !(detail.server_name ?? "").toLowerCase().includes(needle)) + continue; + if (total >= offset && selected.length < pageSize) selected.push(detail); + total++; + } + if (scanned + data.items.length >= data.total) break; } - const dataV2 = (dataField.DataV2 as Record | undefined) ?? {}; - const inner = - (dataV2.data as { data?: { mcpServerDetailList?: unknown[]; total?: number } } | undefined) - ?.data ?? {}; - const list = (inner.mcpServerDetailList ?? []) as Array>; - const total = (inner.total as number) ?? 0; - - const servers: ServerSummary[] = list.map((item) => ({ - code: (item.serverCode as string | undefined) ?? "", - name: (item.serverName as string | undefined) ?? "", - description: item.description as string | undefined, - type: (item.type as string | undefined) ?? "", - source: item.source as string | undefined, - bizType: item.bizType as string | undefined, - installType: item.installType as string | undefined, - streamable: item.streamable === true, - })); - + const pathsByCode = connectedMcpPaths( + getConfigDir(), + homedir(), + new Set(selected.map((detail) => detail.server_code)), + (path) => { + ctx.output.warning({ + code: "MCP_REGISTRATIONS_UNREADABLE", + message: { + "en-US": `Could not read ${path}. Local registrations may be incomplete.`, + "zh-CN": `无法读取 ${path},本地注册信息可能不完整。`, + }, + }); + }, + ); + const servers = selected.map((detail) => { + const paths = pathsByCode.get(detail.server_code) ?? {}; + const streamable = detail.endpoint + ? /\/mcp\/?(?:[?#].*)?$/.test(detail.endpoint) + : detail.server_type === "HTTP"; + return { + ...detail, + code: detail.server_code, + name: detail.server_name ?? "", + streamable, + connected_agents: Object.keys(paths), + config_paths: paths, + }; + }); ctx.output.result({ total, servers }); }, }); diff --git a/packages/commands/src/commands/mcp/protocol-endpoint.ts b/packages/commands/src/commands/mcp/protocol-endpoint.ts new file mode 100644 index 000000000..c7ec7d699 --- /dev/null +++ b/packages/commands/src/commands/mcp/protocol-endpoint.ts @@ -0,0 +1,22 @@ +export const endpointFlag = { + type: "string", + valueHint: "", + description: { + "en-US": + "MCP endpoint that receives the API key. Try Streamable HTTP first, then classic SSE at the same URL if initialization returns HTTP 404 or 405.", + "zh-CN": + "指定接收 API Key 的 MCP 端点。先尝试 Streamable HTTP,初始化返回 HTTP 404 或 405 时在同一 URL 上尝试传统 SSE。", + }, +} as const; + +export function validateEndpoint(url?: string) { + if ( + url !== undefined && + (!URL.canParse(url) || !["https:", "http:"].includes(new URL(url).protocol)) + ) { + return { + "en-US": "--url must be an absolute HTTP or HTTPS MCP endpoint.", + "zh-CN": "--url 须为 HTTP 或 HTTPS 的 MCP 端点绝对地址。", + }; + } +} diff --git a/packages/commands/src/commands/mcp/registration.ts b/packages/commands/src/commands/mcp/registration.ts new file mode 100644 index 000000000..158db4d7f --- /dev/null +++ b/packages/commands/src/commands/mcp/registration.ts @@ -0,0 +1,170 @@ +import { homedir } from "node:os"; +import { + BailianError, + ExitCode, + formatCommand, + getConfigDir, + type CommandContext, + type LocalizedText, +} from "bailian-cli-core"; +import { normalizeError } from "bailian-cli-runtime"; +import { + MCP_AGENT_IDS, + McpRegistrationError, + projectAgents, + resolveMcpAgentTargets, + type McpAgentResult, + type McpScope, + type NativeMcpAgent, +} from "./agent-config.ts"; + +export const registrationFlags = { + server: { + type: "string", + valueHint: "", + required: true, + description: { + "en-US": "Bailian MCP server code", + "zh-CN": "百炼 MCP 服务编码", + }, + }, + agent: { + type: "string", + required: true, + valueHint: "", + choices: [...MCP_AGENT_IDS, "all"], + description: { + "en-US": `Target Agent: ${[...MCP_AGENT_IDS, "all"].join(", ")}`, + "zh-CN": `目标 Agent:${[...MCP_AGENT_IDS, "all"].join("、")}`, + }, + }, + scope: { + type: "string", + valueHint: "", + choices: ["user", "project"], + description: { + "en-US": `Registration scope (default user). Run project scope in the project root. Supported: ${projectAgents.join(", ")}.`, + "zh-CN": `注册范围(默认 user)。请在项目根目录执行 project 模式,支持 ${projectAgents.join("、")}。`, + }, + }, +} as const; + +type CommonContext = Pick; +export function registrationLocation( + flags: { server: string; agent: NativeMcpAgent | "all"; scope?: McpScope }, + localize: CommandContext["localize"], +) { + const scope = flags.scope ?? "user"; + const projectRoot = scope === "project" ? process.cwd() : undefined; + const home = homedir(); + const configDir = getConfigDir(); + let agents; + try { + agents = resolveMcpAgentTargets(flags.agent, home, { + configDir, + server: flags.server, + projectRoot, + }); + } catch (error) { + if (error instanceof McpRegistrationError) + throw new BailianError(localize(error.text), error.exitCode); + throw error; + } + if (!agents.length) + throw new BailianError( + localize({ + "en-US": "No installed or registered Agent was found for --agent all.", + "zh-CN": "--agent all 未找到已安装或已注册的 Agent。", + }), + ExitCode.USAGE, + ); + return { scope, projectRoot, home, configDir, agents }; +} + +export interface RegistrationResult { + agent: NativeMcpAgent; + status: "succeeded" | "noop" | "failed"; + path?: string; + action?: McpAgentResult["status"]; + reason?: string; + error_code?: string | number; + api_code?: string; + request_id?: string; + http_status?: number; + message?: string; + hint?: string; + detail?: { console_url: string }; + outcome_unknown?: boolean; +} +export interface RegistrationOutcome { + result: RegistrationResult; + error?: BailianError; +} + +export function registrationFailure( + ctx: CommonContext, + agent: NativeMcpAgent, + cause: unknown, + fields?: Partial, +): RegistrationOutcome { + const local = cause instanceof McpRegistrationError; + const error = local + ? new BailianError(ctx.localize(cause.text), cause.exitCode) + : normalizeError(cause, formatCommand(ctx.identity), ctx.localize); + return { + error, + result: { + agent, + status: "failed", + error_code: local ? cause.reason : (error.api?.apiCode ?? error.exitCode), + message: error.message, + hint: error.hint, + api_code: error.api?.apiCode, + request_id: error.api?.requestId, + http_status: error.api?.httpStatus, + ...fields, + }, + }; +} + +export function registrationAttempt( + ctx: CommonContext, + agent: NativeMcpAgent, + operation: () => McpAgentResult, +): RegistrationOutcome { + try { + const { path, status } = operation(); + const reason = + status === "absent" + ? "NOT_CONNECTED" + : status === "unchanged" + ? "ALREADY_CONNECTED" + : undefined; + return { + result: { agent, path, action: status, status: reason ? "noop" : "succeeded", reason }, + }; + } catch (error) { + return registrationFailure(ctx, agent, error); + } +} + +export function reportRegistrations( + ctx: Pick, + metadata: Record, + outcomes: RegistrationOutcome[], +) { + const summary = { succeeded: 0, failed: 0, noop: 0 }; + const results = outcomes.map(({ result }) => { + summary[result.status]++; + return { code: metadata.server, ...result }; + }); + ctx.output.result({ ...metadata, summary, results }); + const failure = outcomes.find(({ error }) => error); + if (failure?.error) throw failure.error; +} + +export const projectCredentialNote: LocalizedText = { + "en-US": + "Agent configuration contains the resolved API key. Keep project configuration and its backups out of version control.", + "zh-CN": "Agent 配置含当前 API Key。请勿将项目配置及其备份提交到版本库。", +}; diff --git a/packages/commands/src/commands/mcp/server-config.ts b/packages/commands/src/commands/mcp/server-config.ts new file mode 100644 index 000000000..c62ad1995 --- /dev/null +++ b/packages/commands/src/commands/mcp/server-config.ts @@ -0,0 +1,237 @@ +import { readFile } from "node:fs/promises"; +import { UsageError, type CommandContext } from "bailian-cli-core"; + +export const MCP_TYPES = ["STDIO", "HTTP", "SSE", "OPENAPI"] as const; +type JsonObject = Record; +type InvalidField = (field: string, english: string, chinese: string) => never; + +function isObject(value: unknown): value is JsonObject { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function isText(value: unknown): value is string { + return typeof value === "string" && value.trim().length > 0; +} + +function objectFields( + value: unknown, + path: string, + allowed: string[], + invalid: InvalidField, +): JsonObject { + if (!isObject(value)) return invalid(path, "expected a JSON object", "需要 JSON 对象"); + for (const [key, entry] of Object.entries(value)) { + if (!allowed.includes(key) || entry === null) { + invalid(`${path}.${key}`, "unsupported field or null value", "不支持该字段或 null 值"); + } + } + return value; +} + +function checkMap( + value: unknown, + kind: "env" | "headers", + nonblank: boolean, + invalid: InvalidField, +) { + if (value === undefined) return; + const keyPattern = kind === "env" ? /^[A-Za-z_][A-Za-z0-9_]*$/ : /^[!#$%&'*+.^_`|~0-9a-zA-Z-]+$/; + if ( + !isObject(value) || + Object.entries(value).some( + ([key, entry]) => + !keyPattern.test(key) || + typeof entry !== "string" || + (kind === "headers" && /[\r\n]/.test(entry)) || + (nonblank && !entry.trim()), + ) + ) { + invalid(kind, "invalid name or string value", "名称或字符串值无效"); + } +} + +function checkUrl(value: unknown, field: "url" | "api_host", invalid: InvalidField) { + if (!isText(value) || !/^https?:\/\//i.test(value) || !URL.canParse(value)) { + invalid(field, "expected a public HTTP(S) URL", "需要公网 HTTP(S) 地址"); + } + const url = new URL(value); + if ( + /[#\\]/.test(value) || + url.username || + url.password || + url.port === "0" || + (field === "api_host" && value.includes("?")) + ) { + invalid(field, "invalid MCP endpoint URL", "MCP 服务地址格式无效"); + } +} + +const PARAMETER_TYPES = ["String", "Number", "Integer", "Boolean", "Object"]; +const LOCATIONS = ["Query", "Path", "Header", "Body"]; + +function checkParameters( + value: unknown, + path: string, + method: unknown, + depth: number, + invalid: InvalidField, +) { + if (!Array.isArray(value) || depth > 32) + invalid(path, "expected a parameter array within 32 levels", "需要深度不超过 32 层的参数数组"); + const names = new Set(); + for (const [index, entry] of value.entries()) { + const item = `${path}[${index}]`; + const param = objectFields( + entry, + item, + ["name", "description", "location", "type", "required", "properties"], + invalid, + ); + if (!isText(param.name) || names.has(param.name) || !isText(param.description)) { + invalid(item, "expected a unique name and a nonblank description", "需要唯一名称和非空描述"); + } + names.add(param.name); + if (!PARAMETER_TYPES.some((type) => param.type === type || param.type === `Array<${type}>`)) { + invalid(`${item}.type`, "unsupported parameter type", "不支持的参数类型"); + } + if ( + (depth === 1 || param.location !== undefined) && + !LOCATIONS.some((location) => location === param.location) + ) { + invalid( + `${item}.location`, + "expected Query, Path, Header or Body", + "须为 Query、Path、Header 或 Body", + ); + } + const complex = param.type === "Object" || String(param.type).startsWith("Array<"); + if ( + depth === 1 && + ((complex && param.location !== "Body") || (method === "GET" && param.location === "Body")) + ) { + invalid( + `${item}.location`, + "objects and arrays require Body, and GET cannot use Body", + "对象及数组须放在 Body,GET 不支持 Body", + ); + } + if (param.required !== undefined && typeof param.required !== "boolean") + invalid(`${item}.required`, "expected a boolean", "需要布尔值"); + const hasChildren = param.type === "Object" || param.type === "Array"; + if (hasChildren) { + if (!Array.isArray(param.properties) || !param.properties.length) + invalid(`${item}.properties`, "expected nonempty properties", "需要非空子属性"); + checkParameters(param.properties, `${item}.properties`, method, depth + 1, invalid); + } else if ( + param.properties !== undefined && + !(Array.isArray(param.properties) && param.properties.length === 0) + ) { + invalid( + `${item}.properties`, + "only object types can define properties", + "只有对象类型能定义子属性", + ); + } + } +} + +function checkApis(value: unknown, invalid: InvalidField) { + if (!Array.isArray(value) || !value.length) + invalid("api_list", "expected a nonempty API array", "需要非空 API 数组"); + const names = new Set(); + for (const [index, entry] of value.entries()) { + const path = `api_list[${index}]`; + const api = objectFields( + entry, + path, + ["name", "description", "path", "method", "content_type", "input_params"], + invalid, + ); + if (!isText(api.name) || names.has(api.name) || !isText(api.description)) + invalid(path, "expected a unique name and a nonblank description", "需要唯一名称和非空描述"); + names.add(api.name); + if ( + !isText(api.path) || + !api.path.startsWith("/") || + api.path.startsWith("//") || + /[#\\]/.test(api.path) + ) + invalid( + `${path}.path`, + "expected a relative path starting with /", + "需要以 / 开头的相对路径", + ); + if (api.method !== "GET" && api.method !== "POST") + invalid(`${path}.method`, "expected GET or POST", "须为 GET 或 POST"); + if ( + api.content_type !== undefined && + api.content_type !== "application/json" && + api.content_type !== "application/x-www-form-urlencoded" + ) + invalid(`${path}.content_type`, "unsupported content type", "不支持的内容类型"); + if (api.input_params !== undefined) + checkParameters(api.input_params, `${path}.input_params`, api.method, 1, invalid); + } +} + +export async function readMcpConfig( + argument: string, + type: string, + localize: CommandContext["localize"], +) { + const invalid: InvalidField = (field, english, chinese) => { + throw new UsageError( + localize({ + "en-US": `--mcp-config ${field}: ${english}.`, + "zh-CN": `--mcp-config ${field}:${chinese}。`, + }), + ); + }; + const input = argument.trim(); + let value: unknown; + // An object, array or literal is inline JSON. All other inputs are file paths. + const inline = + /^[{["]/.test(input) || /^(?:null|true|false|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)$/.test(input); + const source = inline ? input : await readFile(argument, "utf8"); + try { + value = JSON.parse(source.trimStart()); + } catch { + invalid("", "invalid JSON", "JSON 格式错误"); + } + if (type === "STDIO") { + const config = objectFields( + value, + "STDIO", + ["command", "args", "env", "fc_deploy_region"], + invalid, + ); + if (config.command !== "npx" && config.command !== "uvx") + invalid("command", "expected npx or uvx", "须为 npx 或 uvx"); + if ( + !Array.isArray(config.args) || + !config.args.length || + !config.args.every((arg) => isText(arg) && /^[A-Za-z0-9_@./:=,+-]+$/.test(arg)) + ) { + invalid( + "args", + "expected nonempty npx/uvx arguments using supported characters", + "需要非空的 npx/uvx 参数数组,参数只能包含接口支持的字符", + ); + } + checkMap(config.env, "env", false, invalid); + if (config.fc_deploy_region !== undefined && !isText(config.fc_deploy_region)) + invalid("fc_deploy_region", "expected a nonblank region", "需要非空地域"); + return config; + } + if (type === "OPENAPI") { + const config = objectFields(value, "OPENAPI", ["api_host", "headers", "api_list"], invalid); + checkUrl(config.api_host, "api_host", invalid); + checkMap(config.headers, "headers", true, invalid); + checkApis(config.api_list, invalid); + return config; + } + const config = objectFields(value, type, ["url", "headers"], invalid); + checkUrl(config.url, "url", invalid); + checkMap(config.headers, "headers", false, invalid); + return config; +} diff --git a/packages/commands/src/commands/mcp/server-lifecycle.ts b/packages/commands/src/commands/mcp/server-lifecycle.ts new file mode 100644 index 000000000..2fca640be --- /dev/null +++ b/packages/commands/src/commands/mcp/server-lifecycle.ts @@ -0,0 +1,345 @@ +import { + BailianError, + ExitCode, + formatCommand, + mcpServersPath, + type CommandContext, + type LocalizedText, +} from "bailian-cli-core"; +import { mcpMarketplaceDetailPage, normalizeError } from "bailian-cli-runtime"; +import { openInBrowser } from "../shared/local-server.ts"; +import { serverFlag, validateServer } from "./server-management.ts"; +import { + publicServer, + requestMcpData, + requestMcpServer, + type McpRequestContext, + type ServerDto, + type ServerBilling, +} from "./server-response.ts"; + +export const batchServerFlag = { + ...serverFlag, + valueHint: "", + description: { + "en-US": "Comma-separated server codes (up to 30 distinct servers)", + "zh-CN": "逗号分隔的服务编码,去重后最多 30 个", + }, +} as const; + +type Operation = "activate" | "deactivate"; +type Action = Operation | "enable" | "disable"; +type Context = McpRequestContext & Pick; + +function serverCodes(value: string) { + return [...new Set(value.split(",").map((code) => code.trim()))]; +} + +export function validateServers(value: string) { + const codes = serverCodes(value); + for (const code of codes) { + const error = validateServer(code); + if (error) return error; + } + if (codes.length > 30) + return { + "en-US": "--server accepts at most 30 distinct server codes.", + "zh-CN": "--server 去重后最多支持 30 个服务编码。", + }; +} + +interface WriteStep { + billing?: ServerBilling; + code: string; + action: Action; + type: string; + server_status: string; + is_onekey: boolean | null; + console_url: string | null; +} + +interface ItemResult { + billing?: ServerBilling; + code: string; + status: "succeeded" | "failed" | "noop"; + server_status?: string | null; + server_status_text?: string | null; + request_id?: string; + reason?: string; + error_code?: string | number; + message?: string; + hint?: string; + outcome_unknown?: boolean; + api_code?: string; + http_status?: number; + detail?: { console_url: string; browser_opened?: boolean }; +} + +interface Completed { + result: ItemResult; + error?: BailianError; +} + +export type LifecyclePlan = (WriteStep | Completed)[]; + +function responseError(ctx: Context, message: LocalizedText, requestId?: string) { + return new BailianError(ctx.localize(message), ExitCode.GENERAL, undefined, { + api: { requestId }, + }); +} + +function failure(code: string, error: BailianError, fields?: Partial): Completed { + return { + error, + result: { + code, + status: "failed", + error_code: error.api?.apiCode ?? error.exitCode, + api_code: error.api?.apiCode, + message: error.message, + hint: error.hint, + http_status: error.api?.httpStatus, + request_id: error.api?.requestId, + ...fields, + }, + }; +} + +const marketSetupMessage = "当前云市场MCP不允许通过OpenAPI开通,请前往控制台手动开通:"; + +function trustedConsoleUrl(value: string | null) { + if (!value || !URL.canParse(value)) return; + const url = new URL(value); + if ( + url.protocol === "https:" && + !url.username && + !url.password && + !url.port && + /(^|\.)console\.(aliyun|alibabacloud)\.com$/.test(url.hostname) + ) + return url.href; +} + +function manualSetup( + code: string, + error: BailianError, + consoleUrl: string | null, + billing?: ServerBilling, +): Completed { + const marketUrl = error.message.startsWith(marketSetupMessage) + ? error.message.slice(marketSetupMessage.length) + : null; + const url = + trustedConsoleUrl(marketUrl) ?? + trustedConsoleUrl(consoleUrl) ?? + mcpMarketplaceDetailPage(encodeURIComponent(code)); + return failure(code, error, { + error_code: "MANUAL_SETUP_REQUIRED", + ...(billing && { billing }), + detail: { console_url: url }, + }); +} + +// These activation responses explicitly require an input that can only be supplied in the console. +function requiresManualSetup(error: BailianError) { + switch (error.api?.apiCode) { + case "MANUAL_SETUP_REQUIRED": + return true; + case "InvalidParameter": + return error.message.startsWith("缺少开通所需的环境变量:"); + case "OperationNotSupported": + return ( + error.message === "当前MCP需要选择凭据,不支持通过OpenAPI开通,请登录百炼控制台手动开通" || + error.message === + "当前MCP需要选择Ram角色,不支持通过OpenAPI开通,请登录百炼控制台手动开通" || + error.message.startsWith(marketSetupMessage) + ); + default: + return false; + } +} + +export function planServerLifecycle( + ctx: Context, + code: string, + operation: Operation, + { detail, requestId, requiresManualSetup: manual }: Awaited>, +): WriteStep | Completed { + const { type, server_status: status, is_onekey, console_url, billing } = detail; + const price = billing ? { billing } : {}; + const activating = operation === "activate"; + if ( + (activating && (status === "ACTIVATED" || status === "ACTIVATING")) || + (!activating && status === "INACTIVE") + ) { + const reason = + status === "ACTIVATING" + ? "ALREADY_ACTIVATING" + : activating + ? "ALREADY_ACTIVATED" + : "NOT_ACTIVATED"; + return { + result: { + code, + status: "noop", + reason, + ...price, + server_status: status, + request_id: requestId, + }, + }; + } + if ( + (type !== "OFFICIAL" && type !== "CUSTOMER") || + !status || + !["ACTIVATED", "ACTIVATING", "INACTIVE", "ACTIVATE_FAILED"].includes(status) + ) { + return failure( + code, + responseError( + ctx, + { + "en-US": "The MCP detail response did not confirm an actionable server type and status.", + "zh-CN": "MCP 详情未返回可操作的服务类型和状态。", + }, + requestId, + ), + { server_status: status, ...price }, + ); + } + if (activating && type === "OFFICIAL" && manual) { + return manualSetup( + code, + responseError( + ctx, + { + "en-US": "Complete this service's configuration in the Bailian console.", + "zh-CN": "请在百炼控制台完成此服务的配置。", + }, + requestId, + ), + console_url, + billing, + ); + } + const action = type === "OFFICIAL" ? operation : activating ? "enable" : "disable"; + return { code, type, action, server_status: status, is_onekey, console_url, ...price }; +} + +export async function prepareLifecycle(ctx: Context, servers: string, operation: Operation) { + const data: LifecyclePlan = []; + for (const code of serverCodes(servers)) { + try { + data.push( + planServerLifecycle(ctx, code, operation, await requestMcpServer(ctx, "GET", code)), + ); + } catch (error) { + data.push(failure(code, normalizeError(error, formatCommand(ctx.identity), ctx.localize))); + } + } + return { + data, + preview: { operation, targets: data.map((step) => ("result" in step ? step.result : step)) }, + risk: null, + notices: [], + }; +} + +export async function writeServer(ctx: Context, step: WriteStep): Promise { + const { code, action } = step; + try { + const { data, requestId } = await requestMcpData(ctx, { + method: "POST", + path: `${mcpServersPath(code)}/${action}`, + }); + const { server_status, server_status_text } = publicServer(ctx, data, requestId, code); + const fields = { + server_status, + server_status_text, + request_id: requestId, + ...(step.billing && { billing: step.billing }), + }; + if (server_status === "ACTIVATE_FAILED") { + const message = + data.activate_fail_reason ?? data.activateFailReason ?? server_status_text ?? server_status; + return failure( + code, + new BailianError(message, ExitCode.GENERAL, undefined, { api: { requestId } }), + { + ...fields, + error_code: server_status, + }, + ); + } + const activating = action === "activate" || action === "enable"; + if ( + activating + ? server_status === "ACTIVATED" || server_status === "ACTIVATING" + : server_status === "INACTIVE" + ) { + return { result: { code, status: "succeeded", ...fields } }; + } + return failure( + code, + responseError( + ctx, + { + "en-US": "The MCP response did not confirm the requested change.", + "zh-CN": "MCP 响应未确认请求的状态变更。", + }, + requestId, + ), + fields, + ); + } catch (error) { + const cause = normalizeError(error, formatCommand(ctx.identity), ctx.localize); + if (action === "activate" && requiresManualSetup(cause)) + return manualSetup(code, cause, step.console_url, step.billing); + if (cause.exitCode === ExitCode.TIMEOUT || cause.exitCode === ExitCode.NETWORK) { + const hint = ctx.localize({ + "en-US": "The write outcome is unknown. Check the server status before retrying.", + "zh-CN": "写入结果尚未确认,请先核对服务状态再决定是否重试。", + }); + return failure(code, new BailianError(cause.message, cause.exitCode, hint, { cause }), { + outcome_unknown: true, + }); + } + return failure(code, cause); + } +} + +export async function runLifecycle( + ctx: Context & Pick & { prepared?: LifecyclePlan }, + allowBrowser: boolean, +) { + if (!ctx.prepared) + throw new BailianError( + ctx.localize({ + "en-US": "Missing MCP operation plan.", + "zh-CN": "缺少 MCP 操作计划。", + }), + ); + const summary = { succeeded: 0, failed: 0, noop: 0 }; + const results: ItemResult[] = []; + let firstError: BailianError | undefined; + for (const step of ctx.prepared) { + const { result, error } = "action" in step ? await writeServer(ctx, step) : step; + if ( + result.detail && + allowBrowser && + process.stdin.isTTY && + process.stdout.isTTY && + ctx.settings.output === "text" + ) { + result.detail.browser_opened = await openInBrowser(result.detail.console_url).then( + () => true, + () => false, + ); + } + summary[result.status]++; + results.push(result); + firstError ??= error; + } + ctx.output.result({ summary, results }); + if (firstError) throw firstError; +} diff --git a/packages/commands/src/commands/mcp/server-management.ts b/packages/commands/src/commands/mcp/server-management.ts new file mode 100644 index 000000000..c82afa0cc --- /dev/null +++ b/packages/commands/src/commands/mcp/server-management.ts @@ -0,0 +1,212 @@ +import { + BailianError, + ExitCode, + type CommandContext, + type FlagsDef, + type LocalizedText, + type ParsedFlags, +} from "bailian-cli-core"; +import { MCP_TYPES, readMcpConfig } from "./server-config.ts"; +import { requestMcpServer, type McpRequestContext } from "./server-response.ts"; + +export const serverFlag = { + type: "string", + required: true, + valueHint: "", + description: { "en-US": "Custom MCP server code", "zh-CN": "自定义 MCP 服务编码" }, +} as const; + +export const editableFlags = { + name: { + type: "string", + valueHint: "", + description: { "en-US": "Server name", "zh-CN": "服务名称" }, + }, + description: { + type: "string", + valueHint: "", + description: { "en-US": "Server description", "zh-CN": "服务描述" }, + }, + mcpType: { + type: "string", + valueHint: "", + description: { "en-US": "MCP type (case-insensitive)", "zh-CN": "MCP 类型(不区分大小写)" }, + }, + mcpConfig: { + type: "string", + valueHint: "", + description: { + "en-US": "Complete MCP configuration as a JSON object or JSON file path", + "zh-CN": "完整 MCP 配置,接受 JSON 对象字符串或 JSON 文件路径", + }, + }, +} satisfies FlagsDef; + +export const deploymentNote = { + "en-US": + "Deploying a custom MCP server may incur charges, including Function Compute usage for STDIO.", + "zh-CN": "部署自定义 MCP 服务可能产生费用,STDIO 部署可能产生函数计算用量费用。", +} satisfies LocalizedText; + +type EditFlags = ParsedFlags; +type OperationContext = McpRequestContext & Pick; + +export function validateServer(server: string): LocalizedText | undefined { + if (!server.trim() || server === "." || server === "..") { + return { + "en-US": "--server requires a server code.", + "zh-CN": "--server 需要有效的服务编码。", + }; + } +} + +export function validateEdits(flags: EditFlags): LocalizedText | undefined { + for (const [name, value] of [ + ["--name", flags.name], + ["--description", flags.description], + ["--mcp-config", flags.mcpConfig], + ]) { + if (value !== undefined && !value.trim()) + return { "en-US": `${name} cannot be blank.`, "zh-CN": `${name} 不能为空。` }; + } + if ( + flags.mcpType !== undefined && + !MCP_TYPES.some((type) => type === flags.mcpType?.toUpperCase()) + ) { + return { + "en-US": "--mcp-type must be stdio, http, sse or openapi.", + "zh-CN": "--mcp-type 须为 stdio、http、sse 或 openapi。", + }; + } + if ((flags.mcpConfig === undefined) !== (flags.mcpType === undefined)) { + return { + "en-US": "Provide --mcp-type and --mcp-config together.", + "zh-CN": "--mcp-type 和 --mcp-config 须同时提供。", + }; + } + if ( + flags.name === undefined && + flags.description === undefined && + flags.mcpConfig === undefined + ) { + return { + "en-US": "Provide --name, --description, or both --mcp-type and --mcp-config.", + "zh-CN": "请提供 --name、--description,或同时提供 --mcp-type 和 --mcp-config。", + }; + } +} + +export async function buildServerBody(flags: EditFlags, localize: CommandContext["localize"]) { + const type = flags.mcpType?.toUpperCase(); + return { + ...(flags.name !== undefined && { server_name: flags.name }), + ...(flags.description !== undefined && { description: flags.description }), + ...(type && + flags.mcpConfig && { + mcp_type: type, + mcp_config: await readMcpConfig(flags.mcpConfig, type, localize), + }), + }; +} + +type ServerBody = Awaited>; +export interface ServerWrite { + method: "POST" | "DELETE"; + server?: string; + body?: ServerBody; + registeredAgents?: string[]; +} + +async function requestServer( + ctx: OperationContext, + method: "GET" | "POST" | "DELETE", + server?: string, + body?: ServerBody, +) { + const { detail, requestId, failReason } = await requestMcpServer(ctx, method, server, body); + return { + type: detail.type, + result: { + server_code: detail.server_code, + mcp_code: detail.server_code, + ...(detail.billing && { billing: detail.billing }), + server_name: detail.server_name ?? undefined, + server_status: detail.server_status ?? undefined, + server_status_text: detail.server_status_text ?? undefined, + activate_fail_reason: failReason ?? undefined, + request_id: requestId, + }, + }; +} + +export async function getCustomServer(ctx: OperationContext, server: string) { + const { type, result } = await requestServer(ctx, "GET", server); + if (type !== "CUSTOMER") { + throw new BailianError( + ctx.localize({ + "en-US": "This operation requires a custom MCP server (CUSTOMER).", + "zh-CN": "此操作仅适用于自定义 MCP 服务(CUSTOMER)。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId: result.request_id } }, + ); + } + return result; +} + +export async function executeServerWrite(ctx: OperationContext & { prepared?: ServerWrite }) { + if (!ctx.prepared) + throw new BailianError( + ctx.localize({ "en-US": "Missing MCP operation plan.", "zh-CN": "缺少 MCP 操作计划。" }), + ); + const { method, server, body, registeredAgents } = ctx.prepared; + let response; + try { + response = await requestServer(ctx, method, server, body); + } catch (error) { + if ( + error instanceof Error && + (error.name === "AbortError" || + error.name === "TimeoutError" || + (error instanceof BailianError && error.exitCode === ExitCode.TIMEOUT)) + ) { + throw new BailianError( + ctx.localize({ + "en-US": "The MCP write timed out. Its outcome is unknown.", + "zh-CN": "MCP 写请求已超时,操作结果尚未确认。", + }), + ExitCode.TIMEOUT, + ctx.localize({ + "en-US": "Check the server in the Bailian console before retrying.", + "zh-CN": "请先在百炼控制台核对服务状态,再决定是否重试。", + }), + { cause: error }, + ); + } + throw error; + } + const { result } = response; + ctx.output.result({ ...result, ...(registeredAgents && { connected_agents: registeredAgents }) }); + const status = result.server_status; + const api = { requestId: result.request_id }; + if (status === "ACTIVATE_FAILED") { + throw new BailianError( + result.activate_fail_reason ?? result.server_status_text ?? status, + ExitCode.GENERAL, + undefined, + { api }, + ); + } + if ((method === "DELETE" && status !== "DELETED") || (body?.mcp_config && !status)) { + throw new BailianError( + ctx.localize({ + "en-US": "The MCP response did not confirm the operation status.", + "zh-CN": "MCP 响应未确认操作状态。", + }), + ExitCode.GENERAL, + undefined, + { api }, + ); + } +} diff --git a/packages/commands/src/commands/mcp/server-response.ts b/packages/commands/src/commands/mcp/server-response.ts new file mode 100644 index 000000000..828efb2b3 --- /dev/null +++ b/packages/commands/src/commands/mcp/server-response.ts @@ -0,0 +1,166 @@ +import { + BailianError, + ExitCode, + mcpBaseUrl, + mcpServersPath, + type ClientRequestOpts, + type CommandContext, +} from "bailian-cli-core"; + +export type McpRequestContext = Pick & { + flags: { workspaceId?: string }; +}; + +// The gateway can omit pricing. Project only public, structured billing values. +function publicBilling(value: unknown) { + if (!value || typeof value !== "object" || Array.isArray(value)) return null; + const raw = value as Record; + function amount(input: unknown) { + return typeof input === "string" || (typeof input === "number" && Number.isFinite(input)) + ? input + : null; + } + const billing = { + mode: typeof raw.mode === "string" ? raw.mode : null, + unit_price: amount(raw.unit_price ?? raw.unitPrice), + free_quota: amount(raw.free_quota ?? raw.freeQuota), + currency: typeof raw.currency === "string" ? raw.currency : null, + unit: typeof raw.unit === "string" ? raw.unit : null, + }; + return Object.values(billing).some((field) => field !== null) ? billing : null; +} +export type ServerBilling = ReturnType; + +interface ServerMetadata { + billing?: unknown; + provider?: string | null; + icon?: string | null; + is_onekey?: boolean; + isOnekey?: boolean; + console_detail_url?: string; + consoleDetailURL?: string; +} + +export interface ServerDto { + billing?: unknown; + mcp_code?: string; + mcpCode?: string; + server_name?: string; + serverName?: string; + description?: string; + type?: string; + server_type?: string; + serverType?: string; + server_status?: string; + serverStatus?: string; + server_status_text?: string; + serverStatusText?: string; + dashscope_endpoint?: string; + dashscopeEndpoint?: string; + meta_info?: ServerMetadata; + metaInfo?: ServerMetadata; + activate_fail_reason?: string; + activateFailReason?: string; + requires_manual_setup?: boolean; + requiresManualSetup?: boolean; +} + +export async function requestMcpData(ctx: McpRequestContext, options: ClientRequestOpts) { + const path = ctx.client.url(options.path, () => { + const workspaceId = ctx.flags.workspaceId ?? ctx.settings.workspaceId; + if (workspaceId) return mcpBaseUrl(workspaceId); + throw new BailianError( + ctx.localize({ + "en-US": + "Set workspace_id or BAILIAN_WORKSPACE_ID, pass --workspace-id, or provide --base-url to access the MCP API.", + "zh-CN": + "访问 MCP API 需要配置 workspace_id、设置 BAILIAN_WORKSPACE_ID,或传入 --workspace-id、--base-url。", + }), + ExitCode.USAGE, + ); + }); + const response = await ctx.client.requestJson<{ + success: boolean; + data?: Data; + request_id?: string; + requestId?: string; + }>({ ...options, path }); + const requestId = response?.request_id ?? response?.requestId; + if (response?.success !== true || response.data == null) { + throw new BailianError( + ctx.localize({ + "en-US": "The MCP response is missing successful result data.", + "zh-CN": "MCP 响应缺少成功结果数据。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId } }, + ); + } + return { data: response.data, requestId }; +} + +// Whitelist public fields. The detail DTO also carries saved credentials in mcp_config. +export function publicServer( + ctx: McpRequestContext, + data: ServerDto, + requestId?: string, + expectedCode?: string, +) { + const code = data?.mcp_code ?? data?.mcpCode; + if ( + typeof code !== "string" || + !code.trim() || + (expectedCode !== undefined && code !== expectedCode) + ) { + throw new BailianError( + ctx.localize({ + "en-US": "The MCP response did not confirm the requested server.", + "zh-CN": "MCP 响应未确认目标服务。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId } }, + ); + } + const meta = data.meta_info ?? data.metaInfo; + const status = data.server_status ?? data.serverStatus ?? null; + return { + server_code: code, + server_name: data.server_name ?? data.serverName ?? null, + description: data.description ?? null, + type: data.type ?? null, + server_type: data.server_type ?? data.serverType ?? null, + server_status: status, + server_status_text: data.server_status_text ?? data.serverStatusText ?? null, + activated: status === "ACTIVATED", + provider: meta?.provider ?? null, + icon: meta?.icon ?? null, + is_onekey: meta?.is_onekey ?? meta?.isOnekey ?? null, + endpoint: data.dashscope_endpoint ?? data.dashscopeEndpoint ?? null, + console_url: meta?.console_detail_url ?? meta?.consoleDetailURL ?? null, + }; +} + +export async function requestMcpServer( + ctx: McpRequestContext, + method: "GET" | "POST" | "DELETE", + server?: string, + body?: unknown, +) { + const { data, requestId } = await requestMcpData(ctx, { + method, + path: mcpServersPath(server), + body, + }); + const detail = { + ...publicServer(ctx, data, requestId, server), + billing: publicBilling(data.billing ?? (data.meta_info ?? data.metaInfo)?.billing), + }; + return { + detail, + requestId, + failReason: data.activate_fail_reason ?? data.activateFailReason, + requiresManualSetup: (data.requires_manual_setup ?? data.requiresManualSetup) === true, + }; +} diff --git a/packages/commands/src/commands/mcp/tool-call.ts b/packages/commands/src/commands/mcp/tool-call.ts new file mode 100644 index 000000000..c499c48a6 --- /dev/null +++ b/packages/commands/src/commands/mcp/tool-call.ts @@ -0,0 +1,136 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { BailianError, defineCommand, ExitCode, mcpServersPath } from "bailian-cli-core"; +import { + argumentFlags, + toolArguments, + toolErrorMessage, + validateArguments, +} from "./call-arguments.ts"; +import { validateServer } from "./server-management.ts"; +import { requestMcpData } from "./server-response.ts"; +import { toolServerFlag } from "./tool-response.ts"; + +const flags = { + ...WORKSPACE_FLAG, + server: toolServerFlag, + tool: { + type: "string", + required: true, + valueHint: "", + description: { + "en-US": "Tool name returned by tool list or tool search", + "zh-CN": "tool list 或 tool search 返回的工具名", + }, + }, + ...argumentFlags, +} as const; +interface CallPlan { + server: string; + tool: string; + tool_params: Record; +} + +interface ContentBlock { + type?: string | null; + text?: string | null; +} +function isContentBlock(value: unknown): value is ContentBlock { + return ( + !!value && + typeof value === "object" && + !Array.isArray(value) && + (!("type" in value) || value.type == null || typeof value.type === "string") && + (!("text" in value) || value.text == null || typeof value.text === "string") + ); +} + +function readResult(data: unknown) { + if (!data || typeof data !== "object" || Array.isArray(data)) return; + if (!("is_error" in data) && !("isError" in data) && !("content" in data)) return; + const isError = "is_error" in data ? data.is_error : "isError" in data ? data.isError : null; + const content = "content" in data ? data.content : null; + if (isError != null && typeof isError !== "boolean") return; + if (content != null && (!Array.isArray(content) || !content.every(isContentBlock))) return; + return { is_error: isError ?? null, content: content ?? null }; +} + +export default defineCommand({ + auth: "apiKey", + description: { + "en-US": "Call a Bailian MCP tool via OpenAPI", + "zh-CN": "通过百炼 OpenAPI 调用 MCP 工具", + }, + flags, + usageArgs: + "--server --tool [--json '{...}'] [--arg k=v ...] [--query ] [--dry-run]", + exampleArgs: [ + "--server mcp-example --tool getOrder --arg orderId=A123 --dry-run", + "--workspace-id ws-example --server mcp-example --tool getOrder --arg orderId=A123", + ], + notes: [ + { + "en-US": + "Dry-run previews the arguments locally. Calling a tool may activate a OneKey service. A tool-reported error returns its content and exits with code 1.", + "zh-CN": + "--dry-run 在本地预览调用参数。调用工具可能触发 OneKey 服务开通。工具自身报错时输出返回内容,并以退出码 1 结束。", + }, + ], + validate(flags) { + if (!flags.tool.trim()) { + return { + "en-US": "--tool requires a nonblank tool name.", + "zh-CN": "--tool 需要非空白的工具名。", + }; + } + return validateServer(flags.server) ?? validateArguments(flags); + }, + async prepare(ctx) { + const { server, tool } = ctx.flags; + const params = toolArguments(ctx.flags, ctx.localize); + return { + data: { server, tool, tool_params: params }, + preview: { + action: "call_tool", + server, + tool, + ...(ctx.settings.dryRun ? { tool_params: params } : {}), + }, + risk: null, + notices: [], + }; + }, + async run(ctx) { + const plan = ctx.prepared; + if (!plan) + throw new BailianError( + ctx.localize({ + "en-US": "Missing MCP tool call plan.", + "zh-CN": "缺少 MCP 工具调用计划。", + }), + ); + const { data, requestId } = await requestMcpData(ctx, { + method: "POST", + path: `${mcpServersPath(plan.server)}/tools/call`, + body: { tool_name: plan.tool, tool_params: plan.tool_params }, + }); + const result = readResult(data); + if (!result) + throw new BailianError( + ctx.localize({ + "en-US": "The MCP tool call response is invalid.", + "zh-CN": "MCP 工具调用响应格式无效。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId } }, + ); + ctx.output.result(result); + if (result.is_error) + throw new BailianError( + toolErrorMessage(result.content, ctx.localize), + ExitCode.GENERAL, + undefined, + { api: { requestId } }, + ); + }, +}); diff --git a/packages/commands/src/commands/mcp/tool-list.ts b/packages/commands/src/commands/mcp/tool-list.ts new file mode 100644 index 000000000..ff12afd33 --- /dev/null +++ b/packages/commands/src/commands/mcp/tool-list.ts @@ -0,0 +1,33 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineCommand } from "bailian-cli-core"; +import { validateServer } from "./server-management.ts"; +import { listServerTools, toolServerFlag } from "./tool-response.ts"; + +export default defineCommand({ + auth: "apiKey", + description: { + "en-US": "List a Bailian MCP server's tools and input schemas via OpenAPI", + "zh-CN": "通过百炼 OpenAPI 列出指定 MCP 服务的工具及入参定义", + }, + flags: { + ...WORKSPACE_FLAG, + server: toolServerFlag, + }, + usageArgs: "--server [--dry-run]", + exampleArgs: ["--server mcp-example", "--server mcp-example --dry-run"], + notes: [ + { + "en-US": + "Fetching tools may activate a OneKey service. Dry-run previews the request locally.", + "zh-CN": "查询工具可能触发 OneKey 服务开通。--dry-run 仅在本地预览请求。", + }, + ], + validate: (flags) => validateServer(flags.server), + async prepare(ctx) { + const server = ctx.flags.server; + return { data: undefined, preview: { server, action: "list_tools" }, risk: null, notices: [] }; + }, + async run(ctx) { + ctx.output.result(await listServerTools(ctx, ctx.flags.server)); + }, +}); diff --git a/packages/commands/src/commands/mcp/tool-response.ts b/packages/commands/src/commands/mcp/tool-response.ts new file mode 100644 index 000000000..d91f950f5 --- /dev/null +++ b/packages/commands/src/commands/mcp/tool-response.ts @@ -0,0 +1,86 @@ +import { BailianError, ExitCode, mcpServersPath } from "bailian-cli-core"; +import { serverFlag } from "./server-management.ts"; +import { requestMcpData, type McpRequestContext } from "./server-response.ts"; + +export const toolServerFlag = { + ...serverFlag, + description: { + "en-US": "Official or custom MCP server code", + "zh-CN": "官方或自定义 MCP 服务编码", + }, +}; + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function invalidResponse(ctx: McpRequestContext, requestId?: string) { + return new BailianError( + ctx.localize({ + "en-US": "The MCP tools response is invalid.", + "zh-CN": "MCP 工具列表响应格式无效。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId } }, + ); +} + +function inputSchema(value: unknown, ctx: McpRequestContext, requestId?: string) { + if (value == null) return null; + if (!isRecord(value)) throw invalidResponse(ctx, requestId); + // Only the DTO's own keys change casing. Properties and required are downstream schema data. + return { + type: value.type, + properties: value.properties, + required: value.required, + additional_properties: value.additional_properties ?? value.additionalProperties ?? null, + }; +} + +export async function listServerTools(ctx: McpRequestContext, server: string) { + const { data, requestId } = await requestMcpData(ctx, { + method: "GET", + path: `${mcpServersPath(server)}/tools`, + }); + if (!Array.isArray(data)) throw invalidResponse(ctx, requestId); + return data.map((tool: unknown) => { + if (!isRecord(tool)) throw invalidResponse(ctx, requestId); + return { + name: tool.name ?? null, + description: tool.description ?? null, + input_schema: inputSchema(tool.input_schema ?? tool.inputSchema, ctx, requestId), + }; + }); +} + +export async function searchTools(ctx: McpRequestContext, query: string, limit: number) { + const params = new URLSearchParams({ query, topN: String(limit) }); + const { data, requestId } = await requestMcpData(ctx, { + method: "GET", + path: `${mcpServersPath()}/tools/recommend?${params.toString()}`, + }); + if (!Array.isArray(data)) throw invalidResponse(ctx, requestId); + return data.slice(0, limit).map((tool: unknown) => { + if (!isRecord(tool)) throw invalidResponse(ctx, requestId); + const serverCode = tool.mcp_code ?? tool.mcpCode ?? tool.server_code ?? tool.serverCode; + const toolName = tool.tool_name ?? tool.toolName; + if ( + typeof serverCode !== "string" || + !serverCode.trim() || + typeof toolName !== "string" || + !toolName.trim() + ) + throw invalidResponse(ctx, requestId); + return { + server_code: serverCode, + tool_name: toolName, + tool_description: tool.tool_description ?? tool.toolDescription ?? null, + tool_input_schema: inputSchema( + tool.tool_input_schema ?? tool.toolInputSchema, + ctx, + requestId, + ), + }; + }); +} diff --git a/packages/commands/src/commands/mcp/tool-search.ts b/packages/commands/src/commands/mcp/tool-search.ts new file mode 100644 index 000000000..86968f462 --- /dev/null +++ b/packages/commands/src/commands/mcp/tool-search.ts @@ -0,0 +1,73 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineCommand } from "bailian-cli-core"; +import { searchTools } from "./tool-response.ts"; + +const defaultLimit = 10; + +export default defineCommand({ + auth: "apiKey", + description: { + "en-US": "Find recommended MCP tools for a natural-language query", + "zh-CN": "根据自然语言需求查找推荐的 MCP 工具", + }, + flags: { + ...WORKSPACE_FLAG, + query: { + type: "string", + required: true, + valueHint: "", + description: { + "en-US": "Describe what you want the tool to do", + "zh-CN": "描述希望工具完成的任务", + }, + }, + limit: { + type: "number", + valueHint: "", + description: { + "en-US": "Maximum results to show (default 10)", + "zh-CN": "最多展示的工具数(默认 10)", + }, + }, + }, + usageArgs: "--query [--limit ] [--dry-run]", + exampleArgs: [ + { "en-US": '--query "look up an order" --dry-run', "zh-CN": '--query "查询订单" --dry-run' }, + { + "en-US": '--query "look up an order" --limit 5', + "zh-CN": '--query "查询订单" --limit 5', + }, + ], + notes: [ + { + "en-US": "Requesting recommendations may activate a OneKey service and place an order.", + "zh-CN": "请求工具推荐可能触发 OneKey 服务开通并下单。", + }, + ], + validate({ query, limit = defaultLimit }) { + if (!query.trim()) { + return { "en-US": "--query must contain text.", "zh-CN": "--query 须包含非空白文本。" }; + } + if (!Number.isInteger(limit) || limit < 1 || limit > 2_147_483_647) { + return { + "en-US": "--limit must be an integer from 1 to 2147483647.", + "zh-CN": "--limit 须为 1~2147483647 的整数。", + }; + } + }, + async prepare(ctx) { + const query = ctx.flags.query.trim(); + const limit = ctx.flags.limit ?? defaultLimit; + return { + data: undefined, + preview: { action: "recommend_tools", query, limit }, + risk: null, + notices: [], + }; + }, + async run(ctx) { + ctx.output.result( + await searchTools(ctx, ctx.flags.query.trim(), ctx.flags.limit ?? defaultLimit), + ); + }, +}); diff --git a/packages/commands/src/commands/mcp/tools.ts b/packages/commands/src/commands/mcp/tools.ts index d58a856ba..434fe9789 100644 --- a/packages/commands/src/commands/mcp/tools.ts +++ b/packages/commands/src/commands/mcp/tools.ts @@ -1,10 +1,12 @@ -import { defineCommand, bailianMcpPath } from "bailian-cli-core"; +import { BailianError, defineCommand, bailianMcpPath, type McpTool } from "bailian-cli-core"; import { rethrowWithMcpActivateHint } from "./activate-hint.ts"; +import { validateServer } from "./server-management.ts"; +import { endpointFlag, validateEndpoint } from "./protocol-endpoint.ts"; export default defineCommand({ description: { - "en-US": "List tools exposed by an MCP server (tools/list)", - "zh-CN": "列出 MCP 服务器提供的工具(tools/list)", + "en-US": "Open an MCP session and list the server's tools (tools/list)", + "zh-CN": "建立 MCP 会话并列出服务提供的工具(tools/list)", }, auth: "apiKey", usageArgs: "--server [--url ]", @@ -18,30 +20,23 @@ export default defineCommand({ }, required: true, }, - url: { - type: "string", - valueHint: "", - description: { - "en-US": - "Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL.", - "zh-CN": - "覆盖 MCP Endpoint URL(非百炼)。先尝试 Streamable HTTP,再在同一 URL 上回退到传统 SSE。", - }, - }, + url: endpointFlag, }, exampleArgs: [ "--server market-cmapi00073529", "--server market-cmapi00073529 --output json", "--server my-server --url https://example.com/mcp", ], + validate({ server, url }) { + return validateServer(server) ?? validateEndpoint(url); + }, async run(ctx) { const { settings, flags } = ctx; const code = flags.server; - const previewUrl = flags.url || ctx.client.url(bailianMcpPath(code)); - if (settings.dryRun) { - ctx.output.result({ server: code, url: previewUrl, action: "tools/list" }); + const url = flags.url || ctx.client.baseUrl + bailianMcpPath(code); + ctx.output.result({ server: code, url, action: "tools/list" }); return; } @@ -49,7 +44,24 @@ export default defineCommand({ try { const connected = await ctx.client.connectBailianMcp(code, flags.url); client = connected.client; - const tools = await connected.client.listTools(); + const tools: McpTool[] = []; + const seenCursors = new Set(); + let cursor: string | undefined; + for (;;) { + const page = await connected.client.listToolsPage(cursor); + for (const tool of page.tools) tools.push(tool); + cursor = page.nextCursor; + if (cursor === undefined) break; + if (seenCursors.has(cursor)) { + throw new BailianError( + ctx.localize({ + "en-US": "The MCP server returned a repeated tools/list cursor.", + "zh-CN": "MCP 服务返回了重复的 tools/list 分页游标。", + }), + ); + } + seenCursors.add(cursor); + } ctx.output.result({ server: code, url: connected.url, tools }); } catch (error) { if (!flags.url) { diff --git a/packages/commands/src/commands/mcp/update.ts b/packages/commands/src/commands/mcp/update.ts new file mode 100644 index 000000000..6c8fbf8a3 --- /dev/null +++ b/packages/commands/src/commands/mcp/update.ts @@ -0,0 +1,84 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { BailianError, defineCommand, ExitCode } from "bailian-cli-core"; +import { + buildServerBody, + deploymentNote, + editableFlags, + executeServerWrite, + getCustomServer, + serverFlag, + validateEdits, + validateServer, + type ServerWrite, +} from "./server-management.ts"; + +const flags = { + ...WORKSPACE_FLAG, + server: serverFlag, + ...editableFlags, +}; +export default defineCommand({ + description: { + "en-US": "Update a custom MCP server's metadata or replace its configuration", + "zh-CN": "更新自定义 MCP 服务的基本信息或替换完整配置", + }, + auth: "apiKey", + flags, + usageArgs: + "--server [--name ] [--description ] [--mcp-type --mcp-config ] [flags]", + exampleArgs: [ + "--server mcp-example --name weather-v2", + "--server mcp-example --mcp-type sse --mcp-config ./weather.json --dry-run", + ], + notes: [ + deploymentNote, + { + "en-US": + "Name and description changes take effect without redeployment. Stop the instance before replacing its configuration and redeploying.", + "zh-CN": "单改名称或描述可直接生效。替换完整配置前须先停用实例,再重新部署。", + }, + ], + validate(values) { + return validateServer(values.server) ?? validateEdits(values); + }, + async prepare(ctx) { + const body = await buildServerBody(ctx.flags, ctx.localize); + const detail = await getCustomServer(ctx, ctx.flags.server); + const redeploy = body.mcp_config !== undefined; + if ( + redeploy && + (!detail.server_status || ["ACTIVATED", "ACTIVATING"].includes(detail.server_status)) + ) { + throw new BailianError( + ctx.localize({ + "en-US": + "The instance must be stopped before replacing the MCP configuration. Use mcp deactivate --server to stop it.", + "zh-CN": "替换 MCP 配置前须先停用实例。可用 mcp deactivate --server 停用。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId: detail.request_id } }, + ); + } + return { + data: { method: "POST", server: ctx.flags.server, body }, + preview: { + action: "update", + server_code: detail.mcp_code, + server_name: detail.server_name, + server_status: detail.server_status, + ...(detail.billing && { billing: detail.billing }), + changes: { + server_name: body.server_name, + description: body.description, + mcp_type: body.mcp_type, + }, + replace_config: redeploy, + deploy: redeploy, + }, + risk: null, + notices: [], + }; + }, + run: executeServerWrite, +}); diff --git a/packages/commands/src/commands/shared/state-lock.ts b/packages/commands/src/commands/shared/state-lock.ts new file mode 100644 index 000000000..0e80b43ff --- /dev/null +++ b/packages/commands/src/commands/shared/state-lock.ts @@ -0,0 +1,49 @@ +import { randomUUID } from "node:crypto"; +import { mkdir, open, readFile, rm } from "node:fs/promises"; +import { hostname } from "node:os"; +import { dirname } from "node:path"; +import { BailianError, ExitCode, type CommandContext } from "bailian-cli-core"; + +/** Never automatically steal a lock: an old PID may belong to a different host. */ +export async function withStateLock( + path: string, + localize: CommandContext["localize"], + action: () => Result | Promise, +): Promise { + const lockPath = `${path}.lock`; + const nonce = randomUUID(); + await mkdir(dirname(path), { recursive: true }); + const handle = await open(lockPath, "wx", 0o600).catch((error: unknown) => { + if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error; + throw new BailianError( + localize({ + "en-US": `State is locked: ${lockPath}. Verify that no other operation is running before removing the lock.`, + "zh-CN": `状态文件已锁定:${lockPath}。请确认没有其他操作正在运行,再移除锁文件。`, + }), + ExitCode.GENERAL, + ); + }); + try { + try { + await handle.writeFile( + JSON.stringify({ nonce, pid: process.pid, hostname: hostname() }), + "utf8", + ); + await handle.sync(); + } finally { + await handle.close(); + } + return await action(); + } finally { + // A missing, corrupt, or replaced lock is not ours to remove. Cleanup must + // not replace a service error with a secondary filesystem error. + try { + const current: unknown = JSON.parse(await readFile(lockPath, "utf8")); + if (current && typeof current === "object" && "nonce" in current && current.nonce === nonce) { + await rm(lockPath); + } + } catch { + // Retaining an uncertain lock is safer than allowing concurrent writes. + } + } +} diff --git a/packages/commands/src/commands/skill/add.ts b/packages/commands/src/commands/skill/add.ts index d8106cf4e..e4d94ab68 100644 --- a/packages/commands/src/commands/skill/add.ts +++ b/packages/commands/src/commands/skill/add.ts @@ -1,168 +1,145 @@ -import { - formatCommand, - BailianError, - ExitCode, - defineCommand, - detectInstalledAgents, - fetchSkillsIndex, - getSkillRegistryBaseUrl, - installSkillWithFanout, - parseSkillNames, - readSkillLock, - runWithConcurrency, - writeSkillLock, -} from "bailian-cli-core"; -import { formatTable } from "bailian-cli-runtime"; -import { planFanoutLinks, summarizeAgents } from "./dry-run-plan.ts"; +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineSkillCommand } from "./update-check.ts"; +import { BailianError, type CommandContext } from "bailian-cli-core"; +import { runSkillLifecycle, useTargetRecords, withSkillMutation } from "./lifecycle.ts"; +import { runRegistryLifecycle } from "./registry-lifecycle.ts"; +import { SkillAddPackages } from "./mcp-dependencies.ts"; +import { selectorFlags, sourceFlag, targetFlags, validateSelection } from "./targets.ts"; -interface AddOutcome { - name: string; - status: "installed" | "failed"; - publishedAt?: string; - agents?: string[]; - reason?: string; -} +const flags = { + ...WORKSPACE_FLAG, + source: sourceFlag, + ...targetFlags, + skillVersion: { + type: "string", + valueHint: "", + description: { "en-US": "Install and pin this exact version", "zh-CN": "安装并固定指定版本" }, + }, + withMcp: { + type: "boolean", + implicitValue: true, + valueHint: "", + description: { + "en-US": + "Read serverCode entries from mcp-config.json beside SKILL.md and activate inactive dependencies (default true).", + "zh-CN": + "读取 SKILL.md 同目录下 mcp-config.json 声明的 serverCode 并开通未启用的依赖(默认 true)。", + }, + }, + all: { + type: "switch", + description: { + "en-US": "Install all skills from the public OSS registry", + "zh-CN": "安装公开 OSS Registry 中的全部 Skill", + }, + }, + ...selectorFlags, +} as const; -/** Max number of skills downloading/installing at the same time. */ -const INSTALL_CONCURRENCY = 3; +type AddContext = Pick< + CommandContext, + "client" | "settings" | "output" | "localize" | "identity" | "flags" +>; +type AddReport = Awaited>; +async function install(ctx: AddContext, staged?: SkillAddPackages) { + return useTargetRecords(ctx.flags) + ? runSkillLifecycle("add", ctx, ctx.flags, staged) + : runRegistryLifecycle("add", ctx, ctx.flags, staged); +} +function successfulSkills(report: AddReport) { + return new Set( + report.data.results.filter((row) => row.status !== "failed").map((row) => row.code), + ); +} +async function dependencyReport( + ctx: AddContext, + report: AddReport, + staged: SkillAddPackages | undefined, + preview: boolean, +) { + return staged + ? staged.report(ctx, successfulSkills(report), preview) + : { fields: { mcp_dep_results: [], mcp_dependency_status: "disabled" }, firstError: undefined }; +} +function outputReport( + ctx: AddContext, + report: AddReport, + deps: Awaited>, +) { + const text = + "text" in report && !deps.fields.mcp_dep_results.length ? { text: report.text } : undefined; + ctx.output.result( + { + ...report.data, + dry_run: ctx.settings.dryRun, + ...deps.fields, + }, + text, + ); + if (report.firstError || deps.firstError) throw report.firstError ?? deps.firstError; +} -export default defineCommand({ +export default defineSkillCommand({ description: { "en-US": "Install skills from the Bailian skill registry into local agents", "zh-CN": "将百炼 Skill Registry 中的 Skill 安装到本地 Agent", }, - auth: "none", + auth: "apiKey", + requiresApiKey: (values) => values.code !== undefined || (values.withMcp !== false && "optional"), defaultOutput: "json", - usageArgs: "--all | --name ", - flags: { - all: { - type: "switch", - description: { - "en-US": "Install all skills from the registry", - "zh-CN": "安装 Registry 中的全部 Skill", - }, - }, - name: { - type: "string", - valueHint: "", - description: { - "en-US": "Comma-separated skill names to install", - "zh-CN": "要安装的 Skill 名称,以逗号分隔", - }, + usageArgs: + "(--name | --code | --all) [--agent ] [--scope user|project] [--skill-version ] [--with-mcp ]", + flags, + notes: [ + { + "en-US": + "Use --dry-run to inspect the selected package versions and preview MCP activation. Installation activates inactive dependencies and may incur charges. Public OSS packages install without a key. Checking their declared MCP services requires a Bailian API key. Use --with-mcp false to install only.", + "zh-CN": + "用 --dry-run 查看所选版本声明的依赖及开通计划。安装时会开通未启用的依赖,可能产生费用。公开 OSS 包可免鉴权安装,检查其 MCP 服务需要百炼 API Key。只安装 Skill 可用 --with-mcp false。", }, - }, + ], validate(flags) { - if (flags.all && flags.name) return "Use either --all or --name, not both"; - if (!flags.all && !flags.name) - return "Specify --all to install everything or --name for specific skills"; - return undefined; + return validateSelection(flags, "add"); }, - exampleArgs: ["--all", "--name spark-video,bailian-model-recommend"], - async run(ctx) { - const index = await fetchSkillsIndex(); - const remoteNames = Object.keys(index.skills); - const parsed = ctx.flags.all ? "all" : parseSkillNames(ctx.flags.name, false); - const names = parsed === "all" ? remoteNames : parsed; - const agents = detectInstalledAgents(); - - if (ctx.settings.dryRun) { - const skills = names.map((name) => { - const entry = index.skills[name]; - if (!entry) { - return { - name, - status: "failed" as const, - reason: "skill not found in registry", - }; - } - return { - name, - status: "install" as const, - publishedAt: entry.publishedAt, - links: planFanoutLinks(name, agents), - }; - }); + exampleArgs: [ + "--all", + "--name spark-video,bailian-model-recommend", + "--code skill_example --agent cursor --scope project --skill-version 1.0 --dry-run", + ], - ctx.output.result({ - action: "skill.add", - registry: getSkillRegistryBaseUrl(), - agents: summarizeAgents(agents), - skills, - }); - - const failed = skills.filter((skill) => skill.status === "failed"); - if (failed.length > 0) { - throw new BailianError( - `${failed.length}/${skills.length} skill(s) failed to install`, - ExitCode.GENERAL, - `Check the reason for failed skills in the output; network failures can be retried with ${formatCommand(ctx.identity, "skill add")}`, - ); - } - return; + async prepare(ctx) { + const staged = ctx.flags.withMcp === false ? undefined : new SkillAddPackages(ctx.localize); + try { + if (!staged && !ctx.settings.dryRun) + return { data: undefined, preview: {}, risk: null, notices: [] }; + const report = await install({ ...ctx, settings: { ...ctx.settings, dryRun: true } }, staged); + const skills = successfulSkills(report); + await staged?.plan(ctx, skills); + const deps = await dependencyReport(ctx, report, staged, true); + if (!ctx.settings.dryRun && !skills.size && report.firstError) + outputReport(ctx, report, deps); + return { + data: staged, + preview: { ...report.data, ...deps.fields }, + renderDryRun: () => outputReport(ctx, report, deps), + risk: null, + notices: [], + dispose: () => staged?.dispose(), + }; + } catch (error) { + staged?.dispose(); + throw error; } - - const lock = readSkillLock(); - - // collect-then-throw: a single skill failure only affects itself; successful ones are written to disk and lock as usual. - // Skills install concurrently (bounded by INSTALL_CONCURRENCY) — each writes to a disjoint canonical dir, unique tmpDir, and distinct lock key. - const tasks = names.map((name) => async (): Promise => { - const entry = index.skills[name]; - if (!entry) { - return { name, status: "failed", reason: "skill not found in registry" }; - } - try { - const record = await installSkillWithFanout( - name, - entry, - agents, - lock.skills[name]?.links ?? [], - ); - lock.skills[name] = record.lockEntry; - return { - name, - status: "installed", - publishedAt: entry.publishedAt, - agents: record.linkedAgents, - }; - } catch (err) { - return { - name, - status: "failed", - reason: err instanceof Error ? err.message : String(err), - }; - } - }); - const results = await runWithConcurrency(tasks, INSTALL_CONCURRENCY); - writeSkillLock(lock); - - const payload = { - registry: getSkillRegistryBaseUrl(), - agents: agents.map((agent) => agent.id), - skills: results, - }; - const rows = results.map((result) => [ - result.name, - result.status, - result.publishedAt ? result.publishedAt.slice(0, 10) : "-", - result.status === "installed" ? result.agents?.join(", ") || "-" : (result.reason ?? "-"), - ]); - ctx.output.result(payload, { - text: - results.length === 0 - ? ctx.localize({ - "en-US": "Skill registry is empty; no skills to install.", - "zh-CN": "Skill Registry 为空,没有可安装的 Skill。", - }) - : formatTable(["NAME", "STATUS", "PUBLISHED", "AGENTS / REASON"], rows).join("\n"), - }); - - const failed = results.filter((result) => result.status === "failed"); - if (failed.length > 0) { + }, + async run(ctx) { + if (ctx.flags.withMcp !== false && !ctx.prepared) throw new BailianError( - `${failed.length}/${results.length} skill(s) failed to install`, - ExitCode.GENERAL, - `Check the reason for failed skills in the output; network failures can be retried with ${formatCommand(ctx.identity, "skill add")}`, + ctx.localize({ + "en-US": "Missing Skill dependency plan.", + "zh-CN": "缺少 Skill 依赖计划。", + }), ); - } + const report = await withSkillMutation(ctx, () => install(ctx, ctx.prepared)); + outputReport(ctx, report, await dependencyReport(ctx, report, ctx.prepared, false)); }, }); diff --git a/packages/commands/src/commands/skill/catalog.ts b/packages/commands/src/commands/skill/catalog.ts new file mode 100644 index 000000000..d6f0c11df --- /dev/null +++ b/packages/commands/src/commands/skill/catalog.ts @@ -0,0 +1,59 @@ +import { observeCloudSkill } from "./update-check.ts"; +import { BailianError, ExitCode, type CommandContext } from "bailian-cli-core"; + +type CatalogContext = Pick; + +export interface CatalogSkill { + id: string; + display_name: string; + display_description: string; + source: "official" | "customer"; + latest_version: string | null; + status: string; + created_at: string; + updated_at: string; +} + +export function invalidCatalogResponse(ctx: CatalogContext, requestId?: string): never { + throw new BailianError( + ctx.localize({ + "en-US": "The Skill API returned an invalid result.", + "zh-CN": "Skill 接口返回的结果格式不正确。", + }), + ExitCode.GENERAL, + undefined, + { api: { requestId } }, + ); +} + +export async function requestCatalog(ctx: CatalogContext, path: string) { + const response = await ctx.client.requestJson<{ + success: boolean; + data: Data; + request_id?: string; + }>({ method: "GET", path }); + if (response?.success !== true || response.data == null) + invalidCatalogResponse(ctx, response?.request_id); + return response; +} + +export function describeSkill(ctx: CatalogContext, skill: CatalogSkill, requestId?: string) { + if ( + typeof skill?.id !== "string" || + !skill.id.trim() || + (skill.source !== "official" && skill.source !== "customer") + ) + invalidCatalogResponse(ctx, requestId); + observeCloudSkill(ctx, skill); + return { + skill_code: skill.id, + skill_name: skill.display_name, + description: skill.display_description, + type: skill.source === "official" ? "official" : "private", + source: skill.source, + status: skill.status, + latest_version: skill.latest_version ?? null, + created_at: skill.created_at, + updated_at: skill.updated_at, + }; +} diff --git a/packages/commands/src/commands/skill/get.ts b/packages/commands/src/commands/skill/get.ts new file mode 100644 index 000000000..45ca791ab --- /dev/null +++ b/packages/commands/src/commands/skill/get.ts @@ -0,0 +1,163 @@ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + BailianError, + fetchSkillsIndex, + getSkillRegistryBaseUrl, + readCatalogInstalls, + skillsPath, + type CommandContext, +} from "bailian-cli-core"; +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { + describeSkill, + invalidCatalogResponse, + requestCatalog, + type CatalogSkill, +} from "./catalog.ts"; +import { readMcpDependencies } from "./mcp-dependencies.ts"; +import { unpackRevision, type Revision } from "./packages.ts"; +import { needsCloud, validName } from "./targets.ts"; +import { defineSkillCommand, observeRegistry } from "./update-check.ts"; + +type Context = Pick; + +async function getRegistrySkill(ctx: Context, name: string) { + const index = observeRegistry(ctx, await fetchSkillsIndex()); + const entry = Object.hasOwn(index.skills, name) && index.skills[name]; + if (!entry) { + throw new BailianError( + ctx.localize({ + "en-US": `Skill ${name} was not found in the OSS registry.`, + "zh-CN": `OSS Registry 中未找到 Skill ${name}。`, + }), + ); + } + const version = entry.version ?? null; + const local = readCatalogInstalls(getSkillRegistryBaseUrl(), "oss"); + return { + details: { + skill_name: name, + skill_code: entry.remoteId ?? null, + description: entry.description ?? null, + source: "oss", + latest_version: version, + published_at: entry.publishedAt ?? null, + content_hash: entry.contentHash ?? null, + ...local.inspect(entry.remoteId ?? name, version, name, entry.contentHash), + }, + revision: { source: "oss", id: name, version: entry.version, oss: entry } satisfies Revision, + }; +} + +async function getCloudSkill(ctx: Context, code: string, inspectPackage: boolean) { + const path = skillsPath(code); + const { data, request_id } = await requestCatalog(ctx, path); + if (data.id !== code) invalidCatalogResponse(ctx, request_id); + const skill = describeSkill(ctx, data, request_id); + const local = readCatalogInstalls(ctx.client.baseUrl, "openapi"); + let revision: Revision | undefined; + if (inspectPackage && skill.latest_version !== null) { + if (!validName(skill.latest_version)) invalidCatalogResponse(ctx, request_id); + revision = { + source: "cloud", + id: code, + version: skill.latest_version, + versionPath: `${path}/versions/${encodeURIComponent(skill.latest_version)}`, + }; + } + return { details: { ...skill, ...local.inspect(code, skill.latest_version) }, revision }; +} + +export default defineSkillCommand({ + localDryRun: true, + description: { + "en-US": "Get skill details, installed versions and paths from the public registry or OpenAPI", + "zh-CN": "查看 OSS Registry 或 OpenAPI 的 Skill 详情、已安装版本和路径", + }, + auth: "apiKey", + requiresApiKey: needsCloud, + defaultOutput: "json", + usageArgs: "(--name | --code ) [--with-mcp ]", + flags: { + ...WORKSPACE_FLAG, + withMcp: { + type: "boolean", + implicitValue: true, + valueHint: "", + description: { + "en-US": + "Read declared MCP server codes from the latest version package (default true, null if the manifest is absent)", + "zh-CN": "从最新版本的包中读取声明的 MCP 服务编码,默认读取,缺少声明文件时返回 null", + }, + }, + name: { + type: "string", + valueHint: "", + description: { + "en-US": "Skill name in the public OSS registry", + "zh-CN": "公开 OSS Registry 中的 Skill 名称", + }, + }, + code: { + type: "string", + valueHint: "", + description: { + "en-US": "OpenAPI skill_code returned by skill search", + "zh-CN": "skill search 返回的 OpenAPI skill_code", + }, + }, + }, + exampleArgs: ["--name bailian-cli", "--code skill_example --with-mcp false"], + validate({ name, code }) { + if ((name === undefined) === (code === undefined)) + return { + "en-US": "Specify exactly one of --name and --code.", + "zh-CN": "--name 和 --code 请选择一个。", + }; + if (name !== undefined && !validName(name.trim())) + return { + "en-US": "--name requires a valid OSS skill name.", + "zh-CN": "--name 需要有效的 OSS Skill 名称。", + }; + if (code !== undefined && (!code.trim() || [".", ".."].includes(code.trim()))) + return { + "en-US": "--code requires a valid OpenAPI skill code.", + "zh-CN": "--code 需要有效的 OpenAPI Skill 编码。", + }; + }, + async run(ctx) { + const name = ctx.flags.name?.trim(); + const code = ctx.flags.code?.trim(); + const inspectPackage = ctx.flags.withMcp !== false; + if (ctx.settings.dryRun) { + ctx.output.result({ + method: "GET", + ...(name + ? { url: `${getSkillRegistryBaseUrl()}/index.json`, name } + : { path: skillsPath(code) }), + ...(inspectPackage && { inspect_latest_package_file: "mcp-config.json" }), + }); + return; + } + const { details, revision } = name + ? await getRegistrySkill(ctx, name) + : await getCloudSkill(ctx, code!, inspectPackage); + if (!inspectPackage) return ctx.output.result(details); + let dependencies: string[] | undefined; + if (revision) { + const scratch = mkdtempSync(join(tmpdir(), "bl-skill-get-")); + try { + const pkg = await unpackRevision(ctx, revision, scratch); + dependencies = readMcpDependencies(pkg.root, ctx.localize); + } catch (error) { + ctx.output.result({ ...details, depends_on_mcp: null }); + throw error; + } finally { + rmSync(scratch, { recursive: true, force: true }); + } + } + ctx.output.result({ ...details, depends_on_mcp: dependencies ?? null }); + }, +}); diff --git a/packages/commands/src/commands/skill/init.ts b/packages/commands/src/commands/skill/init.ts index 1236b01a8..15c43e10e 100644 --- a/packages/commands/src/commands/skill/init.ts +++ b/packages/commands/src/commands/skill/init.ts @@ -1,9 +1,9 @@ +import { defineSkillCommand, observeRegistry } from "./update-check.ts"; import { commandRef, formatCommand, BailianError, ExitCode, - defineCommand, detectInstalledAgents, fetchSkillsIndex, installSkillWithFanout, @@ -11,7 +11,9 @@ import { runWithConcurrency, writeSkillLock, } from "bailian-cli-core"; -import { planFanoutLinks, summarizeAgents } from "./dry-run-plan.ts"; +import { join } from "node:path"; +import { canonicalSkillPath, planFanoutLinks, summarizeAgents } from "./dry-run-plan.ts"; +import { withSkillMutation } from "./lifecycle.ts"; /** Prefix used to identify first-party Bailian skills in the registry. */ const BAILIAN_PREFIX = "bailian-"; @@ -32,7 +34,8 @@ interface InitOutcome { reason?: string; } -export default defineCommand({ +export default defineSkillCommand({ + updateCheck: "oss", description: { "en-US": "Install all bailian-* skills (one-shot bootstrap for new environments)", "zh-CN": "安装全部 bailian-* Skill(用于新环境的一次性初始化)", @@ -48,108 +51,117 @@ export default defineCommand({ "zh-CN": "获取 Registry 索引并安装名称以 `bailian-` 开头的所有 Skill。", }, { - "en-US": `Equivalent to: \`${commandRef("skill add --all")}\` (filtered to \`bailian-*\` skills).`, - "zh-CN": `等价于:\`${commandRef("skill add --all")}\`(筛选为 \`bailian-*\` Skill)。`, + "en-US": `Installs the \`bailian-*\` subset of \`${commandRef("skill add --all")}\`.`, + "zh-CN": `安装 \`${commandRef("skill add --all")}\` 中名称以 \`bailian-\` 开头的 Skill。`, }, ], async run(ctx) { - const index = await fetchSkillsIndex(); + return withSkillMutation(ctx, async () => { + const index = observeRegistry(ctx, await fetchSkillsIndex()); - // Discover all bailian-* skills from the live registry index - const names = Object.keys(index.skills).filter((name) => name.startsWith(BAILIAN_PREFIX)); - const agents = detectInstalledAgents(); + // Discover all bailian-* skills from the live registry index + const names = Object.keys(index.skills).filter((name) => name.startsWith(BAILIAN_PREFIX)); + const agents = detectInstalledAgents(); - if (ctx.settings.dryRun) { - ctx.output.result({ - action: "skill.init", - skills: names.map((name) => ({ - name, - links: planFanoutLinks(name, agents), - })), - agents: summarizeAgents(agents), - }); - return; - } + if (ctx.settings.dryRun) { + ctx.output.result({ + action: "skill.init", + skills: names.map((name) => ({ + name, + links: planFanoutLinks(name, agents), + })), + agents: summarizeAgents(agents), + }); + return; + } - const lock = readSkillLock(); + const lock = readSkillLock(); + const scopedPaths = new Set(Object.values(lock.skills).map((entry) => entry.installedPath)); - const tasks = names.map((name) => async (): Promise => { - const entry = index.skills[name]; - try { - const record = await installSkillWithFanout( - name, - entry, - agents, - lock.skills[name]?.links ?? [], - ); - lock.skills[name] = record.lockEntry; - return { name, status: STATUS.success }; - } catch (err) { - return { - name, - status: STATUS.failed, - reason: err instanceof Error ? err.message : String(err), - }; - } - }); - const results = await runWithConcurrency(tasks, INIT_CONCURRENCY); - writeSkillLock(lock); + const tasks = names.map((name) => async (): Promise => { + const entry = index.skills[name]; + try { + const paths = [ + canonicalSkillPath(name), + ...agents.map((agent) => join(agent.skillsDir, name)), + ]; + const conflict = paths.find((path) => scopedPaths.has(path)); + if (conflict) throw new BailianError(`SOURCE_CONFLICT: ${conflict}`); + const record = await installSkillWithFanout( + name, + entry, + agents, + lock.skills[name]?.links ?? [], + ); + lock.skills[name] = record.lockEntry; + return { name, status: STATUS.success }; + } catch (err) { + return { + name, + status: STATUS.failed, + reason: err instanceof Error ? err.message : String(err), + }; + } + }); + const results = await runWithConcurrency(tasks, INIT_CONCURRENCY); + writeSkillLock(lock); - const installed = results.filter((result) => result.status === STATUS.success); - const failed = results.filter((result) => result.status === STATUS.failed); + const installed = results.filter((result) => result.status === STATUS.success); + const failed = results.filter((result) => result.status === STATUS.failed); - const status = - failed.length === 0 - ? STATUS.success - : installed.length === 0 - ? STATUS.failed - : STATUS.partial; + const status = + failed.length === 0 + ? STATUS.success + : installed.length === 0 + ? STATUS.failed + : STATUS.partial; - const agentIds = agents.map((agent) => agent.id); - const payload: Record = { - status, - skills: installed.map((result) => result.name), - }; - if (failed.length > 0) - payload.failed = failed.map((result) => ({ - name: result.name, - reason: result.reason, - agents: agentIds, - })); - const lines = - results.length === 0 - ? [ - ctx.localize({ - "en-US": "No bailian-* skills found in the registry.", - "zh-CN": "Registry 中未找到 bailian-* Skill。", - }), - ] - : [ - ctx.localize( - status === STATUS.success - ? { - "en-US": `Installed ${installed.length} bailian-* skills.`, - "zh-CN": `已安装 ${installed.length} 个 bailian-* Skill。`, - } - : { - "en-US": `Installed ${installed.length}/${results.length} bailian-* skills.`, - "zh-CN": `已安装 ${installed.length}/${results.length} 个 bailian-* Skill。`, - }, - ), - ]; - if (failed.length > 0) - lines.push( - ctx.localize({ "en-US": "Failed:", "zh-CN": "失败:" }), - ...failed.map((item) => ` ${item.name}: ${item.reason}`), - ); - ctx.output.result(payload, { text: lines.join("\n") }); + const agentIds = agents.map((agent) => agent.id); + const payload: Record = { + status, + skills: installed.map((result) => result.name), + }; + if (failed.length > 0) + payload.failed = failed.map((result) => ({ + name: result.name, + reason: result.reason, + agents: agentIds, + })); + const lines = + results.length === 0 + ? [ + ctx.localize({ + "en-US": "No bailian-* skills found in the registry.", + "zh-CN": "Registry 中未找到 bailian-* Skill。", + }), + ] + : [ + ctx.localize( + status === STATUS.success + ? { + "en-US": `Installed ${installed.length} bailian-* skills.`, + "zh-CN": `已安装 ${installed.length} 个 bailian-* Skill。`, + } + : { + "en-US": `Installed ${installed.length}/${results.length} bailian-* skills.`, + "zh-CN": `已安装 ${installed.length}/${results.length} 个 bailian-* Skill。`, + }, + ), + ]; + if (failed.length > 0) + lines.push( + ctx.localize({ "en-US": "Failed:", "zh-CN": "失败:" }), + ...failed.map((item) => ` ${item.name}: ${item.reason}`), + ); + ctx.output.result(payload, { text: lines.join("\n") }); - if (failed.length > 0) { - throw new BailianError( - `${failed.length}/${results.length} skill(s) failed to install`, - ExitCode.GENERAL, - `Check the reason for failed skills in the output; network failures can be retried with ${formatCommand(ctx.identity, "skill init")}`, - ); - } + if (failed.length > 0) { + throw new BailianError( + `${failed.length}/${results.length} skill(s) failed to install`, + ExitCode.GENERAL, + `Check the reason for failed skills in the output; network failures can be retried with ${formatCommand(ctx.identity, "skill init")}`, + ); + } + }); }, }); diff --git a/packages/commands/src/commands/skill/lifecycle.ts b/packages/commands/src/commands/skill/lifecycle.ts new file mode 100644 index 000000000..14d24f4cc --- /dev/null +++ b/packages/commands/src/commands/skill/lifecycle.ts @@ -0,0 +1,423 @@ +import { observeRegistry } from "./update-check.ts"; +import { existsSync, lstatSync, mkdtempSync, readlinkSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { + BailianError, + ExitCode, + fetchSkillsIndex, + getSkillLockPath, + getSkillRegistryBaseUrl, + getSkillsDir, + installationRoots, + planUnlinkSkillFromAgents, + readSkillLock, + validateSkillDir, + writeSkillLock, + type CommandContext, + type SkillLockEntry, + type SkillsIndex, +} from "bailian-cli-core"; +import { withStateLock } from "../shared/state-lock.ts"; +import { cloudRevision, unpackRevision, type Revision } from "./packages.ts"; +import { + cachedPackage, + cacheKey, + commitTarget, + fileDiff, + releaseCache, + saveCache, +} from "./managed-files.ts"; +import { + checkContent, + checkProjectRoot, + entrySelector, + installTargets, + otherSourcePaths, + present, + selectedEntries, + selectedNames, + skillSource, + targetForEntry, + validName, + type Selection, + type Target, +} from "./targets.ts"; + +import type { SkillAddPackages } from "./mcp-dependencies.ts"; + +type Action = "add" | "update" | "remove"; +export function withSkillMutation( + ctx: Pick, + run: () => Promise, +) { + return ctx.settings.dryRun ? run() : withStateLock(getSkillLockPath(), ctx.localize, run); +} +export function useTargetRecords(flags: Selection) { + return !!( + skillSource(flags) === "cloud" || + flags.scope || + flags.agent || + flags.skillVersion || + flags.diff || + selectedEntries(flags).some(([, entry]) => entry.installedPath) + ); +} +type Context = Pick; +interface Destination { + target: Target; + key?: string; + entry?: SkillLockEntry; + link?: boolean; +} +interface Result { + code: string; + status: "succeeded" | "noop" | "failed"; + reason: string; + agent?: string | null; + scope?: string; + installed_path?: string; + [key: string]: unknown; +} + +function destinations(key: string, entry: SkillLockEntry, flags: Selection): Destination[] { + const primary = targetForEntry(key, entry); + const targets: Destination[] = [{ target: primary, key, entry }]; + if (!entry.installedPath) { + const roots = installationRoots(); + for (const path of new Set([...(entry.links ?? []), ...planUnlinkSkillFromAgents(key)])) { + const root = dirname(resolve(path)); + const target = roots.get(root); + if (target?.agent && resolve(path) === join(root, key)) + targets.unshift({ target: { root, ...target }, key, entry, link: true }); + } + } + return targets.filter( + ({ target }) => !flags.agent || flags.agent === "all" || target.agent === flags.agent, + ); +} + +function verifyDestination(path: string, name: string, dest: Destination) { + checkProjectRoot(dest.target); + if (dest.link && lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) { + const canonical = join(getSkillsDir(), name); + if (resolve(dirname(path), readlinkSync(path)) === resolve(canonical)) + return checkContent(canonical, dest.entry); + throw new BailianError(`MODIFIED_CONFLICT: ${path}`); + } + checkContent(path, dest.entry); +} + +export async function runSkillLifecycle( + action: Action, + ctx: Context, + flags: Selection, + staged?: SkillAddPackages, +) { + const lock = readSkillLock(); + const reservedPaths = otherSourcePaths(skillSource(flags), lock); + const requested = selectedNames(flags); + const results: Result[] = []; + let firstError: Error | undefined; + function failure(id: string, error: unknown, target?: Target) { + const caught = error instanceof Error ? error : new Error(String(error)); + firstError ??= caught; + const api = caught instanceof BailianError ? caught.api : undefined; + results.push({ + code: id, + status: "failed", + reason: api?.apiCode ?? caught.message.split(":")[0]!, + message: caught.message, + error_code: + api?.apiCode ?? (caught instanceof BailianError ? caught.exitCode : ExitCode.GENERAL), + request_id: api?.requestId, + http_status: api?.httpStatus, + ...(target && { agent: target.agent, scope: target.scope }), + }); + } + let index: Promise | undefined; + const ossIndex = () => + (index ??= (staged?.ossIndex() ?? fetchSkillsIndex()).then((value) => + observeRegistry(ctx, value), + )); + const revisions = staged?.revisions ?? new Map>(); + const packages = + staged?.packages ?? new Map>>(); + const scratch: string[] = []; + async function processSkill( + id: string, + source: "cloud" | "oss", + targets: Destination[], + pinned?: string, + ) { + if (!targets.length) + throw new BailianError("NOT_INSTALLED: No matching target / 没有匹配的安装目标"); + const location = source === "cloud" ? ctx.client.baseUrl : getSkillRegistryBaseUrl(); + let revision: Revision | undefined; + let artifact: Awaited> | undefined; + const known = targets[0]!.entry; + if (action !== "remove") { + if (known?.sourceLocation && known.sourceLocation !== location) + throw new BailianError( + "SOURCE_MISMATCH: Select the original gateway or registry / 请切换至原安装来源", + ); + if (source === "cloud") { + const versionKey = JSON.stringify([id, pinned]); + const pending = revisions.get(versionKey) ?? cloudRevision(ctx, id, pinned); + revisions.set(versionKey, pending); + revision = await pending; + } else { + const entries = (await ossIndex()).skills; + const entry = Object.hasOwn(entries, id) ? entries[id] : undefined; + if (!entry && action === "update") { + results.push({ code: id, status: "noop", reason: "DELISTED" }); + return; + } + if (!entry) throw new BailianError("Skill not found in registry / Registry 中未找到 Skill"); + if (pinned && pinned !== entry.version) + throw new BailianError( + "The OSS registry does not publish the requested version / OSS Registry 未提供指定版本", + ); + revision = { + source, + id, + version: entry.version, + oss: entry, + description: entry.description, + }; + } + } + const revisionKey = cacheKey( + location, + id, + revision?.oss?.contentHash ?? revision?.version ?? "", + ); + async function loadPackage() { + if (!packages.has(revisionKey)) { + const cached = cachedPackage(revisionKey); + const record = Object.values(lock.skills).find((entry) => entry.cacheKey === revisionKey); + if ( + record?.contentHash && + existsSync(cached) && + (source === "cloud" || revision?.oss?.contentHash) + ) { + checkContent(cached, record); + const meta = validateSkillDir(cached, id); + packages.set(revisionKey, { + root: cached, + name: source === "cloud" ? meta.name : id, + hash: record.contentHash, + }); + return packages.get(revisionKey)!; + } + const temp = staged?.temp() ?? mkdtempSync(join(tmpdir(), "bl-skill-")); + if (!staged) scratch.push(temp); + packages.set(revisionKey, await unpackRevision(ctx, revision!, temp)); + } + return packages.get(revisionKey)!; + } + // A legacy canonical directory backs all its symlinks. Validate them before changing it. + if (known && !known.installedPath && targets.some((dest) => !dest.link)) { + for (const dest of targets) { + const name = dest.entry!.canonicalName ?? dest.key!; + verifyDestination(join(dest.target.root, name), name, dest); + } + } + for (const dest of targets) { + try { + let name = dest.entry?.canonicalName ?? (dest.entry ? dest.key! : id); + if (!validName(name)) throw new BailianError("Invalid installation name / 安装名无效"); + // New cloud installs learn the canonical directory name from the verified archive. + if (!dest.entry && source === "cloud" && (!ctx.settings.dryRun || staged)) { + artifact = await loadPackage(); + name = artifact.name; + } + const path = join(dest.target.root, name); + const targetKey = + dest.key ?? `target:${cacheKey(dest.target.scope, dest.target.root, name)}`; + const owned = + dest.entry ?? + (Object.hasOwn(lock.skills, targetKey) ? lock.skills[targetKey] : undefined); + const nameKnown = source !== "cloud" || !!owned || !!artifact; + if ( + (nameKnown && reservedPaths.has(resolve(path))) || + (owned && (owned.sourceType === "openapi" ? "cloud" : "oss") !== source) || + (owned?.remoteId && source === "cloud" && owned.remoteId !== id) || + (action !== "remove" && owned?.sourceLocation && owned.sourceLocation !== location) + ) + throw new BailianError(`SOURCE_CONFLICT: ${path}`); + const details = { + source, + agent: dest.target.agent, + scope: dest.target.scope, + target_root: dest.target.root, + installed_path: nameKnown ? path : undefined, + locked_version: owned?.installedVersion ?? null, + target_version: revision?.version ?? null, + }; + if (nameKnown) verifyDestination(path, name, { ...dest, entry: owned }); + const unchanged = + !!owned && + existsSync(join(path, "SKILL.md")) && + (source === "cloud" + ? owned.installedVersion === revision?.version + : !!revision?.oss?.contentHash && owned.contentHash === revision.oss.contentHash); + const current = + action !== "remove" && unchanged && (action !== "add" || pinned === owned?.pinnedVersion); + if (staged) { + if (!artifact && !(current && owned?.contentHash?.startsWith("sha256:"))) + artifact = await loadPackage(); + staged.inspect(id, artifact?.root ?? path, ctx.settings.dryRun); + } + let diff; + if (flags.diff && revision) { + const next = cachedPackage(revisionKey); + if (!current && !ctx.settings.dryRun) artifact = await loadPackage(); + diff = current + ? { added: [], removed: [], modified: [] } + : artifact || existsSync(next) + ? fileDiff(path, artifact?.root ?? next) + : { + available: false, + download_required: true, + content_path: revision.versionPath + ? revision.versionPath + "/content" + : undefined, + }; + } + const reason = + action === "remove" + ? "REMOVED" + : current + ? action === "add" + ? "ALREADY_INSTALLED" + : "UP_TO_DATE" + : action === "add" + ? "INSTALLED" + : "UPDATED"; + if (!current && !ctx.settings.dryRun) { + let nextEntry: SkillLockEntry | undefined; + if (revision) { + artifact ??= await loadPackage(); + // Keep the established install path if a newer manifest renames itself. + saveCache(revisionKey, artifact.root); + nextEntry = { + sourceType: source === "cloud" ? "openapi" : "oss", + sourceLocation: location, + remoteId: source === "cloud" ? id : revision.oss?.remoteId, + canonicalName: name, + installedVersion: revision.version, + pinnedVersion: pinned, + contentHash: artifact.hash, + cacheKey: revisionKey, + description: revision.description, + publishedAt: revision.oss?.publishedAt, + installedAt: new Date().toISOString(), + agent: dest.target.agent ?? undefined, + scope: dest.target.scope, + projectRoot: dest.target.scope === "project" ? process.cwd() : undefined, + installedPath: path, + }; + } + const commit = () => { + const skills = { ...lock.skills }; + if (dest.link) { + const parent = skills[targetKey]!; + skills[targetKey] = { + ...parent, + links: parent.links?.filter((link) => resolve(link) !== path), + }; + if (nextEntry) + skills[`target:${cacheKey(dest.target.scope, dest.target.root, name)}`] = nextEntry; + } else if (nextEntry) skills[targetKey] = nextEntry; + else delete skills[targetKey]; + writeSkillLock({ version: 1, skills }); + lock.skills = skills; + }; + try { + // A user may have edited the destination while the download was in flight. + verifyDestination(path, name, { ...dest, entry: owned }); + if (action === "remove" && !present(path)) commit(); + else commitTarget(path, nextEntry ? artifact!.root : undefined, commit); + } catch (error) { + releaseCache(nextEntry?.cacheKey, lock); + throw error; + } + releaseCache(owned?.cacheKey, lock); + } + results.push({ + code: id, + status: current ? "noop" : "succeeded", + reason, + ...details, + ...(diff && { diff }), + }); + } catch (error) { + failure(id, error, dest.target); + if (dest.link) break; + } + } + } + try { + const entries = selectedEntries(flags, lock); + if (action === "add") { + const source = skillSource(flags); + const ids = requested === "all" ? Object.keys((await ossIndex()).skills) : requested; + const targets = installTargets(flags); + for (const id of ids) { + try { + const existing = Object.entries(lock.skills).filter( + ([key, entry]) => + (entry.sourceType === "openapi" ? "cloud" : "oss") === source && + entrySelector(key, entry) === id && + (!entry.projectRoot || entry.projectRoot === process.cwd()), + ); + const locations = existing.flatMap(([key, entry]) => destinations(key, entry, flags)); + await processSkill( + id, + source, + targets.map( + (target) => locations.find((dest) => dest.target.root === target.root) ?? { target }, + ), + flags.skillVersion, + ); + } catch (error) { + failure(id, error); + } + } + } else { + for (const [key, entry] of entries) { + const id = entrySelector(key, entry); + try { + await processSkill( + id, + entry.sourceType === "openapi" ? "cloud" : "oss", + destinations(key, entry, flags), + entry.pinnedVersion, + ); + } catch (error) { + failure(id, error); + } + } + if (requested !== "all") + for (const name of requested) { + if (!entries.some(([key, entry]) => name === entrySelector(key, entry))) + failure(name, new BailianError("NOT_INSTALLED: Skill not installed / Skill 未安装")); + } + } + } finally { + for (const temp of scratch) rmSync(temp, { recursive: true, force: true }); + } + const summary = { succeeded: 0, failed: 0, noop: 0 }; + for (const row of results) summary[row.status]++; + return { + data: { + action: `skill.${action}`, + dry_run: ctx.settings.dryRun, + summary, + results, + skills: results.map((row) => ({ ...row, name: row.code })), + }, + firstError, + }; +} diff --git a/packages/commands/src/commands/skill/list.ts b/packages/commands/src/commands/skill/list.ts index 8ed63f18e..0eb2a9eb0 100644 --- a/packages/commands/src/commands/skill/list.ts +++ b/packages/commands/src/commands/skill/list.ts @@ -1,64 +1,223 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineSkillCommand, observeRegistry } from "./update-check.ts"; +import { existsSync, readdirSync } from "node:fs"; +import { join } from "node:path"; import { - defineCommand, - computeSkillStatuses, fetchSkillsIndex, getSkillRegistryBaseUrl, - listSkillDirsOnDisk, + installationRoots, + readCatalogInstalls, readSkillLock, + type SkillStatus, + type SkillStatusRow, } from "bailian-cli-core"; +import { cloudCatalog } from "./packages.ts"; +import { + needsCloud, + selectedEntries, + selectedNames, + selectorFlags, + skillSource, + sourceFlag, + targetFlags, + validateSelection, + validName, +} from "./targets.ts"; import { formatTable } from "bailian-cli-runtime"; -const DESCRIPTION_MAX = 60; - -function truncate(text: string | undefined): string { - if (!text) return "-"; - return text.length > DESCRIPTION_MAX ? `${text.slice(0, DESCRIPTION_MAX - 1)}…` : text; -} - -export default defineCommand({ +const statuses: SkillStatus[] = ["installed", "outdated", "not-installed", "missing", "untracked"]; +export default defineSkillCommand({ description: { - "en-US": "List registry skills and diff against local installs", - "zh-CN": "列出 Registry Skill,并与本地安装结果比较", + "en-US": "List registry skills and local installations by agent, scope and status", + "zh-CN": "按 Agent、范围及状态查看 Skill 目录和本地安装", }, - auth: "none", + auth: "apiKey", + requiresApiKey: needsCloud, defaultOutput: "json", - exampleArgs: ["", "--output json"], + usageArgs: + "[--name | --code | --source oss|cloud] [--agent ] [--scope user|project] [--status ]", + flags: { + ...WORKSPACE_FLAG, + source: sourceFlag, + ...selectorFlags, + ...targetFlags, + status: { + type: "string", + valueHint: "", + description: { + "en-US": "Comma-separated installation states", + "zh-CN": "安装状态,以逗号分隔", + }, + }, + }, + exampleArgs: [ + "", + "--source oss --status not-installed", + "--name spark-video", + "--code skill_example", + "--agent cursor --scope project --status installed,outdated", + ], notes: [ { "en-US": - "STATUS: installed | outdated | not-installed | missing (lock has it, dir deleted) | untracked (dir exists, not managed)", + "States: installed, outdated, not-installed, missing (tracked path absent), untracked (local files without a lock record).", "zh-CN": - "STATUS:installed | outdated | not-installed | missing(Lock 中存在但目录已删除)| untracked(目录存在但未被管理)", + "支持 installed、outdated、not-installed、missing(已记录但路径缺失)、untracked(本地文件无安装记录)。", }, ], + validate(flags) { + if ( + flags.status !== undefined && + flags.status.split(",").some((value) => !statuses.some((status) => status === value.trim())) + ) + return { + "en-US": "Unknown --status. Use installed, outdated, not-installed, missing or untracked.", + "zh-CN": "--status 须为 installed、outdated、not-installed、missing 或 untracked。", + }; + return validateSelection(flags); + }, async run(ctx) { - // Three-way reconciliation: live remote index × skill-lock.json (installation facts) × disk - const index = await fetchSkillsIndex(); + const flags = ctx.flags; + const source = skillSource(flags); + const selected = selectedNames(flags); + const scope = flags.scope ?? "user"; const lock = readSkillLock(); - const rows = computeSkillStatuses(index, lock, listSkillDirsOnDisk()); - - const payload = { - registry: getSkillRegistryBaseUrl(), - ...(index.updatedAt ? { updatedAt: index.updatedAt } : {}), - skills: rows, + const records = selectedEntries(flags, lock); + const wanted = new Set(flags.status?.split(",").map((status) => status.trim())); + const roots = [...installationRoots()].filter( + ([, target]) => + target.scope === scope && + (!flags.agent || flags.agent === "all" || target.agent === flags.agent), + ); + const skills: Array< + SkillStatusRow & { + skill_code: string; + source: string; + install_state: SkillStatus; + agent: string | null; + scope: string; + installed_path: string | null; + latest_version: string | null; + } + > = []; + let updatedAt: string | undefined; + const type = source === "cloud" ? "openapi" : "oss"; + const local = readCatalogInstalls(ctx.client.baseUrl, type, lock); + type Item = { + name: string; + code?: string; + version?: string | null; + hash?: string; + description?: string; + publishedAt?: string; }; - if (rows.length === 0) { - ctx.output.result(payload, { - text: ctx.localize({ - "en-US": "Skill registry is empty and no skills are installed locally.", - "zh-CN": "Skill Registry 为空,且本地未安装 Skill。", - }), + const items = new Map(); + for (const [key, entry] of records) { + if (type === "openapi" && entry.sourceLocation && entry.sourceLocation !== ctx.client.baseUrl) + continue; + const name = entry.canonicalName ?? key; + items.set(source === "oss" ? name : (entry.remoteId ?? name), { + name, + code: entry.remoteId, + description: entry.description, + publishedAt: entry.publishedAt, }); - return; } - const table = rows.map((row) => [ - row.name, - row.status, - row.publishedAt ? row.publishedAt.slice(0, 19).replace("T", " ") : "-", - truncate(row.description), - ]); - ctx.output.result(payload, { - text: formatTable(["NAME", "STATUS", "UPDATEDAT", "DESCRIPTION"], table).join("\n"), - }); + if (source === "oss") { + const index = observeRegistry(ctx, await fetchSkillsIndex()); + updatedAt = index.updatedAt; + for (const [name, entry] of Object.entries(index.skills)) { + items.set(name, { + name, + code: entry.remoteId, + version: entry.version, + hash: entry.contentHash, + description: entry.description, + publishedAt: entry.publishedAt, + }); + } + } else { + for (const [id, remote] of await cloudCatalog(ctx)) { + items.set(id, { + name: items.get(id)?.name ?? id, + version: remote.latest_version, + description: remote.display_description, + }); + } + } + const names = new Set([...items.values()].map((item) => item.name)); + for (const [root] of roots) { + if (!existsSync(root)) continue; + for (const entry of readdirSync(root, { withFileTypes: true })) { + if ( + !(entry.isDirectory() || entry.isSymbolicLink()) || + !validName(entry.name) || + names.has(entry.name) + ) + continue; + const path = join(root, entry.name); + if (!local.claimedPaths.has(path) && existsSync(join(path, "SKILL.md"))) + items.set(entry.name, { name: entry.name }); + } + } + for (const [key, item] of items) { + if (selected !== "all" && !selected.includes(key)) continue; + const id = item.code ?? key; + const version = item.version ?? null; + const locations = local + .inspect(id, version, item.name, item.hash) + .installations.filter( + (row) => + row.scope === scope && + (!flags.agent || flags.agent === "all" || row.agent === flags.agent), + ); + const rows = locations.length + ? locations + : [ + { + agent: flags.agent && flags.agent !== "all" ? flags.agent : null, + scope, + installed_path: null, + locked_version: null, + install_state: "not-installed" as const, + }, + ]; + for (const row of rows) { + const status = row.install_state; + if (!wanted.size || wanted.has(status)) + skills.push({ + name: item.name, + skill_code: id, + source, + description: item.description, + publishedAt: item.publishedAt, + latest_version: version, + ...row, + install_state: status, + status, + }); + } + } + skills.sort((left, right) => left.name.localeCompare(right.name)); + ctx.output.result( + { + registry: source === "oss" ? getSkillRegistryBaseUrl() : ctx.client.baseUrl, + ...(updatedAt && { updatedAt }), + skills, + }, + { + text: formatTable( + ["NAME", "STATUS", "AGENT", "SCOPE", "VERSION", "PATH"], + skills.map((row) => [ + row.name, + row.status, + row.agent ?? "-", + row.scope, + row.latest_version ?? "-", + row.installed_path ?? "-", + ]), + ).join("\n"), + }, + ); }, }); diff --git a/packages/commands/src/commands/skill/managed-files.ts b/packages/commands/src/commands/skill/managed-files.ts new file mode 100644 index 000000000..f15c4876e --- /dev/null +++ b/packages/commands/src/commands/skill/managed-files.ts @@ -0,0 +1,122 @@ +import { + cpSync, + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + renameSync, + rmSync, +} from "node:fs"; +import { createHash } from "node:crypto"; +import { dirname, join } from "node:path"; +import { getSkillsDir, type SkillLockFile } from "bailian-cli-core"; +import { present } from "./targets.ts"; + +/** Stage each path on its own filesystem and keep every original until the ledger is committed. */ +export function commitTargets(targets: { path: string; source?: string }[], commit: () => void) { + const transactions: { path: string; directory: string; backup: string; promoted: boolean }[] = []; + try { + for (const { path, source } of targets) { + if (!source && !present(path)) continue; + mkdirSync(dirname(path), { recursive: true }); + const directory = mkdtempSync(join(dirname(path), ".skill-txn-")); + const backup = join(directory, "original"); + const staged = join(directory, "next"); + const transaction = { path, directory, backup, promoted: false }; + transactions.push(transaction); + if (source) cpSync(source, staged, { recursive: true, errorOnExist: true, force: false }); + if (present(path)) renameSync(path, backup); + if (source) { + renameSync(staged, path); + transaction.promoted = true; + } + } + commit(); + } catch (error) { + const errors: unknown[] = []; + for (const { path, directory, backup, promoted } of transactions.reverse()) { + try { + if (promoted) rmSync(path, { recursive: true, force: true }); + if (present(backup)) renameSync(backup, path); + rmSync(directory, { recursive: true, force: true }); + } catch (restoreError) { + // Keep the backup for recovery and continue restoring the other paths. + errors.push(restoreError); + } + } + if (errors.length) throw new AggregateError([error, ...errors], String(error)); + throw error; + } + for (const { directory } of transactions) { + try { + rmSync(directory, { recursive: true, force: true }); + } catch { + // A host may hold the backup open. The lock and active paths are already committed. + } + } +} + +export function commitTarget(path: string, source: string | undefined, commit: () => void) { + commitTargets([{ path, source }], commit); +} + +export function cacheKey(source: string, id: string, revision: string) { + return createHash("sha256") + .update(JSON.stringify([source, id, revision])) + .digest("hex"); +} +export function cachedPackage(key: string) { + return join(getSkillsDir(), ".packages", key); +} +export function saveCache(key: string, root: string) { + const path = cachedPackage(key); + if (existsSync(path)) return; + mkdirSync(dirname(path), { recursive: true }); + const temp = mkdtempSync(join(dirname(path), ".incoming-")); + try { + cpSync(root, join(temp, "package"), { recursive: true }); + renameSync(join(temp, "package"), path); + } finally { + rmSync(temp, { recursive: true, force: true }); + } +} +export function releaseCache(key: string | undefined, lock: SkillLockFile) { + if ( + key && + /^[0-9a-f]{64}$/.test(key) && + !Object.values(lock.skills).some((entry) => entry.cacheKey === key) + ) + rmSync(cachedPackage(key), { recursive: true, force: true }); +} + +export function fileDiff(current: string, next: string) { + function files(root: string) { + const hashes = new Map(); + function visit(relative: string) { + for (const item of readdirSync(join(root, relative), { withFileTypes: true })) { + const path = join(relative, item.name); + if (item.isDirectory()) visit(path); + else if (item.isFile()) + hashes.set( + path, + createHash("sha256") + .update(readFileSync(join(root, path))) + .digest("hex"), + ); + } + } + if (lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) visit(""); + return hashes; + } + const before = files(current), + after = files(next); + return { + added: [...after.keys()].filter((path) => !before.has(path)).sort(), + removed: [...before.keys()].filter((path) => !after.has(path)).sort(), + modified: [...after.keys()] + .filter((path) => before.has(path) && before.get(path) !== after.get(path)) + .sort(), + }; +} diff --git a/packages/commands/src/commands/skill/mcp-dependencies.ts b/packages/commands/src/commands/skill/mcp-dependencies.ts new file mode 100644 index 000000000..85dce2a27 --- /dev/null +++ b/packages/commands/src/commands/skill/mcp-dependencies.ts @@ -0,0 +1,163 @@ +import { + constants, + closeSync, + fstatSync, + lstatSync, + mkdtempSync, + openSync, + readFileSync, + rmSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { BailianError, fetchSkillsIndex, type CommandContext } from "bailian-cli-core"; +import { prepareLifecycle, writeServer, type LifecyclePlan } from "../mcp/server-lifecycle.ts"; +import type { McpRequestContext } from "../mcp/server-response.ts"; +import type { Revision, unpackRevision } from "./packages.ts"; + +/** Package values may include credentials. Only explicit serverCode fields leave this reader. */ +export function readMcpDependencies( + root: string, + localize: CommandContext["localize"], +): string[] | undefined { + const invalid = () => + new BailianError( + localize({ + "en-US": "Invalid service declaration in mcp-config.json.", + "zh-CN": "mcp-config.json 中的服务声明格式无效。", + }), + ); + const path = join(root, "mcp-config.json"); + const entry = lstatSync(path, { throwIfNoEntry: false }); + if (!entry) return; + if (!entry.isFile()) throw invalid(); + const file = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const stat = fstatSync(file); + if ( + !stat.isFile() || + stat.dev !== entry.dev || + stat.ino !== entry.ino || + stat.size > 1024 * 1024 + ) + throw invalid(); + const manifest: unknown = JSON.parse(readFileSync(file, "utf8").replace(/^\uFEFF/, "")); + if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) throw invalid(); + const codes = new Set(); + for (const value of Object.values(manifest)) { + if (!value || typeof value !== "object") continue; + if (!Object.hasOwn(value, "serverCode")) { + if (Object.hasOwn(value, "serverName")) throw invalid(); + continue; + } + const code: unknown = value.serverCode; + if ( + typeof code !== "string" || + !code.trim() || + /[,/\\?#\s\p{Cc}]/u.test(code) || + code === "." || + code === ".." + ) + throw invalid(); + codes.add(code); + } + return [...codes]; + } catch { + throw invalid(); + } finally { + closeSync(file); + } +} + +type Artifact = Awaited>; +type Context = McpRequestContext & Pick; + +/** One invocation uses the same catalog revisions and verified packages for preview and installation. */ +export class SkillAddPackages { + readonly revisions = new Map>(); + readonly packages = new Map(); + private readonly manifests = new Map(); + private readonly scratch: string[] = []; + private index?: ReturnType; + private steps: LifecyclePlan = []; + + constructor(private readonly localize: CommandContext["localize"]) {} + + ossIndex() { + return (this.index ??= fetchSkillsIndex()); + } + temp() { + const path = mkdtempSync(join(tmpdir(), "bl-skill-add-")); + this.scratch.push(path); + return path; + } + dispose() { + for (const path of this.scratch) rmSync(path, { recursive: true, force: true }); + } + inspect(skill: string, root: string, planning: boolean) { + const codes = readMcpDependencies(root, this.localize); + if (planning) this.manifests.set(skill, codes); + else if ( + !this.manifests.has(skill) || + JSON.stringify(this.manifests.get(skill)) !== JSON.stringify(codes) + ) + throw new BailianError( + this.localize({ + "en-US": "Skill dependencies changed during planning. Retry the install.", + "zh-CN": "安装计划生成后 Skill 依赖发生了变化,请重新安装。", + }), + ); + } + private owners(skills: Set) { + const owners = new Map(); + for (const skill of skills) { + for (const code of this.manifests.get(skill) ?? []) { + const names = owners.get(code) ?? []; + names.push(skill); + owners.set(code, names); + } + } + return owners; + } + async plan(ctx: Context, skills: Set) { + const codes = [...this.owners(skills).keys()]; + this.steps = codes.length + ? (await prepareLifecycle(ctx, codes.join(","), "activate")).data + : []; + } + async report(ctx: Context, skills: Set, preview: boolean) { + const owners = this.owners(skills); + const results = []; + let firstError: BailianError | undefined; + for (const step of this.steps) { + const code = "result" in step ? step.result.code : step.code; + if (!owners.has(code)) continue; + const item = + "result" in step + ? step + : preview + ? { result: { ...step, status: "planned" } } + : await writeServer(ctx, step); + if ("error" in item) firstError ??= item.error; + results.push({ ...item.result, skills: owners.get(code) }); + } + const unknown = [...skills].filter((skill) => this.manifests.get(skill) === undefined); + const status = firstError + ? "failed" + : unknown.length === skills.size + ? "metadata_unavailable" + : unknown.length + ? "partial" + : preview + ? "planned" + : "checked"; + return { + fields: { + mcp_dep_results: results, + mcp_dependency_status: status, + ...(unknown.length && { mcp_dependency_unknown_skills: unknown }), + }, + firstError, + }; + } +} diff --git a/packages/commands/src/commands/skill/packages.ts b/packages/commands/src/commands/skill/packages.ts new file mode 100644 index 000000000..e05767fde --- /dev/null +++ b/packages/commands/src/commands/skill/packages.ts @@ -0,0 +1,148 @@ +import { mkdirSync } from "node:fs"; +import { join } from "node:path"; +import { + BailianError, + computeDirContentHash, + downloadSkillAsset, + downloadSkillZip, + extractSkillZip, + extractTarBr, + skillsPath, + validateSkillDir, + type CommandContext, + type SkillIndexEntry, +} from "bailian-cli-core"; +import { + describeSkill, + invalidCatalogResponse, + requestCatalog, + type CatalogSkill, +} from "./catalog.ts"; +import { validName } from "./targets.ts"; + +type Context = Pick; +export async function cloudCatalog(ctx: Context) { + const skills = new Map(); + const size = 100; + for (let page = 1; page * size <= 10000; page++) { + const { data, request_id } = await requestCatalog<{ + items: CatalogSkill[]; + total: number; + page_no: number; + page_size: number; + }>(ctx, `${skillsPath()}?pageNo=${page}&pageSize=${size}`); + if ( + !Array.isArray(data.items) || + data.page_no !== page || + data.page_size !== size || + !Number.isSafeInteger(data.total) || + data.total < 0 || + data.items.length > size + ) + invalidCatalogResponse(ctx, request_id); + for (const item of data.items) { + describeSkill(ctx, item, request_id); + skills.set(item.id, item); + } + if (page * size >= data.total) return skills; + if (!data.items.length) invalidCatalogResponse(ctx, request_id); + } + throw new BailianError( + ctx.localize({ + "en-US": "The catalog exceeds the 10000-record API window.", + "zh-CN": "云端目录超出接口一万条分页窗口。", + }), + ); +} + +export interface Revision { + id: string; + source: "oss" | "cloud"; + version?: string; + description?: string; + oss?: SkillIndexEntry; + versionPath?: string; +} +export async function cloudRevision( + ctx: Context, + id: string, + requested?: string, +): Promise { + const detail = await requestCatalog(ctx, skillsPath(id)); + if (detail.data.id !== id) invalidCatalogResponse(ctx, detail.request_id); + const skill = describeSkill(ctx, detail.data, detail.request_id); + const version = requested ?? skill.latest_version; + if (!version || !validName(version)) + throw new BailianError( + ctx.localize({ + "en-US": "No installable skill version was returned.", + "zh-CN": "服务未返回可安装的 Skill 版本。", + }), + ); + const versionPath = `${skillsPath(id)}/versions/${encodeURIComponent(version)}`; + const reply = await requestCatalog<{ skill_id: string; version: string; status: string }>( + ctx, + versionPath, + ); + if (reply.data.skill_id !== id || reply.data.version !== version) + invalidCatalogResponse(ctx, reply.request_id); + if (reply.data.status !== "active") + throw new BailianError( + ctx.localize({ + "en-US": `Skill version ${version} is ${reply.data.status}.`, + "zh-CN": `Skill 版本 ${version} 的状态为 ${reply.data.status}。`, + }), + ); + return { id, version, source: "cloud", description: skill.description, versionPath }; +} +export async function unpackRevision(ctx: Context, revision: Revision, scratch: string) { + let root = join(scratch, "package"); + mkdirSync(root); + if (revision.source === "oss") { + if (!revision.oss || !validName(revision.id)) + throw new BailianError("Invalid OSS Skill / OSS Skill 无效"); + if (revision.oss.compression && revision.oss.compression !== "tar.br") + throw new BailianError( + ctx.localize({ + "en-US": `Skill ${revision.id} uses unsupported compression format: ${revision.oss.compression}`, + "zh-CN": `Skill ${revision.id} 使用了不支持的压缩格式:${revision.oss.compression}`, + }), + ); + await extractTarBr(await downloadSkillAsset(revision.id, revision.oss), root); + } else { + const signedUrl = async () => { + const reply = await requestCatalog<{ skill_id: string; version: string; file_url: string }>( + ctx, + revision.versionPath + "/content", + ); + if ( + reply.data.skill_id !== revision.id || + reply.data.version !== revision.version || + typeof reply.data.file_url !== "string" + ) + invalidCatalogResponse(ctx, reply.request_id); + return reply.data.file_url; + }; + const bytes = await downloadSkillZip(await signedUrl(), ctx.settings.timeout).catch( + async (error: unknown) => { + if (error instanceof BailianError && error.api?.httpStatus === 403) + return downloadSkillZip(await signedUrl(), ctx.settings.timeout); + throw error; + }, + ); + root = await extractSkillZip(bytes, root); + } + const meta = validateSkillDir(root, revision.id); + const name = revision.source === "oss" ? revision.id : meta.name; + if (!validName(name)) + throw new BailianError( + ctx.localize({ + "en-US": "Invalid canonical skill name in package.", + "zh-CN": "包内 Skill 安装名无效。", + }), + ); + const hash = computeDirContentHash(root); + if (revision.oss?.contentHash?.startsWith("sha256:") && revision.oss.contentHash !== hash) + throw new BailianError("Skill package checksum mismatch / Skill 包摘要不匹配"); + return { root, name, hash }; +} diff --git a/packages/commands/src/commands/skill/registry-lifecycle.ts b/packages/commands/src/commands/skill/registry-lifecycle.ts new file mode 100644 index 000000000..cf9c59f22 --- /dev/null +++ b/packages/commands/src/commands/skill/registry-lifecycle.ts @@ -0,0 +1,308 @@ +import { observeRegistry } from "./update-check.ts"; +import { existsSync, lstatSync, readlinkSync, rmSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { + BailianError, + detectInstalledAgents, + fanOutSkillToAgents, + fetchSkillsIndex, + getAgentTargets, + getSkillRegistryBaseUrl, + installSkillWithFanout, + planUnlinkSkillFromAgents, + readSkillLock, + runWithConcurrency, + writeSkillLock, + type AgentTarget, + type CommandContext, + type SkillLockEntry, + type LinkResult, +} from "bailian-cli-core"; +import { commitTargets } from "./managed-files.ts"; +import { unpackRevision } from "./packages.ts"; +import type { SkillAddPackages } from "./mcp-dependencies.ts"; +import { formatTable } from "bailian-cli-runtime"; +import { canonicalSkillPath, planFanoutLinks, summarizeAgents } from "./dry-run-plan.ts"; +import { + checkContent, + otherSourcePaths, + present, + selectedEntries, + selectedNames, + validName, + type Selection, +} from "./targets.ts"; + +// Older OSS records own a canonical installation plus agent symlinks or recorded fallback copies. +function checkRegistryTargets( + name: string, + entry: SkillLockEntry | undefined, + agents: AgentTarget[], + reservedPaths: Set, + preview = false, +) { + if (!validName(name)) throw new BailianError("Invalid skill name / Skill 名称无效"); + const canonical = canonicalSkillPath(name); + if (reservedPaths.has(resolve(canonical))) + throw new BailianError(`SOURCE_CONFLICT: ${canonical}`); + checkContent(canonical, entry); + const allowed = new Set(getAgentTargets().map((agent) => resolve(agent.skillsDir, name))); + const recorded = new Set((entry?.links ?? []).map((path) => resolve(path))); + const paths = new Set([ + ...recorded, + ...agents.map((agent) => join(agent.skillsDir, name)), + ...planUnlinkSkillFromAgents(name), + ]); + for (const path of paths) { + if (reservedPaths.has(resolve(path))) throw new BailianError(`SOURCE_CONFLICT: ${path}`); + if (!allowed.has(path)) throw new BailianError(`INVALID_TARGET: ${path}`); + if (!present(path)) continue; + const stat = lstatSync(path); + if (stat.isSymbolicLink() && resolve(dirname(path), readlinkSync(path)) === resolve(canonical)) + continue; + // Include legacy recorded placeholders in the link preview. + if ( + preview && + recorded.has(path) && + stat.isFile() && + !/^sha256:[0-9a-f]{64}$/.test(entry?.contentHash ?? "") + ) + continue; + checkContent(path, recorded.has(path) ? entry : undefined); + } +} + +function agentResult(link: { agent: string; path: string }, reason: string, outcome?: LinkResult) { + const failed = outcome?.mode === "skipped"; + return { + agent: link.agent, + scope: "user", + installed_path: link.path, + status: failed ? "failed" : reason === "UP_TO_DATE" ? "noop" : "succeeded", + reason: failed ? "LINK_FAILED" : reason, + ...(failed && { message: outcome.reason }), + }; +} + +export async function runRegistryLifecycle( + action: "add" | "update" | "remove", + ctx: Pick, + flags: Selection, + staged?: SkillAddPackages, +) { + const lock = readSkillLock(); + const reservedPaths = otherSourcePaths("oss", lock); + const index = + action === "remove" + ? undefined + : observeRegistry(ctx, await (staged?.ossIndex() ?? fetchSkillsIndex())); + const agents = action === "remove" ? [] : detectInstalledAgents(); + const requested = selectedNames(flags); + const installed = new Map(selectedEntries(flags, lock)); + const names = + requested === "all" + ? action === "add" + ? Object.keys(index!.skills) + : [...installed.keys()] + : requested; + const preview = ctx.settings.dryRun; + let firstError: Error | undefined; + const tasks = names.map((name) => async () => { + try { + const locked = installed.get(name); + if (action === "add" && !locked && Object.hasOwn(lock.skills, name)) + throw new BailianError(`SOURCE_CONFLICT: ${name}`); + if (action !== "add" && !locked) + throw new BailianError( + ctx.localize({ + "en-US": "NOT_INSTALLED: Skill not installed", + "zh-CN": "NOT_INSTALLED: Skill 未安装", + }), + ); + const canonical = canonicalSkillPath(name); + const remote = index && Object.hasOwn(index.skills, name) ? index.skills[name] : undefined; + if ( + action !== "remove" && + locked?.sourceLocation && + locked.sourceLocation !== getSkillRegistryBaseUrl() + ) + throw new BailianError( + "SOURCE_MISMATCH: Select the original registry / 请切换至原 OSS Registry", + ); + if (action === "update" && !remote && requested === "all") + return { name, status: "skipped", reason: "DELISTED" }; + if (action !== "remove" && !remote) + throw new BailianError( + ctx.localize({ + "en-US": "Skill not found in registry", + "zh-CN": "Registry 中未找到 Skill", + }), + ); + const targets = agents.filter((agent) => !reservedPaths.has(resolve(agent.skillsDir, name))); + checkRegistryTargets(name, locked, targets, reservedPaths, preview); + if (action === "remove") { + const links = planUnlinkSkillFromAgents(name, locked!.links); + if (preview) return { name, status: "remove", canonical, links }; + commitTargets( + [...new Set([...links, canonical])].map((path) => ({ path })), + () => { + const skills = { ...lock.skills }; + delete skills[name]; + writeSkillLock({ ...lock, skills }); + lock.skills = skills; + }, + ); + return { name, status: "removed", canonical, removedLinks: links.length }; + } + const entry = remote!; + const same = + !!locked && + !!entry.contentHash && + entry.contentHash === locked.contentHash && + existsSync(join(canonical, "SKILL.md")); + let packageRoot: string | undefined; + if (staged) { + if (same && locked?.contentHash?.startsWith("sha256:")) packageRoot = canonical; + else { + let artifact = staged.packages.get(name); + if (!artifact) { + artifact = await unpackRevision( + ctx, + { source: "oss", id: name, oss: entry }, + staged.temp(), + ); + staged.packages.set(name, artifact); + } + packageRoot = artifact.root; + } + staged.inspect(name, packageRoot, preview); + } + if (same) { + const links = planFanoutLinks(name, targets); + const missing = new Set(links.filter((link) => !link.exists).map((link) => link.agent)); + const fanout = + !preview && missing.size + ? fanOutSkillToAgents( + name, + targets.filter((agent) => missing.has(agent.id)), + locked.links, + ) + : undefined; + if (fanout) { + const skills = { ...lock.skills, [name]: { ...locked, links: fanout.links } }; + try { + writeSkillLock({ ...lock, skills }); + } catch (error) { + for (const link of fanout.results) + if (link.mode !== "skipped") rmSync(link.path, { recursive: true, force: true }); + throw error; + } + lock.skills = skills; + } + const agent_results = links.map((link) => + agentResult( + link, + link.exists ? "UP_TO_DATE" : "REPAIRED", + fanout?.results.find((result) => result.agent === link.agent), + ), + ); + const failure = agent_results.find((row) => row.status === "failed"); + if (failure) firstError ??= new BailianError(failure.message ?? failure.reason); + return { + name, + canonical, + publishedAt: locked.publishedAt, + agent_results, + ...(preview && { links }), + status: failure ? "failed" : missing.size ? "repaired" : "up-to-date", + ...(failure && { reason: failure.reason }), + }; + } + const reason = action === "add" ? "INSTALLED" : "UPDATED"; + if (preview) { + const links = planFanoutLinks(name, targets); + return { + name, + status: action === "add" ? "install" : "update", + canonical, + publishedAt: entry.publishedAt, + links, + agent_results: links.map((link) => agentResult(link, reason)), + }; + } + const record = await installSkillWithFanout( + name, + entry, + targets, + locked?.links, + undefined, + packageRoot, + ); + const skills = { + ...lock.skills, + [name]: { ...record.lockEntry, sourceLocation: getSkillRegistryBaseUrl() }, + }; + writeSkillLock({ ...lock, skills }); + lock.skills = skills; + const agent_results = record.linkResults.map((link) => agentResult(link, reason, link)); + const failure = agent_results.find((row) => row.status === "failed"); + if (failure) firstError ??= new BailianError(failure.message ?? failure.reason); + return { + name, + status: failure ? "failed" : action === "add" ? "installed" : "updated", + agent_results, + ...(failure && { reason: failure.reason }), + publishedAt: entry.publishedAt, + agents: record.linkedAgents, + }; + } catch (error) { + const caught = error instanceof Error ? error : new Error(String(error)); + firstError ??= caught; + return { name, status: "failed", reason: caught.message }; + } + }); + const skills = await runWithConcurrency(tasks, 3); + const summary = { succeeded: 0, noop: 0, failed: 0 }; + const results = skills.map((row) => { + const status = + row.status === "failed" + ? "failed" + : ["up-to-date", "skipped"].includes(row.status) + ? "noop" + : "succeeded"; + summary[status]++; + return { + code: row.name, + status, + ...("agent_results" in row && { agent_results: row.agent_results }), + reason: + row.reason?.split(":")[0] ?? + (row.status === "repaired" + ? "REPAIRED" + : row.status === "up-to-date" + ? action === "add" + ? "ALREADY_INSTALLED" + : "UP_TO_DATE" + : { add: "INSTALLED", update: "UPDATED", remove: "REMOVED" }[action]), + installed_path: canonicalSkillPath(row.name), + }; + }); + return { + data: { + action: `skill.${action}`, + dry_run: preview, + skills, + summary, + results, + ...(action !== "remove" && { + registry: getSkillRegistryBaseUrl(), + agents: preview ? summarizeAgents(agents) : agents.map((agent) => agent.id), + }), + }, + text: formatTable( + ["NAME", "STATUS", "DETAIL"], + skills.map((row) => [row.name, row.status, row.reason ?? "-"]), + ).join("\n"), + firstError, + }; +} diff --git a/packages/commands/src/commands/skill/remove.ts b/packages/commands/src/commands/skill/remove.ts index 70868c2b2..c62020b05 100644 --- a/packages/commands/src/commands/skill/remove.ts +++ b/packages/commands/src/commands/skill/remove.ts @@ -1,162 +1,37 @@ -import { - formatCommand, - BailianError, - ExitCode, - defineCommand, - getSkillsDir, - listSkillDirsOnDisk, - parseSkillNames, - planUnlinkSkillFromAgents, - readSkillLock, - removeSkillDir, - unlinkSkillFromAgents, - writeSkillLock, -} from "bailian-cli-core"; -import { formatTable } from "bailian-cli-runtime"; -import { join } from "node:path"; +import { defineSkillCommand } from "./update-check.ts"; +import { runSkillLifecycle, useTargetRecords, withSkillMutation } from "./lifecycle.ts"; +import { runRegistryLifecycle } from "./registry-lifecycle.ts"; +import { selectorFlags, sourceFlag, targetFlags, validateSelection } from "./targets.ts"; -interface RemoveOutcome { - name: string; - status: "removed" | "failed"; - removedLinks?: number; - reason?: string; -} - -interface RemovePlanItem { - name: string; - status: "remove" | "failed"; - canonical?: string; - links?: string[]; - reason?: string; -} - -export default defineCommand({ +export default defineSkillCommand({ + updateCheck: "offline", description: { "en-US": "Remove locally installed skills (registry is untouched)", "zh-CN": "移除本地已安装的 Skill(不修改 Registry)", }, auth: "none", defaultOutput: "json", - usageArgs: "--name ", + usageArgs: + "(--name | --code ) [--agent ] [--scope user|project]", flags: { - name: { - type: "string", - valueHint: "", - description: { - "en-US": "Skills to remove: all or comma-separated skill names", - "zh-CN": "要移除的 Skill:all 或以逗号分隔的 Skill 名称", - }, - required: true, - }, + source: sourceFlag, + ...targetFlags, + ...selectorFlags, }, - exampleArgs: ["--name spark-video", "--name all"], - async run(ctx) { - // Purely local operation: no remote access, works offline - const requested = parseSkillNames(ctx.flags.name, false); - const lock = readSkillLock(); - const names = requested === "all" ? Object.keys(lock.skills) : requested; - - if (names.length === 0) { - ctx.output.result( - { skills: [] }, - { - text: ctx.localize({ - "en-US": "No skills installed locally; nothing to remove.", - "zh-CN": "本地未安装 Skill,无需移除。", - }), - }, - ); - return; - } - - const diskDirs = new Set(listSkillDirsOnDisk()); - const skillsDir = getSkillsDir(); - - if (ctx.settings.dryRun) { - const results: RemovePlanItem[] = names.map((name) => { - const locked = lock.skills[name]; - if (!locked) { - return { - name, - status: "failed", - reason: diskDirs.has(name) - ? "directory not managed by bl skill (untracked); remove manually if needed" - : "not installed", - }; - } - return { - name, - status: "remove", - canonical: join(skillsDir, name), - // 与真实 unlink 同一候选集:含 lock 外的历史托管 symlink - links: planUnlinkSkillFromAgents(name, locked.links ?? []), - }; - }); + validate: (flags) => validateSelection(flags, "remove"), + exampleArgs: [ + "--name spark-video", + "--name all", + "--code skill_example --agent cursor --scope project --dry-run", + ], - ctx.output.result({ action: "skill.remove", skills: results }); - - const failed = results.filter((result) => result.status === "failed"); - if (failed.length > 0) { - throw new BailianError( - `${failed.length}/${results.length} skill(s) failed to remove`, - ExitCode.GENERAL, - `Check the reason for failed skills in the output; use ${formatCommand(ctx.identity, "skill list")} to verify local install status`, - ); - } - return; - } - - const results: RemoveOutcome[] = []; - for (const name of names) { - const locked = lock.skills[name]; - if (!locked) { - results.push({ - name, - status: "failed", - reason: diskDirs.has(name) - ? "directory not managed by bl skill (untracked); remove manually if needed" - : "not installed", - }); - continue; - } - try { - // Reclaim agent fan-out first, then delete canonical, finally clear the lock entry - const removedLinks = unlinkSkillFromAgents(name, locked.links ?? []); - removeSkillDir(name); - delete lock.skills[name]; - results.push({ name, status: "removed", removedLinks: removedLinks.length }); - } catch (err) { - results.push({ - name, - status: "failed", - reason: err instanceof Error ? err.message : String(err), - }); - } - } - writeSkillLock(lock); - - const rows = results.map((result) => [ - result.name, - result.status, - result.status === "removed" - ? ctx.localize({ - "en-US": `reclaimed ${result.removedLinks} agent link(s)`, - "zh-CN": `已回收 ${result.removedLinks} 个 Agent 链接`, - }) - : (result.reason ?? "-"), - ]); - ctx.output.result( - { skills: results }, - { text: formatTable(["NAME", "STATUS", "DETAIL"], rows).join("\n") }, + async run(ctx) { + const report = await withSkillMutation(ctx, async () => + useTargetRecords(ctx.flags) + ? runSkillLifecycle("remove", ctx, ctx.flags) + : runRegistryLifecycle("remove", ctx, ctx.flags), ); - - const failed = results.filter((result) => result.status === "failed"); - if (failed.length > 0) { - throw new BailianError( - `${failed.length}/${results.length} skill(s) failed to remove`, - ExitCode.GENERAL, - `Check the reason for failed skills in the output; use ${formatCommand(ctx.identity, "skill list")} to verify local install status`, - ); - } + ctx.output.result(report.data, "text" in report ? { text: report.text } : undefined); + if (report.firstError) throw report.firstError; }, }); diff --git a/packages/commands/src/commands/skill/search.ts b/packages/commands/src/commands/skill/search.ts new file mode 100644 index 000000000..fa04b0896 --- /dev/null +++ b/packages/commands/src/commands/skill/search.ts @@ -0,0 +1,151 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineSkillCommand } from "./update-check.ts"; +import { readCatalogInstalls, skillsPath } from "bailian-cli-core"; +import { + describeSkill, + invalidCatalogResponse, + requestCatalog, + type CatalogSkill, +} from "./catalog.ts"; + +interface CatalogPage { + items: CatalogSkill[]; + total: number; + page_no: number; + page_size: number; +} + +const defaultPageSize = 30; +const maxWindow = 10_000; + +export default defineSkillCommand({ + localDryRun: true, + description: { + "en-US": "Search cloud skills and show their local installations", + "zh-CN": "搜索云端 Skill 并查看本地安装情况", + }, + auth: "apiKey", + defaultOutput: "json", + usageArgs: + "[--keyword ] [--type official|private] [--page ] [--page-size ] [--limit ]", + flags: { + ...WORKSPACE_FLAG, + keyword: { + type: "string", + valueHint: "", + description: { + "en-US": "Search skill names and descriptions", + "zh-CN": "检索 Skill 名称和描述", + }, + }, + type: { + type: "string", + valueHint: "", + description: { + "en-US": "Filter by source (default: both, case-insensitive)", + "zh-CN": "按来源筛选(默认同时查询两类,不区分大小写)", + }, + }, + page: { + type: "number", + valueHint: "", + description: { "en-US": "Starting page (default 1)", "zh-CN": "起始页码(默认 1)" }, + }, + pageSize: { + type: "number", + valueHint: "", + description: { + "en-US": "Results per request (1–100, default 30)", + "zh-CN": "每次请求的条数(1~100,默认 30)", + }, + }, + limit: { + type: "number", + valueHint: "", + description: { + "en-US": "Maximum results across pages (default one page)", + "zh-CN": "跨页累计返回的最大条数(默认一页)", + }, + }, + }, + notes: [ + { + "en-US": + "Search uses the cloud catalog and a Bailian API key. page_start and page_end identify the requested pages within the API's 10000-record window. installations lists managed, missing and untracked locations.", + "zh-CN": + "使用百炼 API Key 查询云端目录。page_start 和 page_end 表示在接口一万条窗口内实际请求的起止页。installations 列出托管、缺失和未托管的安装位置。", + }, + ], + exampleArgs: ["--keyword pdf --type official", "--page 2 --page-size 10 --limit 25"], + validate({ type, page = 1, pageSize = defaultPageSize, limit = pageSize }) { + if (type !== undefined && !["official", "private"].includes(type.toLowerCase())) + return { + "en-US": "--type must be official or private.", + "zh-CN": "--type 须为 official 或 private。", + }; + if ( + !Number.isSafeInteger(page) || + page < 1 || + !Number.isSafeInteger(pageSize) || + pageSize < 1 || + pageSize > 100 || + page * pageSize > maxWindow + ) + return { + "en-US": + "--page must be a positive integer, --page-size an integer from 1 to 100, and their product at most 10000.", + "zh-CN": "--page 须为正整数,--page-size 须为 1~100 的整数,两者乘积不能超过 10000。", + }; + if (!Number.isSafeInteger(limit) || limit < 1) + return { "en-US": "--limit must be a positive integer.", "zh-CN": "--limit 须为正整数。" }; + }, + async run(ctx) { + const { page = 1, pageSize = defaultPageSize, limit = pageSize } = ctx.flags; + const query = new URLSearchParams({ pageNo: String(page), pageSize: String(pageSize) }); + const keyword = ctx.flags.keyword?.trim(); + if (keyword) query.set("keywords", keyword); + if (ctx.flags.type) + query.set("type", ctx.flags.type.toLowerCase() === "official" ? "OFFICIAL" : "CUSTOMER"); + const path = skillsPath(); + if (ctx.settings.dryRun) { + ctx.output.result({ method: "GET", path: `${path}?${query.toString()}`, limit }); + return; + } + + const local = readCatalogInstalls(ctx.client.baseUrl, "openapi"); + const skills = []; + let pageEnd = page; + let total: number; + for (;;) { + query.set("pageNo", String(pageEnd)); + const { data, request_id } = await requestCatalog( + ctx, + `${path}?${query.toString()}`, + ); + if ( + data.page_no !== pageEnd || + data.page_size !== pageSize || + !Number.isSafeInteger(data.total) || + data.total < 0 || + !Array.isArray(data.items) || + data.items.length > pageSize + ) + invalidCatalogResponse(ctx, request_id); + total = data.total; + for (const item of data.items.slice(0, limit - skills.length)) { + const skill = describeSkill(ctx, item, request_id); + skills.push({ ...skill, ...local.inspect(skill.skill_code, skill.latest_version) }); + } + if ( + ctx.flags.limit === undefined || + skills.length >= limit || + data.items.length === 0 || + pageEnd * pageSize >= total || + (pageEnd + 1) * pageSize > maxWindow + ) + break; + pageEnd++; + } + ctx.output.result({ skills, total, page_start: page, page_end: pageEnd, page_size: pageSize }); + }, +}); diff --git a/packages/commands/src/commands/skill/targets.ts b/packages/commands/src/commands/skill/targets.ts new file mode 100644 index 000000000..66a061cdb --- /dev/null +++ b/packages/commands/src/commands/skill/targets.ts @@ -0,0 +1,240 @@ +import { existsSync, lstatSync, readdirSync, realpathSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { + BailianError, + computeDirContentHash, + detectInstalledAgents, + getSkillsDir, + installationRoots, + isSafeSkillName, + parseSkillNames, + readSkillLock, + type SkillLockEntry, + type SkillLockFile, + type FlagsDef, + type LocalizedText, +} from "bailian-cli-core"; + +export const sourceFlag = { + type: "string", + choices: ["oss", "cloud"], + valueHint: "", + description: { + "en-US": "Skill catalog. Use oss for the public registry or cloud for the workspace OpenAPI.", + "zh-CN": "Skill 目录。oss 表示公开 Registry,cloud 表示工作空间 OpenAPI。", + }, +} as const; +export const selectorFlags = { + name: { + type: "string", + valueHint: "", + description: { + "en-US": "Public OSS registry skill names, separated by commas", + "zh-CN": "公开 OSS Registry 的 Skill 名称,多个名称用逗号分隔", + }, + }, + code: { + type: "string", + valueHint: "", + description: { + "en-US": "Cloud OpenAPI skill codes returned by skill search, separated by commas", + "zh-CN": "skill search 返回的云端 OpenAPI Skill 编码,多个编码用逗号分隔", + }, + }, +} as const satisfies FlagsDef; +export const targetFlags = { + agent: { + type: "string", + valueHint: "", + description: { + "en-US": "Target agent ID, or all detected agents", + "zh-CN": "目标 Agent ID,all 表示全部已检测 Agent", + }, + }, + scope: { + type: "string", + choices: ["user", "project"], + valueHint: "", + description: { "en-US": "Installation scope (default user)", "zh-CN": "安装范围(默认 user)" }, + }, +} as const satisfies FlagsDef; + +export interface Selection { + workspaceId?: string; + agent?: string; + scope?: "user" | "project"; + source?: "oss" | "cloud"; + name?: string; + code?: string; + all?: boolean; + skillVersion?: string; + withMcp?: boolean; + diff?: boolean; +} +export function skillSource(flags: Selection) { + if (flags.all || flags.name !== undefined) return "oss"; + if (flags.code !== undefined) return "cloud"; + return flags.source ?? "cloud"; +} +export function needsCloud(flags: Selection) { + return skillSource(flags) === "cloud"; +} +// A missing directory can still belong to another source and be restored by its next update. +export function otherSourcePaths(source: "cloud" | "oss", lock: SkillLockFile) { + const paths = new Set(); + for (const [key, entry] of Object.entries(lock.skills)) { + if ((entry.sourceType === "openapi" ? "cloud" : "oss") === source) continue; + paths.add(resolve(entry.installedPath ?? join(getSkillsDir(), entry.canonicalName ?? key))); + for (const link of entry.links ?? []) paths.add(resolve(link)); + } + return paths; +} +export function validateSelection( + flags: Selection, + action?: "add" | "remove", +): LocalizedText | undefined { + const hasName = flags.name !== undefined; + const hasCode = flags.code !== undefined; + if ( + (hasName && hasCode) || + (flags.all && (hasName || hasCode)) || + (action && !flags.all && !hasName && !hasCode) + ) { + if (action === "add" || flags.all) + return { + "en-US": "Specify exactly one of --name, --code or --all.", + "zh-CN": "请在 --name、--code、--all 中选择一个。", + }; + return { + "en-US": "Specify either --name or --code.", + "zh-CN": "请在 --name 与 --code 中选择一个。", + }; + } + if (flags.source && flags.source !== skillSource(flags)) + return { + "en-US": + "--name and --all use OSS. --code uses the cloud OpenAPI. Set --source accordingly or omit it.", + "zh-CN": + "--name 和 --all 使用 OSS,--code 使用云端 OpenAPI。请省略 --source 或选择对应来源。", + }; + const selector = flags.name ?? flags.code; + if (selector !== undefined) { + const names = selector.split(",").map((name) => name.trim()); + if ( + names.some((name) => !validName(name)) || + new Set(names).size > 30 || + (hasName && names.includes("all") && names.length > 1) + ) + return { + "en-US": + "Provide 1–30 valid skill names or codes. Use --name all by itself for all registry skills.", + "zh-CN": + "请提供 1~30 个有效的 Skill 名称或编码。选择所有 OSS Skill 可单独使用 --name all。", + }; + } + if (flags.skillVersion !== undefined && !validName(flags.skillVersion)) + return { "en-US": "Invalid --skill-version.", "zh-CN": "--skill-version 无效。" }; + if ( + flags.agent !== undefined && + flags.agent !== "all" && + ![...installationRoots().values()].some( + (root) => root.agent === flags.agent && root.scope === (flags.scope ?? "user"), + ) + ) + return { + "en-US": "Unknown agent or unsupported --scope for this agent.", + "zh-CN": "未知 Agent,或该 Agent 不支持指定的 --scope。", + }; +} +export function validName(name: string) { + return ( + isSafeSkillName(name) && + !name.includes("\0") && + !["skill-lock.json", "skill-lock.json.lock", "__proto__", "constructor", "prototype"].includes( + name, + ) + ); +} +export function selectedNames(flags: Selection) { + if (flags.code !== undefined) + return [...new Set(flags.code.split(",").map((code) => code.trim()))]; + return flags.name === undefined ? "all" : parseSkillNames(flags.name, false); +} +export function entrySelector(key: string, entry: SkillLockEntry) { + const name = entry.canonicalName ?? key; + return entry.sourceType === "openapi" ? (entry.remoteId ?? name) : name; +} +export function selectedEntries(flags: Selection, lock = readSkillLock()) { + const names = selectedNames(flags); + return Object.entries(lock.skills).filter(([key, entry]) => { + if ((entry.scope ?? "user") !== (flags.scope ?? "user")) return false; + if (entry.scope === "project" && entry.projectRoot !== process.cwd()) return false; + if ((entry.sourceType === "openapi" ? "cloud" : "oss") !== skillSource(flags)) return false; + if (flags.agent && flags.agent !== "all" && entry.installedPath && entry.agent !== flags.agent) + return false; + return names === "all" || names.includes(entrySelector(key, entry)); + }); +} +export type Target = { root: string; agent: string | null; scope: "user" | "project" }; +export function installTargets(flags: Selection): Target[] { + const scope = flags.scope ?? "user"; + const agents = new Set(detectInstalledAgents().map((target) => target.id)); + const targets: Target[] = []; + for (const [root, target] of installationRoots()) { + if (!target.agent || target.scope !== scope) continue; + const selected = + flags.agent && flags.agent !== "all" + ? target.agent === flags.agent + : agents.has(target.agent) || (scope === "project" && existsSync(dirname(root))); + if (selected) targets.push({ root, ...target }); + } + if (targets.length === 0 && (!flags.agent || flags.agent === "all")) { + const root = + scope === "user" ? resolve(getSkillsDir()) : join(process.cwd(), ".agents", "skills"); + targets.push({ root, agent: scope === "user" ? null : "universal", scope }); + } + return targets; +} +export function targetForEntry(key: string, entry: SkillLockEntry): Target { + const name = entry.canonicalName ?? key; + const path = entry.installedPath ?? join(getSkillsDir(), name); + const root = dirname(resolve(path)); + const target = installationRoots().get(root); + if ( + !validName(name) || + !target || + resolve(path) !== join(root, name) || + target.agent !== (entry.agent ?? null) || + target.scope !== (entry.scope ?? "user") + ) + throw new BailianError( + "Installation path does not match its agent and scope. / 安装路径与 Agent、范围不符。", + ); + return { root, ...target }; +} +export function present(path: string) { + return !!lstatSync(path, { throwIfNoEntry: false }); +} +export function checkContent(path: string, entry?: SkillLockEntry) { + if (!present(path)) return; + if (!entry) throw new BailianError(`UNTRACKED_CONFLICT: ${path}`); + if (!lstatSync(path).isDirectory()) throw new BailianError(`MODIFIED_CONFLICT: ${path}`); + if (entry.contentHash && /^sha256:[0-9a-f]{64}$/.test(entry.contentHash)) { + function checkTree(directory: string) { + for (const item of readdirSync(directory, { withFileTypes: true })) { + if (item.isDirectory()) checkTree(join(directory, item.name)); + else if (!item.isFile()) throw new BailianError(`MODIFIED_CONFLICT: ${path}`); + } + } + checkTree(path); + if (computeDirContentHash(path) !== entry.contentHash) + throw new BailianError(`MODIFIED_CONFLICT: ${path}`); + } +} +export function checkProjectRoot(target: Target) { + if (target.scope !== "project") return; + let path = target.root; + while (!present(path)) path = dirname(path); + if (realpathSync(path) !== resolve(path)) + throw new BailianError(`Project skill root is redirected / 项目 Skill 目录已被重定向:${path}`); +} diff --git a/packages/commands/src/commands/skill/update-check.ts b/packages/commands/src/commands/skill/update-check.ts new file mode 100644 index 000000000..080809887 --- /dev/null +++ b/packages/commands/src/commands/skill/update-check.ts @@ -0,0 +1,212 @@ +import { createHash } from "node:crypto"; +import { join } from "node:path"; +import { + BailianError, + ExitCode, + defineCommand, + fetchSkillsIndex, + formatCommand, + getConfigDir, + getSkillRegistryBaseUrl, + readSkillLock, + runWithConcurrency, + skillBaseUrl, + skillsPath, + type Command, + type CommandContext, + type FlagsDef, + type SkillsIndex, +} from "bailian-cli-core"; +import { readJson, writeJsonAtomic } from "../config/agent/writers/utils.ts"; +import type { CatalogSkill } from "./catalog.ts"; +import { skillSource, validName, type Selection } from "./targets.ts"; + +type Context = Pick; +type Source = "cloud" | "oss"; +const maxAge = 24 * 60 * 60 * 1000; +const timeoutMs = 2000; + +// Reuse catalog reads from the same invocation, including add's preparation stage. +const cloudReads = new WeakMap>(); +const ossReads = new WeakMap(); + +function activeVersion(skill: CatalogSkill) { + return skill.status === "active" && typeof skill.latest_version === "string" + ? skill.latest_version + : null; +} +export function observeCloudSkill(ctx: Pick, skill: CatalogSkill) { + let latest = cloudReads.get(ctx.client); + if (!latest) { + latest = new Map(); + cloudReads.set(ctx.client, latest); + } + latest.set(skill.id, activeVersion(skill)); +} +export function observeRegistry(ctx: Pick, index: SkillsIndex) { + ossReads.set(ctx.client, index); + return index; +} + +async function checkInstalled(ctx: Context, source: Source, offline: boolean) { + const location = source === "oss" ? getSkillRegistryBaseUrl() : ctx.client.baseUrl; + const installs = Object.entries(readSkillLock().skills).flatMap(([key, entry]) => { + const id = source === "oss" ? (entry.canonicalName ?? key) : entry.remoteId; + const current = source === "oss" ? entry.contentHash : entry.installedVersion; + if ( + !id || + !validName(id) || + !current || + entry.pinnedVersion || + (entry.sourceType === "openapi" ? "cloud" : "oss") !== source || + (entry.sourceLocation && entry.sourceLocation !== location) || + (entry.scope === "project" && entry.projectRoot !== process.cwd()) + ) + return []; + return [{ id, current, scope: entry.scope ?? "user", agent: entry.agent }]; + }); + if (!installs.length) return; + const latest = new Map(); + let index: Promise | undefined; + const signal = AbortSignal.timeout(timeoutMs); + const ids = [...new Set(installs.map((entry) => entry.id))]; + const observed = source === "oss" ? ossReads.get(ctx.client) : undefined; + const versions = source === "cloud" ? cloudReads.get(ctx.client) : undefined; + await runWithConcurrency( + ids.map((id) => async () => { + const digest = createHash("sha256") + .update(JSON.stringify([source, location, id])) + .digest("hex"); + const path = join(getConfigDir(), "skill-update-cache", digest + ".json"); + const cached = readJson(path); + const fresh = + typeof cached?.checkedAt === "number" && + Date.now() - cached.checkedAt >= 0 && + Date.now() - cached.checkedAt < maxAge; + let revision = observed ? (observed.skills[id]?.contentHash ?? null) : versions?.get(id); + if ( + revision === undefined && + fresh && + (typeof cached.revision === "string" || cached.revision === null) + ) { + latest.set(id, cached.revision); + return; + } + try { + if (revision === undefined) { + if (offline || signal.aborted) return; + if (source === "oss") { + index ??= fetchSkillsIndex(timeoutMs, 1); + revision = (await index).skills[id]?.contentHash ?? null; + } else { + const reply = await ctx.client.requestJson<{ success: boolean; data?: CatalogSkill }>({ + method: "GET", + path: skillsPath(id), + signal, + }); + if (!reply?.success || reply.data?.id !== id) return; + revision = activeVersion(reply.data); + } + } + latest.set(id, revision); + if (!fresh || cached.revision !== revision) + writeJsonAtomic(path, { checkedAt: Date.now(), revision }); + } catch { + // A secondary lookup or a read-only cache directory cannot fail the command. + } + }), + 3, + ); + for (const scope of ["user", "project"] as const) { + const outdated = installs.filter((entry) => { + const revision = latest.get(entry.id); + return ( + entry.scope === scope && + revision && + (source === "oss" + ? revision !== entry.current + : revision.localeCompare(entry.current, "en", { numeric: true }) > 0) + ); + }); + if (!outdated.length) continue; + const names = [...new Set(outdated.map((entry) => entry.id))].join(", "); + const command = formatCommand( + ctx.identity, + `skill update${source === "oss" ? " --all" : ""}${scope === "project" ? " --scope project" : ""}`, + ); + ctx.output.warning({ + code: "SKILL_UPDATE_AVAILABLE", + message: { + "en-US": `Updates available for ${names}. Run ${command}.`, + "zh-CN": `${names} 有更新,可运行 ${command}。`, + }, + details: { + source, + scope, + update_command: command, + skills: outdated.map(({ id, current, agent }) => ({ + skill_code: id, + agent, + current, + latest: latest.get(id), + })), + }, + }); + } +} + +export function defineSkillCommand({ + updateCheck, + localDryRun, + ...command +}: Command & { + updateCheck?: "oss" | "offline"; + localDryRun?: boolean; +}): Command { + return defineCommand({ + ...command, + defaultApiBaseUrl({ flags, settings, localize }) { + const selection: Selection = flags as Selection; + if (updateCheck || (localDryRun && settings.dryRun)) return; + // Public packages only use the cloud when add checks their MCP dependencies. + const source = skillSource(selection); + if (source === "oss" && (!command.prepare || selection.withMcp === false)) return; + const id = selection.workspaceId ?? settings.workspaceId; + if (id) return skillBaseUrl(id); + if (source === "oss") return; + throw new BailianError( + localize({ + "en-US": + "Set workspace_id or BAILIAN_WORKSPACE_ID, pass --workspace-id, or provide --base-url to access the cloud Skill API.", + "zh-CN": + "访问云端 Skill API 需要配置 workspace_id、设置 BAILIAN_WORKSPACE_ID,或传入 --workspace-id、--base-url。", + }), + ExitCode.USAGE, + ); + }, + async run(ctx) { + try { + await command.run(ctx); + if (ctx.settings.dryRun) return; + const source = updateCheck === "oss" ? "oss" : skillSource(ctx.flags as Selection); + try { + const offline = updateCheck === "offline"; + const workspaceId = ctx.settings.workspaceId; + const client = + offline && source === "cloud" && workspaceId + ? ctx.client.withDefaultBaseUrl(() => skillBaseUrl(workspaceId)) + : ctx.client; + await checkInstalled({ ...ctx, client }, source, offline); + } catch { + ctx.output.debug({ + "en-US": "Skill update check unavailable.", + "zh-CN": "暂时无法检查 Skill 更新。", + }); + } + } finally { + cloudReads.delete(ctx.client); + ossReads.delete(ctx.client); + } + }, + }); +} diff --git a/packages/commands/src/commands/skill/update.ts b/packages/commands/src/commands/skill/update.ts index 795ee99b2..cc1c8be3f 100644 --- a/packages/commands/src/commands/skill/update.ts +++ b/packages/commands/src/commands/skill/update.ts @@ -1,242 +1,75 @@ +import { WORKSPACE_FLAG } from "../shared/workspace.ts"; +import { defineSkillCommand } from "./update-check.ts"; +import { runSkillLifecycle, useTargetRecords, withSkillMutation } from "./lifecycle.ts"; +import { runRegistryLifecycle } from "./registry-lifecycle.ts"; import { - formatCommand, - BailianError, - ExitCode, - defineCommand, - detectInstalledAgents, - fanOutSkillToAgents, - fetchSkillsIndex, - getSkillRegistryBaseUrl, - installSkillWithFanout, - listSkillDirsOnDisk, - parseSkillNames, - readSkillLock, - runWithConcurrency, - writeSkillLock, -} from "bailian-cli-core"; -import { formatTable } from "bailian-cli-runtime"; -import { planFanoutLinks, summarizeAgents } from "./dry-run-plan.ts"; + needsCloud, + selectorFlags, + sourceFlag, + targetFlags, + validateSelection, +} from "./targets.ts"; -interface UpdateOutcome { - name: string; - status: "updated" | "up-to-date" | "skipped" | "failed"; - publishedAt?: string; - reason?: string; -} - -interface UpdatePlanItem { - name: string; - status: "update" | "up-to-date" | "skipped" | "failed"; - publishedAt?: string; - reason?: string; - links?: ReturnType; -} - -/** Max number of skills downloading/installing at the same time. */ -const UPDATE_CONCURRENCY = 3; - -export default defineCommand({ +export default defineSkillCommand({ description: { "en-US": "Update installed skills to the latest registry versions", "zh-CN": "将已安装的 Skill 更新到 Registry 最新版本", }, - auth: "none", + auth: "apiKey", + requiresApiKey: needsCloud, defaultOutput: "json", - usageArgs: "[--all] [--name ]", + usageArgs: + "[--name | --code | --all] [--agent ] [--scope user|project] [--diff]", flags: { - all: { + ...WORKSPACE_FLAG, + source: sourceFlag, + ...targetFlags, + diff: { type: "switch", description: { - "en-US": "Update all installed skills (default when neither --all nor --name is given)", - "zh-CN": "更新全部已安装 Skill(未指定 --all 或 --name 时的默认行为)", + "en-US": "Show changed files, or the required download in a preview", + "zh-CN": "显示文件差异,预览时标明所需下载", }, }, - name: { - type: "string", - valueHint: "", + all: { + type: "switch", description: { - "en-US": "Comma-separated skill names to update (must be already installed)", - "zh-CN": "要更新的 Skill 名称,以逗号分隔(必须已安装)", + "en-US": "Update all installed public OSS skills in the selected scope", + "zh-CN": "更新所选范围内全部已安装的公开 OSS Skill", }, }, + ...selectorFlags, }, + notes: [ + { + "en-US": + "--name all is an alias for --all. With no selector, update installed cloud skills in the selected scope.", + "zh-CN": "--name all 是 --all 的兼容写法。省略选择参数时,更新所选范围内已安装的云端 Skill。", + }, + { + "en-US": + "Other Skill commands check for updates to unpinned installations from the selected source. Available updates appear on stderr. Removal uses the cached check offline.", + "zh-CN": + "其他 Skill 命令会检查所选来源中未固定版本的安装项,有更新时在 stderr 提示。卸载时仅读取有效缓存。", + }, + ], validate(flags) { - if (flags.all && flags.name) return "Use either --all or --name, not both"; - return undefined; + return validateSelection(flags); }, - exampleArgs: ["", "--all", "--name spark-video"], - async run(ctx) { - const updateAll = ctx.flags.all || !ctx.flags.name; - const requested = updateAll ? "all" : parseSkillNames(ctx.flags.name, false); - const index = await fetchSkillsIndex(); - const lock = readSkillLock(); - const disk = new Set(listSkillDirsOnDisk()); - const agents = detectInstalledAgents(); - - const results: UpdateOutcome[] = []; - const targets: string[] = []; + exampleArgs: [ + "", + "--all", + "--name spark-video", + "--code skill_example --agent cursor --scope project --diff --dry-run", + ], - if (requested === "all") { - // Default: only process skills already installed in lock; reinstall only if version changed or local dir is missing - for (const [name, locked] of Object.entries(lock.skills)) { - const entry = index.skills[name]; - if (!entry) { - results.push({ - name, - status: "skipped", - reason: "delisted from remote; local copy retained", - }); - continue; - } - if (entry.contentHash === locked.contentHash && disk.has(name)) { - if (ctx.settings.dryRun) { - // 真实路径仍会 fan-out 自愈;dry-run 只展示目标路径与存在性,不写盘 - results.push({ name, status: "up-to-date", publishedAt: locked.publishedAt }); - continue; - } - // Self-healing: content unchanged, but still fill fan-out links for agents - // detected since the last install (and refresh recorded copies); the merged - // ledger keeps paths of unvisited agents reclaimable by bl skill remove - const fanout = fanOutSkillToAgents(name, agents, locked.links ?? []); - lock.skills[name] = { ...locked, links: fanout.links }; - results.push({ name, status: "up-to-date", publishedAt: locked.publishedAt }); - continue; - } - targets.push(name); - } - } else { - // Explicit names: only update skills that are already installed; reject uninstalled ones - for (const name of requested) { - if (!lock.skills[name]) { - results.push({ - name, - status: "failed", - reason: - `not installed; run ${formatCommand(ctx.identity, "skill add")} --name ` + - name + - " first", - }); - continue; - } - targets.push(name); - } - } - - if (ctx.settings.dryRun) { - const plan: UpdatePlanItem[] = results.map((result) => { - if (result.status === "up-to-date") { - return { - name: result.name, - status: "up-to-date" as const, - publishedAt: result.publishedAt, - links: planFanoutLinks(result.name, agents), - }; - } - if (result.status === "skipped") { - return { - name: result.name, - status: "skipped" as const, - publishedAt: result.publishedAt, - reason: result.reason, - }; - } - return { - name: result.name, - status: "failed" as const, - publishedAt: result.publishedAt, - reason: result.reason, - }; - }); - - for (const name of targets) { - const entry = index.skills[name]; - if (!entry) { - plan.push({ name, status: "failed", reason: "skill not found in registry" }); - continue; - } - plan.push({ - name, - status: "update", - publishedAt: entry.publishedAt, - links: planFanoutLinks(name, agents), - }); - } - - ctx.output.result({ - action: "skill.update", - registry: getSkillRegistryBaseUrl(), - agents: summarizeAgents(agents), - skills: plan, - }); - - const failed = plan.filter((item) => item.status === "failed"); - if (failed.length > 0) { - throw new BailianError( - `${failed.length} skill(s) failed to update`, - ExitCode.GENERAL, - `Check the reason for failed skills in the output; network failures can be retried with ${formatCommand(ctx.identity, "skill update")}`, - ); - } - return; - } - - const tasks = targets.map((name) => async (): Promise => { - const entry = index.skills[name]; - if (!entry) { - return { name, status: "failed", reason: "skill not found in registry" }; - } - try { - const record = await installSkillWithFanout( - name, - entry, - agents, - lock.skills[name]?.links ?? [], - ); - lock.skills[name] = record.lockEntry; - return { name, status: "updated", publishedAt: entry.publishedAt }; - } catch (err) { - return { - name, - status: "failed", - reason: err instanceof Error ? err.message : String(err), - }; - } - }); - const updateResults = await runWithConcurrency(tasks, UPDATE_CONCURRENCY); - results.push(...updateResults); - writeSkillLock(lock); - - const rows = results.map((result) => [ - result.name, - result.status, - result.publishedAt ? result.publishedAt.slice(0, 10) : "-", - ]); - const lines = - results.length === 0 - ? [ - ctx.localize({ - "en-US": `No skills installed locally; run ${formatCommand(ctx.identity, "skill add")} first.`, - "zh-CN": `本地未安装 Skill,请先运行 ${formatCommand(ctx.identity, "skill add")}。`, - }), - ] - : formatTable(["NAME", "STATUS", "PUBLISHED"], rows); - const annotated = results.filter( - (result) => (result.status === "skipped" || result.status === "failed") && result.reason, - ); - if (annotated.length > 0) - lines.push("", ...annotated.map((result) => ` ${result.name}: ${result.reason}`)); - ctx.output.result( - { registry: getSkillRegistryBaseUrl(), skills: results }, - { text: lines.join("\n") }, + async run(ctx) { + const report = await withSkillMutation(ctx, async () => + useTargetRecords(ctx.flags) + ? runSkillLifecycle("update", ctx, ctx.flags) + : runRegistryLifecycle("update", ctx, ctx.flags), ); - - const failed = results.filter((result) => result.status === "failed"); - if (failed.length > 0) { - throw new BailianError( - `${failed.length} skill(s) failed to update`, - ExitCode.GENERAL, - `Check the reason for failed skills in the output; network failures can be retried with ${formatCommand(ctx.identity, "skill update")}`, - ); - } + ctx.output.result(report.data, "text" in report ? { text: report.text } : undefined); + if (report.firstError) throw report.firstError; }, }); diff --git a/packages/commands/src/commands/update.ts b/packages/commands/src/commands/update.ts index 3b0d63a31..57561ef94 100644 --- a/packages/commands/src/commands/update.ts +++ b/packages/commands/src/commands/update.ts @@ -23,7 +23,7 @@ import { performBinaryUpdate, } from "bailian-cli-runtime"; -const SKILL_UPDATE_CMD = "bl skill update"; +const SKILL_UPDATE_CMD = "bl skill update --all"; /** Own nested output so installer and skill subprocesses cannot corrupt stdout. */ function runUpdateCommand(command: string, output: CommandOutput, jsonDiagnostics = false): Buffer { @@ -119,8 +119,8 @@ function updateAgentSkill( : undefined; output.warning({ message: { - "en-US": `Agent skill update skipped. Run manually: ${formatCommand(invocation, "skill update")}`, - "zh-CN": `已跳过 Agent Skill 更新。请手动运行:${formatCommand(invocation, "skill update")}`, + "en-US": `Agent skill update skipped. Run manually: ${formatCommand(invocation, "skill update --all")}`, + "zh-CN": `已跳过 Agent Skill 更新。请手动运行:${formatCommand(invocation, "skill update --all")}`, }, code: "SKILL_UPDATE_SKIPPED", details: { exit_code: failure?.status, signal: failure?.signal, error: failure?.diagnostic }, diff --git a/packages/commands/src/index.ts b/packages/commands/src/index.ts index fcec12708..c0c9351b2 100644 --- a/packages/commands/src/index.ts +++ b/packages/commands/src/index.ts @@ -100,11 +100,20 @@ export { default as knowledgeFileDelete } from "./commands/knowledge/file-delete export { default as knowledgeCollectionCreate } from "./commands/knowledge/collection-create.ts"; export { default as knowledgeCollectionGet } from "./commands/knowledge/collection-get.ts"; export { default as knowledgeDocImportOss } from "./commands/knowledge/doc-import-oss.ts"; +export { default as mcpActivate } from "./commands/mcp/activate.ts"; export { default as mcpCall } from "./commands/mcp/call.ts"; export { default as mcpConnect } from "./commands/mcp/connect.ts"; +export { default as mcpCreate } from "./commands/mcp/create.ts"; +export { default as mcpDeactivate } from "./commands/mcp/deactivate.ts"; +export { default as mcpDelete } from "./commands/mcp/delete.ts"; export { default as mcpDisconnect } from "./commands/mcp/disconnect.ts"; +export { default as mcpGet } from "./commands/mcp/get.ts"; export { default as mcpList } from "./commands/mcp/list.ts"; export { default as mcpTools } from "./commands/mcp/tools.ts"; +export { default as mcpToolCall } from "./commands/mcp/tool-call.ts"; +export { default as mcpToolList } from "./commands/mcp/tool-list.ts"; +export { default as mcpToolSearch } from "./commands/mcp/tool-search.ts"; +export { default as mcpUpdate } from "./commands/mcp/update.ts"; export { default as searchWeb } from "./commands/search/web.ts"; export { default as speechSynthesize } from "./commands/speech/synthesize.ts"; export { default as speechRecognize } from "./commands/speech/recognize.ts"; @@ -381,6 +390,8 @@ export { default as pluginLink } from "./commands/plugin/link.ts"; export { default as pluginList } from "./commands/plugin/list.ts"; export { default as pluginRemove } from "./commands/plugin/remove.ts"; export { default as skillAdd } from "./commands/skill/add.ts"; +export { default as skillSearch } from "./commands/skill/search.ts"; +export { default as skillGet } from "./commands/skill/get.ts"; export { default as skillUpdate } from "./commands/skill/update.ts"; export { default as skillRemove } from "./commands/skill/remove.ts"; export { default as skillList } from "./commands/skill/list.ts"; diff --git a/packages/commands/tests/e2e/console-flags-dry-run.e2e.test.ts b/packages/commands/tests/e2e/console-flags-dry-run.e2e.test.ts index a60c39a82..40eb98a4b 100644 --- a/packages/commands/tests/e2e/console-flags-dry-run.e2e.test.ts +++ b/packages/commands/tests/e2e/console-flags-dry-run.e2e.test.ts @@ -98,7 +98,7 @@ describe("e2e: console global flags (dry-run)", () => { expect(stderr).toMatch(/(?:Unknown flag|未知参数).*--region/); }); - test("mcp list --dry-run --console-region 透传", async () => { + test("mcp list uses API-key authentication and rejects --console-region", async () => { const { stdout, stderr, exitCode } = await runCommandInProcess(CONSOLE_FLAGS_DRY_RUN_ROUTES, [ "mcp", "list", @@ -108,9 +108,9 @@ describe("e2e: console global flags (dry-run)", () => { "--console-region", "cn-hangzhou", ]); - expect(exitCode, stderr).toBe(0); - const data = parseStdoutJson(stdout); - expect(data.consoleRegion).toBe("cn-hangzhou"); + expect(exitCode, stderr).toBe(2); + expect(stdout).toBe(""); + expect(stderr).toContain("--console-region"); }); test("quota check --dry-run --console-region 透传", async () => { diff --git a/packages/commands/tests/e2e/fixtures/mcp-detail.ts b/packages/commands/tests/e2e/fixtures/mcp-detail.ts new file mode 100644 index 000000000..0c8c3449f --- /dev/null +++ b/packages/commands/tests/e2e/fixtures/mcp-detail.ts @@ -0,0 +1,40 @@ +import { createServer } from "node:http"; +import { afterAll, beforeAll } from "vite-plus/test"; + +/** Read-only detail endpoint shared by the native Agent subprocess smoke tests. */ +export function activeMcpFixture(code: string) { + const endpoint = `https://workspace.fixture.example/api/v1/mcps/${code}/mcp`; + const fixture = { baseUrl: "", endpoint }; + const server = createServer((request, response) => { + if (request.method !== "GET" || request.url !== `/api/v1/mcp/servers/${code}`) { + response.writeHead(404).end(); + return; + } + response.setHeader("Content-Type", "application/json"); + response.end( + JSON.stringify({ + success: true, + data: { + mcp_code: code, + type: "OFFICIAL", + server_status: "ACTIVATED", + dashscope_endpoint: endpoint, + }, + }), + ); + }); + beforeAll(async () => { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Expected a local TCP port"); + fixture.baseUrl = `http://127.0.0.1:${address.port}`; + }); + afterAll(async () => { + server.closeAllConnections(); + await new Promise((resolve) => server.close(() => resolve())); + }); + return fixture; +} diff --git a/packages/commands/tests/e2e/mcp-management.e2e.test.ts b/packages/commands/tests/e2e/mcp-management.e2e.test.ts new file mode 100644 index 000000000..ec045efe5 --- /dev/null +++ b/packages/commands/tests/e2e/mcp-management.e2e.test.ts @@ -0,0 +1,1676 @@ +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { httpTransport } from "bailian-cli-core"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + test, + vi, +} from "vite-plus/test"; +import { runCommandHelp, runCommandInProcess } from "./helpers.ts"; +import { MCP_ROUTES, SKILL_ROUTES } from "./topic-routes.ts"; + +const collection = "/api/v1/mcp/servers"; +const code = "mcp-example"; +const item = `${collection}/${code}`; +const remoteConfig = { + url: "https://mcp.example.com", + headers: { "X-My-Token": "private-fixture" }, +}; +const configArgs = ["--mcp-type", "http", "--mcp-config", JSON.stringify(remoteConfig)]; +const createArgs = [ + "create", + "--name", + "weather", + "--description", + "Weather lookup", + ...configArgs, +]; +const target = ["--server", code]; +const initialize = { + status: 200, + body: { + protocolVersion: "2024-11-05", + capabilities: { tools: {} }, + serverInfo: { name: "fixture", version: "1" }, + }, +}; +let requests: { method?: string; path?: string; auth?: string; body: string }[]; +let replies: ({ status: number; body: unknown } | "disconnect")[]; +const gateway = createServer(async (request, response) => { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(Buffer.from(chunk)); + requests.push({ + method: request.method, + path: request.url, + auth: request.headers.authorization, + body: Buffer.concat(chunks).toString(), + }); + if (request.url === "/protocol") { + if (request.method !== "POST") { + response.writeHead(405).end(); + return; + } + const message = JSON.parse(Buffer.concat(chunks).toString()); + if (message.id === undefined) { + response.writeHead(202).end(); + return; + } + const page = replies.shift(); + if (page === undefined || page === "disconnect") { + response.writeHead(500).end(); + return; + } + response.writeHead(page.status, { "Content-Type": "application/json" }); + if (page.status >= 400) { + response.end(JSON.stringify(page.body)); + return; + } + const payload = + page.body && typeof page.body === "object" && "error" in page.body + ? page.body + : { result: page.body }; + response.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, ...payload })); + return; + } + const reply = replies.shift() ?? { status: 500, body: { message: "Unexpected request" } }; + if (reply === "disconnect") { + response.destroy(); + return; + } + response.writeHead(reply.status, { "Content-Type": "application/json" }); + response.end(JSON.stringify(reply.body)); +}); +let origin: string; +let directory: string; +beforeAll(async () => { + await new Promise((resolve, reject) => { + gateway.once("error", reject); + gateway.listen(0, "127.0.0.1", resolve); + }); + const address = gateway.address(); + if (!address || typeof address === "string") throw new Error("Expected a local TCP server."); + origin = `http://127.0.0.1:${address.port}`; +}); +afterAll(async () => { + gateway.closeAllConnections(); + await new Promise((resolve) => gateway.close(() => resolve())); +}); +beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "bl-mcp-management-")); + requests = []; + replies = []; +}); +afterEach(() => rmSync(directory, { recursive: true, force: true })); + +function run(args: string[], overrides: NodeJS.ProcessEnv = {}) { + return runCommandInProcess( + MCP_ROUTES, + ["mcp", ...args, "--output", "json"], + { + DASHSCOPE_API_KEY: "offline-key", + DASHSCOPE_BASE_URL: origin, + BAILIAN_WORKSPACE_ID: "", + NODE_OPTIONS: "", + HTTP_PROXY: "", + HTTPS_PROXY: "", + ALL_PROXY: "", + NO_PROXY: "", + http_proxy: "", + https_proxy: "", + all_proxy: "", + no_proxy: "", + NODE_USE_ENV_PROXY: "", + ...overrides, + }, + { cwd: directory }, + ); +} +function reply(data: unknown, status = 200) { + replies.push({ status, body: { success: true, data, request_id: "req-write" } }); +} +function detail(status = "INACTIVE", type = "CUSTOMER") { + reply({ + mcp_code: code, + type, + server_name: "original", + server_status: status, + mcp_config: remoteConfig, + }); +} +function expectRequests(...expected: [string, string, unknown?][]) { + expect(requests).toEqual( + expected.map(([method, path, body]) => ({ + method, + path, + auth: "Bearer offline-key", + body: body === undefined ? "" : expect.any(String), + })), + ); + expected.forEach(([, , body], index) => { + if (body !== undefined) expect(JSON.parse(requests[index]!.body)).toEqual(body); + }); +} + +test("MCP OpenAPI selects the production workspace origin and honors explicit base URLs", async ({ + onTestFinished, +}) => { + const urls: string[] = []; + const fetch = vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + urls.push(request.url); + expect(request.headers.get("Authorization")).toBe("Bearer offline-key"); + return Response.json({ success: true, data: [] }); + }); + onTestFinished(() => fetch.mockRestore()); + writeFileSync(join(directory, "config.json"), JSON.stringify({ workspace_id: "ws-config" })); + const env = { BAILIAN_CONFIG_DIR: directory, DASHSCOPE_BASE_URL: "" }; + const args = ["tool", "list", ...target]; + for (const [extra, overrides] of [ + [[], {}], + [[], { BAILIAN_WORKSPACE_ID: "ws-env" }], + [["--workspace-id", "ws-flag"], { BAILIAN_WORKSPACE_ID: "ws-env" }], + [["--base-url", origin], {}], + ] as const) { + const result = await run([...args, ...extra], { ...env, ...overrides }); + expect(result.exitCode, result.stderr).toBe(0); + } + expect(urls).toEqual( + [ + "https://ws-config.cn-beijing.maas.aliyuncs.com", + "https://ws-env.cn-beijing.maas.aliyuncs.com", + "https://ws-flag.cn-beijing.maas.aliyuncs.com", + origin, + ].map((base) => base + item + "/tools"), + ); + writeFileSync(join(directory, "config.json"), "{}"); + const missing = await run(args, env); + expect(missing.exitCode, missing.stderr).toBe(2); + expect(missing.stderr).toContain("--workspace-id"); + const invalid = await run([...args, "--workspace-id", "other.example/path"], env); + expect(invalid.exitCode, invalid.stderr).toBe(2); + const preview = await run([...args, "--dry-run"], env); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(urls).toHaveLength(4); +}); + +describe("MCP tool discovery", () => { + const properties = { orderId: { type: "object", additionalProperties: false } }; + const schema = { type: "object", properties, required: ["orderId"], additionalProperties: false }; + const publicSchema = { + type: "object", + properties, + required: ["orderId"], + additional_properties: false, + }; + const recommendation = `${collection}/tools/recommend`; + + test("tool search previews locally and requests recommendations directly", async () => { + const args = ["tool", "search", "--query", " 查订单 "]; + const preview = await run([...args, "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout)).toMatchObject({ + plan: { query: "查订单", limit: 10 }, + risk: null, + }); + expectRequests(); + reply([]); + const result = await run(args); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([]); + expectRequests(["GET", `${recommendation}?query=${encodeURIComponent("查订单")}&topN=10`]); + }); + + test("tool search encodes the query, limits results in order and keeps schema property names", async () => { + reply([ + { serverCode: "one", toolName: "lookup", toolInputSchema: schema, score: 10 }, + { + server_code: "two", + tool_name: "other", + tool_description: "Order status", + tool_input_schema: null, + }, + { server_code: "three", tool_name: "discarded" }, + ]); + const result = await run(["tool", "search", "--query", " 订单 &+% ", "--limit", "2"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([ + { + server_code: "one", + tool_name: "lookup", + tool_description: null, + tool_input_schema: publicSchema, + }, + { + server_code: "two", + tool_name: "other", + tool_description: "Order status", + tool_input_schema: null, + }, + ]); + expectRequests(["GET", `${recommendation}?query=%E8%AE%A2%E5%8D%95+%26%2B%25&topN=2`]); + }); + + test("tool search exposes the recommended mcp_code as server_code", async () => { + reply([ + { + mcp_code: "weather", + tool_name: "forecast", + tool_description: "Forecast", + tool_input_schema: schema, + }, + { mcpCode: "orders", toolName: "lookup" }, + ]); + const result = await run(["tool", "search", "--query", "lookup"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([ + { + server_code: "weather", + tool_name: "forecast", + tool_description: "Forecast", + tool_input_schema: publicSchema, + }, + { + server_code: "orders", + tool_name: "lookup", + tool_description: null, + tool_input_schema: null, + }, + ]); + expectRequests(["GET", `${recommendation}?query=lookup&topN=10`]); + }); + + test.each([ + ["tool", "search", "--query", " "], + ...["0", "-1", "1.5", "2147483648"].map((limit) => [ + "tool", + "search", + "--query", + "order", + "--limit", + limit, + ]), + ["tool", "list", "--server", ".."], + ["tools", "--server", " "], + ["tools", ...target, "--url", "missing-scheme"], + ])("invalid discovery flags %s %s %s %s fail locally", async (...args) => { + const result = await run(args); + expect(result.exitCode, result.stderr).toBe(2); + expectRequests(); + }); + + test("tool list directly retrieves the public tool definitions", async () => { + const server = "name/with space"; + const path = `${collection}/name%2Fwith%20space`; + reply([ + { name: "lookup", description: "Find order", input_schema: publicSchema, internal: true }, + ]); + const result = await run(["tool", "list", "--server", server]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual([ + { name: "lookup", description: "Find order", input_schema: publicSchema }, + ]); + expectRequests(["GET", `${path}/tools`]); + }); + + test("tool list previews offline and preserves upstream failures", async () => { + const args = ["tool", "list", ...target]; + const preview = await run([...args, "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout)).toMatchObject({ + plan: { server: code }, + risk: null, + }); + expectRequests(); + replies.push({ + status: 200, + body: { + success: false, + error_code: "NotAvailable", + error_msg: "原始服务错误", + request_id: "req-tools", + }, + }); + const failed = await run(args); + expect(failed.exitCode).toBe(1); + expect(failed.stdout).toBe(""); + expect(JSON.parse(failed.stderr).error).toMatchObject({ + api_code: "NotAvailable", + message: "原始服务错误", + request_id: "req-tools", + }); + expectRequests(["GET", `${item}/tools`]); + }); + + test.each([ + { args: ["tool", "list", ...target], data: { items: [] } }, + { + args: ["tool", "search", "--query", "order"], + data: [{ tool_name: "missing_server_code" }], + }, + ])("rejects malformed discovery data for $args", async ({ args, data }) => { + reply(data); + const result = await run(args); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + expect(JSON.parse(result.stderr).error.request_id).toBe("req-write"); + }); + + test.each(["initialize", "tools/list"])( + "native tools preserves HTTP failures during %s", + async (stage) => { + if (stage === "tools/list") replies.push(initialize); + replies.push({ + status: stage === "initialize" ? 401 : 404, + body: { + message: "original upstream failure", + code: "ServerReportedCode", + request_id: "req-protocol", + }, + }); + const result = await run(["tools", ...target, "--url", `${origin}/protocol`]); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + expect(JSON.parse(result.stderr).error).toMatchObject({ + message: expect.stringContaining("original upstream failure"), + api_code: "ServerReportedCode", + http_status: stage === "initialize" ? 401 : 404, + request_id: "req-protocol", + }); + if (stage === "initialize") + expect(requests.map((request) => request.method)).toEqual(["POST"]); + }, + ); + + test("native tools keeps an explicit upstream auth code and the JSON-RPC message", async () => { + replies.push(initialize, { + status: 200, + body: { + error: { + code: -32003, + message: "Upstream credentials expired", + data: { error_code: "UPSTREAM_AUTH_FAILED", request_id: "req-rpc" }, + }, + }, + }); + const result = await run(["tools", ...target, "--url", `${origin}/protocol`]); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stderr).error).toMatchObject({ + message: "MCP error (-32003): Upstream credentials expired", + api_code: "UPSTREAM_AUTH_FAILED", + request_id: "req-rpc", + }); + }); + + test.each([false, true])("native tools follows opaque cursors (repeated=%s)", async (repeat) => { + const first = { name: "one", inputSchema: { type: "object" }, _meta: { source: "native" } }; + const second = { name: "two", inputSchema: { type: "object" } }; + const cursor = "page /+"; + const url = `${origin}/protocol`; + replies.push( + initialize, + { status: 200, body: { tools: [first], nextCursor: cursor } }, + { status: 200, body: { tools: [second], ...(repeat ? { nextCursor: cursor } : {}) } }, + ); + const result = await run(["tools", ...target, "--url", url]); + const messages = requests + .filter((request) => request.method === "POST") + .map((request) => JSON.parse(request.body)); + expect(messages.map((message) => message.method)).toEqual([ + "initialize", + "notifications/initialized", + "tools/list", + "tools/list", + ]); + expect(messages.at(-1).params.cursor).toBe(cursor); + if (repeat) { + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + } else { + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ server: code, url, tools: [first, second] }); + } + }); +}); + +describe("MCP tool invocation", () => { + const args = ["tool", "call", ...target, "--tool", "get.order"]; + const path = `${item}/tools/call`; + + test("OpenAPI previews merged arguments locally and sends the tool request directly", async () => { + const preview = await run([...args, "--query", "业务查询", "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout)).toMatchObject({ + plan: { + action: "call_tool", + server: code, + tool: "get.order", + tool_params: { query: "业务查询" }, + }, + risk: null, + }); + expectRequests(); + reply({ is_error: false, content: [] }); + const called = await run([...args, "--arg", "value=fixture-sensitive"]); + expect(called.exitCode, called.stderr).toBe(0); + expect(called.stdout + called.stderr).not.toContain("fixture-sensitive"); + expectRequests([ + "POST", + path, + { tool_name: "get.order", tool_params: { value: "fixture-sensitive" } }, + ]); + }); + + test("OpenAPI encodes the server in the path and sends the literal tool name and merged parameters in the body", async () => { + const server = "srv /one"; + const tool = "查/订单?#"; + const options = [ + "--json", + '{"orderId":"old","nested":{"keepCase":null},"query":1,"__proto__":"base"}', + "--arg", + "orderId=new=value", + "--arg", + "number=0", + "--arg", + "items=[true,null]", + "--arg", + "query=false", + "--arg", + "__proto__=literal", + "--arg", + "empty=", + "--query", + "42", + ]; + const content = [{ type: "text", text: '{"OrderId":3}' }, { type: "image" }]; + reply({ isError: false, content }); + const called = await run(["tool", "call", "--server", server, "--tool", tool, ...options]); + expect(called.exitCode, called.stderr).toBe(0); + expect(JSON.parse(called.stdout)).toEqual({ is_error: false, content }); + expectRequests([ + "POST", + `${collection}/srv%20%2Fone/tools/call`, + { + tool_name: tool, + tool_params: { + orderId: "new=value", + nested: { keepCase: null }, + query: "42", + ["__proto__"]: "literal", + number: 0, + items: [true, null], + empty: "", + }, + }, + ]); + expect(Object.hasOwn(JSON.parse(requests[0]!.body).tool_params, "__proto__")).toBe(true); + }); + + test("a parameterless tool with a dot-segment name is sent in the body and retains nullable results", async () => { + reply({ is_error: null, content: null }); + const called = await run(["tool", "call", ...target, "--tool", ".."]); + expect(called.exitCode, called.stderr).toBe(0); + expect(JSON.parse(called.stdout)).toEqual({ is_error: null, content: null }); + expectRequests(["POST", path, { tool_name: "..", tool_params: {} }]); + }); + + test.each(["is_error", "isError"])( + "OpenAPI reports tool failure with %s even on HTTP 200", + async (key) => { + const content = [ + { type: null, text: "原始服务错误" }, + { type: "image" }, + { type: "text", text: "more detail" }, + ]; + reply({ [key]: true, content }); + const called = await run(args); + expect(called.exitCode).toBe(1); + expect(JSON.parse(called.stdout)).toEqual({ is_error: true, content }); + expect(JSON.parse(called.stderr).error).toMatchObject({ + message: "原始服务错误\nmore detail", + request_id: "req-write", + }); + expectRequests(["POST", path, { tool_name: "get.order", tool_params: {} }]); + }, + ); + + test.each([400, 200])("OpenAPI preserves envelope failures on HTTP %i", async (status) => { + replies.push({ + status, + body: { + success: false, + data: null, + error_code: "CallFailed", + error_msg: "Call failed upstream", + request_id: "request-call", + }, + }); + const called = await run(args); + expect(called.exitCode).toBe(1); + expect(called.stdout).toBe(""); + expect(JSON.parse(called.stderr).error).toMatchObject({ + api_code: "CallFailed", + message: "Call failed upstream", + request_id: "request-call", + }); + expectRequests(["POST", path, { tool_name: "get.order", tool_params: {} }]); + }); + + test.each([{ is_error: "false" }, { content: [42] }, { unrelated: true }])( + "rejects malformed tool result %j", + async (data) => { + reply(data); + const called = await run(args); + expect(called.exitCode).toBe(1); + expect(called.stdout).toBe(""); + expect(JSON.parse(called.stderr).error.request_id).toBe("req-write"); + }, + ); + + test.each([ + ["tool", "call", "--server", "..", "--tool", "get.order"], + ["tool", "call", ...target, "--tool", " "], + [...args, "--json", "null"], + [...args, "--arg", " =123"], + ["call", "--target", " .name"], + ["call", "--target", "srv.tool", "--url", "no-scheme"], + ["call", "--target", "srv.tool", "--json", ""], + ])("invalid call flags %j fail before any request", async (...argv) => { + const invalid = await run(argv); + expect(invalid.exitCode, invalid.stderr).toBe(2); + expectRequests(); + }); + + test.each([false, true])( + "native call sends tools/call once and preserves the result contract (error=%s)", + async (isError) => { + const result = { + isError, + content: [{ type: "text", text: "native tool message" }], + structuredContent: { orderId: "A1" }, + }; + replies.push(initialize, { status: 200, body: result }); + const called = await run([ + "call", + "--target", + "srv.get.order", + "--url", + `${origin}/protocol`, + "--json", + '{"orderId":1}', + "--arg", + "orderId=2", + "--query", + "false", + ]); + const messages = requests + .filter((request) => request.method === "POST") + .map((request) => JSON.parse(request.body)); + expect(messages.map((message) => message.method)).toEqual([ + "initialize", + "notifications/initialized", + "tools/call", + ]); + expect(messages.at(-1).params).toEqual({ + name: "get.order", + arguments: { orderId: 2, query: "false" }, + }); + if (isError) { + expect(called.exitCode).toBe(1); + expect(called.stdout).toBe(""); + expect(JSON.parse(called.stderr).error.message).toBe("native tool message"); + } else { + expect(called.exitCode, called.stderr).toBe(0); + expect(JSON.parse(called.stdout)).toEqual(result); + } + }, + ); +}); + +describe("MCP detail and activated inventory", () => { + test("get combines both responses and preserves downstream schema keys", async () => { + reply({ + mcpCode: code, + serverName: "weather", + type: "OFFICIAL", + serverStatus: "ACTIVATED", + serverType: "HTTP", + description: "Weather", + dashscopeEndpoint: "https://example.com/mcp", + metaInfo: { + provider: "fixture", + billing: { + mode: "per_call", + unitPrice: "0.010", + currency: "CNY", + freeQuota: 0, + privateKey: "private-fixture", + }, + isOnekey: false, + consoleDetailURL: "https://example.com/detail", + }, + mcpConfig: remoteConfig, + }); + const properties = { myCity: { type: "object", additionalProperties: false } }; + reply([ + { + name: "lookup", + description: "Weather", + inputSchema: { properties, required: ["myCity"], additionalProperties: false }, + }, + ]); + const result = await run(["get", ...target]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + server_code: code, + server_name: "weather", + activated: true, + provider: "fixture", + billing: { + mode: "per_call", + unit_price: "0.010", + currency: "CNY", + free_quota: 0, + unit: null, + }, + console_url: "https://example.com/detail", + endpoint: "https://example.com/mcp", + tools: [ + { + name: "lookup", + input_schema: { properties, required: ["myCity"], additional_properties: false }, + }, + ], + }); + expect(result.stdout + result.stderr).not.toContain("private-fixture"); + expectRequests(["GET", item], ["GET", `${item}/tools`]); + }); + + test.each([true, undefined])( + "get previews details and retrieves tools directly for OneKey or unknown policy (%s)", + async (onekey) => { + const server = { + mcp_code: code, + type: "OFFICIAL", + server_status: "INACTIVE", + meta_info: { is_onekey: onekey }, + }; + reply(server); + const preview = await run(["get", ...target, "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout)).toMatchObject({ + plan: { activated: false, billing: null, server_code: code }, + risk: null, + }); + expectRequests(["GET", item]); + reply(server); + reply([{ name: "ready", input_schema: null, description: null }]); + const result = await run(["get", ...target]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout).tools[0].name).toBe("ready"); + expectRequests(["GET", item], ["GET", item], ["GET", `${item}/tools`]); + }, + ); + + test("get retains details and the original service error when only tool discovery fails", async () => { + detail(); + replies.push({ + status: 400, + body: { + success: false, + error_code: "11200026", + error_msg: "未开通该MCP或非可用开通状态", + request_id: "tool-request", + }, + }); + const result = await run(["get", ...target]); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + server_code: code, + activated: false, + tools: null, + }); + expect(JSON.parse(result.stderr).error).toMatchObject({ + api_code: "11200026", + message: "未开通该MCP或非可用开通状态", + request_id: "tool-request", + }); + expectRequests(["GET", item], ["GET", `${item}/tools`]); + }); + + test("a missing server stops before fetching tools", async () => { + replies.push({ + status: 404, + body: { + success: false, + error_code: "McpServerNotFound", + error_msg: "服务不存在", + request_id: "lookup", + }, + }); + const result = await run(["get", ...target]); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + expect(JSON.parse(result.stderr).error.request_id).toBe("lookup"); + expectRequests(["GET", item]); + }); + + test("list filters all candidate pages before selecting a page or counting matches", async () => { + const candidates = Array.from({ length: 102 }, (_unused, index) => ({ + mcp_code: `fixture-${index}`, + type: "CUSTOMER", + server_name: index === 2 ? "Other" : "MyWeather", + server_status: [0, 2, 100, 101].includes(index) ? "ACTIVATED" : "ACTIVATING", + dashscope_endpoint: "https://example.com/mcp", + mcp_config: remoteConfig, + })); + reply({ items: candidates.slice(0, 100), total: 102, pageNo: 1, pageSize: 100 }); + reply({ items: candidates.slice(100), total: 102, page_no: 2, page_size: 100 }); + const result = await run([ + "list", + "--type", + "PRIVATE", + "--name", + "WEATH", + "--page", + "2", + "--page-size", + "1", + ]); + expect(result.exitCode, result.stderr).toBe(0); + const parsed = JSON.parse(result.stdout); + expect(parsed.total).toBe(3); + expect(parsed.servers).toHaveLength(1); + expect(parsed.servers[0]).toMatchObject({ + code: "fixture-100", + name: "MyWeather", + streamable: true, + connected_agents: [], + config_paths: {}, + }); + expect(result.stdout).not.toContain("private-fixture"); + expectRequests( + ["GET", `${collection}/list?type=CUSTOMER&pageNo=1&pageSize=100`], + ["GET", `${collection}/list?type=CUSTOMER&pageNo=2&pageSize=100`], + ); + }); + + test("list reports only registrations matching the actual native configuration", async () => { + const env = { BAILIAN_CONFIG_DIR: directory, CODEX_HOME: join(directory, "codex") }; + reply({ + mcp_code: code, + type: "OFFICIAL", + server_status: "ACTIVATED", + dashscope_endpoint: "https://workspace.example/mcp", + }); + const connected = await run( + ["connect", ...target, "--agent", "codex", "--transport", "streamable-http"], + env, + ); + expect(connected.exitCode, connected.stderr).toBe(0); + const path = join(env.CODEX_HOME, "config.toml"); + const inventory = { + total: 1, + items: [ + { mcp_code: code, server_name: "weather", type: "OFFICIAL", server_status: "ACTIVATED" }, + ], + }; + reply(inventory); + const listed = await run(["list"], env); + expect(listed.exitCode, listed.stderr).toBe(0); + expect(JSON.parse(listed.stdout).servers[0]).toMatchObject({ + connected_agents: ["codex"], + config_paths: { codex: [path] }, + }); + expect(listed.stdout).not.toContain("offline-key"); + const changed = readFileSync(path, "utf8").replace("offline-key", "local-change"); + writeFileSync(path, changed); + reply(inventory); + const stale = await run(["list"], env); + expect(stale.exitCode, stale.stderr).toBe(0); + expect(JSON.parse(stale.stdout).servers[0].connected_agents).toEqual([]); + expect(readFileSync(path, "utf8")).toBe(changed); + const pagePath = `${collection}/list?type=OFFICIAL&pageNo=1&pageSize=100`; + expectRequests(["GET", item], ["GET", pagePath], ["GET", pagePath]); + }); + + test("list never returns an unverified total outside the scan window", async () => { + reply({ items: [], total: 10_001, page_no: 1, page_size: 100 }); + const result = await run(["list"]); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("10000"); + expectRequests(["GET", `${collection}/list?type=OFFICIAL&pageNo=1&pageSize=100`]); + }); + + test("invalid get and list flags fail before requests and list preview stays offline", async () => { + for (const args of [ + ["get"], + ["get", "--server", " "], + ["list", "--page", "0"], + ["list", "--page-size", "1.5"], + ["list", "--page-size", "101"], + ["list", "--page", "101", "--page-size", "100"], + ["list", "--type", "all"], + ]) { + expect((await run([...args, "--dry-run"])).exitCode, args.join(" ")).toBe(2); + } + const preview = await run(["list", "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout)).toMatchObject({ type: "OFFICIAL", page: 1, page_size: 30 }); + expectRequests(); + }); +}); + +describe("native Agent registration", () => { + const endpoint = "https://workspace.example/api/v1/mcps/mcp-example/mcp"; + const connect = ["connect", ...target, "--transport", "streamable-http"]; + const project = ["--agent", "cursor", "--scope", "project"]; + function env() { + return { + HOME: join(directory, "user"), + CODEX_HOME: join(directory, "user", ".codex"), + BAILIAN_CONFIG_DIR: join(directory, "state"), + DSH_HOME: join(directory, "user", ".dsh"), + ZCODE_HOME: join(directory, "user", ".zcode"), + OPENCLAW_CONFIG_PATH: "", + PI_CODING_AGENT_DIR: join(directory, "user", ".pi", "agent"), + }; + } + function ready(url = endpoint) { + reply({ mcpCode: code, type: "OFFICIAL", serverStatus: "ACTIVATED", dashscopeEndpoint: url }); + } + + test("user and project records coexist, project disconnect works offline and respects a manual edit", async () => { + const local = env(); + for (const scope of ["user", "project"]) { + ready(); + const result = await run([...connect, "--agent", "cursor", "--scope", scope], local); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 1 }, + results: [{ agent: "cursor", action: "added" }], + }); + } + const userPath = join(local.HOME, ".cursor/mcp.json"); + const projectPath = join(directory, ".cursor/mcp.json"); + const manifestPath = join(local.BAILIAN_CONFIG_DIR, "mcp-registrations.json"); + const manifest = readFileSync(manifestPath, "utf8"); + expect(Object.values(JSON.parse(manifest).registrations)).toEqual( + expect.arrayContaining([ + expect.objectContaining({ scope: "user", projectRoot: null, configPath: userPath }), + expect.objectContaining({ + scope: "project", + projectRoot: realpathSync(directory), + configPath: realpathSync(projectPath), + }), + ]), + ); + expect(manifest).not.toContain("offline-key"); + const offline = { ...local, DASHSCOPE_API_KEY: "", DASHSCOPE_BASE_URL: "http://127.0.0.1:1" }; + const args = ["disconnect", ...target, ...project]; + const original = readFileSync(projectPath, "utf8"); + writeFileSync(projectPath, original.replace("offline-key", "manual-change")); + for (const extra of [["--dry-run"], []]) { + const result = await run([...args, ...extra], offline); + const output = JSON.parse(result.stdout); + expect((output.targets ?? output.results)[0]).toMatchObject({ + status: "failed", + error_code: "MODIFIED_CONFLICT", + }); + expect(result.exitCode).toBe(extra.length ? 0 : 1); + expect(readFileSync(manifestPath, "utf8")).toBe(manifest); + expect(readFileSync(projectPath, "utf8")).toContain("manual-change"); + } + writeFileSync(projectPath, original); + expect((await run(args, offline)).exitCode).toBe(0); + const again = await run(args, offline); + expect(JSON.parse(again.stdout).results[0]).toMatchObject({ + status: "noop", + reason: "NOT_CONNECTED", + }); + expect(readFileSync(userPath, "utf8")).toContain(endpoint); + expect(JSON.parse(readFileSync(projectPath, "utf8")).mcpServers).toEqual({}); + expectRequests(["GET", item], ["GET", item]); + }); + + test("connect previews activation and registers the endpoint returned after enable", async () => { + const local = env(); + const file = join(directory, ".cursor/mcp.json"); + for (const extra of [["--dry-run"], ["--and-activate=false"]]) { + detail("INACTIVE", "CUSTOMER"); + const result = await run([...connect, ...project, ...extra], local); + if (extra[0] === "--dry-run") { + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + plan: { activation: "enable", endpoint: null }, + risk: null, + }); + } else { + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout).results[0].error_code).toBe("NOT_ACTIVATED"); + } + expect(existsSync(file)).toBe(false); + expect(existsSync(join(local.BAILIAN_CONFIG_DIR, "mcp-registrations.json"))).toBe(false); + } + detail("INACTIVE", "CUSTOMER"); + reply({ mcp_code: code, server_status: "ACTIVATED" }); + ready(); + const applied = await run([...connect, ...project], local); + expect(applied.exitCode, applied.stderr).toBe(0); + expect(JSON.parse(applied.stdout)).toMatchObject({ + results: [{ status: "succeeded" }], + next_step: expect.stringContaining("mcp tools --server"), + }); + expect(JSON.parse(readFileSync(file, "utf8")).mcpServers[code].url).toBe(endpoint); + expectRequests( + ["GET", item], + ["GET", item], + ["GET", item], + ["POST", item + "/enable"], + ["GET", item], + ); + }); + + test("pending deployments, incomplete endpoints and manual activation do not create a local connection", async () => { + const local = env(); + const args = [...connect, ...project]; + detail("INACTIVE", "OFFICIAL"); + reply({ mcp_code: code, server_status: "ACTIVATING" }); + const pending = await run(args, local); + expect(JSON.parse(pending.stdout)).toMatchObject({ + server_status: "ACTIVATING", + results: [{ error_code: "SERVER_NOT_READY" }], + }); + for (const [url, errorCode] of [ + ["", "ENDPOINT_UNAVAILABLE"], + [endpoint.replace("/mcp-example/mcp", "/mcp-example/sse"), "TRANSPORT_MISMATCH"], + ]) { + ready(url); + const result = await run(args, local); + expect(JSON.parse(result.stdout).results[0].error_code).toBe(errorCode); + } + detail("INACTIVE", "OFFICIAL"); + replies.push({ + status: 400, + body: { + error_code: "OperationNotSupported", + error_msg: "当前MCP需要选择凭据,不支持通过OpenAPI开通,请登录百炼控制台手动开通", + request_id: "manual-id", + }, + }); + const manual = await run(args, local); + expect(manual.exitCode).toBe(1); + expect(JSON.parse(manual.stdout).results[0]).toMatchObject({ + error_code: "MANUAL_SETUP_REQUIRED", + api_code: "OperationNotSupported", + request_id: "manual-id", + detail: { console_url: expect.stringMatching(/^https:/) }, + }); + expect(existsSync(join(directory, ".cursor/mcp.json"))).toBe(false); + expectRequests( + ["GET", item], + ["POST", item + "/activate"], + ["GET", item], + ["GET", item], + ["GET", item], + ["POST", item + "/activate"], + ); + }); + + test("a concurrent registration prevents activation and preserves the other owner's lock", async () => { + const local = env(); + mkdirSync(local.BAILIAN_CONFIG_DIR); + const lock = join(local.BAILIAN_CONFIG_DIR, "mcp-registrations.json.lock"); + writeFileSync(lock, "other owner"); + detail("INACTIVE", "OFFICIAL"); + const result = await run([...connect, ...project], local); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout).summary).toEqual({ succeeded: 0, failed: 1, noop: 0 }); + expect(readFileSync(lock, "utf8")).toBe("other owner"); + expect(existsSync(join(directory, ".cursor", "mcp.json"))).toBe(false); + expectRequests(["GET", item]); + }); + + test("all isolates each Agent's conflict, unsupported scope and successful registration", async () => { + const local = env(); + for (const folder of [".cursor", ".qwenwork", ".claude"]) + mkdirSync(join(local.HOME, folder), { recursive: true }); + const unrelated = JSON.stringify({ + mcpServers: { [code]: { url: "https://existing.example/mcp" } }, + }); + writeFileSync(join(directory, ".mcp.json"), unrelated); + ready(); + const result = await run([...connect, "--scope", "project", "--agent", "all"], local); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 1, failed: 2, noop: 0 }, + results: [ + { agent: "claude-code", error_code: "UNMANAGED_CONFLICT" }, + { agent: "cursor", action: "added" }, + { agent: "qwenwork", error_code: "SCOPE_UNSUPPORTED" }, + ], + }); + const stopped = await run( + ["disconnect", ...target, "--scope", "project", "--agent", "all"], + local, + ); + expect(JSON.parse(stopped.stdout).summary).toEqual({ succeeded: 1, noop: 1, failed: 1 }); + expect(readFileSync(join(directory, ".mcp.json"), "utf8")).toBe(unrelated); + const conflict = await run([...connect, "--scope", "project", "--agent", "claude-code"], local); + expect(JSON.parse(conflict.stdout).results[0].error_code).toBe("UNMANAGED_CONFLICT"); + expectRequests(["GET", item]); + }); + + test("legacy user records migrate lazily and ambiguous paths remain intact", async () => { + const local = env(); + ready(); + const args = [...connect, "--agent", "cursor"]; + expect((await run(args, local)).exitCode).toBe(0); + const file = join(local.BAILIAN_CONFIG_DIR, "mcp-registrations.json"); + const manifest = JSON.parse(readFileSync(file, "utf8")); + const record = manifest.registrations["cursor:" + code]; + for (const field of ["scope", "projectRoot", "configPath", "configPaths"]) delete record[field]; + const legacy = JSON.stringify(manifest); + writeFileSync(file, legacy); + ready(); + expect((await run([...args, "--dry-run"], local)).exitCode).toBe(0); + expect(readFileSync(file, "utf8")).toBe(legacy); + ready(); + const noop = await run(args, local); + expect(JSON.parse(noop.stdout).results[0]).toMatchObject({ + status: "noop", + reason: "ALREADY_CONNECTED", + }); + expect(JSON.parse(readFileSync(file, "utf8")).registrations["cursor:" + code]).toMatchObject({ + scope: "user", + configPath: record.path, + }); + record.path = join(directory, "unknown.json"); + const ambiguous = JSON.stringify(manifest); + writeFileSync(file, ambiguous); + const refused = await run(["disconnect", ...target, "--agent", "cursor"], local); + expect(refused.exitCode).toBe(1); + expect(JSON.parse(refused.stdout).results[0].error_code).toBe("AMBIGUOUS_REGISTRATION"); + expect(readFileSync(file, "utf8")).toBe(ambiguous); + expectRequests(["GET", item], ["GET", item], ["GET", item]); + }); +}); + +describe("batch MCP activation and deactivation", () => { + function server( + code: string, + type: string, + status: string, + extras: Record = {}, + ) { + reply({ mcp_code: code, type, server_status: status, mcp_config: remoteConfig, ...extras }); + } + + test.each(["activate", "deactivate"])( + "%s validates targets before any lookup", + async (command) => { + for (const value of [ + "a,,b", + "a, ..", + Array.from({ length: 31 }, (_, index) => `s${index}`).join(","), + ]) { + expect((await run([command, "--server", value])).exitCode).toBe(2); + } + expect((await run([command, "--dry-run"])).exitCode).toBe(2); + expectRequests(); + }, + ); + + test.each([ + ["activate", "INACTIVE", "activate", "enable"], + ["deactivate", "ACTIVATED", "deactivate", "disable"], + ])( + "%s previews every distinct target without writing", + async (command, status, officialAction, customAction) => { + const args = [ + command, + "--server", + ["custom", ...Array(30).fill(" official "), "custom"].join(","), + ]; + server("custom", "CUSTOMER", status); + server("official", "OFFICIAL", status, { meta_info: { is_onekey: true } }); + const result = await run([...args, "--dry-run"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + plan: { + targets: [ + { code: "custom", action: customAction }, + { code: "official", action: officialAction, is_onekey: true }, + ], + }, + risk: null, + }); + expect(result.stdout + result.stderr).not.toContain("private-fixture"); + expectRequests(["GET", collection + "/custom"], ["GET", collection + "/official"]); + }, + ); + + test("activation reports accepted deployments, enabled custom services and idempotent skips in order", async () => { + server("official/one", "OFFICIAL", "INACTIVE", { meta_info: { is_onekey: true } }); + server("custom", "CUSTOMER", "ACTIVATE_FAILED"); + server("ready", "OFFICIAL", "ACTIVATED"); + server("pending", "CUSTOMER", "ACTIVATING"); + reply({ mcpCode: "official/one", serverStatus: "ACTIVATING", serverStatusText: "开通中" }); + reply({ mcp_code: "custom", server_status: "ACTIVATED", mcp_config: remoteConfig }); + const result = await run(["activate", "--server", "official/one,custom,ready,pending,custom"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 2, failed: 0, noop: 2 }, + results: [ + { + code: "official/one", + status: "succeeded", + server_status: "ACTIVATING", + server_status_text: "开通中", + }, + { code: "custom", status: "succeeded", server_status: "ACTIVATED" }, + { code: "ready", status: "noop", reason: "ALREADY_ACTIVATED" }, + { code: "pending", status: "noop", reason: "ALREADY_ACTIVATING" }, + ], + }); + expect(result.stdout + result.stderr).not.toContain("private-fixture"); + expectRequests( + ["GET", collection + "/official%2Fone"], + ["GET", collection + "/custom"], + ["GET", collection + "/ready"], + ["GET", collection + "/pending"], + ["POST", collection + "/official%2Fone/activate"], + ["POST", collection + "/custom/enable"], + ); + }); + + test("deactivation keeps original OneKey and lookup errors and completes independent targets", async () => { + server("onekey", "OFFICIAL", "ACTIVATED", { meta_info: { is_onekey: true } }); + replies.push({ + status: 404, + body: { error_code: "McpServerNotFound", error_msg: "服务不存在", request_id: "missing" }, + }); + server("custom", "CUSTOMER", "ACTIVATED"); + server("official", "OFFICIAL", "ACTIVATED"); + server("stopped", "CUSTOMER", "INACTIVE"); + replies.push({ + status: 400, + body: { + error_code: "DeActivateFailed", + error_msg: "OnekeyMCP不支持此操作", + request_id: "onekey-denied", + }, + }); + reply({ mcpCode: "custom", serverStatus: "INACTIVE" }); + reply({ mcpCode: "official", serverStatus: "INACTIVE" }); + const result = await run(["deactivate", "--server", "onekey,missing,custom,official,stopped"]); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 2, failed: 2, noop: 1 }, + results: [ + { + code: "onekey", + status: "failed", + error_code: "DeActivateFailed", + message: "OnekeyMCP不支持此操作", + http_status: 400, + request_id: "onekey-denied", + }, + { + code: "missing", + status: "failed", + error_code: "McpServerNotFound", + http_status: 404, + request_id: "missing", + }, + { code: "custom", status: "succeeded", server_status: "INACTIVE" }, + { code: "official", status: "succeeded", server_status: "INACTIVE" }, + { code: "stopped", status: "noop", reason: "NOT_ACTIVATED" }, + ], + }); + expect(JSON.parse(result.stderr).error.request_id).toBe("onekey-denied"); + expectRequests( + ["GET", collection + "/onekey"], + ["GET", collection + "/missing"], + ["GET", collection + "/custom"], + ["GET", collection + "/official"], + ["GET", collection + "/stopped"], + ["POST", collection + "/onekey/deactivate"], + ["POST", collection + "/custom/disable"], + ["POST", collection + "/official/deactivate"], + ); + }); + + test.each([ + ["activate", "ACTIVATED", "ALREADY_ACTIVATED"], + ["deactivate", "INACTIVE", "NOT_ACTIVATED"], + ])("%s skips a satisfied batch without confirmation", async (command, status, reason) => { + detail(status); + const result = await run([command, ...target]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 0, failed: 0, noop: 1 }, + results: [{ status: "noop", reason }], + }); + expectRequests(["GET", item]); + }); + + test("manual setup from detail or an explicit activation error retains the console link and original message", async () => { + const url = "https://bailian.console.aliyun.com/example"; + const meta_info = { console_detail_url: url }; + const message = "当前MCP需要选择Ram角色,不支持通过OpenAPI开通,请登录百炼控制台手动开通"; + server("role", "OFFICIAL", "INACTIVE", { meta_info }); + server("manual", "OFFICIAL", "INACTIVE", { meta_info, requires_manual_setup: true }); + server("busy", "OFFICIAL", "INACTIVE", { meta_info }); + replies.push({ + status: 400, + body: { error_code: "OperationNotSupported", error_msg: message, request_id: "role-request" }, + }); + replies.push({ + status: 409, + body: { + error_code: "OperationNotSupported", + error_msg: "服务部署中", + request_id: "busy-request", + }, + }); + const result = await run(["activate", "--server", "role,manual,busy", "--no-browser"]); + expect(result.exitCode).toBe(1); + const batch = JSON.parse(result.stdout); + expect(batch).toMatchObject({ + summary: { succeeded: 0, failed: 3, noop: 0 }, + results: [ + { + code: "role", + status: "failed", + error_code: "MANUAL_SETUP_REQUIRED", + api_code: "OperationNotSupported", + message, + request_id: "role-request", + detail: { console_url: url }, + }, + { + code: "manual", + status: "failed", + error_code: "MANUAL_SETUP_REQUIRED", + detail: { console_url: url }, + }, + { + code: "busy", + status: "failed", + error_code: "OperationNotSupported", + http_status: 409, + request_id: "busy-request", + }, + ], + }); + expect(batch.results[0].detail).not.toHaveProperty("browser_opened"); + expect(batch.results[2]).not.toHaveProperty("detail"); + expectRequests( + ["GET", collection + "/role"], + ["GET", collection + "/manual"], + ["GET", collection + "/busy"], + ["POST", collection + "/role/activate"], + ["POST", collection + "/busy/activate"], + ); + }); + + test("market activation uses the console link supplied with the manual setup error", async () => { + const url = "https://modelstudio.console.alibabacloud.com/store/mcp/detail/example"; + detail("INACTIVE", "OFFICIAL"); + replies.push({ + status: 400, + body: { + error_code: "OperationNotSupported", + error_msg: "当前云市场MCP不允许通过OpenAPI开通,请前往控制台手动开通:" + url, + request_id: "market", + }, + }); + const result = await run(["activate", ...target, "--no-browser"]); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout).results[0]).toMatchObject({ + status: "failed", + error_code: "MANUAL_SETUP_REQUIRED", + request_id: "market", + detail: { console_url: url }, + }); + expectRequests(["GET", item], ["POST", item + "/activate"]); + }); + + test("a lost response leaves the write outcome unknown and sends only one POST", async () => { + detail("ACTIVATED", "CUSTOMER"); + replies.push("disconnect"); + const result = await run(["deactivate", ...target]); + expect(result.exitCode, result.stderr).toBe(6); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 0, failed: 1, noop: 0 }, + results: [{ code, status: "failed", outcome_unknown: true, hint: expect.any(String) }], + }); + expectRequests(["GET", item], ["POST", item + "/disable"]); + }); + + test("a successful envelope still requires the correct server and lifecycle status", async () => { + for (const targetCode of ["failed", "missing-status", "wrong-code"]) + server(targetCode, "CUSTOMER", "INACTIVE"); + reply({ + mcp_code: "failed", + server_status: "ACTIVATE_FAILED", + server_status_text: "部署失败", + activate_fail_reason: "upstream deployment error", + }); + reply({ mcp_code: "missing-status" }); + reply({ mcp_code: "different", server_status: "ACTIVATED" }); + const result = await run(["activate", "--server", "failed,missing-status,wrong-code"]); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 0, failed: 3, noop: 0 }, + results: [ + { + code: "failed", + status: "failed", + error_code: "ACTIVATE_FAILED", + message: "upstream deployment error", + }, + { code: "missing-status", status: "failed", request_id: "req-write" }, + { code: "wrong-code", status: "failed", request_id: "req-write" }, + ], + }); + expect(requests.map((request) => request.method)).toEqual([ + "GET", + "GET", + "GET", + "POST", + "POST", + "POST", + ]); + }); +}); + +describe("custom MCP management", () => { + test.each([...Object.keys(MCP_ROUTES), ...Object.keys(SKILL_ROUTES)])( + "%s exposes confirmation only for MCP deletion", + async (path) => { + const routes = path.startsWith("mcp ") ? MCP_ROUTES : SKILL_ROUTES; + const help = await runCommandHelp(routes, [...path.split(" "), "--help"]); + expect(help.exitCode, help.stderr).toBe(0); + expect(help.stderr.includes("--yes")).toBe(path === "mcp delete"); + if (path.startsWith("mcp ") && path !== "mcp disconnect") { + expect(help.stderr).toContain("--api-key"); + expect(help.stderr).not.toContain("--console-region"); + } + }, + ); + + test("invalid flags and JSON never reach the gateway", async () => { + for (const flag of ["--name", "--description", "--mcp-type", "--mcp-config"]) { + const args = [...createArgs]; + args.splice(args.indexOf(flag), 2); + expect((await run(args)).exitCode, flag).toBe(2); + } + for (const args of [ + ["delete"], + ["update", "--name", "new"], + ["update", ...target], + ["update", ...target, "--name", " "], + ["update", ...target, "--mcp-type", "HTTP"], + ["update", ...target, "--mcp-config", "{}"], + ["update", ...target, "--mcp-type", "ftp", "--mcp-config", "{}"], + ...[ + "{", + "null", + "[]", + '{"api_host":"invalid"}', + '{"url":"ftp://bad"}', + '{"url":"https://example.com","headers":{"X":null}}', + ].map((input) => ["update", ...target, "--mcp-type", "http", "--mcp-config", input]), + ]) { + const result = await run([...args, "--dry-run"]); + expect(result.exitCode, args.join(" ")).toBe(2); + } + expectRequests(); + }); + + test("a create preview sends no requests and reveals no configuration values", async () => { + const preview = await run([...createArgs, "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout)).toMatchObject({ + plan: { action: "create", deploy: true, mcp_type: "HTTP" }, + risk: null, + }); + expect(preview.stdout + preview.stderr).not.toContain("private-fixture"); + expectRequests(); + }); + + test("dry-run requires API-key authentication before planning", async () => { + const result = await run(["delete", ...target, "--dry-run"], { + DASHSCOPE_API_KEY: "", + BAILIAN_CONFIG_DIR: directory, + }); + expect(result.exitCode, result.stderr).toBe(3); + expectRequests(); + }); + + test("missing and malformed config files produce distinct errors before the detail lookup", async () => { + const args = ["update", ...target, "--mcp-type", "http", "--mcp-config", "./config.json"]; + const missing = await run(args); + expect(missing.exitCode, missing.stderr).toBe(1); + writeFileSync(join(directory, "config.json"), '{"token":"private-fixture",'); + const malformed = await run(args); + expect(malformed.exitCode, malformed.stderr).toBe(2); + expect(malformed.stderr).not.toContain("private-fixture"); + expectRequests(); + }); + + test.each([ + ["hTTp", remoteConfig], + ["sse", { url: "https://mcp.example.com/sse" }], + [ + "stdio", + { + command: "npx", + args: ["-y", "@example/weather"], + env: { API_Key: "private-fixture" }, + fc_deploy_region: "cn-beijing", + }, + ], + [ + "openapi", + { + api_host: "https://api.example.com", + api_list: [ + { + name: "getOrder", + description: "Find order", + path: "/orders/{orderId}", + method: "GET", + input_params: [ + { + name: "orderId", + description: "Order ID", + location: "Path", + type: "String", + required: true, + }, + ], + }, + ], + }, + ], + ] as const)( + "create sends a snake_case %s body and preserves business keys", + async (type, config) => { + reply({ mcpCode: code, serverName: "weather", serverStatus: "ACTIVATING" }, 201); + const result = await run([ + "create", + "--name", + "weather", + "--description", + "Weather lookup", + "--mcp-type", + type, + "--mcp-config", + JSON.stringify(config), + ]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + mcp_code: code, + server_status: "ACTIVATING", + }); + expectRequests([ + "POST", + collection, + { + server_name: "weather", + description: "Weather lookup", + mcp_type: type.toUpperCase(), + mcp_config: config, + }, + ]); + }, + ); + + test("metadata-only update on a running server omits the deployment fields", async () => { + detail("ACTIVATED"); + reply({ mcp_code: code, server_name: "new" }); + const result = await run(["update", ...target, "--name", "new"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).not.toHaveProperty("server_status"); + expectRequests(["GET", item], ["POST", item, { server_name: "new" }]); + }); + + test.each(["ACTIVATING", "ACTIVATED"])( + "rejects configuration replacement while %s", + async (status) => { + detail(status); + expect((await run(["update", ...target, ...configArgs])).exitCode).toBe(1); + expectRequests(["GET", item]); + }, + ); + + test("update reads a relative or absolute JSON file and posts the complete replacement directly", async () => { + const path = join(directory, "weather.json"); + writeFileSync(path, JSON.stringify(remoteConfig)); + const updateArgs = ["update", ...target, "--mcp-type", "http", "--mcp-config"]; + detail(); + const preview = await run([...updateArgs, path, "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout).plan).toMatchObject({ replace_config: true, deploy: true }); + expectRequests(["GET", item]); + expect(preview.stdout + preview.stderr).not.toContain("private-fixture"); + detail(); + reply({ mcp_code: code, server_status: "ACTIVATED" }); + const updated = await run([...updateArgs, "./weather.json"]); + expect(updated.exitCode, updated.stderr).toBe(0); + expectRequests( + ["GET", item], + ["GET", item], + ["POST", item, { mcp_type: "HTTP", mcp_config: remoteConfig }], + ); + }); + + test.each(["update", "delete"])("%s checks ownership before writing", async (command) => { + detail("ACTIVATED", "OFFICIAL"); + const args = command === "update" ? ["--name", "new"] : ["--yes"]; + expect((await run([command, ...target, ...args])).exitCode).toBe(1); + expectRequests(["GET", item]); + }); + + test("delete previews local registrations, requires confirmation, and sends an empty DELETE", async () => { + const manifestPath = join(directory, "mcp-registrations.json"); + const manifest = JSON.stringify({ + version: 1, + registrations: { [`codex:${code}`]: { agent: "codex", serverCode: code } }, + }); + writeFileSync(manifestPath, manifest); + const env = { BAILIAN_CONFIG_DIR: directory }; + detail(); + const preview = await run(["delete", ...target, "--dry-run"], env); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout).plan.connected_agents).toEqual(["codex"]); + detail(); + const refused = await run(["delete", ...target], env); + expect(refused.exitCode).toBe(7); + expect(refused.stderr).toContain("requires_confirmation"); + detail(); + reply({ mcp_code: code, server_status: "DELETED" }); + const deleted = await run(["delete", ...target, "--yes"], env); + expect(deleted.exitCode, deleted.stderr).toBe(0); + expect(JSON.parse(deleted.stdout)).toMatchObject({ + server_status: "DELETED", + connected_agents: ["codex"], + }); + expect(readFileSync(manifestPath, "utf8")).toBe(manifest); + expectRequests(["GET", item], ["GET", item], ["GET", item], ["DELETE", item]); + }); + + test("HTTP 201 deployment failure preserves the resource code and original cause", async () => { + reply( + { + mcp_code: code, + server_status: "ACTIVATE_FAILED", + activate_fail_reason: "upstream handshake failed", + }, + 201, + ); + const failed = await run(createArgs); + expect(failed.exitCode).toBe(1); + expect(JSON.parse(failed.stdout)).toMatchObject({ + server_code: code, + server_status: "ACTIVATE_FAILED", + }); + expect(JSON.parse(failed.stderr).error).toMatchObject({ + message: "upstream handshake failed", + request_id: "req-write", + }); + }); + + test("delete requires DELETED even when the service returns HTTP 200", async () => { + detail(); + reply({ mcp_code: code, server_status: "INACTIVE" }); + const result = await run(["delete", ...target, "--yes"]); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout).server_status).toBe("INACTIVE"); + expectRequests(["GET", item], ["DELETE", item]); + }); + + test.each([ + [ + 404, + { error_code: "McpServerUnavailable", error_msg: "当前MCP已删除", request_id: "req-error" }, + ], + [ + 200, + { error_code: "McpServerBusy", error_msg: "MCP 当前有操作执行中", request_id: "req-error" }, + ], + [409, { errorCode: "McpServerBusy", errorMsg: "MCP 当前有操作执行中", requestId: "req-error" }], + ] as const)( + "HTTP %s preserves service error details and stops before writing", + async (status, error) => { + replies.push({ status, body: { success: false, data: null, ...error } }); + const failed = await run(["delete", ...target, "--yes"]); + expect(failed.exitCode).toBe(1); + expect(JSON.parse(failed.stderr).error).toMatchObject({ + message: "error_msg" in error ? error.error_msg : error.errorMsg, + api_code: "error_code" in error ? error.error_code : error.errorCode, + request_id: "req-error", + http_status: status, + }); + expectRequests(["GET", item]); + }, + ); +}); diff --git a/packages/commands/tests/e2e/mcp.e2e.test.ts b/packages/commands/tests/e2e/mcp.e2e.test.ts index ebbeb7def..34b655956 100644 --- a/packages/commands/tests/e2e/mcp.e2e.test.ts +++ b/packages/commands/tests/e2e/mcp.e2e.test.ts @@ -11,6 +11,7 @@ import { runCommandInProcess, } from "./helpers.ts"; import { MCP_ROUTES } from "./topic-routes.ts"; +import { activeMcpFixture } from "./fixtures/mcp-detail.ts"; /** * `bl mcp` E2E. @@ -27,6 +28,7 @@ import { MCP_ROUTES } from "./topic-routes.ts"; */ describe("e2e: mcp", () => { + const activeServer = activeMcpFixture("ImageGenerate"); test("mcp list --help 正常退出", async () => { const { stderr, exitCode } = await runCommandHelp(MCP_ROUTES, ["mcp", "list", "--help"]); expect(exitCode, stderr).toBe(0); @@ -90,7 +92,9 @@ describe("e2e: mcp", () => { "--agent", "codex", "--base-url", - "https://custom-model-gateway.example.com", + activeServer.baseUrl, + "--api-key", + "offline-connect", "--dry-run", "--output", "json", @@ -102,15 +106,17 @@ describe("e2e: mcp", () => { }, ); expect(exitCode, stderr).toBe(0); - const data = parseStdoutJson<{ - server?: string; - transport?: string; - endpoint?: string; - header_names?: string[]; + const { plan: data } = parseStdoutJson<{ + plan: { + server?: string; + transport?: string; + endpoint?: string; + header_names?: string[]; + }; }>(stdout); expect(data.server).toBe("ImageGenerate"); expect(data.transport).toBe("streamable-http"); - expect(data.endpoint).toBe("https://dashscope.aliyuncs.com/api/v1/mcps/ImageGenerate/mcp"); + expect(data.endpoint).toBe(activeServer.endpoint); expect(data.header_names).toEqual( expect.arrayContaining([ "Authorization", @@ -149,7 +155,7 @@ describe("e2e: mcp", () => { "--api-key", "sk-test-secret", "--base-url", - "https://dashscope.aliyuncs.com", + activeServer.baseUrl, "--output", "json", ], @@ -161,6 +167,7 @@ describe("e2e: mcp", () => { const registered = (config.mcp_servers as Record>) .ImageGenerate; expect(registered).toBeDefined(); + expect(registered.url).toBe(activeServer.endpoint); const httpHeaders = registered.http_headers as Record; expect(httpHeaders["X-Dashscope-Service"]).toBe("bailian-cli"); expect(httpHeaders["x-dashscope-openapisource"]).toBe("BailianCLI"); @@ -208,8 +215,8 @@ describe("e2e: mcp", () => { expect(stderr).not.toMatch(/--all/); }); - test("mcp list --dry-run 仅打印计划且固定 activated=1", async () => { - const { stdout, stderr, exitCode } = await runCommandInProcess(MCP_ROUTES, [ + test("mcp list previews the activated-name filter and requested page", async () => { + const result = await runCommandInProcess(MCP_ROUTES, [ "mcp", "list", "--dry-run", @@ -222,43 +229,24 @@ describe("e2e: mcp", () => { "--page-size", "5", ]); - expect(exitCode, stderr).toBe(0); - const data = parseStdoutJson<{ - api?: string; - consoleRegion?: string; - data?: { - reqDTO?: { - type?: string; - activated?: number; - serverName?: string; - pageNo?: number; - pageSize?: number; - displayTools?: boolean; - }; - }; - }>(stdout); - expect(data.api).toBe("zeldaEasy.broadscope-bailian.mcp-server.PageList"); - expect(data.data?.reqDTO?.activated).toBe(1); - expect(data.data?.reqDTO?.displayTools).toBe(false); - expect(data.data?.reqDTO?.type).toBe("OFFICIAL"); - expect(data.data?.reqDTO?.serverName).toBe("金融"); - expect(data.data?.reqDTO?.pageNo).toBe(2); - expect(data.data?.reqDTO?.pageSize).toBe(5); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + method: "GET", + path: "/api/v1/mcp/servers/list", + type: "OFFICIAL", + activated: true, + name: "金融", + page: 2, + page_size: 5, + }); }); - test("mcp list --dry-run 自定义 --console-region 透传", async () => { - const { stdout, stderr, exitCode } = await runCommandInProcess(MCP_ROUTES, [ - "mcp", - "list", - "--dry-run", - "--output", - "json", - "--console-region", - "cn-hangzhou", - ]); - expect(exitCode, stderr).toBe(0); - const data = parseStdoutJson<{ consoleRegion?: string }>(stdout); - expect(data.consoleRegion).toBe("cn-hangzhou"); + test("mcp get exposes the required server code and API key for tool lookup", async () => { + const help = await runCommandHelp(MCP_ROUTES, ["mcp", "get", "--help"]); + expect(help.exitCode).toBe(0); + expect(help.stderr).toContain("--server"); + expect(help.stderr).toContain("--api-key"); + expect(help.stderr).not.toContain("--yes"); }); test("mcp tools --server --dry-run 输出 /api/v1/mcps//mcp 形态 URL", async () => { @@ -391,7 +379,7 @@ describe("e2e: mcp", () => { "json", ]); expect(exitCode).not.toBe(0); - expect(stderr).toMatch(/--arg must be in K=V/); + expect(stderr).toMatch(/--arg.*K=V/); }); test("mcp call --json 无效 JSON 报错且非零退出", async () => { @@ -406,7 +394,7 @@ describe("e2e: mcp", () => { "json", ]); expect(exitCode).not.toBe(0); - expect(stderr).toMatch(/--json is not valid JSON|--json must decode/); + expect(stderr).toMatch(/--json.*JSON/); }); test("mcp call 缺少 --target 时报用法错误并退出 (2)", async () => { diff --git a/packages/commands/tests/e2e/pi-agent.e2e.test.ts b/packages/commands/tests/e2e/pi-agent.e2e.test.ts index f664f79b3..5abc755ed 100644 --- a/packages/commands/tests/e2e/pi-agent.e2e.test.ts +++ b/packages/commands/tests/e2e/pi-agent.e2e.test.ts @@ -4,8 +4,10 @@ import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, test } from "vite-plus/test"; import { parseStdoutJson, runCommandE2e, runCommandHelp } from "./helpers.ts"; import { CONFIG_ROUTES, MCP_ROUTES } from "./topic-routes.ts"; +import { activeMcpFixture } from "./fixtures/mcp-detail.ts"; const PLACEHOLDER_KEY = "sk-pi-e2e-placeholder-secret"; +const activeServer = activeMcpFixture("TextGenerateImage"); let probeRoot: string; let agentDir: string; let probeEnv: NodeJS.ProcessEnv; @@ -13,7 +15,11 @@ let probeEnv: NodeJS.ProcessEnv; beforeEach(() => { probeRoot = mkdtempSync(join(tmpdir(), "bl-pi-e2e-")); agentDir = join(probeRoot, "pi-agent"); - probeEnv = { PI_CODING_AGENT_DIR: agentDir, BAILIAN_CONFIG_DIR: join(probeRoot, "bailian") }; + probeEnv = { + PI_CODING_AGENT_DIR: agentDir, + BAILIAN_CONFIG_DIR: join(probeRoot, "bailian"), + DASHSCOPE_BASE_URL: activeServer.baseUrl, + }; }); afterEach(() => rmSync(probeRoot, { recursive: true, force: true })); @@ -98,11 +104,11 @@ describe("e2e: Pi Agent integration", () => { test("MCP dry-run reports only non-secret metadata without writing configuration", async () => { const result = await runCommandE2e(MCP_ROUTES, [...mcpArgs, "--dry-run"], probeEnv); expect(result.exitCode, result.stderr).toBe(0); - const plan = parseStdoutJson<{ agents: string[]; endpoint: string; header_names: string[] }>( - result.stdout, - ); + const { plan } = parseStdoutJson<{ + plan: { agents: string[]; endpoint: string; header_names: string[] }; + }>(result.stdout); expect(plan.agents).toEqual(["pi"]); - expect(plan.endpoint).toBe("https://dashscope.aliyuncs.com/api/v1/mcps/TextGenerateImage/mcp"); + expect(plan.endpoint).toBe(activeServer.endpoint); expect(plan.header_names).toContain("Authorization"); expect(result.stdout + result.stderr).not.toContain(PLACEHOLDER_KEY); expect(existsSync(agentDir)).toBe(false); @@ -113,13 +119,13 @@ describe("e2e: Pi Agent integration", () => { expect(first.exitCode, first.stderr).toBe(0); expect(first.stdout + first.stderr).not.toContain(PLACEHOLDER_KEY); expect(parseStdoutJson<{ results: { status: string }[] }>(first.stdout).results[0].status).toBe( - "added", + "succeeded", ); const repeated = await runCommandE2e(MCP_ROUTES, mcpArgs, probeEnv); expect(repeated.exitCode, repeated.stderr).toBe(0); expect( parseStdoutJson<{ results: { status: string }[] }>(repeated.stdout).results[0].status, - ).toBe("unchanged"); + ).toBe("noop"); const disconnected = await runCommandE2e( MCP_ROUTES, ["mcp", "disconnect", "--agent", "pi", "--server", "TextGenerateImage", "--output", "json"], @@ -128,7 +134,7 @@ describe("e2e: Pi Agent integration", () => { expect(disconnected.exitCode, disconnected.stderr).toBe(0); expect( parseStdoutJson<{ results: { status: string }[] }>(disconnected.stdout).results[0].status, - ).toBe("removed"); + ).toBe("succeeded"); expect(JSON.parse(readFileSync(join(agentDir, "mcp.json"), "utf8")).mcpServers).toEqual({}); }); diff --git a/packages/commands/tests/e2e/skill-catalog.e2e.test.ts b/packages/commands/tests/e2e/skill-catalog.e2e.test.ts new file mode 100644 index 000000000..0c6919366 --- /dev/null +++ b/packages/commands/tests/e2e/skill-catalog.e2e.test.ts @@ -0,0 +1,608 @@ +import { + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { buildSkillLockEntry, httpTransport } from "bailian-cli-core"; +import { afterEach, describe, expect, test, vi } from "vite-plus/test"; +import { buildTarBr } from "../../../core/tests/helpers/skill-archive.ts"; +import { + isDashScopeE2EReady, + runCommandE2e, + runCommandHelp, + runCommandInProcess, +} from "./helpers.ts"; +import { SKILL_ROUTES } from "./topic-routes.ts"; + +const origin = "https://skills.example.test"; +const collection = "/api/v1/skills"; +const offlineEnv = { + DASHSCOPE_API_KEY: "fixture-key", + DASHSCOPE_BASE_URL: origin, + NODE_OPTIONS: "", + NODE_USE_ENV_PROXY: "", + HTTP_PROXY: "", + HTTPS_PROXY: "", + ALL_PROXY: "", + NO_PROXY: "", + http_proxy: "", + https_proxy: "", + all_proxy: "", + no_proxy: "", +}; + +function run(args: string[], env = {}, cwd?: string) { + return runCommandInProcess( + SKILL_ROUTES, + ["skill", ...args, "--output", "json"], + { ...offlineEnv, ...env }, + { cwd }, + ); +} + +function skill(id: string, source = "official") { + return { + id, + display_name: "Display name", + display_description: "Description", + source, + status: "active", + latest_version: "2.0", + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-02-01T00:00:00Z", + }; +} + +function page(pageNo: number, pageSize: number, total: number, items: ReturnType[]) { + return { page_no: pageNo, page_size: pageSize, total, items }; +} + +function success(data: unknown) { + return Response.json({ success: true, data, request_id: "fixture-request" }); +} + +// Exercise the parser, auth middleware, HTTP client and output in-process. +function gateway(...responses: Response[]) { + const requests: URL[] = []; + vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + const url = new URL(request.url); + expect(url.origin).toBe(origin); + expect(request.method).toBe("GET"); + expect(request.headers.get("Authorization")).toBe("Bearer fixture-key"); + expect(request.body).toBeNull(); + requests.push(url); + const response = responses.shift(); + if (!response) throw new Error("Unexpected catalog request"); + return response; + }); + return requests; +} + +afterEach(() => vi.restoreAllMocks()); + +test.each([ + ["search", "--keyword"], + ["get", "--code"], +])("%s help exposes API key auth", async (command, flag) => { + const result = await runCommandHelp(SKILL_ROUTES, ["skill", command, "--help"]); + expect(result.exitCode).toBe(0); + expect(result.stderr).toContain(flag); + if (command === "get") expect(result.stderr).toContain("--name"); + expect(result.stderr).toContain("--api-key"); + expect(result.stderr).toContain("--workspace-id"); + expect(result.stderr).not.toContain("--console-region"); +}); + +test("cloud requests derive the workspace gateway only when the base URL is implicit", async ({ + onTestFinished, +}) => { + const config = mkdtempSync(join(tmpdir(), "bl-skill-workspace-")); + onTestFinished(() => rmSync(config, { recursive: true, force: true })); + const env = { BAILIAN_CONFIG_DIR: config, BAILIAN_WORKSPACE_ID: "", DASHSCOPE_BASE_URL: "" }; + const path = join(config, "config.json"); + writeFileSync(path, JSON.stringify({ workspace_id: "ws-config" })); + const requests: string[] = []; + vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + expect(request.headers.get("Authorization")).toBe("Bearer fixture-key"); + expect(new URL(request.url).pathname).toBe(collection); + requests.push(new URL(request.url).origin); + return success(page(1, 30, 0, [])); + }); + async function search(flags: string[], overrides = {}) { + const result = await run(["search", ...flags], { ...env, ...overrides }); + expect(result.exitCode, result.stderr).toBe(0); + } + await search([]); + await search([], { BAILIAN_WORKSPACE_ID: "ws-env" }); + await search(["--workspace-id", "ws-flag"], { BAILIAN_WORKSPACE_ID: "ws-env" }); + writeFileSync( + path, + JSON.stringify({ workspace_id: "ws-config", base_url: "https://dashscope.aliyuncs.com" }), + ); + await search(["--workspace-id", "ws-flag"]); + await search([], { DASHSCOPE_BASE_URL: origin }); + await search(["--base-url", "https://override.example.test"], { DASHSCOPE_BASE_URL: origin }); + expect(requests).toEqual([ + "https://ws-config.cn-beijing.maas.aliyuncs.com", + "https://ws-env.cn-beijing.maas.aliyuncs.com", + "https://ws-flag.cn-beijing.maas.aliyuncs.com", + "https://dashscope.aliyuncs.com", + origin, + "https://override.example.test", + ]); + + writeFileSync(path, "{}"); + const missing = await run(["search"], env); + expect(missing.exitCode, missing.stderr).toBe(2); + expect(missing.stderr).toContain("--workspace-id"); + const invalid = await run(["search", "--workspace-id", "other.example/path"], env); + expect(invalid.exitCode, invalid.stderr).toBe(2); + expect(requests).toHaveLength(6); +}); + +test.each([ + ["get", "--quiet"], + ["get", "--name", " "], + ["get", "--name", ".."], + ["get", "--code", " "], + ["get", "--code", ".."], + ["get", "--name", "pdf", "--code", "pdf"], + ["search", "--type", "other"], + ["search", "--page", "0"], + ["search", "--page-size", "101"], + ["search", "--page", "101", "--page-size", "100"], + ["search", "--limit", "0"], + ["search", "--limit", "1.5"], +])("invalid args fail before a request (%s %s %s)", async (...args) => { + const requests = gateway(); + const result = await run(args); + expect(result.exitCode, result.stderr).toBe(2); + expect(requests).toHaveLength(0); +}); + +test("dry-run previews encoded paths without credentials or requests", async () => { + const requests = gateway(); + const env = { DASHSCOPE_API_KEY: "", DASHSCOPE_BASE_URL: "", BAILIAN_WORKSPACE_ID: "" }; + const search = await run(["search", "--keyword", " ", "--type", "OFFICIAL", "--dry-run"], env); + expect(search.exitCode, search.stderr).toBe(0); + expect(JSON.parse(search.stdout)).toEqual({ + method: "GET", + path: collection + "?pageNo=1&pageSize=30&type=OFFICIAL", + limit: 30, + }); + const registry = "https://skills-registry.example.test/skills"; + const registryPreview = await run(["get", "--name", "sample", "--dry-run"], { + ...env, + BAILIAN_SKILL_REGISTRY_URL: registry, + }); + expect(registryPreview.exitCode, registryPreview.stderr).toBe(0); + expect(JSON.parse(registryPreview.stdout)).toEqual({ + method: "GET", + url: registry + "/index.json", + name: "sample", + inspect_latest_package_file: "mcp-config.json", + }); + const detail = await run(["get", "--code", "a/b?#", "--dry-run"], env); + expect(detail.exitCode, detail.stderr).toBe(0); + expect(JSON.parse(detail.stdout)).toEqual({ + method: "GET", + path: collection + "/a%2Fb%3F%23", + inspect_latest_package_file: "mcp-config.json", + }); + const unauthenticated = await run(["search"], env); + expect(unauthenticated.exitCode).toBe(3); + expect(requests).toHaveLength(0); +}); + +test("filtered search checks other installed cloud revisions, reuses fresh checks and tolerates lookup errors", async ({ + onTestFinished, +}) => { + const config = mkdtempSync(join(tmpdir(), "bl-update-check-")); + onTestFinished(() => rmSync(config, { recursive: true, force: true })); + const remote = skill("skill_managed"); + const skills = join(config, "skills"); + mkdirSync(skills); + const lock = join(skills, "skill-lock.json"); + const installed = JSON.stringify({ + version: 1, + skills: { + reader: { + sourceType: "openapi", + remoteId: remote.id, + installedVersion: "1.9", + sourceLocation: origin, + }, + }, + }); + writeFileSync(lock, installed); + const empty = () => success(page(1, 30, 0, [])); + const requests = gateway( + empty(), + success(remote), + empty(), + empty(), + Response.json({ success: false }, { status: 503 }), + ); + const args = ["search", "--keyword", "unrelated"]; + const env = { BAILIAN_CONFIG_DIR: config }; + expect((await run([...args, "--dry-run"], env)).exitCode).toBe(0); + expect(requests).toHaveLength(0); + for (let attempt = 0; attempt < 2; attempt++) { + const result = await run(args, env); + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stderr)).toMatchObject({ + warning: { code: "SKILL_UPDATE_AVAILABLE", details: { update_command: "bl skill update" } }, + }); + expect(JSON.parse(result.stdout).skills).toEqual([]); + } + const cache = join(config, "skill-update-cache"); + const file = join(cache, readdirSync(cache)[0]!); + writeFileSync(file, JSON.stringify({ checkedAt: 0, revision: remote.latest_version })); + const offline = await run(args, env); + expect(offline.exitCode, offline.stderr).toBe(0); + expect(offline.stderr).not.toContain("SKILL_UPDATE_AVAILABLE"); + expect(requests.map((url) => url.pathname)).toEqual([ + collection, + collection + "/" + remote.id, + collection, + collection, + collection + "/" + remote.id, + ]); + expect(readFileSync(lock, "utf8")).toBe(installed); +}); + +test("search returns an empty mixed catalog page", async () => { + const requests = gateway(success(page(1, 30, 0, []))); + const result = await run(["search"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + total: 0, + page_start: 1, + page_end: 1, + page_size: 30, + skills: [], + }); + expect(requests.map((url) => url.pathname + url.search)).toEqual([ + collection + "?pageNo=1&pageSize=30", + ]); +}); + +test("search sends the filters on every page and only returns as many items as requested", async () => { + const skills = ["third", "fourth", "fifth", "sixth"].map((id) => skill(id, "customer")); + const requests = gateway( + success(page(2, 2, 8, skills.slice(0, 2))), + success(page(3, 2, 8, skills.slice(2))), + ); + const result = await run([ + "search", + "--keyword", + " 订单 & pdf ", + "--type", + "PRIVATE", + "--page", + "2", + "--page-size", + "2", + "--limit", + "3", + ]); + expect(result.exitCode, result.stderr).toBe(0); + const output = JSON.parse(result.stdout); + expect(output).toMatchObject({ total: 8, page_start: 2, page_end: 3, page_size: 2 }); + expect(output.skills.map((item: { skill_code: string }) => item.skill_code)).toEqual([ + "third", + "fourth", + "fifth", + ]); + expect(output.skills[0]).toMatchObject({ + type: "private", + skill_name: "Display name", + description: "Description", + latest_version: "2.0", + installed: false, + install_state: "not-installed", + installations: [], + }); + expect(requests.map((url) => [url.pathname, Object.fromEntries(url.searchParams)])).toEqual( + ["2", "3"].map((pageNo) => [ + collection, + { pageNo, pageSize: "2", type: "CUSTOMER", keywords: "订单 & pdf" }, + ]), + ); +}); + +test("search stops at the service window even if more matches exist", async () => { + const requests = gateway(success(page(10000, 1, 10001, [skill("last")]))); + const result = await run(["search", "--page", "10000", "--page-size", "1", "--limit", "2"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + page_end: 10000, + total: 10001, + skills: [{ skill_code: "last" }], + }); + expect(requests).toHaveLength(1); +}); + +test("an inconsistent later page fails without emitting a partial search result", async () => { + const requests = gateway( + success(page(1, 1, 3, [skill("first")])), + success(page(1, 1, 3, [skill("first")])), + ); + const result = await run(["search", "--page-size", "1", "--limit", "3"]); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + expect(JSON.parse(result.stderr).error.request_id).toBe("fixture-request"); + expect(requests.map((url) => url.searchParams.get("pageNo"))).toEqual(["1", "2"]); +}); + +test("cloud search and get by code reconcile canonical installation names, user links and project installations", async ({ + onTestFinished, +}) => { + const directory = realpathSync(mkdtempSync(join(tmpdir(), "bl-skill-catalog-"))); + onTestFinished(() => rmSync(directory, { recursive: true, force: true })); + const project = join(directory, "project"); + const config = join(directory, "config"); + const canonical = join(config, "skills", "canonical"); + const missingLink = join(directory, ".claude", "skills", "canonical"); + const projectPath = join(project, ".cursor", "skills", "canonical"); + for (const path of [canonical, projectPath]) { + mkdirSync(path, { recursive: true }); + writeFileSync(join(path, "SKILL.md"), "---\nname: canonical\ndescription: fixture\n---\n"); + } + const remote = skill("skill_abc"); + const lockPath = join(dirname(canonical), "skill-lock.json"); + const lock = JSON.stringify({ + version: 1, + skills: { + canonical: { + ...buildSkillLockEntry({ remoteId: remote.id, version: "1.0" }, [missingLink]), + sourceType: "openapi", + }, + }, + }); + writeFileSync(lockPath, lock); + const requests = gateway(success(remote), success(page(1, 30, 1, [remote]))); + const env = { HOME: directory, USERPROFILE: directory, BAILIAN_CONFIG_DIR: config }; + const result = await run(["get", "--code", remote.id, "--with-mcp", "false"], env, project); + expect(result.exitCode, result.stderr).toBe(0); + const detail = JSON.parse(result.stdout); + expect(detail).toMatchObject({ + skill_code: remote.id, + install_state: "outdated", + locked_version: "1.0", + installed: true, + installations: [ + { + agent: null, + scope: "user", + installed_path: canonical, + install_state: "outdated", + locked_version: "1.0", + }, + { + agent: "claude-code", + scope: "user", + installed_path: missingLink, + install_state: "missing", + }, + { + agent: "cursor", + scope: "project", + installed_path: projectPath, + install_state: "untracked", + locked_version: null, + }, + ], + }); + const search = await run(["search"], env, project); + expect(search.exitCode, search.stderr).toBe(0); + expect(JSON.parse(search.stdout).skills).toEqual([detail]); + expect(requests.map((url) => url.pathname)).toEqual([collection + "/skill_abc", collection]); + expect(readFileSync(lockPath, "utf8")).toBe(lock); +}); + +test("get by name reads an unversioned OSS archive and distinguishes installations from same-code OpenAPI results", async ({ + onTestFinished, +}) => { + const config = mkdtempSync(join(tmpdir(), "bl-skill-legacy-")); + onTestFinished(() => rmSync(config, { recursive: true, force: true })); + const canonical = join(config, "skills", "pdf"); + mkdirSync(canonical, { recursive: true }); + writeFileSync(join(canonical, "SKILL.md"), "fixture"); + writeFileSync( + join(dirname(canonical), "skill-lock.json"), + JSON.stringify({ version: 1, skills: { pdf: { sourceType: "oss", contentHash: "old" } } }), + ); + const registry = "https://registry.example.test/skills"; + const env = { + BAILIAN_CONFIG_DIR: config, + BAILIAN_SKILL_REGISTRY_URL: registry, + DASHSCOPE_API_KEY: "", + DASHSCOPE_BASE_URL: "", + BAILIAN_WORKSPACE_ID: "", + }; + const archive = await buildTarBr({ + "SKILL.md": "---\nname: pdf\ndescription: OSS sample\n---\n", + "mcp-config.json": JSON.stringify({ service: { serverCode: "declared-mcp" } }), + }); + const requests: string[] = []; + vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + requests.push(request.url); + expect(request.method).toBe("GET"); + if (request.url.startsWith(origin + collection)) { + expect(request.headers.get("Authorization")).toBe("Bearer fixture-key"); + return success(skill("pdf")); + } + expect(request.headers.get("Authorization")).toBeNull(); + if (request.url === registry + "/index.json") + return Response.json({ + skills: { pdf: { remoteId: "skill_pdf", description: "OSS sample", contentHash: "new" } }, + }); + if (request.url === registry + "/pdf/skill.tar.br") return new Response(Buffer.from(archive)); + throw new Error("unexpected request"); + }); + const first = await run(["get", "--name", "pdf"], env); + expect(first.exitCode, first.stderr).toBe(0); + expect(JSON.parse(first.stdout)).toMatchObject({ + skill_name: "pdf", + skill_code: "skill_pdf", + source: "oss", + description: "OSS sample", + latest_version: null, + install_state: "outdated", + locked_version: null, + depends_on_mcp: ["declared-mcp"], + installations: [{ installed_path: canonical, install_state: "outdated" }], + }); + const metadata = await run(["get", "--name", "pdf", "--with-mcp", "false"], env); + expect(metadata.exitCode, metadata.stderr).toBe(0); + expect(JSON.parse(metadata.stdout)).not.toHaveProperty("depends_on_mcp"); + const missing = await run(["get", "--name", "absent"], env); + expect(missing.exitCode, missing.stderr).toBe(1); + expect(missing.stderr).toContain("OSS"); + const unauthenticated = await run(["get", "--code", "pdf", "--with-mcp", "false"], env); + expect(unauthenticated.exitCode, unauthenticated.stderr).toBe(3); + const cloud = await run(["get", "--code", "pdf", "--with-mcp", "false"], { + BAILIAN_CONFIG_DIR: config, + }); + expect(cloud.exitCode, cloud.stderr).toBe(0); + expect(JSON.parse(cloud.stdout)).toMatchObject({ + source: "official", + installed: false, + installations: [], + }); + expect(requests).toEqual([ + registry + "/index.json", + registry + "/pdf/skill.tar.br", + registry + "/index.json", + registry + "/index.json", + origin + collection + "/pdf", + ]); +}); + +test("get keeps distinct target versions and ignores records from another gateway or project", async ({ + onTestFinished, +}) => { + const directory = realpathSync(mkdtempSync(join(tmpdir(), "bl-skill-targets-"))); + onTestFinished(() => rmSync(directory, { recursive: true, force: true })); + const project = join(directory, "project"); + const config = join(directory, "config"); + const userPath = join(directory, ".claude", "skills", "reader"); + const projectPath = join(project, ".cursor", "skills", "reader"); + for (const path of [userPath, projectPath]) { + mkdirSync(path, { recursive: true }); + writeFileSync(join(path, "SKILL.md"), "fixture"); + } + const user = { + canonicalName: "reader", + remoteId: "skill_reader", + sourceType: "openapi", + sourceLocation: origin, + agent: "claude-code", + scope: "user", + installedPath: userPath, + installedVersion: "1.0", + }; + const scoped = { + ...user, + agent: "cursor", + scope: "project", + projectRoot: project, + installedPath: projectPath, + installedVersion: "2.0", + }; + mkdirSync(join(config, "skills"), { recursive: true }); + writeFileSync( + join(config, "skills", "skill-lock.json"), + JSON.stringify({ + version: 1, + skills: { + first: user, + second: scoped, + foreign: { ...user, remoteId: "elsewhere", sourceLocation: "https://other.example.test" }, + otherProject: { + ...scoped, + remoteId: "other-project", + projectRoot: join(directory, "other"), + }, + }, + }), + ); + const requests = gateway(success(skill(user.remoteId))); + const detail = await run( + ["get", "--code", user.remoteId, "--with-mcp", "false"], + { HOME: directory, USERPROFILE: directory, BAILIAN_CONFIG_DIR: config }, + project, + ); + expect(detail.exitCode, detail.stderr).toBe(0); + expect(JSON.parse(detail.stdout)).toMatchObject({ + skill_code: user.remoteId, + locked_version: null, + installations: [ + { agent: "claude-code", scope: "user", install_state: "outdated", locked_version: "1.0" }, + { agent: "cursor", scope: "project", install_state: "installed", locked_version: "2.0" }, + ], + }); + expect(requests.map((url) => url.pathname)).toEqual([collection + "/skill_reader"]); +}); + +test.each([200, 500])("get preserves a server error returned with HTTP %i", async (status) => { + gateway( + Response.json( + { + success: false, + error_code: "SKILL_NOT_EXIST", + error_msg: "skill不存在", + data: null, + request_id: "req-detail", + }, + { status }, + ), + ); + const result = await run(["get", "--code", "unknown"]); + expect(result.exitCode).toBe(1); + expect(result.stdout).toBe(""); + expect(JSON.parse(result.stderr).error).toMatchObject({ + api_code: "SKILL_NOT_EXIST", + message: "skill不存在", + request_id: "req-detail", + }); +}); + +describe.skipIf(!isDashScopeE2EReady())("cloud skill gateway", () => { + // Live subprocess smoke uses the configured API key and gateway through normal CLI startup. + test("a returned official code opens its detail", async () => { + const search = await runCommandE2e(SKILL_ROUTES, [ + "skill", + "search", + "--type", + "official", + "--page-size", + "1", + "--output", + "json", + ]); + expect(search.exitCode, search.stderr).toBe(0); + const code = JSON.parse(search.stdout).skills[0]?.skill_code; + expect(code).toEqual(expect.any(String)); + const detail = await runCommandE2e(SKILL_ROUTES, [ + "skill", + "get", + "--code", + code, + "--output", + "json", + ]); + expect(detail.exitCode, detail.stderr).toBe(0); + expect(JSON.parse(detail.stdout).skill_code).toBe(code); + }); +}); diff --git a/packages/commands/tests/e2e/skill-lifecycle.e2e.test.ts b/packages/commands/tests/e2e/skill-lifecycle.e2e.test.ts new file mode 100644 index 000000000..e10b84ecc --- /dev/null +++ b/packages/commands/tests/e2e/skill-lifecycle.e2e.test.ts @@ -0,0 +1,783 @@ +import { + existsSync, + lstatSync, + mkdirSync, + mkdtempSync, + readFileSync, + realpathSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import * as core from "bailian-cli-core"; +import { httpTransport } from "bailian-cli-core"; +import { afterEach, expect, test, vi } from "vite-plus/test"; +import { buildTarBr } from "../../../core/tests/helpers/skill-archive.ts"; +import { createZip } from "../../src/commands/managed-agent/session-debug.ts"; +import { runCommandInProcess } from "./helpers.ts"; +import { SKILL_ROUTES } from "./topic-routes.ts"; + +const id = "skill_document"; +const origin = "https://catalog.example.test"; +const registry = "https://registry.example.test"; +const collection = "/api/v1/skills"; +const temporary: string[] = []; +afterEach(() => { + vi.restoreAllMocks(); + for (const path of temporary.splice(0)) rmSync(path, { recursive: true, force: true }); +}); + +function fixture(workspaceId?: string) { + const apiOrigin = workspaceId ? `https://${workspaceId}.cn-beijing.maas.aliyuncs.com` : origin; + const home = realpathSync(mkdtempSync(join(tmpdir(), "bl-skill-lifecycle-"))); + temporary.push(home); + const project = join(home, "project"); + mkdirSync(project); + const state = { + latest: "1.0", + cloudCodes: [id], + expire: false, + malformed: false, + manifest: undefined as string | undefined, + ossNames: ["reader"], + ossHash: undefined as string | undefined, + active: new Set(["ready"]), + }; + const requests: string[] = []; + const env = { + HOME: home, + USERPROFILE: home, + BAILIAN_CONFIG_DIR: join(home, "config"), + DASHSCOPE_API_KEY: "fixture-key", + DASHSCOPE_BASE_URL: workspaceId ? "" : origin, + BAILIAN_WORKSPACE_ID: workspaceId ?? "", + BAILIAN_SKILL_REGISTRY_URL: registry, + NODE_OPTIONS: "", + NODE_USE_ENV_PROXY: "", + HTTP_PROXY: "", + HTTPS_PROXY: "", + ALL_PROXY: "", + NO_PROXY: "", + http_proxy: "", + https_proxy: "", + all_proxy: "", + no_proxy: "", + }; + const run = (args: string[], config = {}) => + runCommandInProcess( + SKILL_ROUTES, + ["skill", ...args, "--output", "json"], + { ...env, ...config }, + { cwd: project }, + ); + const ok = (data: unknown) => + Response.json({ success: true, data, request_id: "fixture-request" }); + vi.spyOn(httpTransport, "fetch").mockImplementation(async (input, init) => { + const request = new Request(input, init); + const url = new URL(request.url); + requests.push(url.pathname); + if (url.pathname.startsWith("/api/v1/mcp/servers/")) { + expect(url.origin).toBe(apiOrigin); + expect(request.headers.get("Authorization")).toBe("Bearer fixture-key"); + const [code, action] = url.pathname.slice("/api/v1/mcp/servers/".length).split("/"); + expect(request.method).toBe(action ? "POST" : "GET"); + if (action) { + expect(action).toBe(code === "custom" ? "enable" : "activate"); + state.active.add(code!); + } + return ok({ + mcp_code: code, + ...(code === "market-finance" && { + billing: { mode: "per_call", unit_price: "0.01", free_quota: 0 }, + }), + type: code === "custom" ? "CUSTOMER" : "OFFICIAL", + server_status: state.active.has(code!) ? "ACTIVATED" : "INACTIVE", + requires_manual_setup: code === "manual", + }); + } + expect(request.method).toBe("GET"); + if (url.origin === registry) { + expect(request.headers.has("Authorization")).toBe(false); + const name = state.ossNames.find( + (candidate) => url.pathname === `/${candidate}/skill.tar.br`, + ); + if (name) { + const files = { + "SKILL.md": `---\nname: ${name}\ndescription: Public fixture\n---\n`, + ...(state.manifest !== undefined && { "mcp-config.json": state.manifest }), + }; + return new Response(Buffer.from(await buildTarBr(files))); + } + expect(url.pathname).toBe("/index.json"); + return Response.json({ + skills: Object.fromEntries( + state.ossNames.map((name) => [ + name, + { description: `Public ${name}`, contentHash: state.ossHash }, + ]), + ), + }); + } + if (url.hostname === "download.example.test") { + expect(request.headers.has("Authorization")).toBe(false); + if (state.expire) { + state.expire = false; + return new Response("expired", { status: 403 }); + } + const version = url.pathname.slice(1); + const path = version === "1.0" ? "wrapped/SKILL.md" : "SKILL.md"; + const archive = createZip([ + { + name: state.malformed ? "other.md" : path, + content: Buffer.from("---\nname: reader\ndescription: Reader fixture\n---\n" + version), + }, + ...(state.manifest !== undefined + ? [ + { + name: path.replace("SKILL.md", "mcp-config.json"), + content: Buffer.from(state.manifest), + }, + ] + : []), + ]); + return new Response(Buffer.from(archive)); + } + expect(url.origin).toBe(apiOrigin); + expect(request.headers.get("Authorization")).toBe("Bearer fixture-key"); + const skill = { + id, + source: "official", + status: "active", + latest_version: state.latest, + display_name: "Document reader", + }; + if (url.pathname === collection) + return ok({ + items: state.cloudCodes.map((code) => ({ ...skill, id: code })), + page_no: 1, + page_size: 100, + total: state.cloudCodes.length, + }); + if (url.pathname === collection + "/" + id) return ok(skill); + if (url.pathname.startsWith(collection + "/" + id + "/versions/")) { + const [version, content] = url.pathname + .slice((collection + "/" + id + "/versions/").length) + .split("/"); + return ok({ + skill_id: id, + version, + status: "active", + ...(content && { file_url: "https://download.example.test/" + version }), + }); + } + return Response.json( + { success: false, error_msg: "Unknown skill", error_code: "NOT_FOUND" }, + { status: 404 }, + ); + }); + return { home, project, state, run, requests }; +} + +const cursor = ["--agent", "cursor", "--scope", "project"]; +const claude = ["--agent", "claude-code", "--scope", "project"]; +test("ambiguous lifecycle selectors fail before authentication, requests or writes", async () => { + const { home, requests, run } = fixture(); + const noKey = { DASHSCOPE_API_KEY: "" }; + for (const command of ["add", "update", "remove", "list"]) { + const result = await run([command, "--name", "reader", "--code", id], noKey); + expect(result.exitCode, result.stderr).toBe(2); + } + for (const args of [ + ["add", "--code", id, "--all"], + ["update", "--name", "reader", "--all"], + ["update", "--code", ""], + ["add", "--name", "reader,"], + ["list", "--name", "reader", "--source", "cloud"], + ["list", "--code", id, "--source", "oss"], + ["add", "--source", "cloud", "--all"], + ["update", "--source", "cloud", "--all"], + ["add", "--source", "oss", "--code", id], + ["update", "--source", "cloud", "--name", "reader"], + ["remove", "--source", "oss", "--code", id], + ]) { + const result = await run(args, noKey); + expect(result.exitCode, result.stderr).toBe(2); + } + expect(requests).toEqual([]); + expect(existsSync(join(home, "config", "skills"))).toBe(false); +}); + +test("bare add --all installs only public packages without cloud credentials", async () => { + const { home, state, requests, run } = fixture(); + state.ossNames = ["reader", id]; + const result = await run(["add", "--all"], { DASHSCOPE_API_KEY: "", DASHSCOPE_BASE_URL: "" }); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout).summary).toMatchObject({ succeeded: 2, failed: 0 }); + expect(requests.sort()).toEqual(["/index.json", "/reader/skill.tar.br", `/${id}/skill.tar.br`]); + for (const name of state.ossNames) + expect(readFileSync(join(home, "config", "skills", name, "SKILL.md"), "utf8")).toContain( + "Public fixture", + ); +}); + +test("update --all applies a new OSS revision only to installed project skills", async () => { + const { home, project, state, requests, run } = fixture(); + const noCloud = { DASHSCOPE_API_KEY: "", DASHSCOPE_BASE_URL: "", BAILIAN_WORKSPACE_ID: "" }; + state.ossNames = ["reader", "not-installed"]; + const add = await run(["add", "--name", "reader", ...cursor, "--with-mcp", "false"], noCloud); + expect(add.exitCode, add.stderr).toBe(0); + const root = join(project, ".cursor", "skills"); + const installed = join(root, "reader"); + const revision = join(home, "new-revision"); + mkdirSync(revision); + writeFileSync(join(revision, "SKILL.md"), readFileSync(join(installed, "SKILL.md"))); + state.manifest = "{}"; + writeFileSync(join(revision, "mcp-config.json"), state.manifest); + state.ossHash = core.computeDirContentHash(revision); + + const list = await run(["list", "--name", "reader", ...cursor], noCloud); + expect(list.exitCode, list.stderr).toBe(0); + expect(JSON.parse(list.stderr).warning.details.update_command).toBe( + "bl skill update --all --scope project", + ); + requests.length = 0; + const update = await run(["update", "--all", "--scope", "project"], noCloud); + expect(update.exitCode, update.stderr).toBe(0); + expect(JSON.parse(update.stdout).results).toMatchObject([ + { code: "reader", source: "oss", reason: "UPDATED", agent: "cursor", scope: "project" }, + ]); + expect(requests).toEqual(["/index.json", "/reader/skill.tar.br"]); + expect(core.computeDirContentHash(installed)).toBe(state.ossHash); + expect(existsSync(join(root, "not-installed"))).toBe(false); +}); + +test("list selects and filters by public name or exact OpenAPI code", async () => { + const { state, requests, run } = fixture(); + state.ossNames = ["reader", id]; + state.cloudCodes.push("other_code"); + const publicList = await run(["list", "--name", id], { DASHSCOPE_API_KEY: "" }); + expect(publicList.exitCode, publicList.stderr).toBe(0); + expect(JSON.parse(publicList.stdout).skills).toMatchObject([{ name: id, source: "oss" }]); + expect(requests.splice(0)).toEqual(["/index.json"]); + const cloudList = await run(["list", "--code", id]); + expect(cloudList.exitCode, cloudList.stderr).toBe(0); + expect(JSON.parse(cloudList.stdout).skills).toMatchObject([{ skill_code: id, source: "cloud" }]); + expect(requests).not.toContain("/index.json"); +}); + +test("name and code select separate sources for same-name installs, including legacy records", async () => { + const { home, run, requests } = fixture(); + const root = join(home, "config", "skills"); + const localFile = join(root, "reader", "SKILL.md"); + const cloudFile = join(home, ".cursor", "skills", "reader", "SKILL.md"); + const missingOssPath = join(home, ".claude", "skills", "reader"); + mkdirSync(join(root, "reader"), { recursive: true }); + writeFileSync(localFile, "public copy"); + writeFileSync( + join(root, "skill-lock.json"), + JSON.stringify({ + version: 1, + skills: { reader: { installedAt: "2026-01-01", links: [missingOssPath] } }, + }), + ); + const noKey = { DASHSCOPE_API_KEY: "", DASHSCOPE_BASE_URL: "", BAILIAN_WORKSPACE_ID: "" }; + const unauthenticated = await run(["list"], noKey); + expect(unauthenticated.exitCode, unauthenticated.stderr).toBe(3); + expect(requests).toEqual([]); + const ossList = await run(["list", "--source", "oss", "--status", "installed"], noKey); + expect(ossList.exitCode, ossList.stderr).toBe(0); + expect(JSON.parse(ossList.stdout).skills).toMatchObject([ + { name: "reader", source: "oss", status: "installed" }, + ]); + expect(requests.splice(0)).toEqual(["/index.json"]); + const cloudList = await run(["list"]); + expect(cloudList.exitCode, cloudList.stderr).toBe(0); + expect(JSON.parse(cloudList.stdout).skills).toMatchObject([ + { skill_code: id, source: "cloud", status: "not-installed" }, + ]); + const conflict = await run(["add", "--code", id, "--agent", "claude-code"]); + expect(conflict.exitCode).toBe(1); + expect(JSON.parse(conflict.stdout).results[0].reason).toBe("SOURCE_CONFLICT"); + expect(existsSync(missingOssPath)).toBe(false); + const add = await run(["add", "--code", id, "--agent", "cursor"]); + expect(add.exitCode, add.stderr).toBe(0); + expect(existsSync(cloudFile)).toBe(true); + const byAlias = await run([ + "add", + "--code", + "reader", + "--agent", + "cursor", + "--with-mcp", + "false", + ]); + expect(byAlias.exitCode, byAlias.stderr).toBe(1); + expect(requests).toContain(`${collection}/reader`); + const update = await run(["update"]); + expect(update.exitCode, update.stderr).toBe(0); + expect(JSON.parse(update.stdout).results).toMatchObject([{ code: id, reason: "UP_TO_DATE" }]); + expect(requests).not.toContain("/index.json"); + requests.length = 0; + const ossUpdate = await run(["update", "--all", "--dry-run"], noKey); + expect(ossUpdate.exitCode, ossUpdate.stderr).toBe(0); + expect(JSON.parse(ossUpdate.stdout).results).toMatchObject([{ code: "reader" }]); + expect(requests.splice(0)).toEqual(["/index.json"]); + for (const selector of [ + ["--source", "oss"], + ["--name", "all"], + ]) { + const legacyUpdate = await run(["update", ...selector, "--dry-run"], noKey); + expect(legacyUpdate.exitCode, legacyUpdate.stderr).toBe(0); + expect(JSON.parse(legacyUpdate.stdout)).toEqual(JSON.parse(ossUpdate.stdout)); + expect(requests.splice(0)).toEqual(["/index.json"]); + } + const wrongCode = await run(["remove", "--code", "reader"], noKey); + expect(wrongCode.exitCode, wrongCode.stderr).toBe(1); + expect(JSON.parse(wrongCode.stdout).results).toMatchObject([ + { code: "reader", reason: "NOT_INSTALLED" }, + ]); + expect(existsSync(cloudFile)).toBe(true); + const remove = await run(["remove", "--code", id], noKey); + expect(remove.exitCode, remove.stderr).toBe(0); + expect(existsSync(cloudFile)).toBe(false); + expect(readFileSync(localFile, "utf8")).toBe("public copy"); + const removeOss = await run(["remove", "--name", "reader"], noKey); + expect(removeOss.exitCode, removeOss.stderr).toBe(0); + expect(existsSync(localFile)).toBe(false); + expect(requests).toEqual([]); +}); +test("cloud installs share packages, respect pins, preview and apply updates, then remove offline", async () => { + const { home, project, state, run, requests } = fixture("ws-install"); + const cursorFile = join(project, ".cursor", "skills", "reader", "SKILL.md"); + const claudeFile = join(project, ".claude", "skills", "reader", "SKILL.md"); + const lock = join(home, "config", "skills", "skill-lock.json"); + const add = ["add", "--code", id]; + const preview = await run([...add, ...cursor, "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(requests.splice(0)).toEqual([ + `${collection}/${id}`, + `${collection}/${id}/versions/1.0`, + `${collection}/${id}/versions/1.0/content`, + "/1.0", + ]); + expect(existsSync(lock)).toBe(false); + state.expire = true; + const installed = await run([...add, ...cursor]); + expect(installed.exitCode, installed.stderr).toBe(0); + expect(JSON.parse(installed.stdout)).toMatchObject({ + summary: { succeeded: 1 }, + mcp_dependency_status: "metadata_unavailable", + }); + expect(requests.filter((path) => path.endsWith("/content"))).toHaveLength(2); + expect(readFileSync(cursorFile, "utf8")).toContain("1.0"); + expect(Object.values(JSON.parse(readFileSync(lock, "utf8")).skills)).toMatchObject([ + { sourceLocation: "https://ws-install.cn-beijing.maas.aliyuncs.com" }, + ]); + const again = await run([...add, ...cursor]); + expect(JSON.parse(again.stdout).summary.noop).toBe(1); + const pinned = await run([...add, ...claude, "--skill-version", "1.0", "--with-mcp", "false"]); + expect(pinned.exitCode, pinned.stderr).toBe(0); + expect(JSON.parse(pinned.stdout).mcp_dependency_status).toBe("disabled"); + state.latest = "1.1"; + const list = await run(["list", "--source", "cloud", ...cursor, "--status", "outdated"]); + expect(JSON.parse(list.stdout).skills).toMatchObject([ + { + name: "reader", + skill_code: id, + locked_version: "1.0", + latest_version: "1.1", + agent: "cursor", + }, + ]); + const notice = JSON.parse(list.stderr); + expect(notice).toMatchObject({ + warning: { + code: "SKILL_UPDATE_AVAILABLE", + details: { + scope: "project", + source: "cloud", + update_command: "bl skill update --scope project", + skills: [{ skill_code: id, agent: "cursor", current: "1.0", latest: "1.1" }], + }, + }, + }); + const update = ["update", "--code", id, ...cursor, "--diff"]; + const before = readFileSync(lock); + const plan = await run([...update, "--dry-run"]); + expect(JSON.parse(plan.stdout).results[0].diff).toEqual({ + available: false, + download_required: true, + content_path: collection + "/" + id + "/versions/1.1/content", + }); + expect(readFileSync(lock)).toEqual(before); + expect(requests).not.toContain("/1.1"); + const updated = await run(update); + expect(updated.exitCode, updated.stderr).toBe(0); + expect(JSON.parse(updated.stdout).results[0].diff.modified).toEqual(["SKILL.md"]); + expect(readFileSync(cursorFile, "utf8")).toContain("1.1"); + const fixed = await run(["update", "--code", id, ...claude]); + expect(JSON.parse(fixed.stdout).summary.noop).toBe(1); + expect(readFileSync(claudeFile, "utf8")).toContain("1.0"); + const count = requests.length; + const removed = await run(["remove", "--code", id, ...cursor], { + DASHSCOPE_API_KEY: "", + BAILIAN_WORKSPACE_ID: "", + }); + expect(removed.exitCode, removed.stderr).toBe(0); + expect(requests).toHaveLength(count); + expect(existsSync(claudeFile)).toBe(true); + expect(existsSync(cursorFile)).toBe(false); +}); + +test("untracked and edited files survive; invalid replacement preserves both installation and lock", async () => { + const { home, project, run, state } = fixture(); + const directory = join(project, ".cursor", "skills", "reader"); + mkdirSync(directory, { recursive: true }); + const file = join(directory, "SKILL.md"); + writeFileSync(file, "existing"); + const add = ["add", "--code", id, ...cursor]; + const conflict = await run(add); + expect(JSON.parse(conflict.stdout).results[0].reason).toBe("UNTRACKED_CONFLICT"); + expect(readFileSync(file, "utf8")).toBe("existing"); + rmSync(directory, { recursive: true }); + const partial = await run(["add", "--code", id + ",unknown", ...cursor]); + expect(partial.exitCode).toBe(1); + expect(JSON.parse(partial.stdout).summary).toEqual({ succeeded: 1, failed: 1, noop: 0 }); + const lock = join(home, "config", "skills", "skill-lock.json"); + const before = readFileSync(lock); + state.latest = "1.1"; + state.malformed = true; + const failed = await run(["update", "--code", id, ...cursor]); + expect(failed.exitCode).toBe(1); + expect(readFileSync(lock)).toEqual(before); + expect(readFileSync(file, "utf8")).toContain("1.0"); + writeFileSync(file, "local edit"); + for (const action of ["update", "remove"]) { + const result = await run([action, "--code", id, ...cursor]); + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout).results[0].reason).toBe("MODIFIED_CONFLICT"); + } + expect(readFileSync(file, "utf8")).toBe("local edit"); + expect(readFileSync(lock)).toEqual(before); +}); + +test("list reconciles disk, scoped records and the catalog; update restores a missing target from cache", async () => { + const { run, project, requests } = fixture(); + const args = ["list", ...cursor]; + const empty = await run(args); + expect(JSON.parse(empty.stdout).skills[0].status).toBe("not-installed"); + const installed = await run(["add", "--code", id, ...cursor]); + expect(installed.exitCode, installed.stderr).toBe(0); + const root = join(project, ".cursor", "skills"); + mkdirSync(join(root, "handmade")); + writeFileSync(join(root, "handmade", "SKILL.md"), "handmade"); + const mixed = await run([...args, "--status", "untracked,installed"]); + expect(JSON.parse(mixed.stdout).skills).toMatchObject([ + { name: "handmade", status: "untracked" }, + { name: "reader", status: "installed" }, + ]); + rmSync(join(root, "reader"), { recursive: true }); + const missing = await run([...args, "--status", "missing"]); + expect(JSON.parse(missing.stdout).skills[0].status).toBe("missing"); + const fetched = requests.filter((path) => path === "/1.0").length; + const repair = await run(["update", ...cursor]); + expect(repair.exitCode, repair.stderr).toBe(0); + expect(readFileSync(join(root, "reader", "SKILL.md"), "utf8")).toContain("1.0"); + expect(requests.filter((path) => path === "/1.0")).toHaveLength(fetched); + const emptyUser = await run(["list", "--source", "cloud", "--scope", "user"]); + expect(JSON.parse(emptyUser.stdout).skills).toMatchObject([ + { status: "not-installed", scope: "user" }, + ]); +}); + +test("skill add previews dependencies without writing and activates each required server once", async () => { + const { home, project, run, requests, state } = fixture("ws-dependencies"); + state.manifest = JSON.stringify({ + finance: { + serverCode: "market-finance", + serverName: "Finance", + url: "https://untrusted.invalid/tool", + }, + alias: { serverCode: "market-finance" }, + ready: { serverCode: "ready" }, + custom: { serverCode: "custom" }, + DASHSCOPE_API_KEY: "private-placeholder", + }); + const base = "/api/v1/mcp/servers/"; + const args = ["add", "--code", id, ...cursor]; + const destinations = [ + join(home, "config", "skills", "skill-lock.json"), + join(project, ".cursor", "skills", "reader"), + ]; + const preview = await run([...args, "--dry-run"]); + expect(preview.exitCode, preview.stderr).toBe(0); + expect(JSON.parse(preview.stdout).mcp_dep_results).toMatchObject([ + { + code: "market-finance", + action: "activate", + status: "planned", + skills: [id], + billing: { mode: "per_call", unit_price: "0.01", free_quota: 0 }, + }, + { code: "ready", reason: "ALREADY_ACTIVATED", status: "noop" }, + { code: "custom", action: "enable", status: "planned" }, + ]); + expect(destinations.some((path) => existsSync(path))).toBe(false); + expect(requests.some((path) => path.endsWith("/activate") || path.endsWith("/enable"))).toBe( + false, + ); + requests.length = 0; + const installed = await run(args); + expect(installed.exitCode, installed.stderr).toBe(0); + expect(destinations.every((path) => existsSync(path))).toBe(true); + expect(requests.filter((path) => path.startsWith(base))).toEqual( + ["market-finance", "ready", "custom", "market-finance/activate", "custom/enable"].map( + (path) => base + path, + ), + ); + expect(requests.filter((path) => path === "/1.0")).toHaveLength(1); + expect(installed.stdout + installed.stderr + preview.stdout).not.toMatch( + /private-placeholder|untrusted\.invalid/, + ); + requests.length = 0; + const again = await run(args); + expect(again.exitCode, again.stderr).toBe(0); + expect( + JSON.parse(again.stdout).mcp_dep_results.every( + (row: { status: string }) => row.status === "noop", + ), + ).toBe(true); + expect(requests).not.toContain("/1.0"); +}); + +test("manual MCP setup preserves local installation and reports a console link", async () => { + const { run, project, state } = fixture(); + state.manifest = JSON.stringify({ manual: { serverCode: "manual" } }); + const result = await run(["add", "--code", id, ...cursor]); + expect(result.exitCode, result.stderr).toBe(1); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 1 }, + mcp_dependency_status: "failed", + mcp_dep_results: [ + { + code: "manual", + error_code: "MANUAL_SETUP_REQUIRED", + detail: { console_url: expect.stringMatching(/^https:/) }, + }, + ], + }); + expect(existsSync(join(project, ".cursor", "skills", "reader", "SKILL.md"))).toBe(true); +}); + +test("OSS fan-out reads the same manifest, supports explicit credentials and keeps installation available without a key", async () => { + const { home, run, requests, state } = fixture(); + state.manifest = JSON.stringify({ finance: { serverCode: "market-finance" } }); + const args = ["add", "--name", "reader"]; + const offline = await run(args, { DASHSCOPE_API_KEY: "" }); + expect(offline.exitCode, offline.stderr).toBe(3); + expect(JSON.parse(offline.stdout)).toMatchObject({ + summary: { succeeded: 1 }, + mcp_dep_results: [{ code: "market-finance", status: "failed" }], + }); + expect(existsSync(join(home, "config", "skills", "reader", "mcp-config.json"))).toBe(true); + expect(requests).toEqual(["/index.json", "/reader/skill.tar.br"]); + const activated = await run(args); + expect(activated.exitCode, activated.stderr).toBe(0); + expect(JSON.parse(activated.stdout).mcp_dep_results).toMatchObject([ + { code: "market-finance", status: "succeeded" }, + ]); + requests.length = 0; + const disabled = await run([...args, "--with-mcp", "false"], { DASHSCOPE_API_KEY: "" }); + expect(disabled.exitCode, disabled.stderr).toBe(0); + expect(JSON.parse(disabled.stdout)).toMatchObject({ + mcp_dep_results: [], + mcp_dependency_status: "disabled", + }); + expect(requests.some((path) => path.includes("/mcp/"))).toBe(false); +}); + +test("invalid manifests do not disclose their contents or issue MCP requests", async () => { + const { run, requests, state } = fixture(); + state.manifest = '{"DASHSCOPE_API_KEY":"private-placeholder",'; + const args = ["add", "--code", id, ...cursor]; + const invalid = await run(args); + expect(invalid.exitCode, invalid.stderr).toBe(1); + expect(invalid.stderr + invalid.stdout).not.toContain("private-placeholder"); + const disabled = await run([...args, "--with-mcp", "false"]); + expect(disabled.exitCode, disabled.stderr).toBe(0); + expect(requests.some((path) => path.includes("/mcp/"))).toBe(false); +}); + +test("skill get reads by default from the latest package without installing or contacting MCP; absent and empty declarations differ", async () => { + const { run, state, requests, home } = fixture(); + const get = ["get", "--code", id]; + const detail = await run([...get, "--with-mcp", "false"]); + expect(detail.exitCode, detail.stderr).toBe(0); + expect(requests.splice(0)).toEqual([`${collection}/${id}`]); + const inspect = [...get, "--with-mcp"]; + const absent = await run(get); + expect(JSON.parse(absent.stdout).depends_on_mcp).toBe(null); + state.manifest = "{}"; + expect(JSON.parse((await run(inspect)).stdout).depends_on_mcp).toEqual([]); + state.manifest = JSON.stringify({ + alias: { serverCode: "market-finance" }, + other: { serverCode: "market-finance" }, + DASHSCOPE_API_KEY: "private-placeholder", + }); + const result = await run(get); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + latest_version: "1.0", + depends_on_mcp: ["market-finance"], + }); + expect(result.stdout).not.toContain("private-placeholder"); + state.manifest = "invalid private-placeholder"; + const broken = await run(get); + expect(broken.exitCode).toBe(1); + expect(JSON.parse(broken.stdout)).toMatchObject({ skill_code: id, depends_on_mcp: null }); + expect(broken.stderr).not.toContain("private-placeholder"); + expect(requests.some((path) => path.includes("/mcp/"))).toBe(false); + expect(existsSync(join(home, "config", "skills"))).toBe(false); +}); + +test("bulk OSS installation activates a shared dependency once and identifies both owners", async () => { + const { state, run, requests } = fixture(); + state.manifest = JSON.stringify({ shared: { serverCode: "shared" } }); + state.ossNames = ["reader", "writer"]; + const result = await run(["add", "--all"]); + expect(result.exitCode, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toMatchObject({ + summary: { succeeded: 2 }, + mcp_dep_results: [{ code: "shared", status: "succeeded", skills: ["reader", "writer"] }], + }); + expect(requests.filter((path) => path.includes("/mcp/"))).toEqual([ + "/api/v1/mcp/servers/shared", + "/api/v1/mcp/servers/shared/activate", + ]); + expect(requests.filter((path) => path.endsWith(".tar.br"))).toHaveLength(2); +}); + +test("legacy OSS previews and repairs only missing agent links, then reports a noop", async () => { + const { home, state, run, requests } = fixture(); + const canonical = join(home, "config", "skills", "reader"); + const existing = join(home, ".claude", "skills", "reader"); + const missing = join(home, ".cursor", "skills", "reader"); + mkdirSync(canonical, { recursive: true }); + mkdirSync(join(home, ".claude", "skills"), { recursive: true }); + mkdirSync(join(home, ".cursor")); + writeFileSync(join(canonical, "SKILL.md"), "legacy"); + symlinkSync(canonical, existing, "junction"); + state.ossHash = "same-index-hash"; + const lock = join(home, "config", "skills", "skill-lock.json"); + writeFileSync( + lock, + JSON.stringify({ + version: 1, + skills: { + reader: { sourceType: "oss", contentHash: state.ossHash, links: [existing] }, + }, + }), + ); + const args = ["update", "--name", "reader"]; + const before = readFileSync(lock); + for (const preview of [true, false]) { + const result = await run(preview ? [...args, "--dry-run"] : args); + expect(result.exitCode, result.stderr).toBe(0); + const payload = JSON.parse(result.stdout); + expect(payload.summary).toEqual({ succeeded: 1, noop: 0, failed: 0 }); + expect(payload.results[0]).toMatchObject({ status: "succeeded", reason: "REPAIRED" }); + expect(payload.results[0].agent_results).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + agent: "cursor", + installed_path: missing, + status: "succeeded", + reason: "REPAIRED", + }), + expect.objectContaining({ agent: "claude-code", installed_path: existing, status: "noop" }), + ]), + ); + expect(existsSync(missing)).toBe(!preview); + if (preview) expect(readFileSync(lock)).toEqual(before); + } + expect(JSON.parse(readFileSync(lock, "utf8")).skills.reader.links).toContain(missing); + const again = await run(args); + expect(JSON.parse(again.stdout).results[0]).toMatchObject({ + status: "noop", + reason: "UP_TO_DATE", + }); + expect(requests).toEqual(["/index.json", "/index.json", "/index.json"]); +}); + +test("legacy OSS removal restores the canonical package, symlink, fallback copy and ledger on commit failure", async () => { + const { home, run, requests } = fixture(); + const root = join(home, "config", "skills"); + const canonical = join(root, "reader"); + const link = join(home, ".claude", "skills", "reader"); + const copy = join(home, ".cursor", "skills", "reader"); + for (const path of [canonical, copy]) { + mkdirSync(path, { recursive: true }); + writeFileSync(join(path, "SKILL.md"), "original"); + } + mkdirSync(join(home, ".claude", "skills"), { recursive: true }); + symlinkSync(canonical, link, "junction"); + const lock = join(root, "skill-lock.json"); + writeFileSync( + lock, + JSON.stringify({ + version: 1, + skills: { + reader: { sourceType: "oss", links: [link, copy] }, + }, + }), + ); + const before = readFileSync(lock); + vi.spyOn(core, "writeSkillLock").mockImplementationOnce(() => { + expect( + [canonical, link, copy].every((path) => !lstatSync(path, { throwIfNoEntry: false })), + ).toBe(true); + throw new Error("fixture lock write failed"); + }); + const args = ["remove", "--name", "reader"]; + const failed = await run(args); + expect(failed.exitCode).toBe(1); + expect(failed.stderr).toContain("fixture lock write failed"); + expect(readFileSync(lock)).toEqual(before); + expect(lstatSync(link).isSymbolicLink()).toBe(true); + for (const path of [canonical, link, copy]) + expect(readFileSync(join(path, "SKILL.md"), "utf8")).toBe("original"); + expect((await run(args)).exitCode).toBe(0); + expect(JSON.parse(readFileSync(lock, "utf8")).skills).toEqual({}); + expect(requests).toEqual([]); +}); + +test("OSS update checks use one catalog read, notify without modifying installs and use the cache on offline removal", async () => { + const { home, state, run, requests } = fixture(); + state.ossHash = "new-index-hash"; + const root = join(home, "config", "skills"); + for (const name of ["reader", "old"]) { + mkdirSync(join(root, name), { recursive: true }); + writeFileSync(join(root, name, "SKILL.md"), "original"); + } + const record = { sourceType: "oss", contentHash: "old-index-hash" }; + const lock = join(root, "skill-lock.json"); + writeFileSync(lock, JSON.stringify({ version: 1, skills: { reader: record, old: record } })); + const before = readFileSync(lock); + const list = await run(["list", "--source", "oss"], { DASHSCOPE_API_KEY: "" }); + expect(list.exitCode, list.stderr).toBe(0); + expect(JSON.parse(list.stderr)).toMatchObject({ + warning: { + code: "SKILL_UPDATE_AVAILABLE", + details: { update_command: "bl skill update --all" }, + }, + }); + expect(readFileSync(lock)).toEqual(before); + expect(readFileSync(join(root, "reader", "SKILL.md"), "utf8")).toBe("original"); + expect(requests.splice(0)).toEqual(["/index.json"]); + const removal = await run(["remove", "--name", "old"]); + expect(removal.exitCode, removal.stderr).toBe(0); + expect(removal.stderr).toContain("SKILL_UPDATE_AVAILABLE"); + expect(requests).toEqual([]); +}); diff --git a/packages/commands/tests/e2e/skill.e2e.test.ts b/packages/commands/tests/e2e/skill.e2e.test.ts index 8f12c48c9..426a0091b 100644 --- a/packages/commands/tests/e2e/skill.e2e.test.ts +++ b/packages/commands/tests/e2e/skill.e2e.test.ts @@ -45,6 +45,7 @@ describe("e2e: skill", () => { expect(exitCode, stderr).toBe(0); expect(stderr).toMatch(/--all/); expect(stderr).toMatch(/--name/); + expect(stderr).toContain("--code"); }); test("skill update --help exits successfully", async () => { @@ -52,12 +53,14 @@ describe("e2e: skill", () => { expect(exitCode, stderr).toBe(0); expect(stderr).toMatch(/--all/); expect(stderr).toMatch(/--name/); + expect(stderr).toContain("--code"); }); test("skill remove --help exits successfully", async () => { const { stderr, exitCode } = await runCommandHelp(SKILL_ROUTES, ["skill", "remove", "--help"]); expect(exitCode, stderr).toBe(0); expect(stderr).toMatch(/--name/); + expect(stderr).toContain("--code"); }); test("skill list --help exits successfully", async () => { @@ -75,7 +78,7 @@ describe("e2e: skill", () => { // Local-only cases: no credentials; update uses a loopback registry fixture. describe("e2e: skill (local, no credentials)", () => { - test("skill add without --all or --name errors as usage error (2)", async () => { + test("skill add without a selector errors as usage error (2)", async () => { const { stdout, stderr, exitCode } = await runCommandE2e(SKILL_ROUTES, [ "skill", "add", @@ -98,7 +101,7 @@ describe("e2e: skill (local, no credentials)", () => { expect(`${stdout}\n${stderr}`).toMatch(/--all|--name|either/i); }); - test("skill remove without --name errors as usage error (2)", async () => { + test("skill remove without a selector errors as usage error (2)", async () => { const { stdout, stderr, exitCode } = await runCommandE2e(SKILL_ROUTES, [ "skill", "remove", @@ -236,7 +239,7 @@ describe.skipIf(!isBailianE2EEnabled())("e2e: skill (real registry)", () => { const configDir = makeTempConfigDir(); const { stdout, stderr, exitCode } = await runCommandE2e( SKILL_ROUTES, - ["skill", "list", "--output", "json"], + ["skill", "list", "--source", "oss", "--output", "json"], { BAILIAN_CONFIG_DIR: configDir }, ); expect(exitCode, stderr).toBe(0); diff --git a/packages/commands/tests/e2e/topic-routes.ts b/packages/commands/tests/e2e/topic-routes.ts index b639e77e6..bc7a59236 100644 --- a/packages/commands/tests/e2e/topic-routes.ts +++ b/packages/commands/tests/e2e/topic-routes.ts @@ -194,11 +194,20 @@ export const SPEECH_GENERATE_ROUTES: E2eRouteExports = { }; export const MCP_ROUTES: E2eRouteExports = { + "mcp activate": "mcpActivate", "mcp call": "mcpCall", "mcp connect": "mcpConnect", + "mcp create": "mcpCreate", + "mcp deactivate": "mcpDeactivate", + "mcp delete": "mcpDelete", "mcp disconnect": "mcpDisconnect", + "mcp get": "mcpGet", "mcp list": "mcpList", "mcp tools": "mcpTools", + "mcp tool call": "mcpToolCall", + "mcp tool list": "mcpToolList", + "mcp tool search": "mcpToolSearch", + "mcp update": "mcpUpdate", }; export const SEARCH_WEB_ROUTES: E2eRouteExports = { "search web": "searchWeb" }; @@ -450,6 +459,8 @@ export const TOKEN_PLAN_ROUTES: E2eRouteExports = { export const SKILL_ROUTES: E2eRouteExports = { "skill add": "skillAdd", + "skill search": "skillSearch", + "skill get": "skillGet", "skill update": "skillUpdate", "skill remove": "skillRemove", "skill list": "skillList", diff --git a/packages/commands/tests/mcp-agent-config.test.ts b/packages/commands/tests/mcp-agent-config.test.ts index dbfc0aa9c..9d1efe7bb 100644 --- a/packages/commands/tests/mcp-agent-config.test.ts +++ b/packages/commands/tests/mcp-agent-config.test.ts @@ -1,9 +1,18 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { enterIsolatedHome, type IsolatedHomeHandle } from "e2e/isolation"; import { parse as parseToml } from "smol-toml"; -import { afterEach, beforeEach, describe, expect, test } from "vite-plus/test"; +import { afterEach, beforeEach, describe, expect, test, vi } from "vite-plus/test"; +import * as writers from "../src/commands/config/agent/writers/utils.ts"; import { connectMcpAgents, disconnectMcpAgents, @@ -53,6 +62,120 @@ function readJson(path: string): Record { } describe("MCP Agent registration", () => { + test("project registrations keep their native paths and independent ownership across projects", () => { + const firstProject = join(home, "first"); + const secondProject = join(home, "second"); + for (const projectRoot of [firstProject, secondProject]) { + mkdirSync(projectRoot); + const paths = connectMcpAgents({ + agents: [ + "codex", + "claude-code", + "cursor", + "qoder", + "qwen-code", + "gemini", + "opencode", + "pi", + "workbuddy", + ], + spec: spec(), + cliVersion: "test", + home, + configDir, + scope: "project", + projectRoot, + }).map((result) => result.path); + expect(paths).toEqual( + [ + ".codex/config.toml", + ".mcp.json", + ".cursor/mcp.json", + ".qoder/settings.json", + ".qwen/settings.json", + ".gemini/settings.json", + "opencode.json", + ".pi/mcp.json", + ".workbuddy/mcp.json", + ].map((file) => join(projectRoot, file)), + ); + } + disconnectMcpAgents({ + agents: ["claude-code"], + name: "ImageGenerate", + home, + configDir, + scope: "project", + projectRoot: firstProject, + }); + expect(readJson(join(firstProject, ".mcp.json")).mcpServers).toEqual({}); + expect(readJson(join(secondProject, ".mcp.json")).mcpServers).toHaveProperty("ImageGenerate"); + }); + + test("a manifest write failure restores the target file and permits retry", () => { + const path = join(home, ".claude.json"); + const original = '{"mcpServers":{"other":{"url":"https://example.org"}}}'; + writeFileSync(path, original); + const options = { + agents: ["claude-code" as const], + spec: spec(), + home, + configDir, + cliVersion: "test", + }; + const writer = vi.spyOn(writers, "writeJsonAtomic").mockImplementationOnce(() => { + throw new Error("manifest write failed"); + }); + try { + expect(() => connectMcpAgents(options)).toThrow("manifest write failed"); + expect(readFileSync(path, "utf8")).toBe(original); + expect(existsSync(join(configDir, "mcp-registrations.json"))).toBe(false); + expect(connectMcpAgents(options)[0].status).toBe("added"); + } finally { + writer.mockRestore(); + } + }); + + test("WorkBuddy and CodeBuddy use their own project files and disconnect follows recorded paths", () => { + const projectRoot = join(home, "project"); + mkdirSync(projectRoot); + mkdirSync(join(home, ".workbuddy")); + mkdirSync(join(home, ".codebuddy")); + const options = { + agents: ["workbuddy" as const], + home, + configDir, + projectRoot, + scope: "project" as const, + }; + connectMcpAgents({ ...options, spec: spec(), cliVersion: "test" }); + const files = [join(projectRoot, ".workbuddy", "mcp.json"), join(projectRoot, ".mcp.json")]; + for (const path of files) expect(readJson(path).mcpServers).toHaveProperty("ImageGenerate"); + rmSync(join(home, ".codebuddy"), { recursive: true }); + disconnectMcpAgents({ ...options, name: "ImageGenerate" }); + for (const path of files) expect(readJson(path).mcpServers).toEqual({}); + }); + + test("project credentials cannot be written through a directory link outside the project", () => { + const projectRoot = join(home, "project"); + const external = join(home, "elsewhere"); + mkdirSync(projectRoot); + mkdirSync(external); + symlinkSync(external, join(projectRoot, ".cursor"), "junction"); + expect(() => + connectMcpAgents({ + agents: ["cursor"], + spec: spec(), + home, + configDir, + cliVersion: "test", + scope: "project", + projectRoot, + }), + ).toThrow(/outside the project/); + expect(existsSync(join(external, "mcp.json"))).toBe(false); + }); + test("Codex writes a Streamable HTTP server without a type field", () => { const codexDir = join(home, ".codex"); mkdirSync(codexDir, { recursive: true }); diff --git a/packages/commands/tests/output/local-command-output.test.ts b/packages/commands/tests/output/local-command-output.test.ts index 8296be4ed..87dd91f8d 100644 --- a/packages/commands/tests/output/local-command-output.test.ts +++ b/packages/commands/tests/output/local-command-output.test.ts @@ -13,6 +13,7 @@ import { type AnyCommand, type LocalizedText, } from "bailian-cli-core"; +import { runPreparedCommand } from "../../../runtime/src/preparation.ts"; import { createOutputReporter } from "bailian-cli-runtime"; import { enterIsolatedHome } from "e2e/isolation"; import authLogin from "../../src/commands/auth/login.ts"; @@ -70,7 +71,7 @@ const scenarios: Scenario[] = [ { name: "skill list installed", command: skillList, - flags: {}, + flags: { source: "oss" }, seedSkill: true, registry: { "bailian-fixture": { @@ -83,12 +84,22 @@ const scenarios: Scenario[] = [ { name: "skill update up-to-date", command: skillUpdate, - flags: {}, + flags: { all: true }, seedSkill: true, registry: { "bailian-fixture": { contentHash: "fixture" } }, }, - { name: "skill update delisted", command: skillUpdate, flags: {}, seedSkill: true }, - { name: "skill remove installed", command: skillRemove, flags: { name: "all" }, seedSkill: true }, + { + name: "skill update delisted", + command: skillUpdate, + flags: { all: true }, + seedSkill: true, + }, + { + name: "skill remove installed", + command: skillRemove, + flags: { name: "all" }, + seedSkill: true, + }, { name: "skill remove preview", command: skillRemove, @@ -99,7 +110,7 @@ const scenarios: Scenario[] = [ { name: "skill add preview", command: skillAdd, - flags: { all: true }, + flags: { all: true, withMcp: false }, registry: { "bailian-fixture": {} }, dryRun: true, }, @@ -143,10 +154,10 @@ const scenarios: Scenario[] = [ }, }, { name: "config UI preview", command: configUi, flags: {}, dryRun: true }, - { name: "skill list empty", command: skillList, flags: {} }, + { name: "skill list empty", command: skillList, flags: { source: "oss" } }, { name: "skill add empty", command: skillAdd, flags: { all: true } }, { name: "skill remove empty", command: skillRemove, flags: { name: "all" } }, - { name: "skill update empty", command: skillUpdate, flags: {} }, + { name: "skill update empty", command: skillUpdate, flags: { all: true } }, { name: "skill init empty", command: skillInit, flags: {} }, { name: "MCP list", command: mcpList, flags: {} }, { name: "MCP tools", command: mcpTools, flags: { server: "fixture" } }, @@ -228,30 +239,47 @@ async function invoke( baseUrl: "https://fixture.invalid", apiCred: { source: "flag", token: "sk-fixture", baseUrl: "https://fixture.invalid" }, }); - vi.spyOn(client, "console").mockResolvedValue({ - data: { DataV2: { data: { data: { total: 0, mcpServerDetailList: [] } } } }, - }); + if (scenario.command === mcpList) { + vi.spyOn(client, "requestJson").mockResolvedValue({ + success: true, + data: { total: 0, items: [] }, + }); + } + if (scenario.command === mcpConnect) { + vi.spyOn(client, "requestJson").mockResolvedValue({ + success: true, + data: { + mcp_code: "fixture", + type: "OFFICIAL", + server_status: "ACTIVATED", + dashscope_endpoint: "https://fixture.invalid/mcp", + }, + }); + } const closed = vi.fn(); vi.spyOn(client, "connectBailianMcp").mockResolvedValue({ url: "https://fixture.invalid/mcp", client: { - listTools: async () => [], + listToolsPage: async () => ({ tools: [] }), callTool: async () => ({ content: [], ...retained }), close: closed, }, } as never); let error: unknown; try { - await scenario.command.run({ + const ctx = { identity, settings, flags: scenario.flags, + command: scenario.command, + confirmed: false, client, localize, output: reporter.output, configStore: makeConfigStore(), authStore: makeAuthStore({ flags: {}, file: {}, env: {} }), - } as never); + } as never; + await runPreparedCommand(ctx); } catch (caught) { error = caught; } diff --git a/packages/commands/tests/update-binary-skill-sync.test.ts b/packages/commands/tests/update-binary-skill-sync.test.ts index aa377feff..8510eabca 100644 --- a/packages/commands/tests/update-binary-skill-sync.test.ts +++ b/packages/commands/tests/update-binary-skill-sync.test.ts @@ -97,7 +97,7 @@ test.each([undefined, "aliyun bl"])( warning.code === "SKILL_UPDATE_SKIPPED", ); expect(JSON.stringify(skipped)).toContain( - `Run manually: ${commandPrefix ?? "bl"} skill update`, + `Run manually: ${commandPrefix ?? "bl"} skill update --all`, ); expectSkillUpdateNotInit(); }, @@ -132,7 +132,7 @@ test.each([ ); function expectSkillUpdateNotInit(): void { - expect(childProcessMocks.spawnSync).toHaveBeenCalledWith("bl skill update --output json", { + expect(childProcessMocks.spawnSync).toHaveBeenCalledWith("bl skill update --all --output json", { shell: true, stdio: ["inherit", "pipe", "pipe"], }); diff --git a/packages/core/package.json b/packages/core/package.json index 871c62667..1d663ee5a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-core", - "version": "2.13.0", + "version": "2.14.0", "description": "Core SDK for bailian-cli. See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/core/src/client/client.ts b/packages/core/src/client/client.ts index a161923c1..41d89adf9 100644 --- a/packages/core/src/client/client.ts +++ b/packages/core/src/client/client.ts @@ -190,6 +190,20 @@ export class Client { return requestUrl; } + /** Bind a service default for the whole command, including delegated requests. */ + withDefaultBaseUrl(resolveDefault: () => string | undefined): Client { + if (!this.deps.baseUrlIsDefault) return this; + const baseUrl = resolveDefault(); + if (!baseUrl || baseUrl === this.baseUrl) return this; + return new Client({ + ...this.deps, + requestSignals: this.requestSignals, + baseUrl, + baseUrlIsDefault: false, + apiCred: this.deps.apiCred && { ...this.deps.apiCred, baseUrl }, + }); + } + private toOpts({ path, ...rest }: ClientRequestOpts): RequestOpts { const cred = this.requireApi(); const requestUrl = /^https?:\/\//.test(path) ? path : cred.baseUrl + path; @@ -288,13 +302,20 @@ export class Client { serverCode: string, urlOverride?: string, serviceSource?: string, - ): Promise<{ client: McpConnectedClient; url: string }> { - this.requireApi(); + ): ReturnType { + const { baseUrl, token } = this.requireApi(); + const httpUrl = baseUrl + bailianMcpPath(serverCode); + if (urlOverride) { + // A user-supplied path can resemble a different Bailian product's API. + if (URL.canParse(urlOverride)) this.recordRequest(new URL(urlOverride).origin); + } else { + this.recordRequest(httpUrl); + } return connectBailianMcpWithFallback({ deps: this.http, - authToken: this.deps.apiCred?.token, - httpUrl: this.url(bailianMcpPath(serverCode)), - sseUrl: this.url(bailianMcpSsePath(serverCode)), + authToken: token, + httpUrl, + sseUrl: baseUrl + bailianMcpSsePath(serverCode), serverCode, urlOverride, serviceSource, diff --git a/packages/core/src/client/endpoints.ts b/packages/core/src/client/endpoints.ts index 6a1294801..cc81f8297 100644 --- a/packages/core/src/client/endpoints.ts +++ b/packages/core/src/client/endpoints.ts @@ -268,6 +268,25 @@ export function mcpWebSearchPath(): string { return "/api/v1/mcps/WebSearch/mcp"; } +export function mcpBaseUrl(workspaceId: string): string { + return workspaceEndpoint(workspaceId, ""); +} + +export function mcpServersPath(serverCode?: string): string { + const collection = "/api/v1/mcp/servers"; + return serverCode === undefined ? collection : `${collection}/${encodeURIComponent(serverCode)}`; +} + +export function skillBaseUrl(workspaceId: string): string { + return workspaceEndpoint(workspaceId, ""); +} + +export function skillsPath(skillId?: string): string { + if (skillId !== undefined && (!skillId.trim() || skillId === "." || skillId === "..")) + throw new UsageError("Invalid skill ID. / Skill ID 无效。"); + return skillId === undefined ? "/api/v1/skills" : `/api/v1/skills/${encodeURIComponent(skillId)}`; +} + // ---- Datasets / Fine-tune Files ---- /** diff --git a/packages/core/src/client/http.ts b/packages/core/src/client/http.ts index ddb37e21b..38468c402 100644 --- a/packages/core/src/client/http.ts +++ b/packages/core/src/client/http.ts @@ -122,7 +122,8 @@ async function performRequest( } catch { body = { message: raw }; } - body.request_id ??= res.headers.get("x-request-id") ?? undefined; + body.request_id ??= + body.requestID ?? body.requestId ?? res.headers.get("x-request-id") ?? undefined; const mapped = mapApiError(res.status, body, opts.url); throw new BailianError(mapped.message, mapped.exitCode, mapped.hint, { api: mapped.api, @@ -278,14 +279,23 @@ export async function requestJson(deps: HttpDeps, opts: RequestOpts): Promise data !== null && typeof data === "object" && ((data.code && data.code !== "200" && data.code !== 200 && data.code !== "Success") || - data.error) + data.error || + (data.success === false && + ("error_code" in data || + "errorCode" in data || + "error_msg" in data || + "errorMsg" in data))) ) { const mapped = mapApiError( res.status, { ...data, request_id: - data.request_id ?? data.requestID ?? res.headers.get("x-request-id") ?? undefined, + data.request_id ?? + data.requestID ?? + data.requestId ?? + res.headers.get("x-request-id") ?? + undefined, }, opts.url, ); diff --git a/packages/core/src/client/index.ts b/packages/core/src/client/index.ts index 844d2de4c..4b0776e0b 100644 --- a/packages/core/src/client/index.ts +++ b/packages/core/src/client/index.ts @@ -18,6 +18,10 @@ export { memorySearchPath, memorySkillExportPath, mcpWebSearchPath, + mcpBaseUrl, + mcpServersPath, + skillBaseUrl, + skillsPath, modelsLimitsPath, modelsPermissionsPath, profileSchemaItemPath, diff --git a/packages/core/src/client/mcp-sdk.ts b/packages/core/src/client/mcp-sdk.ts index 59549eeaa..c8e33784d 100644 --- a/packages/core/src/client/mcp-sdk.ts +++ b/packages/core/src/client/mcp-sdk.ts @@ -30,6 +30,7 @@ import { ErrorCode, McpError } from "@modelcontextprotocol/sdk/types.js"; import type { FetchLike, Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; import { BailianError } from "../errors/base.ts"; +import { apiErrorContext } from "../errors/api.ts"; import { ExitCode } from "../errors/codes.ts"; import { trackingHeaders } from "./headers.ts"; import type { HttpDeps } from "./http.ts"; @@ -120,7 +121,11 @@ export function mapSdkError( if (error.code === ErrorCode.ConnectionClosed && options?.localCloseFired) { return new BailianError(raw || "MCP connection closed.", ExitCode.NETWORK); } - return new BailianError(`MCP error (${error.code}): ${raw}`, ExitCode.GENERAL); + const context = + error.data && typeof error.data === "object" ? apiErrorContext(error.data) : undefined; + return new BailianError(`MCP error (${error.code}): ${raw}`, ExitCode.GENERAL, undefined, { + api: { apiCode: context?.apiCode ?? String(error.code), requestId: context?.requestId }, + }); } if (error instanceof StreamableHTTPError) { @@ -132,12 +137,7 @@ export function mapSdkError( } if (error instanceof SseError && sseGetFailure && sseGetFailure.status === error.code) { - let message = `MCP request failed: ${sseGetFailure.status} ${sseGetFailure.statusText}`; - if (sseGetFailure.body) message += ` - ${sseGetFailure.body.slice(0, 500)}`; - return new BailianError(message, ExitCode.GENERAL, undefined, { - api: { httpStatus: sseGetFailure.status }, - cause: error, - }); + return mcpHttpError(sseGetFailure, error); } return error; @@ -168,6 +168,21 @@ export interface SseGetFailure { body: string; } +function mcpHttpError({ status, statusText, body }: SseGetFailure, cause?: unknown) { + let context; + try { + const parsed: unknown = JSON.parse(body); + if (parsed && typeof parsed === "object") context = apiErrorContext(parsed); + } catch { + // Plain-text and HTML errors retain the same transport message. + } + const message = `MCP request failed: ${status} ${statusText}${body ? ` - ${body.slice(0, 500)}` : ""}`; + return new BailianError(message, ExitCode.GENERAL, undefined, { + api: { httpStatus: status, ...context }, + cause, + }); +} + /** * Build the transport-level fetch. Requests go through the shared * `httpTransport` (packaged Undici fetch on Node, native fetch on Bun) so the @@ -206,14 +221,8 @@ function createMcpFetch( debugResponse(deps, response); if (!response.ok && method === "POST" && !isRedirectStatus(response.status)) { - let message = `MCP request failed: ${response.status} ${response.statusText}`; - try { - const errorBody = await response.text(); - if (errorBody) message += ` - ${errorBody.slice(0, 500)}`; - } catch { - /* body already consumed or unreadable */ - } - throw new BailianError(message, ExitCode.GENERAL); + const body = await response.text().catch(() => ""); + throw mcpHttpError({ status: response.status, statusText: response.statusText, body }); } if ( @@ -294,16 +303,20 @@ export class SdkMcpAdapter implements McpConnectedClient { } async listTools(): Promise { + return (await this.listToolsPage()).tools; + } + + async listToolsPage(cursor?: string): Promise<{ tools: McpTool[]; nextCursor?: string }> { const client = await this.requireClient(); try { const result = await this.withLocalTimeout( - client.listTools(undefined, this.requestOptions()), + client.listTools(cursor === undefined ? undefined : { cursor }, this.requestOptions()), ); // Returned verbatim (the SDK-validated Tool objects): callers such as // `bl mcp tools --output json` keep every standard field the server // declares (outputSchema / annotations / title / `_meta`, …), matching // the old hand-rolled client's passthrough. - return result.tools as McpTool[]; + return { tools: result.tools, nextCursor: result.nextCursor }; } catch (error) { throw this.mapTransportError(error); } diff --git a/packages/core/src/client/mcp.ts b/packages/core/src/client/mcp.ts index fb0577221..ec19e16e0 100644 --- a/packages/core/src/client/mcp.ts +++ b/packages/core/src/client/mcp.ts @@ -73,12 +73,12 @@ export interface McpToolResult { * verbatim from `bl mcp list` (e.g. `WebSearch`, `market-cmapi00073529`). */ export function bailianMcpPath(serverCode: string): string { - return `/api/v1/mcps/${serverCode}/mcp`; + return `/api/v1/mcps/${encodeURIComponent(serverCode)}/mcp`; } /** Classic SSE path: `/api/v1/mcps//sse`. */ export function bailianMcpSsePath(serverCode: string): string { - return `/api/v1/mcps/${serverCode}/sse`; + return `/api/v1/mcps/${encodeURIComponent(serverCode)}/sse`; } /** @@ -132,7 +132,7 @@ export type ConnectBailianMcpOptions = { */ export async function connectBailianMcpWithFallback( options: ConnectBailianMcpOptions, -): Promise<{ client: McpConnectedClient; url: string }> { +): Promise<{ client: McpConnectedClient & Pick; url: string }> { const { deps, authToken, httpUrl, sseUrl, serverCode, urlOverride, serviceSource } = options; if (urlOverride) { diff --git a/packages/core/src/client/service-planes.ts b/packages/core/src/client/service-planes.ts index cdc92fe5b..a855428e9 100644 --- a/packages/core/src/client/service-planes.ts +++ b/packages/core/src/client/service-planes.ts @@ -31,7 +31,7 @@ export interface ServicePlane { /** Stable identifier; consumed by the coverage guard test and the telemetry docs. */ key: string; site: PlaneSite; - /** Request pathname prefixes, matched longest-first. */ + /** Path-segment prefixes, matched longest-first. A trailing slash matches descendants. */ prefixes: readonly string[]; } @@ -67,6 +67,16 @@ export const SERVICE_PLANES: readonly ServicePlane[] = [ site: "follow", prefixes: ["/api/v1/agentstudio/"], }, + { + key: "mcp", + site: "follow", + prefixes: ["/api/v1/mcp/servers", "/api/v1/mcps/"], + }, + { + key: "cloud-skill", + site: "follow", + prefixes: ["/api/v1/skills"], + }, { key: "custom-model-import", // `CUSTOM_MODEL_IMPORT_ENDPOINT` hardcodes the public mainland DashScope @@ -80,7 +90,11 @@ export const SERVICE_PLANES: readonly ServicePlane[] = [ // Longest prefix first so a specific namespace wins over a broader one. const PREFIX_ENTRIES = SERVICE_PLANES.flatMap((plane) => - plane.prefixes.map((prefix) => ({ prefix, plane })), + plane.prefixes.map((prefix) => ({ + prefix, + descendants: prefix.endsWith("/") ? prefix : prefix + "/", + plane, + })), ).sort((left, right) => right.prefix.length - left.prefix.length); /** @@ -96,7 +110,9 @@ export function classifyServicePlane(requestUrl: string): ServicePlane | undefin } catch { return undefined; } - return PREFIX_ENTRIES.find((entry) => pathname.startsWith(entry.prefix))?.plane; + return PREFIX_ENTRIES.find( + ({ prefix, descendants }) => pathname === prefix || pathname.startsWith(descendants), + )?.plane; } /** diff --git a/packages/core/src/errors/api.ts b/packages/core/src/errors/api.ts index 8523c4142..45b457b4f 100644 --- a/packages/core/src/errors/api.ts +++ b/packages/core/src/errors/api.ts @@ -2,6 +2,7 @@ import { BailianError } from "./base.ts"; import { ExitCode } from "./codes.ts"; export interface ApiErrorBody { + success?: boolean; error?: { message?: string; type?: string; @@ -11,11 +12,16 @@ export interface ApiErrorBody { message?: string; request_id?: string; requestID?: string; + requestId?: string; + error_code?: string; + error_msg?: string; + errorCode?: string; + errorMsg?: string; } -export function mapApiError(status: number, body: ApiErrorBody, _url?: string): BailianError { - const apiMsg = body.error?.message || body.message || `HTTP ${status}`; - const rawCode = body.error?.type ?? body.error?.code ?? body.code; +export function apiErrorContext(body: ApiErrorBody) { + const rawCode = + body.error?.type ?? body.error?.code ?? body.code ?? body.error_code ?? body.errorCode; const apiCode = typeof rawCode === "string" ? rawCode @@ -23,11 +29,13 @@ export function mapApiError(status: number, body: ApiErrorBody, _url?: string): ? String(rawCode) : undefined; + return { apiCode, requestId: body.request_id ?? body.requestID ?? body.requestId }; +} + +export function mapApiError(status: number, body: ApiErrorBody, _url?: string): BailianError { + const apiMsg = + body.error?.message || body.message || body.error_msg || body.errorMsg || `HTTP ${status}`; return new BailianError(apiMsg, ExitCode.GENERAL, undefined, { - api: { - httpStatus: status, - apiCode, - requestId: body.request_id ?? body.requestID, - }, + api: { httpStatus: status, ...apiErrorContext(body) }, }); } diff --git a/packages/core/src/skills/catalog-installs.ts b/packages/core/src/skills/catalog-installs.ts new file mode 100644 index 000000000..f6e283576 --- /dev/null +++ b/packages/core/src/skills/catalog-installs.ts @@ -0,0 +1,165 @@ +import { existsSync, statSync } from "node:fs"; +import { dirname, isAbsolute, join, resolve } from "node:path"; +import { getAgentTargets } from "./agents.ts"; +import { getSkillsDir, readSkillLock } from "./lock.ts"; +import { isSafeSkillName } from "./sanitize.ts"; +import type { SkillLockEntry, SkillStatus } from "./types.ts"; + +type Scope = "user" | "project"; +interface SkillLocation { + agent: string | null; + scope: Scope; + installed_path: string; + locked_version: string | null; + install_state: SkillStatus; +} + +function hasSkillManifest(path: string): boolean { + try { + return statSync(join(path, "SKILL.md"), { throwIfNoEntry: false })?.isFile() ?? false; + } catch (error) { + if (["ENOENT", "ENOTDIR", "ELOOP"].includes((error as NodeJS.ErrnoException).code ?? "")) + return false; + throw error; + } +} + +export function installationRoots(project = process.cwd(), canonical = resolve(getSkillsDir())) { + const roots = new Map(); + roots.set(canonical, { agent: null, scope: "user" }); + for (const target of getAgentTargets()) { + roots.set(resolve(target.skillsDir), { agent: target.id, scope: "user" }); + } + // These agents also have a native skills directory relative to the project. + for (const [agent, directory] of Object.entries({ + universal: ".agents", + "claude-code": ".claude", + cursor: ".cursor", + "qwen-code": ".qwen", + "gemini-cli": ".gemini", + pi: ".pi", + trae: ".trae", + opencode: ".opencode", + })) { + const root = join(project, directory, "skills"); + if (!roots.has(root)) roots.set(root, { agent, scope: "project" }); + } + return roots; +} + +/** One read-only snapshot of the lock and skill roots, shared by all hits in a search. */ +export function readCatalogInstalls( + baseUrl: string, + source?: SkillLockEntry["sourceType"], + lock = readSkillLock(), +) { + const project = process.cwd(); + const canonical = resolve(getSkillsDir()); + const roots = installationRoots(project, canonical); + const existingRoots = [...roots].filter(([root]) => existsSync(root)); + const records = new Map(); + const claimedPaths = new Set(); + const idsByName = new Map>(); + for (const [key, entry] of Object.entries(lock.skills)) { + if (!entry || typeof entry !== "object") continue; + const name = entry.canonicalName ?? key; + const id = source === "oss" ? name : (entry.remoteId ?? name); + if ( + typeof name !== "string" || + !isSafeSkillName(name) || + name.includes("\0") || + typeof id !== "string" + ) + continue; + const primary = entry.installedPath ?? join(canonical, name); + if (typeof primary !== "string" || !isAbsolute(primary)) continue; + const paths = [primary, ...(Array.isArray(entry.links) ? entry.links : [])] + .filter((path) => typeof path === "string" && isAbsolute(path)) + .map((path) => resolve(path)); + for (const path of paths) claimedPaths.add(path); + if (source && (entry.sourceType ?? "oss") !== source) continue; + if (entry.scope === "project" && entry.projectRoot && resolve(entry.projectRoot) !== project) + continue; + if ( + entry.sourceType === "openapi" && + entry.sourceLocation && + entry.sourceLocation.replace(/\/+$/, "") !== baseUrl.replace(/\/+$/, "") + ) + continue; + const entries = records.get(id) ?? []; + entries.push({ name, entry, paths }); + records.set(id, entries); + const ids = idsByName.get(name) ?? new Set(); + ids.add(id); + idsByName.set(name, ids); + } + + function inspect( + id: string, + latestVersion: string | null, + canonicalName?: string, + latestContentHash?: string, + ) { + const locations = new Map(); + const lookupId = source === "oss" ? (canonicalName ?? id) : id; + const names = new Set(); + if (canonicalName) names.add(canonicalName); + if (!idsByName.has(lookupId) || idsByName.get(lookupId)?.has(lookupId)) names.add(lookupId); + for (const { name, entry, paths } of records.get(lookupId) ?? []) { + names.add(name); + for (const path of paths) { + const root = roots.get(dirname(path)); + const lockedVersion = entry.installedVersion ?? null; + const state = !hasSkillManifest(path) + ? "missing" + : (lockedVersion && latestVersion && lockedVersion !== latestVersion) || + (latestContentHash && latestContentHash !== entry.contentHash) + ? "outdated" + : "installed"; + locations.set(path, { + installed_path: path, + agent: (path === paths[0] ? entry.agent : undefined) ?? root?.agent ?? null, + scope: (path === paths[0] ? entry.scope : undefined) ?? root?.scope ?? "user", + locked_version: lockedVersion, + install_state: state, + }); + } + } + for (const name of names) { + if (!isSafeSkillName(name) || name.includes("\0")) continue; + for (const [root, target] of existingRoots) { + const path = join(root, name); + if (!claimedPaths.has(path) && hasSkillManifest(path)) { + locations.set(path, { + ...target, + installed_path: path, + locked_version: null, + install_state: "untracked", + }); + } + } + } + const installations = [...locations.values()]; + const states = new Set(installations.map((location) => location.install_state)); + const priority: SkillStatus[] = ["outdated", "installed", "untracked", "missing"]; + const installState = priority.find((state) => states.has(state)) ?? "not-installed"; + const versions = new Set( + installations + .filter((location) => location.install_state !== "untracked") + .map((location) => location.locked_version), + ); + return { + installed: installations.some((location) => location.install_state !== "missing"), + install_state: installState, + locked_version: versions.size === 1 ? ([...versions][0] ?? null) : null, + installations, + }; + } + return { + claimedPaths, + resolveIds(name: string): string[] { + return records.has(name) ? [name] : [...(idsByName.get(name) ?? [name])]; + }, + inspect, + }; +} diff --git a/packages/core/src/skills/index.ts b/packages/core/src/skills/index.ts index 2f760368f..cf0fefda5 100644 --- a/packages/core/src/skills/index.ts +++ b/packages/core/src/skills/index.ts @@ -49,3 +49,5 @@ export { type SkillInstallRecord, } from "./installer.ts"; export { listSkillDirsOnDisk, computeSkillStatuses } from "./status.ts"; +export { installationRoots, readCatalogInstalls } from "./catalog-installs.ts"; +export { downloadSkillZip, extractSkillZip } from "./zip.ts"; diff --git a/packages/core/src/skills/installer.ts b/packages/core/src/skills/installer.ts index eb0600c4e..caa2925df 100644 --- a/packages/core/src/skills/installer.ts +++ b/packages/core/src/skills/installer.ts @@ -1,8 +1,13 @@ -import { existsSync, mkdirSync, rmSync } from "node:fs"; +import { cpSync, existsSync, mkdirSync, rmSync } from "node:fs"; import { join } from "node:path"; import { BailianError } from "../errors/base.ts"; import { ExitCode } from "../errors/codes.ts"; -import { detectInstalledAgents, fanOutSkillToAgents, type AgentTarget } from "./agents.ts"; +import { + detectInstalledAgents, + fanOutSkillToAgents, + type AgentTarget, + type LinkResult, +} from "./agents.ts"; import { atomicSwap, computeDirContentHash, @@ -42,6 +47,20 @@ export async function installSkillFromBuffer( tarBrBuffer: Buffer, expectedContentHash?: string, windowsPathRoots?: string[], +): Promise { + return installSkillFromSource( + name, + (directory) => extractTarBr(tarBrBuffer, directory), + expectedContentHash, + windowsPathRoots, + ); +} + +async function installSkillFromSource( + name: string, + extract: (directory: string) => void | Promise, + expectedContentHash?: string, + windowsPathRoots?: string[], ): Promise { assertSafeName(name); const skillsDir = getSkillsDir(); @@ -50,7 +69,7 @@ export async function installSkillFromBuffer( const tmpDir = join(skillsDir, `.tmp-${name}-${process.pid}-${Date.now()}`); try { mkdirSync(tmpDir, { recursive: true }); - await extractTarBr(tarBrBuffer, tmpDir); + await extract(tmpDir); const projectedRoots = windowsPathRoots ?? (process.platform === "win32" ? [dest] : []); const pathViolation = findWindowsPathViolation(tmpDir, projectedRoots); if (pathViolation) { @@ -120,6 +139,8 @@ export function removeSkillDir(name: string): boolean { */ export function buildSkillLockEntry(entry: SkillIndexEntry, links: string[]): SkillLockEntry { return { + remoteId: entry.remoteId, + installedVersion: entry.version, ...(entry.contentHash ? { contentHash: entry.contentHash } : {}), ...(entry.publishedAt ? { publishedAt: entry.publishedAt } : {}), installedAt: new Date().toISOString(), @@ -134,6 +155,7 @@ export interface SkillInstallRecord { lockEntry: SkillLockEntry; /** Ids of agents that actually received a link/copy (skipped ones excluded) */ linkedAgents: string[]; + linkResults: LinkResult[]; } /** @@ -151,15 +173,24 @@ export async function installSkillWithFanout( agents: AgentTarget[] = detectInstalledAgents(), recordedLinks: string[] = [], downloadAttempts?: number, + preparedDirectory?: string, ): Promise { const windowsPathRoots = process.platform === "win32" ? [join(getSkillsDir(), name), ...agents.map((agent) => join(agent.skillsDir, name))] : undefined; - await installSkill(name, entry, downloadAttempts, windowsPathRoots); + if (preparedDirectory) + await installSkillFromSource( + name, + (directory) => cpSync(preparedDirectory, directory, { recursive: true }), + entry.contentHash, + windowsPathRoots, + ); + else await installSkill(name, entry, downloadAttempts, windowsPathRoots); const fanout = fanOutSkillToAgents(name, agents, recordedLinks); return { lockEntry: buildSkillLockEntry(entry, fanout.links), linkedAgents: fanout.linkedAgents, + linkResults: fanout.results, }; } diff --git a/packages/core/src/skills/lock.ts b/packages/core/src/skills/lock.ts index f87d97c00..357c1661d 100644 --- a/packages/core/src/skills/lock.ts +++ b/packages/core/src/skills/lock.ts @@ -1,4 +1,5 @@ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { randomUUID } from "node:crypto"; import { join } from "node:path"; import { getConfigDir } from "../config/paths.ts"; import type { SkillLockEntry, SkillLockFile } from "./types.ts"; @@ -43,7 +44,14 @@ export function readSkillLock(): SkillLockFile { export function writeSkillLock(lock: SkillLockFile): void { mkdirSync(getSkillsDir(), { recursive: true }); - writeFileSync(getSkillLockPath(), JSON.stringify(lock, null, 2) + "\n"); + const path = getSkillLockPath(); + const temporary = `${path}.${randomUUID()}.tmp`; + try { + writeFileSync(temporary, JSON.stringify(lock, null, 2) + "\n", { mode: 0o600, flag: "wx" }); + renameSync(temporary, path); + } finally { + rmSync(temporary, { force: true }); + } } /** diff --git a/packages/core/src/skills/types.ts b/packages/core/src/skills/types.ts index b6fa9aa01..206acae3f 100644 --- a/packages/core/src/skills/types.ts +++ b/packages/core/src/skills/types.ts @@ -1,7 +1,7 @@ /** * Data structures for the unified skill publishing protocol (symmetric with FC publisher skills-publish.mjs). * - * Remote layout (public-read OSS, the sole data source for `bl skill`): + * Public OSS layout used by the registry installer: * /index.json — skill catalog (SkillsIndex) * //sha256-.tar.br — content-addressed skill object (tar + brotli); * entry.object names the exact file, so index.json is the single atomic commit point. @@ -14,6 +14,8 @@ /** A single skill entry in index.json */ export interface SkillIndexEntry { + /** Stable cloud ID, when the publisher associates this package with a catalog entry. */ + remoteId?: string; /** Reserved for the skill's own semantic version (x.y.z); not yet populated by the publisher */ version?: string; /** Beijing-time publish timestamp; refreshed whenever content changes — the human-facing release marker */ @@ -44,8 +46,18 @@ export interface SkillLockEntry { /** Publish timestamp of the installed revision (for display) */ publishedAt?: string; installedAt: string; - /** Reserved: future support for github/gitlab and other sources */ - sourceType: "oss"; + sourceType: "oss" | "openapi"; + sourceLocation?: string; + remoteId?: string; + canonicalName?: string; + installedVersion?: string; + pinnedVersion?: string; + cacheKey?: string; + /** Target-specific records identify their installation directly. Legacy OSS records use links. */ + agent?: string; + scope?: "user" | "project"; + projectRoot?: string; + installedPath?: string; description?: string; /** Fan-out link/copy paths to each agent; used for precise reclamation on remove */ links?: string[]; diff --git a/packages/core/src/skills/zip.ts b/packages/core/src/skills/zip.ts new file mode 100644 index 000000000..ff65c0b50 --- /dev/null +++ b/packages/core/src/skills/zip.ts @@ -0,0 +1,137 @@ +import { createWriteStream, existsSync, mkdirSync, readdirSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { Transform } from "node:stream"; +import { pipeline } from "node:stream/promises"; +import zlib from "node:zlib"; +import { fromBufferPromise } from "yauzl"; +import { ExitCode } from "../errors/codes.ts"; +import { BailianError } from "../errors/base.ts"; +import { httpTransport } from "../client/transport.ts"; +import { isSafeEntryName } from "./extract.ts"; + +const compressedLimit = 50 * 1024 * 1024; +const expandedLimit = 100 * 1024 * 1024; + +// Node 18 has no native CRC32. Use the standard ZIP polynomial on that runtime. +function updateChecksum(chunk: Buffer, previous: number) { + if (typeof zlib.crc32 === "function") return zlib.crc32(chunk, previous); + let checksum = previous ^ 0xffffffff; + for (const byte of chunk) { + checksum ^= byte; + for (let bit = 0; bit < 8; bit++) checksum = (checksum >>> 1) ^ (checksum & 1 ? 0xedb88320 : 0); + } + return (checksum ^ 0xffffffff) >>> 0; +} + +/** The signed URL authenticates itself. Never send a gateway credential to object storage. */ +export async function downloadSkillZip(fileUrl: string, timeout: number): Promise { + const url = URL.canParse(fileUrl) ? new URL(fileUrl) : undefined; + if (url?.protocol !== "https:" || url.username || url.password) + throw new BailianError("Invalid signed Skill download URL. / Skill 签名下载地址无效。"); + const response = await httpTransport.fetch(url, { + signal: AbortSignal.timeout(timeout * 1000), + redirect: "error", + }); + if (!response.ok || !response.body) { + const message = await response.text(); + throw new BailianError(message || `HTTP ${response.status}`, ExitCode.GENERAL, undefined, { + api: { httpStatus: response.status }, + }); + } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + try { + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + size += value.byteLength; + if (size > compressedLimit) { + await reader.cancel(); + throw new BailianError("Skill ZIP exceeds 50 MiB. / Skill ZIP 超过 50 MiB。"); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + return Buffer.concat(chunks, size); +} + +/** Extract to a fresh staging directory and locate the manifest at the root or inside its wrapper. */ +export async function extractSkillZip(bytes: Buffer, directory: string): Promise { + const archive = await fromBufferPromise(bytes, { strictFileNames: true }); + let expanded = 0; + try { + for await (const entry of archive.eachEntry()) { + let filename = entry.fileName; + if ( + !(entry.generalPurposeBitFlag & 0x800) && + !entry.extraFields.some((field) => field.id === 0x7075) && + entry.fileNameRaw.some((byte) => byte >= 128) + ) { + // Older publishers used UTF-8 or GBK without setting the UTF-8 ZIP flag. + try { + filename = new TextDecoder("utf-8", { fatal: true }).decode(entry.fileNameRaw); + } catch { + filename = new TextDecoder("gbk", { fatal: true }).decode(entry.fileNameRaw); + } + } + const name = filename.replace(/\/$/, ""); + const parts = name.split("/"); + const kind = (entry.externalFileAttributes >>> 16) & 0o170000; + if ( + !isSafeEntryName(name) || + parts.some( + (part) => + !part || + part === "." || + part.includes(":") || + /\p{Cc}/u.test(part) || + /[. ]$/.test(part) || + /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(part), + ) || + ![0, 0o100000, 0o040000].includes(kind) || + entry.isEncrypted() + ) { + throw new BailianError("Unsupported Skill ZIP entry. / Skill ZIP 包含不支持的条目。"); + } + expanded += entry.uncompressedSize; + if (expanded > expandedLimit) + throw new BailianError( + "Expanded Skill ZIP exceeds 100 MiB. / Skill ZIP 展开后超过 100 MiB。", + ); + const path = join(directory, ...parts); + if (filename.endsWith("/")) { + mkdirSync(path, { recursive: true }); + continue; + } + mkdirSync(dirname(path), { recursive: true }); + const executable = (entry.externalFileAttributes >>> 16) & 0o111; + let checksum = 0; + await pipeline( + await archive.openReadStreamPromise(entry), + new Transform({ + transform(chunk: Buffer, _encoding, done) { + checksum = updateChecksum(chunk, checksum); + done(null, chunk); + }, + }), + createWriteStream(path, { flags: "wx", mode: executable ? 0o755 : 0o644 }), + ); + if (checksum !== entry.crc32) + throw new BailianError("Skill ZIP checksum mismatch / Skill ZIP 校验失败"); + } + } finally { + archive.close(); + } + if (existsSync(join(directory, "SKILL.md"))) return directory; + const roots = readdirSync(directory, { withFileTypes: true }).filter( + (entry) => entry.isDirectory() && existsSync(join(directory, entry.name, "SKILL.md")), + ); + if (roots.length !== 1) + throw new BailianError( + "Expected one Skill package root with SKILL.md. / 压缩包须有一个包含 SKILL.md 的 Skill 根目录。", + ); + return join(directory, roots[0]!.name); +} diff --git a/packages/core/src/types/command.ts b/packages/core/src/types/command.ts index 2d3724810..13e0df957 100644 --- a/packages/core/src/types/command.ts +++ b/packages/core/src/types/command.ts @@ -263,6 +263,8 @@ export function credentialFlagDefs(cmd: { * for parsed arguments. Never handle tokens or baseUrl. */ export interface CommandContext { + /** Explicit runtime confirmation. A read-only planner may skip lookups used solely to classify risk. */ + readonly confirmed?: boolean; /** Resolve a unique registered product path; older hosts may omit this capability. */ commandPath?: (command: AnyCommand) => string[] | undefined; /** Read-only preparation result, supplied only after the runtime confirmation gate. */ @@ -316,6 +318,10 @@ export interface CommandNotice { export interface CommandPreparation { data: Prepared; preview: unknown; + /** Existing commands may render their established preview format and partial-failure exit status. */ + renderDryRun?: () => void; + /** Release temporary artifacts on preview, declined confirmation, success and failure. */ + dispose?: () => void; risk: CommandRisk | null; notices: readonly CommandNotice[]; } @@ -330,6 +336,10 @@ export interface Command { /** Apply defaultOutput over a Profile preference; flag/env still take precedence. */ defaultOutputOverridesProfile?: boolean; description: LocalizedText; + /** Service origin when flags, environment and the active API profile supply no base URL. */ + defaultApiBaseUrl?: ( + ctx: Pick, "flags" | "settings" | "localize">, + ) => string | undefined; /** Credential this command requires. See {@link AuthRequirement}. */ auth: AuthRequirement; /** @@ -341,6 +351,8 @@ export interface Command { * `--mode mcp` keeps the MCP-only `search.web` capability. */ authCapability?: (flags: ParsedFlags) => string; + /** A public source can optionally use an available key to resolve authenticated dependencies. */ + requiresApiKey?: (flags: ParsedFlags) => boolean | "optional"; /** * Best-effort secondary console credential for `auth: "apiKey"` commands. * When true, the runtime additionally resolves the console credential and @@ -356,7 +368,7 @@ export interface Command { * remote request or local write; runtime only owns the confirmation gate. */ risk?: CommandRisk; - /** Authenticated, read-only planning. Never write files, request leases, or mutate resources. */ + /** Read-only planning. Temporary package inspection must be cleaned up via dispose; do not change installed files or remote resources. */ prepare?: (ctx: CommandContext) => Promise>; /** Usage line arg portion, e.g. "--prompt [flags]". Manually written. */ usageArgs?: string; diff --git a/packages/core/tests/helpers/skill-archive.ts b/packages/core/tests/helpers/skill-archive.ts new file mode 100644 index 000000000..a173efc5f --- /dev/null +++ b/packages/core/tests/helpers/skill-archive.ts @@ -0,0 +1,19 @@ +import { brotliCompressSync } from "node:zlib"; +import tar from "tar-stream"; + +/** Build a skill archive the same way as the publisher (tar.pack + brotli) */ +export async function buildTarBr(files: Record): Promise { + const pack = tar.pack(); + const chunks: Buffer[] = []; + pack.on("data", (chunk: Buffer) => chunks.push(chunk)); + const done = new Promise((resolvePromise, reject) => { + pack.on("end", resolvePromise); + pack.on("error", reject); + }); + for (const [rel, content] of Object.entries(files)) { + pack.entry({ name: rel }, content); + } + pack.finalize(); + await done; + return brotliCompressSync(Buffer.concat(chunks)); +} diff --git a/packages/core/tests/skills-installer.test.ts b/packages/core/tests/skills-installer.test.ts index 7bcf816b8..6a3af6bbf 100644 --- a/packages/core/tests/skills-installer.test.ts +++ b/packages/core/tests/skills-installer.test.ts @@ -12,8 +12,7 @@ import { import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { brotliCompressSync } from "node:zlib"; -import tar from "tar-stream"; +import { buildTarBr } from "./helpers/skill-archive.ts"; import { afterEach, expect, test, vi } from "vite-plus/test"; import { BailianError } from "../src/errors/base.ts"; import type { AgentTarget } from "../src/skills/agents.ts"; @@ -49,23 +48,6 @@ async function inTempConfigDir(fn: () => Promise): Promise { } } -/** Build a skill archive the same way as the publisher (tar.pack + brotli) */ -async function buildTarBr(files: Record): Promise { - const pack = tar.pack(); - const chunks: Buffer[] = []; - pack.on("data", (chunk: Buffer) => chunks.push(chunk)); - const done = new Promise((resolvePromise, reject) => { - pack.on("end", resolvePromise); - pack.on("error", reject); - }); - for (const [rel, content] of Object.entries(files)) { - pack.entry({ name: rel }, content); - } - pack.finalize(); - await done; - return brotliCompressSync(Buffer.concat(chunks)); -} - const VALID_SKILL_MD = "---\nname: demo\ndescription: demo skill\n---\n\n# Demo v1\n"; test("installer: valid archive installs to canonical and returns metadata", async () => { diff --git a/packages/core/tests/telemetry-service-planes.test.ts b/packages/core/tests/telemetry-service-planes.test.ts index 1dc853760..f07104490 100644 --- a/packages/core/tests/telemetry-service-planes.test.ts +++ b/packages/core/tests/telemetry-service-planes.test.ts @@ -3,6 +3,8 @@ import { RAG_PATHS, SANDBOX_PATHS, agentStudioHost, + bailianMcpPath, + bailianMcpSsePath, chatPath, classifyServicePlane, classifyModelHost, @@ -10,6 +12,8 @@ import { httpTransport, knowledgeChatEndpoint, knowledgeSearchEndpoint, + mcpBaseUrl, + mcpServersPath, memoryAddAsyncPath, memoryEndpoint, memoryEventPath, @@ -25,6 +29,8 @@ import { sandboxEndpoint, securityOverviewEndpoint, SERVICE_PLANES, + skillBaseUrl, + skillsPath, userProfilePath, Client, type Identity, @@ -38,6 +44,7 @@ import { customModelImportJobEndpoint, } from "../src/client/endpoints.ts"; import { resolveTelemetrySite } from "../src/telemetry/site.ts"; +import { SdkMcpAdapter } from "../src/client/mcp-sdk.ts"; afterEach(() => vi.restoreAllMocks()); @@ -118,7 +125,21 @@ test("overridable planes carry no product verdict", () => { expect(classifyServicePlane(securityOverviewEndpoint(agentStudioHost(workspaceId)))?.key).toBe( "agentstudio", ); - for (const key of ["parsex", "agentstudio"]) { + const mcpOrigin = mcpBaseUrl(workspaceId); + for (const path of [ + mcpServersPath(), + mcpServersPath("example"), + bailianMcpPath("example"), + bailianMcpSsePath("example"), + ]) { + expect(classifyServicePlane(mcpOrigin + path)?.key, path).toBe("mcp"); + } + const skillOrigin = skillBaseUrl(workspaceId); + for (const path of [skillsPath(), skillsPath("example")]) { + expect(classifyServicePlane(skillOrigin + path)?.key, path).toBe("cloud-skill"); + } + expect(classifyServicePlane(skillOrigin + skillsPath() + "-other")).toBeUndefined(); + for (const key of ["parsex", "agentstudio", "mcp", "cloud-skill"]) { expect(SERVICE_PLANES.find((plane) => plane.key === key)?.site).toBe("follow"); } }); @@ -273,3 +294,30 @@ test("a run-level record is shared with derived Clients", () => { // derived Client made instead of falling back to the shared base URL. expect(client.lastResolvedOrigin).toBe(`https://${workspaceId}.cn-beijing.maas.aliyuncs.com`); }); + +test("a workspace client shares its parent's private request record", () => { + const client = new Client({ + identity, + settings: { telemetry: true, timeout: 30 } as Settings, + baseUrl: "https://dashscope.aliyuncs.com", + baseUrlIsDefault: true, + }); + const workspaceOrigin = `https://${workspaceId}.cn-beijing.maas.aliyuncs.com`; + const workspaceClient = client.withDefaultBaseUrl(() => workspaceOrigin); + + workspaceClient.url("/api/v1/indices/rag/index/list"); + + expect(client.lastResolvedOrigin).toBe(workspaceOrigin); + expect(client.productSite).toBe("domestic"); +}); + +test("an explicit MCP URL records the actual host even if its path resembles another service", async () => { + const client = makeClient("https://dashscope.aliyuncs.com"); + const overrideOrigin = "https://dashscope-intl.aliyuncs.com"; + vi.spyOn(SdkMcpAdapter.prototype, "initialize").mockResolvedValue(undefined); + + await client.connectBailianMcp("example", overrideOrigin + "/api/v1/indices/custom"); + + expect(client.lastResolvedOrigin).toBe(overrideOrigin); + expect(client.productSite).toBeUndefined(); +}); diff --git a/packages/kscli/README.md b/packages/kscli/README.md index 17c05b0ff..6da8d354a 100644 --- a/packages/kscli/README.md +++ b/packages/kscli/README.md @@ -69,7 +69,7 @@ Deletion requires confirmation; add `--yes` only after confirming that scope. Su ### Use with an AI assistant -Install the knowledge workflow through `bl skill init`, or select `bl skill add --name bailian-protocol,bailian-knowledge`. Use `bl skill update` to update installed skills. This uses the full Bailian CLI installer; `kscli` has no `skill` subcommand. +Install the knowledge workflow through `bl skill init`, or select `bl skill add --name bailian-protocol,bailian-knowledge`. Use `bl skill update --all` to update installed skills. This uses the full Bailian CLI installer; `kscli` has no `skill` subcommand. The assistant first reads `kscli --introspect` to check the installed capabilities. It previews changes and explains billing before creating resources. Capabilities absent from that schema are not available in the installed version. diff --git a/packages/kscli/README.zh.md b/packages/kscli/README.zh.md index 9ae23efc6..9fee7220e 100644 --- a/packages/kscli/README.zh.md +++ b/packages/kscli/README.zh.md @@ -69,7 +69,7 @@ kscli kb delete --index-id --workspace-id ### 通过 AI 助手使用 -通过 `bl skill init` 安装知识库工作流,或用 `bl skill add --name bailian-protocol,bailian-knowledge` 选择安装。更新已安装 Skill 使用 `bl skill update`。安装渠道属于完整百炼 CLI,`kscli` 没有 `skill` 子命令。 +通过 `bl skill init` 安装知识库工作流,或用 `bl skill add --name bailian-protocol,bailian-knowledge` 选择安装。更新已安装 Skill 使用 `bl skill update --all`。安装渠道属于完整百炼 CLI,`kscli` 没有 `skill` 子命令。 助手先读取 `kscli --introspect` 确认当前能力,创建资源前预览变更并解释计费。当前 schema 未列出的能力不能视为已安装版本支持。 diff --git a/packages/kscli/package.json b/packages/kscli/package.json index 3ee0be66d..9bd1bed13 100644 --- a/packages/kscli/package.json +++ b/packages/kscli/package.json @@ -1,6 +1,6 @@ { "name": "knowledge-studio-cli", - "version": "2.13.0", + "version": "2.14.0", "description": "Lightweight RAG CLI for Aliyun Model Studio — focused on knowledge-base retrieval.", "keywords": [ "alibaba-cloud", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index f0b740b8f..5dbcc4870 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "bailian-cli-runtime", - "version": "2.13.0", + "version": "2.14.0", "description": "Runtime framework for bailian-cli (createCli, registry, args, output, pipeline). See https://www.npmjs.com/package/bailian-cli for usage.", "homepage": "https://bailian.console.aliyun.com/cli", "bugs": { diff --git a/packages/runtime/src/middleware.ts b/packages/runtime/src/middleware.ts index 35abfc6c5..b3934f80c 100644 --- a/packages/runtime/src/middleware.ts +++ b/packages/runtime/src/middleware.ts @@ -42,7 +42,7 @@ import { shouldAutoUpdate, } from "./utils/update-checker.ts"; import { ConfirmationRequiredError, confirmationHint } from "./confirm.ts"; -import { prepareCommand } from "./preparation.ts"; +import { runPreparedCommand } from "./preparation.ts"; /** * What each middleware stage gets for the invocation in flight: the matched @@ -208,7 +208,8 @@ export const authStage: Middleware = async (ctx, next) => { debug: (diagnostic: Parameters[0]) => ctx.output.debug(diagnostic), ...resolveModelBaseUrlState(sources), }; - if (command.auth === "apiKey") { + const apiKeyRequirement = command.requiresApiKey?.(ctx.flags) ?? true; + if (command.auth === "apiKey" && apiKeyRequirement) { // Commands whose network target switches with a flag declare authCapability // so Profile selection follows the actual connection; others key off path. const capability = command.authCapability @@ -234,7 +235,11 @@ export const authStage: Middleware = async (ctx, next) => { try { cred = resolveApiKey(apiSources); } catch (err) { - if (!settings.dryRun || command.prepare) throw err; + const optionalMissing = + apiKeyRequirement === "optional" && + err instanceof CredentialError && + err.reason === "missing-api-key"; + if (!optionalMissing && (!settings.dryRun || command.prepare)) throw err; } ctx.client = new Client({ ...base, @@ -290,6 +295,8 @@ export const authStage: Middleware = async (ctx, next) => { } ctx.client = new Client({ ...base, openApiCred: cred }); } + const defaultOrigin = command.defaultApiBaseUrl; + if (defaultOrigin) ctx.client = ctx.client.withDefaultBaseUrl(() => defaultOrigin(ctx)); await next(); }; @@ -392,5 +399,5 @@ export const confirmationStage: Middleware = async (ctx, next) => { /** Innermost stage: hand control to the command with its full context. */ export const runCommandStage: Middleware = async (ctx) => { - if (await prepareCommand(ctx)) await ctx.command.run(ctx); + await runPreparedCommand(ctx); }; diff --git a/packages/runtime/src/preparation.ts b/packages/runtime/src/preparation.ts index 6207223de..a8249bce8 100644 --- a/packages/runtime/src/preparation.ts +++ b/packages/runtime/src/preparation.ts @@ -1,33 +1,38 @@ import type { RunContext } from "./middleware.ts"; import { ConfirmationRequiredError, confirmationHint } from "./confirm.ts"; -/** Returns false when the read-only preview has completed the invocation. */ -export async function prepareCommand(context: RunContext): Promise { - if (!context.command.prepare) return true; +/** Keep resources acquired for planning scoped to this invocation. */ +export async function runPreparedCommand(context: RunContext): Promise { + if (!context.command.prepare) return context.command.run(context); const preparation = await context.command.prepare({ ...context, prepared: undefined }); - const notices = preparation.notices.map((notice) => ({ - ...notice, - message: context.localize(notice.message), - })); - if (context.settings.dryRun) { - context.output.result({ plan: preparation.preview, risk: preparation.risk, notices }); - return false; + try { + const notices = preparation.notices.map((notice) => ({ + ...notice, + message: context.localize(notice.message), + })); + if (context.settings.dryRun) { + if (preparation.renderDryRun) return preparation.renderDryRun(); + context.output.result({ plan: preparation.preview, risk: preparation.risk, notices }); + return; + } + if (preparation.risk && !context.confirmed) { + throw new ConfirmationRequiredError({ + message: context.localize(preparation.risk.message), + hint: context.localize(confirmationHint()), + plan: preparation.preview, + notices, + }); + } + for (const notice of notices) { + context.output.warning({ + code: notice.code, + message: notice.message, + ...(notice.url ? { details: { url: notice.url } } : {}), + }); + } + context.prepared = preparation.data; + await context.command.run(context); + } finally { + preparation.dispose?.(); } - if (preparation.risk && !context.confirmed) { - throw new ConfirmationRequiredError({ - message: context.localize(preparation.risk.message), - hint: context.localize(confirmationHint()), - plan: preparation.preview, - notices, - }); - } - for (const notice of notices) { - context.output.warning({ - code: notice.code, - message: notice.message, - ...(notice.url ? { details: { url: notice.url } } : {}), - }); - } - context.prepared = preparation.data; - return true; } diff --git a/packages/runtime/src/registry.ts b/packages/runtime/src/registry.ts index e8a13e27b..edb98baf9 100644 --- a/packages/runtime/src/registry.ts +++ b/packages/runtime/src/registry.ts @@ -40,10 +40,15 @@ interface CommandNode { const AUTH_LABELS = { apiKey: { "en-US": "API Key", "zh-CN": "API Key" }, + conditionalApiKey: { "en-US": "API Key when required by source", "zh-CN": "按来源使用 API Key" }, console: { "en-US": "Console", "zh-CN": "Console" }, openapi: { "en-US": "AK/SK", "zh-CN": "AK/SK" }, none: { "en-US": "No Auth", "zh-CN": "无需鉴权" }, -} satisfies Record; +} satisfies Record; + +function helpAuth(command: AnyCommand): keyof typeof AUTH_LABELS { + return command.requiresApiKey ? "conditionalApiKey" : command.auth; +} const RISK_LEVEL_LABELS = { high: { "en-US": "high", "zh-CN": "高风险" }, @@ -255,7 +260,7 @@ export class CommandRegistry { } private buildCommandLines( - entries: Array<{ path: string; auth: AuthRequirement; desc: string }>, + entries: Array<{ path: string; auth: keyof typeof AUTH_LABELS; desc: string }>, accent: (text: string) => string, dim: (text: string) => string, ): string { @@ -274,7 +279,7 @@ export class CommandRegistry { accent: (text: string) => string, dim: (text: string) => string, ): string { - const entries: Array<{ path: string; auth: AuthRequirement; desc: string }> = []; + const entries: Array<{ path: string; auth: keyof typeof AUTH_LABELS; desc: string }> = []; const collect = (node: CommandNode, prefix: string) => { for (const [name, child] of node.children) { @@ -282,7 +287,7 @@ export class CommandRegistry { if (child.command) { entries.push({ path: fullPath, - auth: child.command.auth, + auth: helpAuth(child.command), desc: this.localize(child.command.description), }); } @@ -479,7 +484,7 @@ ${authFlagSections ? `${authFlagSections}\n\n` : ""}${b(this.localize(HELP_TEXT. `${b(this.localize(HELP_TEXT.usage))} ${prefix}${cmd.usageArgs ? ` ${cmd.usageArgs}` : ""}\n`, ); out.write( - `${b(this.localize(HELP_TEXT.authentication))} ${a(this.localize(AUTH_LABELS[cmd.auth]))}\n`, + `${b(this.localize(HELP_TEXT.authentication))} ${a(this.localize(AUTH_LABELS[helpAuth(cmd)]))}\n`, ); if (cmd.risk !== undefined) { out.write( @@ -529,13 +534,13 @@ ${authFlagSections ? `${authFlagSections}\n\n` : ""}${b(this.localize(HELP_TEXT. } private printChildren(node: CommandNode, prefix: string, out: NodeJS.WriteStream): void { - const entries: Array<{ path: string; auth: AuthRequirement; desc: string }> = []; + const entries: Array<{ path: string; auth: keyof typeof AUTH_LABELS; desc: string }> = []; const collect = (currentNode: CommandNode, currentPath: string) => { for (const [name, child] of currentNode.children) { if (child.command) entries.push({ path: `${currentPath} ${name}`, - auth: child.command.auth, + auth: helpAuth(child.command), desc: this.localize(child.command.description), }); if (child.children.size > 0) collect(child, `${currentPath} ${name}`); diff --git a/packages/runtime/src/utils/update-checker.ts b/packages/runtime/src/utils/update-checker.ts index afeec02ca..707e48e6b 100644 --- a/packages/runtime/src/utils/update-checker.ts +++ b/packages/runtime/src/utils/update-checker.ts @@ -219,14 +219,14 @@ async function syncAgentSkillsAfterUpdate(output: UpdateOutput, invocation: stri try { output.info({ "en-US": "Syncing agent skills...", "zh-CN": "正在同步 Agent 技能……" }); const { execSync } = await import("child_process"); - execSync("bl skill update", { stdio: "pipe" }); + execSync("bl skill update --all", { stdio: "pipe" }); output.info({ "en-US": "Agent skills updated.", "zh-CN": "Agent 技能已更新。" }); } catch (error) { output.warning({ code: "SKILL_SYNC_FAILED", message: { - "en-US": `Agent skill sync failed: ${errorMessage(error)}. Run ${formatCommand(invocation, "skill update")} manually.`, - "zh-CN": `Agent 技能同步失败:${errorMessage(error)}。请手动运行 ${formatCommand(invocation, "skill update")}。`, + "en-US": `Agent skill sync failed: ${errorMessage(error)}. Run ${formatCommand(invocation, "skill update --all")} manually.`, + "zh-CN": `Agent 技能同步失败:${errorMessage(error)}。请手动运行 ${formatCommand(invocation, "skill update --all")}。`, }, }); } diff --git a/packages/runtime/tests/console-flags.e2e.test.ts b/packages/runtime/tests/console-flags.e2e.test.ts index cccdfcd80..fe0ae887a 100644 --- a/packages/runtime/tests/console-flags.e2e.test.ts +++ b/packages/runtime/tests/console-flags.e2e.test.ts @@ -43,7 +43,7 @@ describe.each([ test("跨域 flag 拒绝:console 命令传 --api-key 报未知参数", async () => { const { stdout, stderr, exitCode } = await runRuntimeHarness( - ["mcp", "list", "--api-key", "sk-test", "--dry-run"], + ["workspace", "list", "--api-key", "sk-test", "--dry-run"], language, ); expect(exitCode, stderr).toBe(2); diff --git a/packages/runtime/tests/harness/cross-domain-main.ts b/packages/runtime/tests/harness/cross-domain-main.ts index b8f710b28..63865efa4 100644 --- a/packages/runtime/tests/harness/cross-domain-main.ts +++ b/packages/runtime/tests/harness/cross-domain-main.ts @@ -15,7 +15,7 @@ const textChat = defineCommand({ }); /** console 域 stub:用于跨域 flag 拒绝测试 */ -const mcpList = defineCommand({ +const workspaceList = defineCommand({ description: "runtime e2e stub", auth: "console", flags: {}, @@ -32,7 +32,7 @@ const cmodelImport = defineCommand({ }); void createCli( - { "text chat": textChat, "mcp list": mcpList, "cmodel import": cmodelImport }, + { "text chat": textChat, "workspace list": workspaceList, "cmodel import": cmodelImport }, { binName: "bl", version: pkg.version, diff --git a/packages/runtime/tests/preparation.test.ts b/packages/runtime/tests/preparation.test.ts index af71834e2..43e227603 100644 --- a/packages/runtime/tests/preparation.test.ts +++ b/packages/runtime/tests/preparation.test.ts @@ -185,3 +185,24 @@ test("confirmed preparation keeps billing notices as JSONL under quiet", async ( warning: { code: "BILLING", message: "Creates a billed resource" }, }); }); + +test.each(["preview", "confirmation", "success", "failure"] as const)( + "disposes temporary preparation resources on %s", + async (outcome) => { + const { context, prepare, run } = fixture({ + dryRun: outcome === "preview", + confirmed: outcome !== "confirmation", + }); + const dispose = vi.fn(); + const renderDryRun = vi.fn(); + context.command.prepare = async () => ({ ...(await prepare()), dispose, renderDryRun }); + if (outcome === "failure") run.mockRejectedValueOnce(new Error("execution failed")); + vi.spyOn(context.output, "warning").mockImplementation(() => {}); + const execution = runCommandStage(context, async () => {}); + if (outcome === "confirmation") await expect(execution).rejects.toMatchObject({ exitCode: 7 }); + else if (outcome === "failure") await expect(execution).rejects.toThrow("execution failed"); + else await execution; + expect(renderDryRun).toHaveBeenCalledTimes(outcome === "preview" ? 1 : 0); + expect(dispose).toHaveBeenCalledOnce(); + }, +); diff --git a/packages/runtime/tests/update-checker.test.ts b/packages/runtime/tests/update-checker.test.ts index 012cf5484..9bd9d9ced 100644 --- a/packages/runtime/tests/update-checker.test.ts +++ b/packages/runtime/tests/update-checker.test.ts @@ -72,9 +72,11 @@ test("hosted update instructions use the prefix while skill execution uses the b ).toBe(true); expect(JSON.stringify(output.info.mock.calls)).toContain("Run aliyun bl --version"); expect(JSON.stringify(output.warning.mock.calls)).toContain( - "Run aliyun bl skill update manually.", + "Run aliyun bl skill update --all manually.", ); - expect(childProcessMocks.execSync).toHaveBeenCalledWith("bl skill update", { stdio: "pipe" }); + expect(childProcessMocks.execSync).toHaveBeenCalledWith("bl skill update --all", { + stdio: "pipe", + }); }); test("parseVersion strips pre-release and build metadata", () => { @@ -195,7 +197,9 @@ test("shouldAutoUpdate only targets stable releases with a significant gap", () }); function expectSkillUpdateNotInit(): void { - expect(childProcessMocks.execSync).toHaveBeenCalledWith("bl skill update", { stdio: "pipe" }); + expect(childProcessMocks.execSync).toHaveBeenCalledWith("bl skill update --all", { + stdio: "pipe", + }); expect( childProcessMocks.execSync.mock.calls.some((call) => String(call[0]).includes("skill init")), ).toBe(false); @@ -253,7 +257,9 @@ test("auto-update uses the injected output and captures subprocess streams", asy ).toBe(true); expect(stderr).toBe(""); expect(direct).not.toHaveBeenCalled(); - expect(childProcessMocks.execSync).toHaveBeenCalledWith("bl skill update", { stdio: "pipe" }); + expect(childProcessMocks.execSync).toHaveBeenCalledWith("bl skill update --all", { + stdio: "pipe", + }); } finally { direct.mockRestore(); } @@ -265,7 +271,7 @@ test.each([false, true])( const output = { info: vi.fn(), warning: vi.fn() }; if (fails) { childProcessMocks.execSync.mockImplementation((command) => { - if (command === "bl skill update" || command === "kscli skill update") { + if (command === "bl skill update --all" || command === "kscli skill update --all") { throw new Error("mock skill sync failure"); } return ""; @@ -277,9 +283,11 @@ test.each([false, true])( binName: "kscli", }), ).toBe(true); - expect(childProcessMocks.execSync).toHaveBeenCalledWith("bl skill update", { stdio: "pipe" }); + expect(childProcessMocks.execSync).toHaveBeenCalledWith("bl skill update --all", { + stdio: "pipe", + }); expect(childProcessMocks.execSync).not.toHaveBeenCalledWith( - "kscli skill update", + "kscli skill update --all", expect.anything(), ); if (fails) { @@ -287,8 +295,8 @@ test.each([false, true])( expect.objectContaining({ code: "SKILL_SYNC_FAILED", message: { - "en-US": expect.stringContaining("Run bl skill update manually."), - "zh-CN": expect.stringContaining("请手动运行 bl skill update。"), + "en-US": expect.stringContaining("Run bl skill update --all manually."), + "zh-CN": expect.stringContaining("请手动运行 bl skill update --all。"), }, }), ); diff --git a/skills/bailian-cli/SKILL.md b/skills/bailian-cli/SKILL.md index 0e214ca15..3310be336 100644 --- a/skills/bailian-cli/SKILL.md +++ b/skills/bailian-cli/SKILL.md @@ -1,14 +1,14 @@ --- name: bailian-cli metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- 阿里云百炼 / Aliyun Bailian / DashScope 资源管理与 `bl` CLI hub: 应用调用与管理(bl flow-agent:调用/创建/更新/发布/删除/复制/版本、工作流画布;旧 bl app call/list 已废弃)、决策模型推理(bl decision)、模型目录/模型列表、用量/额度/配额、免费额度、 工作空间、MCP 市场、pipeline、文件上传、ParseX 文档/音视频解析与字段抽取、Batch 批量推理与 CSV 转换、同步 Batch Chat、console API、登录鉴权与配置、 - Agent skill 安装/列表/更新/卸载(bl skill add|list|update|remove,百炼 skill registry)。 + 云端 Skill 检索与详情(bl skill search|get),Agent Skill 安装/列表/更新/卸载(bl skill add|list|update|remove,百炼 skill registry)。 用户点名百炼 / DashScope / `bl`,或继续既有 `bl` 工作流时直接使用。 共享协议(consent / 版本预检 / 鉴权 / 错误上报)在 bailian-protocol;官方安装 `bl skill init`。 家族路由:生图/生视频/配音/语音合成/转写/图片翻译/文档翻译/PDF 翻译 → bailian-gen;精调/微调/训练/训练数据集 → bailian-finetune; @@ -69,49 +69,54 @@ Do not guess flags — use the reference files or `--help`. Use this table only after the decision table in [`bailian-protocol`](../bailian-protocol/SKILL.md#provider-selection-and-consent) has routed the request to `bl` (class 4, or class 2 after the user picks Bailian). Hub-owned intents only — for media / fine-tune / agents.yaml / Sandbox, soft hand-off to the domain skill. -| User intent | Command | Notes | -| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Explicit Bailian model chat / text execution | `bl text chat` | Default `qwen3.8-max` | -| Dedicated text translation (Qwen-MT) | `bl text translate --target-lang ` | Default `qwen-mt-flash`; language names are English full names (`Chinese`/`English`), not `zh`/`en`; only user messages; see `reference/text.md` | -| 百炼异步文件批量推理 / CSV 转换 | `bl batch convert` / `create` / `list` / `get` / `cancel` / `download` | CSV → JSONL → 异步任务 → 原始结果,可额外导出 CSV;格式样例见 `reference/batch.md` | -| 百炼单次同步 Batch Chat | `bl text chat --batch` | 等待单次响应,不创建任务 ID;messages-file 是同一请求的对话上下文,边界见 `reference/text.md` | -| Typed decision model inference | `bl decision` | Workspace endpoint; returns `choice` / `noul` / `score` values and probabilities, not generated text | -| Explicit ParseX parsing / structured field extraction | `bl parsex parse submit` / `result`; `bl parsex extract submit` / `result` | Workspace + API key; submit returns biz_id, result --follow waits. HTTP(S) source URLs; extraction can reuse a parsed document. See `reference/parsex.md`. | -| Bailian agent / workflow | `bl flow-agent call` | Needs `--app-id` | -| Find app by name | `bl flow-agent list` then `bl flow-agent call` | Console auth; `--type workflow` lists workflows | -| Create / update / publish / delete / copy an app | `bl flow-agent create` / `update` / `publish` / `delete` / `copy` / `get` / `versions` | Console auth; agent config via `--model`/`--instructions`/`--config-json`; `delete` needs `--yes`; see [`reference/flow-agent.md`](reference/flow-agent.md) | -| Workflow canvas read / save / publish / export | `bl flow-agent workflow get` / `save` / `publish` / `export` | Console auth; `save` replaces the whole draft canvas; see [`reference/flow-agent.md`](reference/flow-agent.md) | -| Personal memory / Bailian memory resources | → skill `bailian-memory` | User-enabled personal memory; explicit resource operations use `bl memory --help` as fallback. | -| Personal documents / Bailian knowledge workflows | Read skill `bailian-knowledge` | If missing: `bl knowledge --help` or `bl skill init` | -| Resolve a Console file key / error-report URL | `bl file url` | Console auth; use the returned business file key, not a file ID or upload URI. Resolves only; no download or fixed expiry. Existing URLs need no resolution. | -| Upload a file as a step of a Bailian workflow | `bl file upload` | When you need `oss://` URL explicitly; not for generic hosting | -| Bailian model selection / recommendation | `bl advisor recommend` | Intent → candidate recall → LLM ranking | -| Bailian model catalog / pricing / params | `bl model list` | No auth (public catalog); `--model ` for detail, `--enrich` for input params | -| Find a model by keyword / modality | `bl model search` | Weighted ranking; `--input-modality` / `--output-modality`; offline models hidden by default | -| SDK sample code for calling a model | `bl model code` | `--sdk openai\|dashscope`, `--lang`; text output is the snippet alone, safe to redirect | -| Install / list / update / remove registry skills | `bl skill add` / `list` / `update` / `remove` | Bailian skill registry; see [`reference/skill.md`](reference/skill.md) | -| Bailian MCP marketplace discovery / call | `bl mcp list` / `tools` / `call` | — | -| Register or remove a Bailian MCP in an Agent | `bl mcp connect` / `disconnect` | Codex, Claude Code, Cursor, Qoder, Qoder Work, QwenWork, Qwen Code, Gemini, OpenCode, OpenClaw, DeepSeek Harness, ZCode, WorkBuddy | -| Bailian pipeline workflow (a step in a bl flow) | `bl pipeline run` / `validate` | JSON/YAML workflow definitions | -| Bailian rate limits / quota | `bl quota list` / `check` / `request` | Console auth; class 2 — ask which product first if unnamed | -| Bailian free tier / usage stats | `bl usage free` / `stats` / `freetier` | Console auth; class 2 — ask which product first if unnamed | -| Bailian Token Plan quota usage | `bl usage token-plan` | Console auth; class 2 — ask which product first if unnamed | -| Token Plan harness entitlement quota | `bl token-plan harness-quota` | Console auth; issued quota usage + still-issuing harnesses | -| Bailian Coding Plan quota usage | `bl usage coding-plan` | Console auth; class 2 — ask which product first if unnamed | -| Model monitoring (calls, latency, errors, delivery) | `bl monitor overview` / `models` / `metrics` / `errors` / `delivery *` | Console auth; see [`reference/monitor.md`](reference/monitor.md) | -| Model call logs / traces | `bl log audit *` / `bl log inference *` / `bl log status` / `bl log trace *` | Console auth; audit and inference logs have separate APIs and switches; see [`reference/log.md`](reference/log.md) | -| Model alert rules / templates / history | `bl alert list` / `create` / `update` / `delete` / `enable` / `disable` / `history` / `metrics` / `template *` | Console auth; contacts are managed in the CloudMonitor console; see [`reference/alert.md`](reference/alert.md) | -| Console API (advanced) | `bl console call` | Console auth | -| Bailian workspace listing | `bl workspace list` | Console auth | -| Switch CLI Help / Quick Start language | `bl config set --key language --value zh-CN` | Use `en-US` to switch back; follows the active config profile | -| Image / video / speech / omni / vision | → skill `bailian-gen` | Fallback: `bl image\|video\|speech\|omni\|vision --help` | -| Training dataset / fine-tune / deploy | → skill `bailian-finetune` | Fallback: `bl dataset\|finetune\|deploy --help` | -| 百炼模型智能路由 / smart routing / model routing | → skill `bailian-finetune` | 独立于精调流程;fallback: `bl deploy router --help`。 | -| 吞吐预留(PTU)/ ModelCode 容量购买与扩缩容 | → skill `bailian-finetune` | 独立于精调流程;包括容量查询、购买、扩缩容、续费、释放、退订与溢出策略;fallback: `bl deploy --help`。 | -| Guided end-to-end OPD distillation workflow | → skill `bailian-opd` | Authorize → validate → preflight → consent → submit → wait; fallback: `bl finetune opd --help` | -| agents.yaml IaC / managed-agent sessions | → skill `bailian-managed-agent` | Fallback: `bl managed-agent --help`; `apply`/`destroy` need `--yes` after `plan` | -| Bailian Sandbox instance / template lifecycle | → skill `bailian-sandbox` | Fallback: `bl sandbox --help` | -| Web search (mode-aware routing) | → skill `bailian-web-search` | Default model mode vs explicit `--mode mcp` + fallback; fallback: `bl search web --help` | +| User intent | Command | Notes | +| ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Explicit Bailian model chat / text execution | `bl text chat` | Default `qwen3.8-max` | +| Dedicated text translation (Qwen-MT) | `bl text translate --target-lang ` | Default `qwen-mt-flash`; language names are English full names (`Chinese`/`English`), not `zh`/`en`; only user messages; see `reference/text.md` | +| 百炼异步文件批量推理 / CSV 转换 | `bl batch convert` / `create` / `list` / `get` / `cancel` / `download` | CSV → JSONL → 异步任务 → 原始结果,可额外导出 CSV;格式样例见 `reference/batch.md` | +| 百炼单次同步 Batch Chat | `bl text chat --batch` | 等待单次响应,不创建任务 ID;messages-file 是同一请求的对话上下文,边界见 `reference/text.md` | +| Typed decision model inference | `bl decision` | Workspace endpoint; returns `choice` / `noul` / `score` values and probabilities, not generated text | +| Explicit ParseX parsing / structured field extraction | `bl parsex parse submit` / `result`; `bl parsex extract submit` / `result` | Workspace + API key; submit returns biz_id, result --follow waits. HTTP(S) source URLs; extraction can reuse a parsed document. See `reference/parsex.md`. | +| Bailian agent / workflow | `bl flow-agent call` | Needs `--app-id` | +| Find app by name | `bl flow-agent list` then `bl flow-agent call` | Console auth; `--type workflow` lists workflows | +| Create / update / publish / delete / copy an app | `bl flow-agent create` / `update` / `publish` / `delete` / `copy` / `get` / `versions` | Console auth; agent config via `--model`/`--instructions`/`--config-json`; `delete` needs `--yes`; see [`reference/flow-agent.md`](reference/flow-agent.md) | +| Workflow canvas read / save / publish / export | `bl flow-agent workflow get` / `save` / `publish` / `export` | Console auth; `save` replaces the whole draft canvas; see [`reference/flow-agent.md`](reference/flow-agent.md) | +| Personal memory / Bailian memory resources | → skill `bailian-memory` | User-enabled personal memory; explicit resource operations use `bl memory --help` as fallback. | +| Personal documents / Bailian knowledge workflows | Read skill `bailian-knowledge` | If missing: `bl knowledge --help` or `bl skill init` | +| Resolve a Console file key / error-report URL | `bl file url` | Console auth; use the returned business file key, not a file ID or upload URI. Resolves only; no download or fixed expiry. Existing URLs need no resolution. | +| Upload a file as a step of a Bailian workflow | `bl file upload` | When you need `oss://` URL explicitly; not for generic hosting | +| Bailian model selection / recommendation | `bl advisor recommend` | Intent → candidate recall → LLM ranking | +| Bailian model catalog / pricing / params | `bl model list` | No auth (public catalog); `--model ` for detail, `--enrich` for input params | +| Find a model by keyword / modality | `bl model search` | Weighted ranking; `--input-modality` / `--output-modality`; offline models hidden by default | +| SDK sample code for calling a model | `bl model code` | `--sdk openai\|dashscope`, `--lang`; text output is the snippet alone, safe to redirect | +| Install / list / update / remove registry skills | `bl skill add` / `list` / `update` / `remove` | OSS `--name`, cloud `--code`. `add --all` installs the registry. `update --all` updates installed OSS skills. Filter by `--agent` / `--scope`. [Reference](reference/skill.md) | +| Find cloud skills or inspect local installation paths | `bl skill search` / `bl skill get` | Search the cloud with a Bailian API key. Pass the returned `skill_code` to `get --code`. Use `get --name` for an OSS skill. | +| Inspect activated MCP servers, details or tools | `bl mcp list` / `get` / `tools` / `call` | — | +| Find MCP tools by task or inspect a server's tools | `bl mcp tool search` / `bl mcp tool list` | Search with `--query` or list with `--server`. Both operations may trigger OneKey activation. Preview with `--dry-run`. | +| Call a tool by server code and tool name | `bl mcp tool call` / `bl mcp call` | Use `--server` and `--tool` for OpenAPI, or `--target ` for an MCP session. | +| Activate or stop MCP servers | `bl mcp activate` / `deactivate` | API key. Use `--server ` to select servers and `--dry-run` to preview the batch. | +| Manage a custom Bailian MCP server | `bl mcp create` / `update` / `delete` | API key. Preview changes with `--dry-run`. Deleting a server requires `--yes`. | +| Register or remove a Bailian MCP in an Agent | `bl mcp connect` / `disconnect` | Choose `--agent` and `--scope user\|project`. Connect previews the workspace endpoint and any activation. Disconnect uses the local registration. | +| Bailian pipeline workflow (a step in a bl flow) | `bl pipeline run` / `validate` | JSON/YAML workflow definitions | +| Bailian rate limits / quota | `bl quota list` / `check` / `request` | Console auth; class 2 — ask which product first if unnamed | +| Bailian free tier / usage stats | `bl usage free` / `stats` / `freetier` | Console auth; class 2 — ask which product first if unnamed | +| Bailian Token Plan quota usage | `bl usage token-plan` | Console auth; class 2 — ask which product first if unnamed | +| Token Plan harness entitlement quota | `bl token-plan harness-quota` | Console auth; issued quota usage + still-issuing harnesses | +| Bailian Coding Plan quota usage | `bl usage coding-plan` | Console auth; class 2 — ask which product first if unnamed | +| Model monitoring (calls, latency, errors, delivery) | `bl monitor overview` / `models` / `metrics` / `errors` / `delivery *` | Console auth; see [`reference/monitor.md`](reference/monitor.md) | +| Model call logs / traces | `bl log audit *` / `bl log inference *` / `bl log status` / `bl log trace *` | Console auth; audit and inference logs have separate APIs and switches; see [`reference/log.md`](reference/log.md) | +| Model alert rules / templates / history | `bl alert list` / `create` / `update` / `delete` / `enable` / `disable` / `history` / `metrics` / `template *` | Console auth; contacts are managed in the CloudMonitor console; see [`reference/alert.md`](reference/alert.md) | +| Console API (advanced) | `bl console call` | Console auth | +| Bailian workspace listing | `bl workspace list` | Console auth | +| Switch CLI Help / Quick Start language | `bl config set --key language --value zh-CN` | Use `en-US` to switch back; follows the active config profile | +| Image / video / speech / omni / vision | → skill `bailian-gen` | Fallback: `bl image\|video\|speech\|omni\|vision --help` | +| Training dataset / fine-tune / deploy | → skill `bailian-finetune` | Fallback: `bl dataset\|finetune\|deploy --help` | +| 百炼模型智能路由 / smart routing / model routing | → skill `bailian-finetune` | 独立于精调流程;fallback: `bl deploy router --help`。 | +| 吞吐预留(PTU)/ ModelCode 容量购买与扩缩容 | → skill `bailian-finetune` | 独立于精调流程;包括容量查询、购买、扩缩容、续费、释放、退订与溢出策略;fallback: `bl deploy --help`。 | +| Guided end-to-end OPD distillation workflow | → skill `bailian-opd` | Authorize → validate → preflight → consent → submit → wait; fallback: `bl finetune opd --help` | +| agents.yaml IaC / managed-agent sessions | → skill `bailian-managed-agent` | Fallback: `bl managed-agent --help`; `apply`/`destroy` need `--yes` after `plan` | +| Bailian Sandbox instance / template lifecycle | → skill `bailian-sandbox` | Fallback: `bl sandbox --help` | +| Web search (mode-aware routing) | → skill `bailian-web-search` | Default model mode vs explicit `--mode mcp` + fallback; fallback: `bl search web --help` | Flags, usage, and examples: see hub [`reference/`](reference/index.md) or `bl --help` — do not guess flags. Domain command details live in the owning skill's `reference/`. Examples in `reference/` stay bare; wrap with Call attribution when running. diff --git a/skills/bailian-cli/reference/index.md b/skills/bailian-cli/reference/index.md index faa45c63a..91d318023 100644 --- a/skills/bailian-cli/reference/index.md +++ b/skills/bailian-cli/reference/index.md @@ -9,133 +9,144 @@ Use this index for the skill-scoped quick index and global flags. ## Quick index -| Command | Authentication | Description | Detail | -| -------------------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------ | -| `bl advisor recommend` | API Key | Recommend the best models for your use case (intent → routing → recall → score → rank, with agent clarification) | [advisor.md](advisor.md) | -| `bl agents security alerts` | API Key | List Agent security alerts | [agents.md](agents.md) | -| `bl agents security overview` | API Key | Show the Agent security protection overview (last 24 hours) | [agents.md](agents.md) | -| `bl alert create` | Console | Create a model alert rule from an alert template | [alert.md](alert.md) | -| `bl alert delete` | Console | Delete model alert rules | [alert.md](alert.md) | -| `bl alert disable` | Console | Disable a model alert rule (keeps the rule, stops notifications) | [alert.md](alert.md) | -| `bl alert enable` | Console | Enable a model alert rule | [alert.md](alert.md) | -| `bl alert history` | Console | List model alert history (firing and recovered events) | [alert.md](alert.md) | -| `bl alert list` | Console | List model alert rules | [alert.md](alert.md) | -| `bl alert metrics` | Console | List metrics that alert rules can be created on, with supported aggregations | [alert.md](alert.md) | -| `bl alert template create` | Console | Create a custom alert template (or copy an official one with --from) | [alert.md](alert.md) | -| `bl alert template delete` | Console | Delete custom alert templates (official templates cannot be deleted) | [alert.md](alert.md) | -| `bl alert template list` | Console | List alert templates (official and custom); pass --template-id for details | [alert.md](alert.md) | -| `bl alert template update` | Console | Update a custom alert template (full replacement of conditions) | [alert.md](alert.md) | -| `bl alert update` | Console | Update a model alert rule (full replacement; same fields as create) | [alert.md](alert.md) | -| `bl app call` | API Key | [Deprecated] Call a Bailian application (agent or workflow) | [app.md](app.md) | -| `bl app list` | Console | [Deprecated] List Bailian applications | [app.md](app.md) | -| `bl auth generate-access-token` | No Auth | Generate a CLI access token using OpenAPI AK/SK | [auth.md](auth.md) | -| `bl auth login` | No Auth | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | [auth.md](auth.md) | -| `bl auth logout` | No Auth | Clear stored credentials; full logout also clears the model Base URL | [auth.md](auth.md) | -| `bl auth status` | No Auth | Show current authentication state | [auth.md](auth.md) | -| `bl batch cancel` | API Key | Request cancellation of a Batch task | [batch.md](batch.md) | -| `bl batch convert` | No Auth | Build Batch JSONL from CSV locally | [batch.md](batch.md) | -| `bl batch create` | API Key | Upload or reference input and create an asynchronous Batch task | [batch.md](batch.md) | -| `bl batch download` | API Key | Download original Batch results/errors, optionally export CSV | [batch.md](batch.md) | -| `bl batch get` | API Key | Get Batch task details, optionally following progress | [batch.md](batch.md) | -| `bl batch list` | API Key | List one page of Batch tasks | [batch.md](batch.md) | -| `bl cmodel base-models` | Console | List base models that can be imported as custom models | [cmodel.md](cmodel.md) | -| `bl cmodel delete` | API Key | Delete a custom model and its Bailian-side import record | [cmodel.md](cmodel.md) | -| `bl cmodel get` | API Key | Get details of a custom model (import job) | [cmodel.md](cmodel.md) | -| `bl cmodel import` | API Key | Import a custom model from OSS (creates an import job) | [cmodel.md](cmodel.md) | -| `bl cmodel list` | API Key | List custom models (import jobs) | [cmodel.md](cmodel.md) | -| `bl cmodel watch` | API Key | Probe a custom model's import status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [cmodel.md](cmodel.md) | -| `bl config agent` | No Auth | Configure a coding agent to use DashScope API | [config.md](config.md) | -| `bl config list` | No Auth | List config profiles and show the active profile | [config.md](config.md) | -| `bl config set` | No Auth | Set a config value | [config.md](config.md) | -| `bl config show` | No Auth | Display current configuration | [config.md](config.md) | -| `bl config ui` | No Auth | Open a local web UI to manage config profiles | [config.md](config.md) | -| `bl config use` | No Auth | Set the active config profile | [config.md](config.md) | -| `bl console call` | Console | Call a Bailian console API via the CLI gateway | [console.md](console.md) | -| `bl decision` | API Key | Run the decision model: typed choice / noul / score answers with probabilities | [decision.md](decision.md) | -| `bl file upload` | API Key | Upload a local file to DashScope temporary storage (48h) | [file.md](file.md) | -| `bl file url` | Console | Resolve a Console business file key to a file URL | [file.md](file.md) | -| `bl flow-agent call` | API Key | Call a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent copy` | Console | Copy a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent create` | Console | Create a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent delete` | Console | Delete a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent get` | Console | Get Bailian application details (agent or workflow) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent list` | Console | List Bailian applications | [flow-agent.md](flow-agent.md) | -| `bl flow-agent publish` | Console | Publish a Bailian agent application | [flow-agent.md](flow-agent.md) | -| `bl flow-agent update` | Console | Update a Bailian application (agent config or workflow metadata) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent versions` | Console | List published versions of a Bailian application | [flow-agent.md](flow-agent.md) | -| `bl flow-agent workflow export` | Console | Export a workflow as a DSL schema (download URL) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent workflow get` | Console | Get a workflow canvas (draft or a published version) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent workflow publish` | Console | Publish a workflow (publishes the current draft canvas) | [flow-agent.md](flow-agent.md) | -| `bl flow-agent workflow save` | Console | Save a workflow canvas (replaces the current draft) | [flow-agent.md](flow-agent.md) | -| `bl log audit count` | Console | Count model audit logs in a time range (useful before exporting) | [log.md](log.md) | -| `bl log audit disable` | Console | Disable audit log delivery for all models in the workspace | [log.md](log.md) | -| `bl log audit enable` | Console | Enable audit log delivery to SLS (SLR check → SLS instance → log switch) | [log.md](log.md) | -| `bl log audit get` | Console | Show a single audit log entry with its raw origin record | [log.md](log.md) | -| `bl log audit list` | Console | Query model audit logs (call metadata; request/response content is not recorded) | [log.md](log.md) | -| `bl log inference count` | Console | Count model inference logs in a time range (useful before exporting) | [log.md](log.md) | -| `bl log inference disable` | Console | Disable inference log delivery for all models in the workspace | [log.md](log.md) | -| `bl log inference enable` | Console | Enable inference log delivery to SLS (SLR check → SLS instance → log switch) | [log.md](log.md) | -| `bl log inference get` | Console | Show a single inference log entry with full request/response content | [log.md](log.md) | -| `bl log inference list` | Console | Query model inference logs (requires inference log delivery; use `log inference get` for request/response content) | [log.md](log.md) | -| `bl log status` | Console | Show model log delivery status (SLS authorization, audit / inference service and switches) | [log.md](log.md) | -| `bl log trace get` | Console | Show a single call trace with its span tree | [log.md](log.md) | -| `bl log trace list` | Console | List call traces for a model or app | [log.md](log.md) | -| `bl log trace stats` | Console | Show per-resource trace statistics (calls, tokens, latency) | [log.md](log.md) | -| `bl mcp call` | API Key | Call a tool on an MCP server (tools/call) | [mcp.md](mcp.md) | -| `bl mcp connect` | API Key | Register a Bailian MCP server in an Agent's native configuration | [mcp.md](mcp.md) | -| `bl mcp disconnect` | No Auth | Remove an unchanged MCP registration previously managed by bailian-cli | [mcp.md](mcp.md) | -| `bl mcp list` | Console | List MCP servers activated under your Bailian account | [mcp.md](mcp.md) | -| `bl mcp tools` | API Key | List tools exposed by an MCP server (tools/list) | [mcp.md](mcp.md) | -| `bl model code` | No Auth | Print a ready-to-run SDK sample for calling a model | [model.md](model.md) | -| `bl model list` | No Auth | Browse model families or show detailed model info in the Bailian model marketplace | [model.md](model.md) | -| `bl model search` | No Auth | Search the model catalog by keyword, ranked by relevance | [model.md](model.md) | -| `bl monitor delivery disable` | Console | Disable monitor delivery for all models in the workspace | [monitor.md](monitor.md) | -| `bl monitor delivery enable` | Console | Activate monitoring delivery: CMS SLR check, CMS service, and the dedicated Prometheus instance | [monitor.md](monitor.md) | -| `bl monitor delivery status` | Console | Show monitoring delivery (Prometheus instance) status | [monitor.md](monitor.md) | -| `bl monitor errors` | Console | Show failure breakdown by HTTP status code and error code | [monitor.md](monitor.md) | -| `bl monitor metrics` | Console | Query time-series monitor metrics (RPM/TPM, latency percentiles, token usage) | [monitor.md](monitor.md) | -| `bl monitor models` | Console | List per-model / per-API-key call statistics with server-side sort and paging | [monitor.md](monitor.md) | -| `bl monitor overview` | Console | Show aggregated model call statistics (calls, failures, latency, token usage) | [monitor.md](monitor.md) | -| `bl parsex extract result` | API Key | Query ParseX extraction status, fields and citations | [parsex.md](parsex.md) | -| `bl parsex extract submit` | API Key | Submit ParseX structured field extraction | [parsex.md](parsex.md) | -| `bl parsex parse result` | API Key | Query ParseX parsing status, results or a result slice | [parsex.md](parsex.md) | -| `bl parsex parse submit` | API Key | Submit a ParseX document or media parsing task | [parsex.md](parsex.md) | -| `bl permission grant` | API Key | Grant model permissions (inference / finetune / deploy) | [permission.md](permission.md) | -| `bl permission list` | API Key | List model permissions (inference / fine-tune / deploy) in the workspace | [permission.md](permission.md) | -| `bl permission revoke` | API Key | Revoke model permissions (inference / finetune / deploy) | [permission.md](permission.md) | -| `bl pipeline run` | No Auth | Run a pipeline workflow definition | [pipeline.md](pipeline.md) | -| `bl pipeline validate` | No Auth | Validate a pipeline definition without executing | [pipeline.md](pipeline.md) | -| `bl plugin install` | No Auth | Install or upgrade an allowlisted Command Pack | [plugin.md](plugin.md) | -| `bl plugin link` | No Auth | Link an allowlisted local Command Pack for development | [plugin.md](plugin.md) | -| `bl plugin list` | No Auth | List installed Command Packs and their load status | [plugin.md](plugin.md) | -| `bl plugin remove` | No Auth | Remove an installed Command Pack | [plugin.md](plugin.md) | -| `bl quota check` | Console | Check current usage against rate limits | [quota.md](quota.md) | -| `bl quota delete` | API Key | Clear all custom rate limits (QPM/TPM) for a model | [quota.md](quota.md) | -| `bl quota history` | Console | View quota change history | [quota.md](quota.md) | -| `bl quota list` | API Key | View model rate limits (QPM/TPM, account and workspace level) | [quota.md](quota.md) | -| `bl quota update` | API Key | Update model rate limits (QPM/TPM) | [quota.md](quota.md) | -| `bl search web` | API Key | Search the web via a chat model with built-in web search (default) or the DashScope MCP WebSearch service | [search.md](search.md) | -| `bl skill add` | No Auth | Install skills from the Bailian skill registry into local agents | [skill.md](skill.md) | -| `bl skill init` | No Auth | Install all bailian-* skills (one-shot bootstrap for new environments) | [skill.md](skill.md) | -| `bl skill list` | No Auth | List registry skills and diff against local installs | [skill.md](skill.md) | -| `bl skill remove` | No Auth | Remove locally installed skills (registry is untouched) | [skill.md](skill.md) | -| `bl skill update` | No Auth | Update installed skills to the latest registry versions | [skill.md](skill.md) | -| `bl text chat` | API Key | Send a text model request (OpenAI compatible, DashScope) | [text.md](text.md) | -| `bl text translate` | API Key | Translate text with Qwen-MT (Chat Completions translation_options) | [text.md](text.md) | -| `bl token-plan add-member` | AK/SK | Add a member to a Token Plan organization | [token-plan.md](token-plan.md) | -| `bl token-plan assign-seats` | AK/SK | Batch assign Token Plan seats to members | [token-plan.md](token-plan.md) | -| `bl token-plan create-key` | AK/SK | Create a Token Plan API key for a seat | [token-plan.md](token-plan.md) | -| `bl token-plan harness-quota` | Console | Show Token Plan harness entitlement quota usage | [token-plan.md](token-plan.md) | -| `bl token-plan list-seats` | AK/SK | List Token Plan subscription seat details | [token-plan.md](token-plan.md) | -| `bl update` | No Auth | Update the CLI to the latest or a specified version | [update.md](update.md) | -| `bl usage coding-plan` | Console | Show Coding Plan quota usage | [usage.md](usage.md) | -| `bl usage free` | Console | Query free-tier quota for models (all models if --model is omitted) | [usage.md](usage.md) | -| `bl usage freetier` | Console | Enable or disable auto-stop for free-tier models. Enables by default; use --off to disable | [usage.md](usage.md) | -| `bl usage stats` | Console | Query model usage statistics | [usage.md](usage.md) | -| `bl usage summary` | Console | Show a unified usage summary: free-tier quota and recent usage overview | [usage.md](usage.md) | -| `bl usage token-plan` | Console | Show Token Plan quota usage | [usage.md](usage.md) | -| `bl workspace init` | No Auth | Initialize Bailian workspace and activate postpaid services | [workspace.md](workspace.md) | -| `bl workspace list` | Console | List all workspaces | [workspace.md](workspace.md) | +| Command | Authentication | Description | Detail | +| -------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------ | +| `bl advisor recommend` | API Key | Recommend the best models for your use case (intent → routing → recall → score → rank, with agent clarification) | [advisor.md](advisor.md) | +| `bl agents security alerts` | API Key | List Agent security alerts | [agents.md](agents.md) | +| `bl agents security overview` | API Key | Show the Agent security protection overview (last 24 hours) | [agents.md](agents.md) | +| `bl alert create` | Console | Create a model alert rule from an alert template | [alert.md](alert.md) | +| `bl alert delete` | Console | Delete model alert rules | [alert.md](alert.md) | +| `bl alert disable` | Console | Disable a model alert rule (keeps the rule, stops notifications) | [alert.md](alert.md) | +| `bl alert enable` | Console | Enable a model alert rule | [alert.md](alert.md) | +| `bl alert history` | Console | List model alert history (firing and recovered events) | [alert.md](alert.md) | +| `bl alert list` | Console | List model alert rules | [alert.md](alert.md) | +| `bl alert metrics` | Console | List metrics that alert rules can be created on, with supported aggregations | [alert.md](alert.md) | +| `bl alert template create` | Console | Create a custom alert template (or copy an official one with --from) | [alert.md](alert.md) | +| `bl alert template delete` | Console | Delete custom alert templates (official templates cannot be deleted) | [alert.md](alert.md) | +| `bl alert template list` | Console | List alert templates (official and custom); pass --template-id for details | [alert.md](alert.md) | +| `bl alert template update` | Console | Update a custom alert template (full replacement of conditions) | [alert.md](alert.md) | +| `bl alert update` | Console | Update a model alert rule (full replacement; same fields as create) | [alert.md](alert.md) | +| `bl app call` | API Key | [Deprecated] Call a Bailian application (agent or workflow) | [app.md](app.md) | +| `bl app list` | Console | [Deprecated] List Bailian applications | [app.md](app.md) | +| `bl auth generate-access-token` | No Auth | Generate a CLI access token using OpenAPI AK/SK | [auth.md](auth.md) | +| `bl auth login` | No Auth | Authenticate with API key, console browser login, or OpenAPI AK/SK (credentials can coexist) | [auth.md](auth.md) | +| `bl auth logout` | No Auth | Clear stored credentials; full logout also clears the model Base URL | [auth.md](auth.md) | +| `bl auth status` | No Auth | Show current authentication state | [auth.md](auth.md) | +| `bl batch cancel` | API Key | Request cancellation of a Batch task | [batch.md](batch.md) | +| `bl batch convert` | No Auth | Build Batch JSONL from CSV locally | [batch.md](batch.md) | +| `bl batch create` | API Key | Upload or reference input and create an asynchronous Batch task | [batch.md](batch.md) | +| `bl batch download` | API Key | Download original Batch results/errors, optionally export CSV | [batch.md](batch.md) | +| `bl batch get` | API Key | Get Batch task details, optionally following progress | [batch.md](batch.md) | +| `bl batch list` | API Key | List one page of Batch tasks | [batch.md](batch.md) | +| `bl cmodel base-models` | Console | List base models that can be imported as custom models | [cmodel.md](cmodel.md) | +| `bl cmodel delete` | API Key | Delete a custom model and its Bailian-side import record | [cmodel.md](cmodel.md) | +| `bl cmodel get` | API Key | Get details of a custom model (import job) | [cmodel.md](cmodel.md) | +| `bl cmodel import` | API Key | Import a custom model from OSS (creates an import job) | [cmodel.md](cmodel.md) | +| `bl cmodel list` | API Key | List custom models (import jobs) | [cmodel.md](cmodel.md) | +| `bl cmodel watch` | API Key | Probe a custom model's import status (default: single non-blocking fetch). Pass --follow to poll until terminal. | [cmodel.md](cmodel.md) | +| `bl config agent` | No Auth | Configure a coding agent to use DashScope API | [config.md](config.md) | +| `bl config list` | No Auth | List config profiles and show the active profile | [config.md](config.md) | +| `bl config set` | No Auth | Set a config value | [config.md](config.md) | +| `bl config show` | No Auth | Display current configuration | [config.md](config.md) | +| `bl config ui` | No Auth | Open a local web UI to manage config profiles | [config.md](config.md) | +| `bl config use` | No Auth | Set the active config profile | [config.md](config.md) | +| `bl console call` | Console | Call a Bailian console API via the CLI gateway | [console.md](console.md) | +| `bl decision` | API Key | Run the decision model: typed choice / noul / score answers with probabilities | [decision.md](decision.md) | +| `bl file upload` | API Key | Upload a local file to DashScope temporary storage (48h) | [file.md](file.md) | +| `bl file url` | Console | Resolve a Console business file key to a file URL | [file.md](file.md) | +| `bl flow-agent call` | API Key | Call a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent copy` | Console | Copy a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent create` | Console | Create a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent delete` | Console | Delete a Bailian application (agent or workflow) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent get` | Console | Get Bailian application details (agent or workflow) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent list` | Console | List Bailian applications | [flow-agent.md](flow-agent.md) | +| `bl flow-agent publish` | Console | Publish a Bailian agent application | [flow-agent.md](flow-agent.md) | +| `bl flow-agent update` | Console | Update a Bailian application (agent config or workflow metadata) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent versions` | Console | List published versions of a Bailian application | [flow-agent.md](flow-agent.md) | +| `bl flow-agent workflow export` | Console | Export a workflow as a DSL schema (download URL) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent workflow get` | Console | Get a workflow canvas (draft or a published version) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent workflow publish` | Console | Publish a workflow (publishes the current draft canvas) | [flow-agent.md](flow-agent.md) | +| `bl flow-agent workflow save` | Console | Save a workflow canvas (replaces the current draft) | [flow-agent.md](flow-agent.md) | +| `bl log audit count` | Console | Count model audit logs in a time range (useful before exporting) | [log.md](log.md) | +| `bl log audit disable` | Console | Disable audit log delivery for all models in the workspace | [log.md](log.md) | +| `bl log audit enable` | Console | Enable audit log delivery to SLS (SLR check → SLS instance → log switch) | [log.md](log.md) | +| `bl log audit get` | Console | Show a single audit log entry with its raw origin record | [log.md](log.md) | +| `bl log audit list` | Console | Query model audit logs (call metadata; request/response content is not recorded) | [log.md](log.md) | +| `bl log inference count` | Console | Count model inference logs in a time range (useful before exporting) | [log.md](log.md) | +| `bl log inference disable` | Console | Disable inference log delivery for all models in the workspace | [log.md](log.md) | +| `bl log inference enable` | Console | Enable inference log delivery to SLS (SLR check → SLS instance → log switch) | [log.md](log.md) | +| `bl log inference get` | Console | Show a single inference log entry with full request/response content | [log.md](log.md) | +| `bl log inference list` | Console | Query model inference logs (requires inference log delivery; use `log inference get` for request/response content) | [log.md](log.md) | +| `bl log status` | Console | Show model log delivery status (SLS authorization, audit / inference service and switches) | [log.md](log.md) | +| `bl log trace get` | Console | Show a single call trace with its span tree | [log.md](log.md) | +| `bl log trace list` | Console | List call traces for a model or app | [log.md](log.md) | +| `bl log trace stats` | Console | Show per-resource trace statistics (calls, tokens, latency) | [log.md](log.md) | +| `bl mcp activate` | API Key | Activate official MCP servers or enable custom servers using their saved configuration | [mcp.md](mcp.md) | +| `bl mcp call` | API Key | Open an MCP session and call a tool (tools/call) | [mcp.md](mcp.md) | +| `bl mcp connect` | API Key | Connect a Bailian MCP service to native Agent configurations | [mcp.md](mcp.md) | +| `bl mcp create` | API Key | Create and deploy a custom MCP server | [mcp.md](mcp.md) | +| `bl mcp deactivate` | API Key | Deactivate official MCP servers or stop custom server deployments | [mcp.md](mcp.md) | +| `bl mcp delete` | API Key | Permanently delete a custom MCP server | [mcp.md](mcp.md) | +| `bl mcp disconnect` | No Auth | Remove a managed MCP registration from local Agent configurations | [mcp.md](mcp.md) | +| `bl mcp get` | API Key | Get an MCP server's details and tool definitions | [mcp.md](mcp.md) | +| `bl mcp list` | API Key | List activated MCP servers and their local Agent registrations | [mcp.md](mcp.md) | +| `bl mcp tool call` | API Key | Call a Bailian MCP tool via OpenAPI | [mcp.md](mcp.md) | +| `bl mcp tool list` | API Key | List a Bailian MCP server's tools and input schemas via OpenAPI | [mcp.md](mcp.md) | +| `bl mcp tool search` | API Key | Find recommended MCP tools for a natural-language query | [mcp.md](mcp.md) | +| `bl mcp tools` | API Key | Open an MCP session and list the server's tools (tools/list) | [mcp.md](mcp.md) | +| `bl mcp update` | API Key | Update a custom MCP server's metadata or replace its configuration | [mcp.md](mcp.md) | +| `bl model code` | No Auth | Print a ready-to-run SDK sample for calling a model | [model.md](model.md) | +| `bl model list` | No Auth | Browse model families or show detailed model info in the Bailian model marketplace | [model.md](model.md) | +| `bl model search` | No Auth | Search the model catalog by keyword, ranked by relevance | [model.md](model.md) | +| `bl monitor delivery disable` | Console | Disable monitor delivery for all models in the workspace | [monitor.md](monitor.md) | +| `bl monitor delivery enable` | Console | Activate monitoring delivery: CMS SLR check, CMS service, and the dedicated Prometheus instance | [monitor.md](monitor.md) | +| `bl monitor delivery status` | Console | Show monitoring delivery (Prometheus instance) status | [monitor.md](monitor.md) | +| `bl monitor errors` | Console | Show failure breakdown by HTTP status code and error code | [monitor.md](monitor.md) | +| `bl monitor metrics` | Console | Query time-series monitor metrics (RPM/TPM, latency percentiles, token usage) | [monitor.md](monitor.md) | +| `bl monitor models` | Console | List per-model / per-API-key call statistics with server-side sort and paging | [monitor.md](monitor.md) | +| `bl monitor overview` | Console | Show aggregated model call statistics (calls, failures, latency, token usage) | [monitor.md](monitor.md) | +| `bl parsex extract result` | API Key | Query ParseX extraction status, fields and citations | [parsex.md](parsex.md) | +| `bl parsex extract submit` | API Key | Submit ParseX structured field extraction | [parsex.md](parsex.md) | +| `bl parsex parse result` | API Key | Query ParseX parsing status, results or a result slice | [parsex.md](parsex.md) | +| `bl parsex parse submit` | API Key | Submit a ParseX document or media parsing task | [parsex.md](parsex.md) | +| `bl permission grant` | API Key | Grant model permissions (inference / finetune / deploy) | [permission.md](permission.md) | +| `bl permission list` | API Key | List model permissions (inference / fine-tune / deploy) in the workspace | [permission.md](permission.md) | +| `bl permission revoke` | API Key | Revoke model permissions (inference / finetune / deploy) | [permission.md](permission.md) | +| `bl pipeline run` | No Auth | Run a pipeline workflow definition | [pipeline.md](pipeline.md) | +| `bl pipeline validate` | No Auth | Validate a pipeline definition without executing | [pipeline.md](pipeline.md) | +| `bl plugin install` | No Auth | Install or upgrade an allowlisted Command Pack | [plugin.md](plugin.md) | +| `bl plugin link` | No Auth | Link an allowlisted local Command Pack for development | [plugin.md](plugin.md) | +| `bl plugin list` | No Auth | List installed Command Packs and their load status | [plugin.md](plugin.md) | +| `bl plugin remove` | No Auth | Remove an installed Command Pack | [plugin.md](plugin.md) | +| `bl quota check` | Console | Check current usage against rate limits | [quota.md](quota.md) | +| `bl quota delete` | API Key | Clear all custom rate limits (QPM/TPM) for a model | [quota.md](quota.md) | +| `bl quota history` | Console | View quota change history | [quota.md](quota.md) | +| `bl quota list` | API Key | View model rate limits (QPM/TPM, account and workspace level) | [quota.md](quota.md) | +| `bl quota update` | API Key | Update model rate limits (QPM/TPM) | [quota.md](quota.md) | +| `bl search web` | API Key | Search the web via a chat model with built-in web search (default) or the DashScope MCP WebSearch service | [search.md](search.md) | +| `bl skill add` | API Key when required by source | Install skills from the Bailian skill registry into local agents | [skill.md](skill.md) | +| `bl skill get` | API Key when required by source | Get skill details, installed versions and paths from the public registry or OpenAPI | [skill.md](skill.md) | +| `bl skill init` | No Auth | Install all bailian-* skills (one-shot bootstrap for new environments) | [skill.md](skill.md) | +| `bl skill list` | API Key when required by source | List registry skills and local installations by agent, scope and status | [skill.md](skill.md) | +| `bl skill remove` | No Auth | Remove locally installed skills (registry is untouched) | [skill.md](skill.md) | +| `bl skill search` | API Key | Search cloud skills and show their local installations | [skill.md](skill.md) | +| `bl skill update` | API Key when required by source | Update installed skills to the latest registry versions | [skill.md](skill.md) | +| `bl text chat` | API Key | Send a text model request (OpenAI compatible, DashScope) | [text.md](text.md) | +| `bl text translate` | API Key | Translate text with Qwen-MT (Chat Completions translation_options) | [text.md](text.md) | +| `bl token-plan add-member` | AK/SK | Add a member to a Token Plan organization | [token-plan.md](token-plan.md) | +| `bl token-plan assign-seats` | AK/SK | Batch assign Token Plan seats to members | [token-plan.md](token-plan.md) | +| `bl token-plan create-key` | AK/SK | Create a Token Plan API key for a seat | [token-plan.md](token-plan.md) | +| `bl token-plan harness-quota` | Console | Show Token Plan harness entitlement quota usage | [token-plan.md](token-plan.md) | +| `bl token-plan list-seats` | AK/SK | List Token Plan subscription seat details | [token-plan.md](token-plan.md) | +| `bl update` | No Auth | Update the CLI to the latest or a specified version | [update.md](update.md) | +| `bl usage coding-plan` | Console | Show Coding Plan quota usage | [usage.md](usage.md) | +| `bl usage free` | Console | Query free-tier quota for models (all models if --model is omitted) | [usage.md](usage.md) | +| `bl usage freetier` | Console | Enable or disable auto-stop for free-tier models. Enables by default; use --off to disable | [usage.md](usage.md) | +| `bl usage stats` | Console | Query model usage statistics | [usage.md](usage.md) | +| `bl usage summary` | Console | Show a unified usage summary: free-tier quota and recent usage overview | [usage.md](usage.md) | +| `bl usage token-plan` | Console | Show Token Plan quota usage | [usage.md](usage.md) | +| `bl workspace init` | No Auth | Initialize Bailian workspace and activate postpaid services | [workspace.md](workspace.md) | +| `bl workspace list` | Console | List all workspaces | [workspace.md](workspace.md) | ## By group @@ -154,7 +165,7 @@ Use this index for the skill-scoped quick index and global flags. | `file` | `upload`, `url` | [file.md](file.md) | | `flow-agent` | `call`, `copy`, `create`, `delete`, `get`, `list`, `publish`, `update`, `versions`, `workflow export`, `workflow get`, `workflow publish`, `workflow save` | [flow-agent.md](flow-agent.md) | | `log` | `audit count`, `audit disable`, `audit enable`, `audit get`, `audit list`, `inference count`, `inference disable`, `inference enable`, `inference get`, `inference list`, `status`, `trace get`, `trace list`, `trace stats` | [log.md](log.md) | -| `mcp` | `call`, `connect`, `disconnect`, `list`, `tools` | [mcp.md](mcp.md) | +| `mcp` | `activate`, `call`, `connect`, `create`, `deactivate`, `delete`, `disconnect`, `get`, `list`, `tool call`, `tool list`, `tool search`, `tools`, `update` | [mcp.md](mcp.md) | | `model` | `code`, `list`, `search` | [model.md](model.md) | | `monitor` | `delivery disable`, `delivery enable`, `delivery status`, `errors`, `metrics`, `models`, `overview` | [monitor.md](monitor.md) | | `parsex` | `extract result`, `extract submit`, `parse result`, `parse submit` | [parsex.md](parsex.md) | @@ -163,7 +174,7 @@ Use this index for the skill-scoped quick index and global flags. | `plugin` | `install`, `link`, `list`, `remove` | [plugin.md](plugin.md) | | `quota` | `check`, `delete`, `history`, `list`, `update` | [quota.md](quota.md) | | `search` | `web` | [search.md](search.md) | -| `skill` | `add`, `init`, `list`, `remove`, `update` | [skill.md](skill.md) | +| `skill` | `add`, `get`, `init`, `list`, `remove`, `search`, `update` | [skill.md](skill.md) | | `text` | `chat`, `translate` | [text.md](text.md) | | `token-plan` | `add-member`, `assign-seats`, `create-key`, `harness-quota`, `list-seats` | [token-plan.md](token-plan.md) | | `update` | `(root)` | [update.md](update.md) | diff --git a/skills/bailian-cli/reference/mcp.md b/skills/bailian-cli/reference/mcp.md index 7cb2b4350..13766e466 100644 --- a/skills/bailian-cli/reference/mcp.md +++ b/skills/bailian-cli/reference/mcp.md @@ -7,36 +7,78 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Authentication | Description | -| ------------------- | -------------- | ---------------------------------------------------------------------- | -| `bl mcp call` | API Key | Call a tool on an MCP server (tools/call) | -| `bl mcp connect` | API Key | Register a Bailian MCP server in an Agent's native configuration | -| `bl mcp disconnect` | No Auth | Remove an unchanged MCP registration previously managed by bailian-cli | -| `bl mcp list` | Console | List MCP servers activated under your Bailian account | -| `bl mcp tools` | API Key | List tools exposed by an MCP server (tools/list) | +| Command | Authentication | Description | +| -------------------- | -------------- | -------------------------------------------------------------------------------------- | +| `bl mcp activate` | API Key | Activate official MCP servers or enable custom servers using their saved configuration | +| `bl mcp call` | API Key | Open an MCP session and call a tool (tools/call) | +| `bl mcp connect` | API Key | Connect a Bailian MCP service to native Agent configurations | +| `bl mcp create` | API Key | Create and deploy a custom MCP server | +| `bl mcp deactivate` | API Key | Deactivate official MCP servers or stop custom server deployments | +| `bl mcp delete` | API Key | Permanently delete a custom MCP server | +| `bl mcp disconnect` | No Auth | Remove a managed MCP registration from local Agent configurations | +| `bl mcp get` | API Key | Get an MCP server's details and tool definitions | +| `bl mcp list` | API Key | List activated MCP servers and their local Agent registrations | +| `bl mcp tool call` | API Key | Call a Bailian MCP tool via OpenAPI | +| `bl mcp tool list` | API Key | List a Bailian MCP server's tools and input schemas via OpenAPI | +| `bl mcp tool search` | API Key | Find recommended MCP tools for a natural-language query | +| `bl mcp tools` | API Key | Open an MCP session and list the server's tools (tools/list) | +| `bl mcp update` | API Key | Update a custom MCP server's metadata or replace its configuration | ## Command details +### `bl mcp activate` + +| Field | Value | +| ------------------ | -------------------------------------------------------------------------------------- | +| **Name** | `mcp activate` | +| **Description** | Activate official MCP servers or enable custom servers using their saved configuration | +| **Authentication** | API Key | +| **Usage** | `bl mcp activate --server [--no-browser] [--dry-run]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------- | ------ | -------- | ----------------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--server ` | string | yes | Comma-separated server codes (up to 30 distinct servers) | +| `--no-browser` | switch | no | Print the console link without opening it when manual setup is required | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- OneKey activation may place an order. ACTIVATING means the deployment is still in progress. Use mcp list to see servers once they are active. + +#### Examples + +```bash +bl mcp activate --server mcp-example,mcp-weather --dry-run +``` + +```bash +bl mcp activate --server mcp-example +``` + ### `bl mcp call` -| Field | Value | -| ------------------ | ----------------------------------------------------------------------------------- | -| **Name** | `mcp call` | -| **Description** | Call a tool on an MCP server (tools/call) | -| **Authentication** | API Key | -| **Usage** | `bl mcp call --target [--arg k=v ...] [--json '{...}'] [--url ]` | +| Field | Value | +| ------------------ | ---------------------------------------------------------------------------------------------------- | +| **Name** | `mcp call` | +| **Description** | Open an MCP session and call a tool (tools/call) | +| **Authentication** | API Key | +| **Usage** | `bl mcp call --target [--arg k=v ...] [--json '{...}'] [--query ] [--url ]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------ | ------ | -------- | ----------------------------------------------------------------------------------------------------------- | -| `--target ` | string | yes | Server code and tool name joined by a dot, e.g. market-cmapi00073529.SmartStockSelection | -| `--arg ` | array | no | Tool argument (repeatable). Values parsed as JSON if possible, else string. | -| `--json ` | string | no | Full arguments object as JSON; merged with --arg (arg wins). | -| `--query ` | string | no | Shortcut for --arg query= (mirrors many DashScope MCP tools). | -| `--url ` | string | no | Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL. | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| ------------------------ | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `--target ` | string | yes | Server code and tool name separated by the first dot | +| `--json ` | string | no | Base tool arguments as a JSON object | +| `--arg ` | array | no | Set a tool argument (repeatable). Values are parsed as JSON when possible and override --json. | +| `--query ` | string | no | Set the query argument to this text after applying --json and --arg | +| `--url ` | string | no | MCP endpoint that receives the API key. Try Streamable HTTP first, then classic SSE at the same URL if initialization returns HTTP 404 or 405. | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Examples @@ -54,95 +96,233 @@ bl mcp call --target market-cmapi00073529.SmartFundSelection --arg riskLevel=R3 ### `bl mcp connect` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------------------------- | -| **Name** | `mcp connect` | -| **Description** | Register a Bailian MCP server in an Agent's native configuration | -| **Authentication** | API Key | -| **Usage** | `bl mcp connect --server --transport --agent ` | +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `mcp connect` | +| **Description** | Connect a Bailian MCP service to native Agent configurations | +| **Authentication** | API Key | +| **Usage** | `bl mcp connect --server --transport --agent [--scope ] [--and-activate[=true\|false]] [--dry-run]` | + +#### Flags + +| Flag | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--server ` | string | yes | Bailian MCP server code | +| `--agent ` | string | yes | Target Agent: codex, claude-code, cursor, qoder, qoderwork, qwenwork, qwen-code, gemini, opencode, openclaw, deepseek-harness, zcode, workbuddy, pi, all | +| `--scope ` | string | no | Registration scope (default user). Run project scope in the project root. Supported: codex, claude-code, cursor, qoder, qwen-code, gemini, opencode, workbuddy, pi. | +| `--transport ` | string | yes | Transport exposed by the service endpoint | +| `--and-activate [true\|false]` | boolean | no | Activate an inactive service before connecting (default true, activation may incur charges). Use --and-activate=false to connect only to active services. | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Agent configuration contains the resolved API key. Keep project configuration and its backups out of version control. +- The service detail supplies the workspace endpoint. Each Agent is updated independently after its registration fingerprint is checked. + +#### Examples + +```bash +bl mcp connect --server TextGenerateImage --transport streamable-http --agent cursor --dry-run +``` + +```bash +bl mcp connect --server mcp-example --transport sse --agent claude-code --scope project --and-activate=false +``` + +### `bl mcp create` + +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------ | +| **Name** | `mcp create` | +| **Description** | Create and deploy a custom MCP server | +| **Authentication** | API Key | +| **Usage** | `bl mcp create --name --description --mcp-type --mcp-config [flags]` | + +#### Flags + +| Flag | Type | Required | Description | +| ---------------------------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--name ` | string | yes | Server name | +| `--description ` | string | yes | Server description | +| `--mcp-type ` | string | yes | MCP type (case-insensitive) | +| `--mcp-config ` | string | yes | Complete MCP configuration as a JSON object or JSON file path | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Deploying a custom MCP server may incur charges, including Function Compute usage for STDIO. + +#### Examples + +```bash +bl mcp create --name weather --description "Weather lookup" --mcp-type http --mcp-config '{"url":"https://mcp.example.com/mcp"}' --dry-run +``` + +```bash +bl mcp create --name weather --description "Weather lookup" --mcp-type http --mcp-config ./weather.json +``` + +### `bl mcp deactivate` + +| Field | Value | +| ------------------ | ----------------------------------------------------------------- | +| **Name** | `mcp deactivate` | +| **Description** | Deactivate official MCP servers or stop custom server deployments | +| **Authentication** | API Key | +| **Usage** | `bl mcp deactivate --server [--dry-run]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--server ` | string | yes | Bailian MCP Server Code, such as TextGenerateImage | -| `--transport ` | string | yes | MCP transport exposed by the server: streamable-http or sse | -| `--agent ` | string | yes | Target Agent: codex, claude-code, cursor, qoder, qoderwork, qwenwork, qwen-code, gemini, opencode, openclaw, deepseek-harness, zcode, workbuddy, pi, all | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| --------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--server ` | string | yes | Comma-separated server codes (up to 30 distinct servers) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes -- This release registers the official China-site MCP endpoint; the model API --base-url does not change the MCP endpoint. -- The resolved API key is written to the selected Agent's private local configuration. Existing unmanaged entries are never overwritten. -- qoder, qoderwork, and qwenwork are independent products. qwenwork is QwenWork (千问办公); qoderwork is Qoder Work. -- workbuddy covers CodeBuddy / WorkBuddy. deepseek-harness is DeepSeek Harness and only accepts streamable-http. +- Stopping a server can interrupt callers. Stopping a custom server keeps its definition and saved configuration. The service may reject deactivation for OneKey servers. #### Examples ```bash -bl mcp connect --server TextGenerateImage --transport streamable-http --agent cursor +bl mcp deactivate --server mcp-example,mcp-weather --dry-run ``` ```bash -bl mcp connect --server VideoGenerate --transport sse --agent claude-code +bl mcp deactivate --server mcp-example +``` + +### `bl mcp delete` + +| Field | Value | +| ------------------ | ----------------------------------------------------------------- | +| **Name** | `mcp delete` | +| **Description** | Permanently delete a custom MCP server | +| **Authentication** | API Key | +| **Usage** | `bl mcp delete --server [flags]` | +| **Risk** | `high` | +| **Risk message** | Permanently delete this custom MCP server. This cannot be undone. | + +> **Agent safety:** Never add `--yes` automatically. On `type="requires_confirmation"`, stop and ask for explicit user confirmation of the same action and scope. + +#### Flags + +| Flag | Type | Required | Description | +| --------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--server ` | string | yes | Custom MCP server code | +| `--yes` | switch | no | Confirm this high-risk operation | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Deletion is irreversible. Use mcp disconnect to remove any local Agent registrations listed in the result. + +#### Examples + +```bash +bl mcp delete --server mcp-example --dry-run ``` ```bash -bl mcp connect --server TextGenerateImage --transport streamable-http --agent all +# Only after explicit user confirmation: +bl mcp delete --server mcp-example --yes ``` ### `bl mcp disconnect` -| Field | Value | -| ------------------ | ---------------------------------------------------------------------- | -| **Name** | `mcp disconnect` | -| **Description** | Remove an unchanged MCP registration previously managed by bailian-cli | -| **Authentication** | No Auth | -| **Usage** | `bl mcp disconnect --server --agent ` | +| Field | Value | +| ------------------ | ---------------------------------------------------------------------------------------------- | +| **Name** | `mcp disconnect` | +| **Description** | Remove a managed MCP registration from local Agent configurations | +| **Authentication** | No Auth | +| **Usage** | `bl mcp disconnect --server --agent [--scope ] [--dry-run]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `--server ` | string | yes | Bailian MCP Server Code used during connect | -| `--agent ` | string | yes | Target Agent: codex, claude-code, cursor, qoder, qoderwork, qwenwork, qwen-code, gemini, opencode, openclaw, deepseek-harness, zcode, workbuddy, pi, all | +| Flag | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------ | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `--server ` | string | yes | Bailian MCP server code | +| `--agent ` | string | yes | Target Agent: codex, claude-code, cursor, qoder, qoderwork, qwenwork, qwen-code, gemini, opencode, openclaw, deepseek-harness, zcode, workbuddy, pi, all | +| `--scope ` | string | no | Registration scope (default user). Run project scope in the project root. Supported: codex, claude-code, cursor, qoder, qwen-code, gemini, opencode, workbuddy, pi. | #### Notes -- A registration changed after connect is left untouched and reported as a conflict. +- Disconnect runs offline. Entries edited since registration are preserved and reported as conflicts. #### Examples ```bash -bl mcp disconnect --server TextGenerateImage --agent cursor +bl mcp disconnect --server mcp-example --agent cursor --scope project --dry-run ``` ```bash -bl mcp disconnect --server TextGenerateImage --agent all +bl mcp disconnect --server mcp-example --agent all +``` + +### `bl mcp get` + +| Field | Value | +| ------------------ | ------------------------------------------------ | +| **Name** | `mcp get` | +| **Description** | Get an MCP server's details and tool definitions | +| **Authentication** | API Key | +| **Usage** | `bl mcp get --server [flags]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--server ` | string | yes | Official or custom MCP server code | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Billing shows the reported mode, unit price and free quota, or null when unavailable. Dry-run retrieves only server details. Tool discovery may activate a OneKey service. If tool discovery fails, the detail result contains tools=null and the command exits with the error. + +#### Examples + +```bash +bl mcp get --server mcp-example +``` + +```bash +bl mcp get --server mcp-example --dry-run ``` ### `bl mcp list` -| Field | Value | -| ------------------ | ----------------------------------------------------- | -| **Name** | `mcp list` | -| **Description** | List MCP servers activated under your Bailian account | -| **Authentication** | Console | -| **Usage** | `bl mcp list [flags]` | +| Field | Value | +| ------------------ | ----------------------------------------------------------------------------------------- | +| **Name** | `mcp list` | +| **Description** | List activated MCP servers and their local Agent registrations | +| **Authentication** | API Key | +| **Usage** | `bl mcp list [--name ] [--type ] [--page ] [--page-size ]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------------ | ------ | -------- | -------------------------------------------------------- | -| `--name ` | string | no | Filter by server name (substring match) | -| `--type ` | string | no | Server type: OFFICIAL \| PRIVATE (default: OFFICIAL) | -| `--page ` | number | no | Page number (default: 1) | -| `--page-size ` | number | no | Results per page (default: 30) | -| `--console-region ` | string | no | Console gateway region (e.g. cn-beijing, ap-southeast-1) | -| `--console-site ` | string | no | Console site: domestic, international | -| `--console-switch-agent ` | number | no | Switch agent UID for delegated access | -| `--workspace-id ` | string | no | Workspace ID (env: BAILIAN_WORKSPACE_ID) | +| Flag | Type | Required | Description | +| ---------------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--name ` | string | no | Filter by server name (substring match) | +| `--type ` | string | no | Ownership type (default official, case-insensitive) | +| `--page ` | number | no | Page of matching servers (default 1) | +| `--page-size ` | number | no | Matching servers per page (1–100, default 30) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- The CLI scans the selected type to compute the activated total before paging. connected_agents and config_paths report managed native entries whose fingerprints still match. #### Examples @@ -155,26 +335,127 @@ bl mcp list --name finance ``` ```bash -bl mcp list --output json +bl mcp list --type private --page 2 --page-size 10 +``` + +### `bl mcp tool call` + +| Field | Value | +| ------------------ | -------------------------------------------------------------------------------------------------------------- | +| **Name** | `mcp tool call` | +| **Description** | Call a Bailian MCP tool via OpenAPI | +| **Authentication** | API Key | +| **Usage** | `bl mcp tool call --server --tool [--json '{...}'] [--arg k=v ...] [--query ] [--dry-run]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------- | ------ | -------- | ---------------------------------------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--server ` | string | yes | Official or custom MCP server code | +| `--tool ` | string | yes | Tool name returned by tool list or tool search | +| `--json ` | string | no | Base tool arguments as a JSON object | +| `--arg ` | array | no | Set a tool argument (repeatable). Values are parsed as JSON when possible and override --json. | +| `--query ` | string | no | Set the query argument to this text after applying --json and --arg | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Dry-run previews the arguments locally. Calling a tool may activate a OneKey service. A tool-reported error returns its content and exits with code 1. + +#### Examples + +```bash +bl mcp tool call --server mcp-example --tool getOrder --arg orderId=A123 --dry-run +``` + +```bash +bl mcp tool call --workspace-id ws-example --server mcp-example --tool getOrder --arg orderId=A123 +``` + +### `bl mcp tool list` + +| Field | Value | +| ------------------ | --------------------------------------------------------------- | +| **Name** | `mcp tool list` | +| **Description** | List a Bailian MCP server's tools and input schemas via OpenAPI | +| **Authentication** | API Key | +| **Usage** | `bl mcp tool list --server [--dry-run]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--server ` | string | yes | Official or custom MCP server code | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Fetching tools may activate a OneKey service. Dry-run previews the request locally. + +#### Examples + +```bash +bl mcp tool list --server mcp-example +``` + +```bash +bl mcp tool list --server mcp-example --dry-run +``` + +### `bl mcp tool search` + +| Field | Value | +| ------------------ | ------------------------------------------------------------- | +| **Name** | `mcp tool search` | +| **Description** | Find recommended MCP tools for a natural-language query | +| **Authentication** | API Key | +| **Usage** | `bl mcp tool search --query [--limit ] [--dry-run]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--query ` | string | yes | Describe what you want the tool to do | +| `--limit ` | number | no | Maximum results to show (default 10) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Requesting recommendations may activate a OneKey service and place an order. + +#### Examples + +```bash +bl mcp tool search --query "look up an order" --dry-run +``` + +```bash +bl mcp tool search --query "look up an order" --limit 5 ``` ### `bl mcp tools` -| Field | Value | -| ------------------ | ------------------------------------------------ | -| **Name** | `mcp tools` | -| **Description** | List tools exposed by an MCP server (tools/list) | -| **Authentication** | API Key | -| **Usage** | `bl mcp tools --server [--url ]` | +| Field | Value | +| ------------------ | ------------------------------------------------------------ | +| **Name** | `mcp tools` | +| **Description** | Open an MCP session and list the server's tools (tools/list) | +| **Authentication** | API Key | +| **Usage** | `bl mcp tools --server [--url ]` | #### Flags -| Flag | Type | Required | Description | -| ------------------ | ------ | -------- | ----------------------------------------------------------------------------------------------------------- | -| `--server ` | string | yes | Server code from `mcp list` (e.g. market-cmapi00073529) | -| `--url ` | string | no | Override the MCP endpoint URL (non-Bailian). Tries Streamable HTTP first, then classic SSE on the same URL. | -| `--api-key ` | string | no | API key | -| `--base-url ` | string | no | API base URL | +| Flag | Type | Required | Description | +| ------------------ | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| `--server ` | string | yes | Server code from `mcp list` (e.g. market-cmapi00073529) | +| `--url ` | string | no | MCP endpoint that receives the API key. Try Streamable HTTP first, then classic SSE at the same URL if initialization returns HTTP 404 or 405. | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Examples @@ -189,3 +470,40 @@ bl mcp tools --server market-cmapi00073529 --output json ```bash bl mcp tools --server my-server --url https://example.com/mcp ``` + +### `bl mcp update` + +| Field | Value | +| ------------------ | ---------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `mcp update` | +| **Description** | Update a custom MCP server's metadata or replace its configuration | +| **Authentication** | API Key | +| **Usage** | `bl mcp update --server [--name ] [--description ] [--mcp-type --mcp-config ] [flags]` | + +#### Flags + +| Flag | Type | Required | Description | +| ---------------------------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--server ` | string | yes | Custom MCP server code | +| `--name ` | string | no | Server name | +| `--description ` | string | no | Server description | +| `--mcp-type ` | string | no | MCP type (case-insensitive) | +| `--mcp-config ` | string | no | Complete MCP configuration as a JSON object or JSON file path | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Deploying a custom MCP server may incur charges, including Function Compute usage for STDIO. +- Name and description changes take effect without redeployment. Stop the instance before replacing its configuration and redeploying. + +#### Examples + +```bash +bl mcp update --server mcp-example --name weather-v2 +``` + +```bash +bl mcp update --server mcp-example --mcp-type sse --mcp-config ./weather.json --dry-run +``` diff --git a/skills/bailian-cli/reference/skill.md b/skills/bailian-cli/reference/skill.md index 807eb6623..5451314f9 100644 --- a/skills/bailian-cli/reference/skill.md +++ b/skills/bailian-cli/reference/skill.md @@ -7,31 +7,46 @@ Index: [index.md](index.md) ## Commands in this group -| Command | Authentication | Description | -| ----------------- | -------------- | ---------------------------------------------------------------------- | -| `bl skill add` | No Auth | Install skills from the Bailian skill registry into local agents | -| `bl skill init` | No Auth | Install all bailian-* skills (one-shot bootstrap for new environments) | -| `bl skill list` | No Auth | List registry skills and diff against local installs | -| `bl skill remove` | No Auth | Remove locally installed skills (registry is untouched) | -| `bl skill update` | No Auth | Update installed skills to the latest registry versions | +| Command | Authentication | Description | +| ----------------- | ------------------------------- | ----------------------------------------------------------------------------------- | +| `bl skill add` | API Key when required by source | Install skills from the Bailian skill registry into local agents | +| `bl skill get` | API Key when required by source | Get skill details, installed versions and paths from the public registry or OpenAPI | +| `bl skill init` | No Auth | Install all bailian-* skills (one-shot bootstrap for new environments) | +| `bl skill list` | API Key when required by source | List registry skills and local installations by agent, scope and status | +| `bl skill remove` | No Auth | Remove locally installed skills (registry is untouched) | +| `bl skill search` | API Key | Search cloud skills and show their local installations | +| `bl skill update` | API Key when required by source | Update installed skills to the latest registry versions | ## Command details ### `bl skill add` -| Field | Value | -| ------------------ | ---------------------------------------------------------------- | -| **Name** | `skill add` | -| **Description** | Install skills from the Bailian skill registry into local agents | -| **Authentication** | No Auth | -| **Usage** | `bl skill add --all \| --name ` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `skill add` | +| **Description** | Install skills from the Bailian skill registry into local agents | +| **Authentication** | API Key when required by source | +| **Usage** | `bl skill add (--name \| --code \| --all) [--agent ] [--scope user\|project] [--skill-version ] [--with-mcp ]` | #### Flags -| Flag | Type | Required | Description | -| ------------------- | ------ | -------- | -------------------------------------- | -| `--all` | switch | no | Install all skills from the registry | -| `--name ` | string | no | Comma-separated skill names to install | +| Flag | Type | Required | Description | +| --------------------------- | ------- | -------- | --------------------------------------------------------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--source ` | string | no | Skill catalog. Use oss for the public registry or cloud for the workspace OpenAPI. | +| `--agent ` | string | no | Target agent ID, or all detected agents | +| `--scope ` | string | no | Installation scope (default user) | +| `--skill-version ` | string | no | Install and pin this exact version | +| `--with-mcp ` | boolean | no | Read serverCode entries from mcp-config.json beside SKILL.md and activate inactive dependencies (default true). | +| `--all` | switch | no | Install all skills from the public OSS registry | +| `--name ` | string | no | Public OSS registry skill names, separated by commas | +| `--code ` | string | no | Cloud OpenAPI skill codes returned by skill search, separated by commas | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Use --dry-run to inspect the selected package versions and preview MCP activation. Installation activates inactive dependencies and may incur charges. Public OSS packages install without a key. Checking their declared MCP services requires a Bailian API key. Use --with-mcp false to install only. #### Examples @@ -43,6 +58,40 @@ bl skill add --all bl skill add --name spark-video,bailian-model-recommend ``` +```bash +bl skill add --code skill_example --agent cursor --scope project --skill-version 1.0 --dry-run +``` + +### `bl skill get` + +| Field | Value | +| ------------------ | ----------------------------------------------------------------------------------- | +| **Name** | `skill get` | +| **Description** | Get skill details, installed versions and paths from the public registry or OpenAPI | +| **Authentication** | API Key when required by source | +| **Usage** | `bl skill get (--name \| --code ) [--with-mcp ]` | + +#### Flags + +| Flag | Type | Required | Description | +| --------------------- | ------- | -------- | ------------------------------------------------------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--with-mcp ` | boolean | no | Read declared MCP server codes from the latest version package (default true, null if the manifest is absent) | +| `--name ` | string | no | Skill name in the public OSS registry | +| `--code ` | string | no | OpenAPI skill_code returned by skill search | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Examples + +```bash +bl skill get --name bailian-cli +``` + +```bash +bl skill get --code skill_example --with-mcp false +``` + ### `bl skill init` | Field | Value | @@ -59,7 +108,7 @@ _No command-specific flags._ #### Notes - Fetches the registry index and installs every skill whose name starts with `bailian-`. -- Equivalent to: `bl skill add --all` (filtered to `bailian-*` skills). +- Installs the `bailian-*` subset of `bl skill add --all`. #### Examples @@ -69,20 +118,30 @@ bl skill init ### `bl skill list` -| Field | Value | -| ------------------ | ---------------------------------------------------- | -| **Name** | `skill list` | -| **Description** | List registry skills and diff against local installs | -| **Authentication** | No Auth | -| **Usage** | `bl skill list` | +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `skill list` | +| **Description** | List registry skills and local installations by agent, scope and status | +| **Authentication** | API Key when required by source | +| **Usage** | `bl skill list [--name \| --code \| --source oss\|cloud] [--agent ] [--scope user\|project] [--status ]` | #### Flags -_No command-specific flags._ +| Flag | Type | Required | Description | +| ------------------------- | ------ | -------- | ---------------------------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--source ` | string | no | Skill catalog. Use oss for the public registry or cloud for the workspace OpenAPI. | +| `--name ` | string | no | Public OSS registry skill names, separated by commas | +| `--code ` | string | no | Cloud OpenAPI skill codes returned by skill search, separated by commas | +| `--agent ` | string | no | Target agent ID, or all detected agents | +| `--scope ` | string | no | Installation scope (default user) | +| `--status ` | string | no | Comma-separated installation states | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | #### Notes -- STATUS: installed | outdated | not-installed | missing (lock has it, dir deleted) | untracked (dir exists, not managed) +- States: installed, outdated, not-installed, missing (tracked path absent), untracked (local files without a lock record). #### Examples @@ -91,23 +150,39 @@ bl skill list ``` ```bash -bl skill list --output json +bl skill list --source oss --status not-installed +``` + +```bash +bl skill list --name spark-video +``` + +```bash +bl skill list --code skill_example +``` + +```bash +bl skill list --agent cursor --scope project --status installed,outdated ``` ### `bl skill remove` -| Field | Value | -| ------------------ | ------------------------------------------------------- | -| **Name** | `skill remove` | -| **Description** | Remove locally installed skills (registry is untouched) | -| **Authentication** | No Auth | -| **Usage** | `bl skill remove --name ` | +| Field | Value | +| ------------------ | -------------------------------------------------------------------------------------------------------------- | +| **Name** | `skill remove` | +| **Description** | Remove locally installed skills (registry is untouched) | +| **Authentication** | No Auth | +| **Usage** | `bl skill remove (--name \| --code ) [--agent ] [--scope user\|project]` | #### Flags -| Flag | Type | Required | Description | -| ------------------------ | ------ | -------- | ---------------------------------------------------- | -| `--name ` | string | yes | Skills to remove: all or comma-separated skill names | +| Flag | Type | Required | Description | +| ------------------------- | ------ | -------- | ---------------------------------------------------------------------------------- | +| `--source ` | string | no | Skill catalog. Use oss for the public registry or cloud for the workspace OpenAPI. | +| `--agent ` | string | no | Target agent ID, or all detected agents | +| `--scope ` | string | no | Installation scope (default user) | +| `--name ` | string | no | Public OSS registry skill names, separated by commas | +| `--code ` | string | no | Cloud OpenAPI skill codes returned by skill search, separated by commas | #### Examples @@ -119,21 +194,74 @@ bl skill remove --name spark-video bl skill remove --name all ``` +```bash +bl skill remove --code skill_example --agent cursor --scope project --dry-run +``` + +### `bl skill search` + +| Field | Value | +| ------------------ | ------------------------------------------------------------------------------------------------------------ | +| **Name** | `skill search` | +| **Description** | Search cloud skills and show their local installations | +| **Authentication** | API Key | +| **Usage** | `bl skill search [--keyword ] [--type official\|private] [--page ] [--page-size ] [--limit ]` | + +#### Flags + +| Flag | Type | Required | Description | +| ---------------------------- | ------ | -------- | --------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--keyword ` | string | no | Search skill names and descriptions | +| `--type ` | string | no | Filter by source (default: both, case-insensitive) | +| `--page ` | number | no | Starting page (default 1) | +| `--page-size ` | number | no | Results per request (1–100, default 30) | +| `--limit ` | number | no | Maximum results across pages (default one page) | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- Search uses the cloud catalog and a Bailian API key. page_start and page_end identify the requested pages within the API's 10000-record window. installations lists managed, missing and untracked locations. + +#### Examples + +```bash +bl skill search --keyword pdf --type official +``` + +```bash +bl skill search --page 2 --page-size 10 --limit 25 +``` + ### `bl skill update` -| Field | Value | -| ------------------ | ------------------------------------------------------- | -| **Name** | `skill update` | -| **Description** | Update installed skills to the latest registry versions | -| **Authentication** | No Auth | -| **Usage** | `bl skill update [--all] [--name ]` | +| Field | Value | +| ------------------ | --------------------------------------------------------------------------------------------------------------------------- | +| **Name** | `skill update` | +| **Description** | Update installed skills to the latest registry versions | +| **Authentication** | API Key when required by source | +| **Usage** | `bl skill update [--name \| --code \| --all] [--agent ] [--scope user\|project] [--diff]` | #### Flags -| Flag | Type | Required | Description | -| ------------------- | ------ | -------- | ---------------------------------------------------------------------------- | -| `--all` | switch | no | Update all installed skills (default when neither --all nor --name is given) | -| `--name ` | string | no | Comma-separated skill names to update (must be already installed) | +| Flag | Type | Required | Description | +| ------------------------- | ------ | -------- | ---------------------------------------------------------------------------------- | +| `--workspace-id ` | string | no | Workspace ID for API endpoint URL (or set BAILIAN_WORKSPACE_ID) | +| `--source ` | string | no | Skill catalog. Use oss for the public registry or cloud for the workspace OpenAPI. | +| `--agent ` | string | no | Target agent ID, or all detected agents | +| `--scope ` | string | no | Installation scope (default user) | +| `--diff` | switch | no | Show changed files, or the required download in a preview | +| `--all` | switch | no | Update all installed public OSS skills in the selected scope | +| `--name ` | string | no | Public OSS registry skill names, separated by commas | +| `--code ` | string | no | Cloud OpenAPI skill codes returned by skill search, separated by commas | +| `--api-key ` | string | no | API key | +| `--base-url ` | string | no | API base URL | + +#### Notes + +- --name all is an alias for --all. With no selector, update installed cloud skills in the selected scope. +- Other Skill commands check for updates to unpinned installations from the selected source. Available updates appear on stderr. Removal uses the cached check offline. #### Examples @@ -148,3 +276,7 @@ bl skill update --all ```bash bl skill update --name spark-video ``` + +```bash +bl skill update --code skill_example --agent cursor --scope project --diff --dry-run +``` diff --git a/skills/bailian-finetune/SKILL.md b/skills/bailian-finetune/SKILL.md index ae63f30e9..d621971ba 100644 --- a/skills/bailian-finetune/SKILL.md +++ b/skills/bailian-finetune/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-finetune metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-gen/SKILL.md b/skills/bailian-gen/SKILL.md index 738e56c1f..ffd0cd901 100644 --- a/skills/bailian-gen/SKILL.md +++ b/skills/bailian-gen/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-gen metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-knowledge/SKILL.md b/skills/bailian-knowledge/SKILL.md index 1e2a4b135..a5f850afe 100644 --- a/skills/bailian-knowledge/SKILL.md +++ b/skills/bailian-knowledge/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-knowledge metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- @@ -74,7 +74,7 @@ description: >- 个人绑定的业务调用显式传已核实的 `--workspace-id`,优先 `--output json`。使用真实返回的 ID;知识库 index ID 不能当作检索 agent ID。凭证与签名上传 URL 不进入回复、绑定或版本库。用户文本作为参数传递,不作为 shell 代码执行。 -整包安装:`bl skill init`;子集安装:`bl skill add --name bailian-protocol,bailian-knowledge`;更新:`bl skill update`(只更新已安装 Skill)。只有 `kscli` 时仍通过现有 `bl skill` 渠道安装,不编造 `kscli skill`。 +整包安装:`bl skill init`;子集安装:`bl skill add --name bailian-protocol,bailian-knowledge`;更新:`bl skill update --all`(只更新已安装 Skill)。只有 `kscli` 时仍通过现有 `bl skill` 渠道安装,不编造 `kscli skill`。 - [资料绑定](references/bindings.md):首次读取状态、建立绑定、暂停或恢复时读取。 - [接入流程](references/setup.md):首次接入、复用资源、补齐服务、续接初始化时读取。 diff --git a/skills/bailian-managed-agent/SKILL.md b/skills/bailian-managed-agent/SKILL.md index d9f270291..313307f0e 100644 --- a/skills/bailian-managed-agent/SKILL.md +++ b/skills/bailian-managed-agent/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-managed-agent metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-memory/SKILL.md b/skills/bailian-memory/SKILL.md index 8e70f3e6d..bae973077 100644 --- a/skills/bailian-memory/SKILL.md +++ b/skills/bailian-memory/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-memory metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-opd/SKILL.md b/skills/bailian-opd/SKILL.md index 9717509e9..caa192ca6 100644 --- a/skills/bailian-opd/SKILL.md +++ b/skills/bailian-opd/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-opd metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl", "node"] description: >- diff --git a/skills/bailian-protocol/SKILL.md b/skills/bailian-protocol/SKILL.md index 9fe682567..1250d2b8a 100644 --- a/skills/bailian-protocol/SKILL.md +++ b/skills/bailian-protocol/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-protocol metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-protocol/assets/issue-reporting.md b/skills/bailian-protocol/assets/issue-reporting.md index 9c0320ded..d79ce65e2 100644 --- a/skills/bailian-protocol/assets/issue-reporting.md +++ b/skills/bailian-protocol/assets/issue-reporting.md @@ -115,7 +115,7 @@ Offer reporting when **none** of EXCLUDE applies **and** any of the following ho ### Before offering to report -1. Align versions: [SKILL.md → Version & updates](../SKILL.md#version--updates-after-provider-selection-before-the-first-bl-command) — run `bl update` and `bl skill update` if mismatched. If needed skills are missing, run `bl skill init`. +1. Align versions: [SKILL.md → Version & updates](../SKILL.md#version--updates-after-provider-selection-before-the-first-bl-command) — run `bl update` and `bl skill update --all` if mismatched. If needed skills are missing, run `bl skill init`. 2. Confirm `bl auth status` is healthy (for commands that need auth). 3. Preserve existing output. If stderr was thin, use the safe diagnostic procedure below; retry is optional and is never a prerequisite for reporting an uncertain write. diff --git a/skills/bailian-protocol/assets/versioning.md b/skills/bailian-protocol/assets/versioning.md index a2a883736..c1fc0d284 100644 --- a/skills/bailian-protocol/assets/versioning.md +++ b/skills/bailian-protocol/assets/versioning.md @@ -18,7 +18,7 @@ Agents wrap middleware `bl` commands with [Call attribution](../SKILL.md#call-at 3. Compare the two versions (ignore the `bl` prefix; compare only `X.Y.Z`): - If `metadata.version` ≠ `bl --version`, refresh already-installed skills before doing anything else: ```bash - bl skill update + bl skill update --all ``` - If `bailian-protocol` or another needed skill is missing, stop and run `bl skill init` (same Call attribution, `bailian-protocol`). Do not use `bl skill init` only to refresh versions — it installs every `bailian-*` skill. - Do not trust a stale `reference/` when versions mismatch — flags may be wrong. @@ -29,7 +29,7 @@ Agents wrap middleware `bl` commands with [Call attribution](../SKILL.md#call-at 5. If the installed `bl` is **older** than the latest npm version, **STOP** the current task and **ask the user** (report skill version, installed CLI version, and npm latest): > A newer version of bl is available (current: X.Y.Z, latest: A.B.C). Upgrade before continuing? - **Do NOT auto-upgrade silently** — the user decides. - - If the user agrees: run `bl update` (same Call attribution), then continue. (`bl update` uses the detected install channel and, on success, also runs `bl skill update` to refresh already-installed skills; it does not install new skills. First-time install still uses `bl skill init`.) + - If the user agrees: run `bl update` (same Call attribution), then continue. (`bl update` uses the detected install channel and, on success, also runs `bl skill update --all` to refresh already-installed skills; it does not install new skills. First-time install still uses `bl skill init`.) ```bash bl update ``` diff --git a/skills/bailian-sandbox/SKILL.md b/skills/bailian-sandbox/SKILL.md index 33fb4f5ad..44479d86b 100644 --- a/skills/bailian-sandbox/SKILL.md +++ b/skills/bailian-sandbox/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-sandbox metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- diff --git a/skills/bailian-web-search/SKILL.md b/skills/bailian-web-search/SKILL.md index 34a1dfb68..ae78d608c 100644 --- a/skills/bailian-web-search/SKILL.md +++ b/skills/bailian-web-search/SKILL.md @@ -1,7 +1,7 @@ --- name: bailian-web-search metadata: - version: "2.13.0" + version: "2.14.0" requires: bins: ["bl"] description: >- diff --git a/tools/generate-reference.ts b/tools/generate-reference.ts index ff0ff0567..0b0aa262e 100644 --- a/tools/generate-reference.ts +++ b/tools/generate-reference.ts @@ -94,6 +94,10 @@ const AUTH_LABELS = { none: "No Auth", } satisfies Record; +function authLabel(command: AnyCommand): string { + return command.requiresApiKey ? "API Key when required by source" : AUTH_LABELS[command.auth]; +} + function escCell(s: string): string { return s.replace(/\|/g, "\\|").replace(/\n/g, " ").trim(); } @@ -172,7 +176,7 @@ function commandSection(path: string, cmd: AnyCommand): string { lines.push(`| Field | Value |`, `| --- | --- |`); lines.push(`| **Name** | \`${escCell(path)}\` |`); lines.push(`| **Description** | ${escCell(referenceText(cmd.description))} |`); - lines.push(`| **Authentication** | ${AUTH_LABELS[cmd.auth]} |`); + lines.push(`| **Authentication** | ${authLabel(cmd)} |`); // Commands store argument-only usage; the `bl ` prefix is added here. const usage = `bl ${path}${cmd.usageArgs ? ` ${cmd.usageArgs}` : ""}`; lines.push(`| **Usage** | \`${escCell(usage)}\` |`); @@ -247,7 +251,7 @@ function buildGroupFile(group: string, groupEntries: [string, AnyCommand][]): st for (const [path, cmd] of groupEntries) { lines.push( - `| \`bl ${path}\` | ${AUTH_LABELS[cmd.auth]} | ${escCell(referenceText(cmd.description))} |`, + `| \`bl ${path}\` | ${authLabel(cmd)} | ${escCell(referenceText(cmd.description))} |`, ); } @@ -282,7 +286,7 @@ function buildIndex( for (const [path, cmd] of entries) { const group = topLevel(path); lines.push( - `| \`bl ${path}\` | ${AUTH_LABELS[cmd.auth]} | ${escCell(referenceText(cmd.description))} | [${group}.md](${group}.md) |`, + `| \`bl ${path}\` | ${authLabel(cmd)} | ${escCell(referenceText(cmd.description))} | [${group}.md](${group}.md) |`, ); }