@tinyforge/dsh-plugin-manager-wj 1.3.4 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,31 +4,37 @@
4
4
  [![npm downloads](https://img.shields.io/npm/dm/@tinyforge/dsh-plugin-manager-wj.svg)](https://www.npmjs.com/package/@tinyforge/dsh-plugin-manager-wj)
5
5
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
6
 
7
- **WJ Plugin Management** is the Web management layer for DeepSeek Harness's three-layer plugin-management design. It extends the independent WJ bundle and adds a management tab under **Settings → Plugins** whose four views switch without leaving the page: **Plugins**, **Configuration**, **Skills** and **MCP**.
7
+ **WJ Plugin Management** is the Web management layer for DeepSeek Harness's three-layer plugin-management design. It extends the independent WJ bundle and adds a management tab under **Settings → Plugins** whose four views switch without leaving the page: **Plugins**, **Configuration**, **Skills** and **Tools**.
8
8
 
9
9
  ## Features
10
10
 
11
- - **Switchable views:** one tab strip switches between plugin health, configuration, the skill catalog, and MCP/tool inventory. A visited view stays mounted, so a configuration draft and the search term survive switching.
11
+ - **Switchable views:** one tab strip switches between plugin health, configuration, the skill catalog, and tool registration ownership. A visited view stays mounted, so a configuration draft and the search term survive switching.
12
12
  - **Harness Core:** consumes the Host's plugin registry, configuration resolver, conflict detector, lifecycle/dependency manager, and settings services.
13
- - **Management API:** shows plugin state and health findings, configuration provenance, and tool/MCP runtime registrations. It can enable or disable profile-addressable plugins.
14
- - **Management UI:** filters the active view, edits non-secret scalar settings through the existing schema-backed `configForms`, and previews supported duplicate-registration repairs.
13
+ - **Management API:** shows plugin state, derived activation findings, configuration provenance, and tool runtime registrations. It can enable or disable profile-addressable plugins.
14
+ - **Management UI:** filters the active view, edits non-secret scalar settings through the existing schema-backed `configForms`, and reports each tool's scope with its owner (an MCP server, or the plugin package the Host half matched).
15
15
 
16
16
  ### Views
17
17
 
18
18
  | View | Source | Notes |
19
19
  | --- | --- | --- |
20
- | Plugins | `pluginManager.listPlugins`, `pluginManager.getHealthSnapshot` | Enable/disable, findings, and bounded repair previews. |
20
+ | Plugins | the Loader projection from `pluginInventory.list()` | Enable/disable addressable entries; findings are derived from failed fibers and their `diagnostic`. |
21
21
  | Configuration | `configForms.describe`, `pluginManager.getConfigProvenance` | Secret fields are omitted; provenance shows layers and redacted identities. |
22
22
  | Skills | `skills/list` through the active session | Session-scoped, so the catalog resolves from the session working directory and reloads automatically when the active session changes. Model-invocable and user-only entries are marked separately. |
23
- | MCP | `pluginInventory.list`, `mcpClientStatus.list` (optional) | MCP client connections plus the owners of registered tools. Servers managed by a companion package live outside the Host's own registry and are merged in by name, with transport, source and tool count. |
23
+ | Tools | this package's Host half, `GET /api/wj/tool-inventory` | Runtime tool registrations, with the plugin that provides each tool and the scope it applies to. |
24
24
 
25
- Enabling or disabling a plugin writes through the Host's existing profile manager. A change can apply immediately, require a restart, be overridden by a higher-priority layer, or be refused by the Host. Repair previews are short-lived and become invalid when their finding changes. Selecting a low-risk repair with one eligible target executes it automatically; a high-risk repair first shows the exact effect and requires an explicit confirmation click. The current repair action disables the selected plugin involved in a duplicate global tool or MCP registration.
25
+ Enabling or disabling a plugin writes through the Host's `pluginManager.setPluginEnabled`. A change can apply immediately, require a restart, be overridden by a higher-priority layer, be cancelled, or be refused by the Host; the outcome is reported as it arrives.
26
+
27
+ Ownership has three sources: a `mcp__<server>__<tool>` name belongs to that server; any other name is matched by the Host half against `name: '…'` literals in each plugin package's entry bundle and labelled **inferred**; a name neither source explains is reported as unrecorded instead of guessed.
28
+
29
+ MCP servers themselves belong to the Host's MCP settings bundle (for example `@tinyforge/dsh-mcp-settings`), which registers the `settings.section` page `mcp` and reads `mcpClientStatus/list`. This bundle neither reads `mcpClientStatus` nor lists MCP servers a second time, so the settings UI has exactly one MCP management entry point; the Tools view still shows MCP tools, attributed to their server.
26
30
 
27
31
  Configuration fields are discovered from each Host-provided schema. Secret fields are omitted from the editor, and provenance shows layer names and redacted identities, never values or filesystem paths. The Host remains responsible for schema validation and persistence.
28
32
 
29
33
  ## Requirements and limitations
30
34
 
31
- Use a Harness Host that exposes the plugin-management Remote, settings forms, and runtime inventory. Older Hosts may show inventory only or report diagnostics as unavailable; upgrade Harness to use management actions. Only plugins addressable through the active profile can be toggled.
35
+ Use a Harness Host that exposes the Loader projection (`pluginInventory.list()`), which the 0.2.2-rc line does. An older Host that still answers with a `toolRegistrations` snapshot keeps working: plugin and tool rows render, only the failed-fiber findings are missing. The Tools view needs the `/api/wj/tool-inventory` route registered by this package's Host half; a Host that mounts only the Client half says so explicitly instead of showing an empty list. Only plugins addressable through the active profile can be toggled.
36
+
37
+ This package no longer depends on a diagnostics Remote: `getHealthSnapshot`, `previewRemediation` and `applyRemediation` do not exist in the current official Host, so the page derives findings from the Loader projection itself (a failed fiber and its `diagnostic`) and never falls back to a whole-page "this Host does not expose diagnostics" notice.
32
38
 
33
39
  The tab hard-injects only two core client services, `slots` and `locale`. Everything else — the `pluginInventory` and `pluginManager` remotes, `configForms`, the skills Remote and the live session — is resolved through `ctx.get` at call time rather than declared in `inject`, because a Client plugin that lists an optional service in `inject` stays pending on a Host without it, and a pending plugin registers no tab at all: the settings page then shows no plugin views instead of a degraded one. The Skills view therefore degrades rather than disappearing: no Remote means an explanatory message, and no session means a waiting state that loads the catalog by itself as soon as a session appears or the active session changes, with no manual refresh. The namespace is discovered rather than hardcoded (`skills`, `skill`, `skillCatalog`, then any registered `remote.*` name containing "skill"), so a Host that renames it needs no code change. Skills are read-only here: the Host exposes only `skills/list` (policy `reader-session-read`) and no skills configuration namespace, so there is no Remote to enable or disable an entry and the view shows what the active session can see instead of offering a switch that cannot work. The UI never loads skill bodies. The UI does not install/remove packages, edit credentials, or run arbitrary repair commands.
34
40
 
@@ -49,25 +55,27 @@ npm install @tinyforge/dsh-plugin-manager-wj
49
55
  ## Release
50
56
 
51
57
  ```sh
52
- npm test # node --test: 14 checks (views, MCP merge, inject contract, module id, patch shape)
58
+ npm test # node --test: 27 checks (views, tool ownership, Host route, inject contract, module id, patch shape)
53
59
  npm publish --access public # writes to registry.npmjs.org
54
60
  ```
55
61
 
56
- The package name is scoped, so publishing a new version needs maintainer access to the `@tinyforge` npm scope. Tag the published commit (`git tag v1.3.4 && git push --tags`) so the GitHub history matches the registry.
62
+ The package name is scoped, so publishing a new version needs maintainer access to the `@tinyforge` npm scope. Tag the published commit (`git tag v1.5.0 && git push --tags`) so the GitHub history matches the registry.
57
63
 
58
64
  ## Development
59
65
 
60
- The package is an ES module. `index.js` is the Host entry point and `client.js` contains the browser UI. Localized package metadata is in `locale/`; the UI's full dictionaries are registered in `client.js`.
66
+ The package is an ES module with two halves: `index.js` is the Host entry point and `client.js` contains the browser UI. Localized package metadata is in `locale/`; the UI's full dictionaries are registered in `client.js`.
67
+
68
+ The Host half publishes what a browser cannot read. The official `ctx.remote` table is a compile-time allowlist, so a third-party package cannot add a namespace, and `ctx.tools` only exists on the Host. The tool registry therefore travels through `ctx.connection.fetch.register()` as `GET /api/wj/tool-inventory`, which the shared channel admits for owner peers only. Its `inject` names just `connection`; a Host without that channel keeps the plugin active and lets the page explain itself, instead of failing activation.
61
69
 
62
70
  `client.js` registers with `__ModuleLoader__.load({ id: '@tinyforge/dsh-plugin-manager-wj', … })`. That id must be the bare package name, scope included: the client module loader keys each Loader row by package name, and a bundle that registers any other id is reported as loaded without registering its row, which leaves the plugin without a fiber and the settings tab missing entirely. Renaming the package means updating that id in the same commit.
63
71
 
64
- - `node --test` runs the bundle behavior checks in `tests/client.test.js`: the four views render and switch, the visited views stay mounted, search and enable/disable act on the active view, a secret configuration object stays out of the editor, opening a session loads the skill catalog without a refresh, a renamed skills namespace is discovered, a transient catalog failure recovers from the inline retry, the tab still registers on a Host that mounts no optional services, and MCP rows merge the optional client-status Remote by server name.
65
- - `node --check client.js` checks the browser bundle syntax.
72
+ - `node --test` runs the bundle behavior checks in `tests/client.test.js` (the four views render and switch, visited views stay mounted, search and enable/disable act on the active view, a secret configuration object stays out of the editor, opening a session loads the skill catalog without a refresh, a renamed skills namespace is discovered, a transient catalog failure recovers from the inline retry, the tab still registers on a Host that mounts no optional services, the tool view reads its Host route, a missing route explains itself, and a legacy snapshot still fills both views) and `tests/host.test.js` (MCP naming, package-source scan budget, per-scope collection, snapshot shape, the authenticated JSON route, and a Host without the shared channel).
73
+ - `node --check client.js` and `node --check index.js` check both halves' syntax.
66
74
  - `tests/patch.test.js` parses `cordis.patch.yml` and asserts no plain scalar starts with a reserved YAML indicator — the scoped package name must stay quoted, or the Host rejects the bundle patch.
67
75
  - `tests/inject.test.js` pins the plugin's `inject` list to the core services only, so a regressed hard-injection of an optional remote fails the suite instead of silently emptying the settings page on some Hosts.
68
76
  - `tests/module-id.test.js` asserts the registered module id equals `package.json`'s `name`, so a rename cannot silently detach the browser bundle from its Loader row.
69
77
  - `tests/harness.html` mounts the real `client.js` against fixtures in a browser and asserts the same behavior without Node; open it directly from disk and read the JSON report.
70
- - `tests/parse-check.html` is a minimal browser smoke page: it confirms `client.js` parses and registers `settings.plugins.tab`.
78
+ - `tests/parse-check.html` is a minimal browser smoke page: it confirms `client.js` parses and registers `plugins.tab`, the Plugins page's tab slot (the older `settings.plugins.tab` does not exist in current DSH, so that registration landed nowhere).
71
79
 
72
80
  Harness API and Host behavior are implemented and tested in the `deepseek-harness` repository.
73
81
 
package/README.zh.md CHANGED
@@ -4,31 +4,37 @@
4
4
  [![npm downloads](https://img.shields.io/npm/dm/@tinyforge/dsh-plugin-manager-wj.svg)](https://www.npmjs.com/package/@tinyforge/dsh-plugin-manager-wj)
5
5
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
6
 
7
- **WJ 插件管理中心**是 DeepSeek Harness 三层插件管理架构的 Web 管理层,扩展现有独立 WJ bundle,并在 **设置 → 插件** 下添加管理标签页。页面内有 **插件 / 配置 / Skill / MCP** 四个视图,可直接切换,不需要离开当前页面。
7
+ **WJ 插件管理中心**是 DeepSeek Harness 三层插件管理架构的 Web 管理层,扩展现有独立 WJ bundle,并在 **设置 → 插件** 下添加管理标签页。页面内有 **插件 / 配置 / Skill / 工具** 四个视图,可直接切换,不需要离开当前页面。
8
8
 
9
9
  ## 功能
10
10
 
11
- - **可切换视图:**一条标签栏在插件健康、配置、Skill 目录与 MCP/工具清单之间切换。已访问过的视图保持挂载,因此切换时配置草稿和搜索词都不会丢失。
11
+ - **可切换视图:**一条标签栏在插件健康、配置、Skill 目录与工具注册归属之间切换。已访问过的视图保持挂载,因此切换时配置草稿和搜索词都不会丢失。
12
12
  - **Harness Core:**使用 Host 提供的插件注册表、配置解析、冲突检测、生命周期与依赖管理,以及设置服务。
13
- - **Management API:**查看插件状态、健康诊断、配置来源和工具/MCP 运行时注册;可启停当前 Profile 能寻址的插件。
14
- - **Management UI:**按视图过滤,通过现有 schema 表单 `configForms` 编辑非密钥标量配置,并预览受支持的重复注册修复。
13
+ - **Management API:**查看插件状态、激活诊断、配置来源和工具运行时注册;可启停当前 Profile 能寻址的插件。
14
+ - **Management UI:**按视图过滤,通过现有 schema 表单 `configForms` 编辑非密钥标量配置;工具视图给出每个工具的作用域与归属(MCP 服务器或推断出的插件包)。
15
15
 
16
16
  ### 视图
17
17
 
18
18
  | 视图 | 数据来源 | 说明 |
19
19
  | --- | --- | --- |
20
- | 插件 | `pluginManager.listPlugins`、`pluginManager.getHealthSnapshot` | 启停、健康诊断与受控修复预览。 |
20
+ | 插件 | `pluginInventory.list()` 的 Loader 投影 | 启停当前 Profile 能寻址的条目,并由失败 fiber 派生激活诊断。 |
21
21
  | 配置 | `configForms.describe`、`pluginManager.getConfigProvenance` | 隐藏密钥字段;来源只显示层名称与脱敏标识。 |
22
22
  | Skill | 通过当前会话读取 `skills/list` | 按会话解析,目录来自会话工作目录,并在活动会话变化时自动重新加载;模型可调用与仅用户可调用分开标记。 |
23
- | MCP | `pluginInventory.list`、`mcpClientStatus.list`(可选) | MCP 客户端连接状态,以及工具注册的归属插件。由配套包管理的服务不在 Host 自身注册表中,会按服务名合并进来,并带上传输方式、连接来源和工具数。 |
23
+ | 工具 | 本包 Host 半边的 `GET /api/wj/tool-inventory` | 运行时工具注册清单,以及每个工具由哪个插件提供、作用于哪个范围。 |
24
24
 
25
- 启停操作通过 Host 现有 Profile 管理器写入。更改可能即时生效、需要重启、被更高优先级配置覆盖,或被 Host 拒绝。修复预览有时效,并会在诊断项变化后失效。用户选择修复后,只有恰好存在一个可操作目标的低风险修复会自动执行;高风险修复先显示具体影响,再要求用户明确确认。当前修复动作是停用参与全局工具名或 MCP 名称冲突的所选插件。
25
+ 启停操作通过 Host 的 `pluginManager.setPluginEnabled` 写入 Profile。更改可能即时生效、需要重启、被更高优先级配置覆盖、被 Host 取消或被拒绝,结果原样回显。
26
+
27
+ 工具归属分三种来源:名字符合 `mcp__<服务器>__<工具>` 的 MCP 工具直接归给该服务器;其余名字由 Host 半边扫描各插件包入口 bundle 中的 `name: '…'` 字面量匹配,标注为**推断**;两者都匹配不到时如实显示"宿主未暴露归属",不做猜测。
28
+
29
+ MCP 服务器本身由 Host 的 MCP 设置 bundle 管理(例如 `@tinyforge/dsh-mcp-settings`):它注册 `settings.section` 的 `mcp` 页面,并读取 `mcpClientStatus/list`。本插件既不读取 `mcpClientStatus`,也不列出 MCP 服务器清单——工具视图只展示工具注册行,MCP 工具由所属服务器标注。
26
30
 
27
31
  配置字段来自 Host 提供的 schema。编辑器隐藏密钥字段;配置来源只显示层名称和脱敏标识,不暴露值或文件系统路径。schema 校验和持久化由 Host 负责。
28
32
 
29
33
  ## 要求与限制
30
34
 
31
- 需要提供插件管理 Remote、设置表单和运行时清单的 Harness Host。较旧 Host 可能只能查看清单,或显示诊断不可用;升级 Harness 后才能执行管理操作。只有当前 Profile 可寻址的插件可以启停。
35
+ 需要提供插件 Loader 投影(`pluginInventory.list()`)的 Harness Host;0.2.2-rc 系列即如此。较旧 Host 若返回的是带 `toolRegistrations` 的旧清单,插件仍能显示插件与工具行,只是没有失败 fiber 诊断。工具视图依赖本包 Host 半边注册的 `/api/wj/tool-inventory`;该路由不存在的 Host(例如只装客户端半边)会明确提示路由缺失,而不是显示空清单。只有当前 Profile 可寻址的插件可以启停。
36
+
37
+ 本包**不再依赖** Host 的诊断接口:`getHealthSnapshot`、`previewRemediation`、`applyRemediation` 在当前官方 Host 中已不存在,页面改为由 Loader 投影自行派生诊断(失败 fiber + 其 `diagnostic`),因此不会再出现"此 Harness Host 尚未提供诊断接口"的整页提示。
32
38
 
33
39
  标签页只硬注入两个核心客户端服务:`slots` 与 `locale`。其余服务 —— `pluginInventory`、`pluginManager` 两个 remote、`configForms`、skills Remote 与存活会话 —— 都在调用时通过 `ctx.get` 解析,而不写进 `inject`:把可选服务写进 `inject` 会让客户端插件在缺少该服务的 Host 上一直处于 pending 状态,而 pending 的插件不注册任何标签页,设置页面会变成完全没有插件视图,而不是降级显示。因此 Skill 视图只会降级而不会消失:没有 Remote 时给出说明;没有会话时进入等待状态,一旦出现会话或活动会话切换,就自动加载目录,无需手动刷新。命名空间是探测出来的而不是写死的(依次尝试 `skills`、`skill`、`skillCatalog`,再扫描任何含 “skill” 的已注册 `remote.*`),所以 Host 改名也不需要改代码。Skill 在这里是只读的:Host 只提供 `skills/list`(策略 `reader-session-read`),也没有 skills 配置命名空间,因此没有可用于启用或停用条目的 Remote,界面展示当前会话可见的内容,而不提供一个实际无效的开关。界面不会加载 skill 正文。此界面不安装或卸载包、不编辑凭据,也不运行任意修复命令。
34
40
 
@@ -49,25 +55,27 @@ npm install @tinyforge/dsh-plugin-manager-wj
49
55
  ## 发布
50
56
 
51
57
  ```sh
52
- npm test # node --test:14 项检查(视图、MCP 合并、inject 契约、模块 id、patch 结构)
58
+ npm test # node --test:27 项检查(视图、工具归属、Host 路由、inject 契约、模块 id、patch 结构)
53
59
  npm publish --access public # 发布到 registry.npmjs.org
54
60
  ```
55
61
 
56
- 包名带 scope,发布新版本需要 `@tinyforge` npm scope 的维护者权限。发布后给对应提交打 tag(`git tag v1.3.4 && git push --tags`),让 GitHub 历史与 registry 版本对应。
62
+ 包名带 scope,发布新版本需要 `@tinyforge` npm scope 的维护者权限。发布后给对应提交打 tag(`git tag v1.5.0 && git push --tags`),让 GitHub 历史与 registry 版本对应。
57
63
 
58
64
  ## 开发
59
65
 
60
- 本包使用 ES module。`index.js` 是 Host 入口,`client.js` 是浏览器界面。本地化包元数据位于 `locale/`,界面完整词典在 `client.js` 中注册。
66
+ 本包使用 ES module,两个半边各有入口:`index.js` 是 Host 入口,`client.js` 是浏览器界面。本地化包元数据位于 `locale/`,界面完整词典在 `client.js` 中注册。
67
+
68
+ Host 半边把浏览器读不到的东西端出去:官方 `ctx.remote` 是编译期白名单,第三方包无法新增命名空间,`ctx.tools` 又只存在于 Host,因此工具清单经 `ctx.connection.fetch.register()` 以 `GET /api/wj/tool-inventory` 提供给自己的客户端,只对 owner peer 开放。`inject` 只写 `connection`,缺少它会话时插件保持 active 并让页面自行说明,而不是启动失败。
61
69
 
62
70
  `client.js` 以 `__ModuleLoader__.load({ id: '@tinyforge/dsh-plugin-manager-wj', … })` 注册。这个 id 必须是完整包名(含 scope):客户端模块加载器按包名给每个 Loader 行建索引,注册成别的 id 会被判定为"加载了却没有注册自身所在的行",插件因此拿不到 fiber,设置里的标签页完全不出现。改包名时必须在同一次提交里一起改这个 id。
63
71
 
64
- - `node --test` 运行 `tests/client.test.js` 的行为检查:四个视图渲染并可切换、访问过的视图保持挂载、搜索与启停作用于当前视图、密钥配置对象不会进入编辑器、打开会话后无需刷新即加载 Skill 目录、改名后的 skills 命名空间能被发现、瞬时目录失败可就地重试恢复、Host 不挂载任何可选服务时标签页仍然注册,以及 MCP 行会按服务名合并可选的客户端状态 Remote。
65
- - `node --check client.js` 检查浏览器 bundle 语法。
72
+ - `node --test` 运行行为检查:四个视图渲染并可切换、访问过的视图保持挂载、搜索与启停作用于当前视图、密钥配置对象不会进入编辑器、打开会话后无需刷新即加载 Skill 目录、改名后的 skills 命名空间能被发现、瞬时目录失败可就地重试恢复、Host 不挂载任何可选服务时标签页仍然注册;Host 半边侧另有一组纯函数与路由检查(MCP 命名、包源码扫描预算、按作用域收集工具、快照形状、`GET /api/wj/tool-inventory` 的 JSON 与响应头、缺少 connection 时不激活路由)。
73
+ - `node --check client.js` 与 `node --check index.js` 检查两个半边的语法。
66
74
  - `tests/patch.test.js` 解析 `cordis.patch.yml`,确保没有裸标量以 YAML 保留字符开头 —— 带 scope 的包名必须保持加引号,否则 Host 会拒绝该 bundle patch。
67
75
  - `tests/inject.test.js` 把插件的 `inject` 固定为仅核心服务,这样一旦有人重新硬注入可选 remote,测试就会失败,而不是在某些 Host 上悄悄把设置页清空。
68
76
  - `tests/module-id.test.js` 断言注册的模块 id 等于 `package.json` 的 `name`,避免改名后浏览器 bundle 悄悄脱离自己的 Loader 行。
69
77
  - `tests/harness.html` 在浏览器中用测试夹具挂载真实 `client.js`,不依赖 Node 也能断言同一批行为;直接从磁盘打开并读取 JSON 报告。
70
- - `tests/parse-check.html` 是最小的浏览器冒烟页:确认 `client.js` 能解析并注册 `settings.plugins.tab`。
78
+ - `tests/parse-check.html` 是最小的浏览器冒烟页:确认 `client.js` 能解析并注册 `plugins.tab`(插件页的标签槽;旧版的 `settings.plugins.tab` 在当前 DSH 中并不存在,注册会落空)。
71
79
 
72
80
  Harness API 和 Host 行为在 `deepseek-harness` 仓库实现并测试。
73
81
 
package/client.js CHANGED
@@ -9,8 +9,13 @@ window.__ModuleLoader__.load({
9
9
  const React = require('react')
10
10
  const h = React.createElement
11
11
  const NS = 'settings.pluginManagerWj'
12
- const TAB_ORDER = ['plugins', 'config', 'skill', 'mcp']
12
+ // MCP server management is owned by the Host's MCP settings bundle, so this page shows no MCP
13
+ // server list of its own: a second list here duplicated that page and read the same remote.
14
+ const TAB_ORDER = ['plugins', 'config', 'skill', 'tools']
13
15
  const TAB_KEY = 'dsh-plugin-manager-wj/tab'
16
+ // The Host half serves the tool registry on the shared authenticated `/api` channel; the
17
+ // official Remote table carries no tool namespace, so this route is the only way in.
18
+ const TOOL_INVENTORY_URL = '/api/wj/tool-inventory'
14
19
 
15
20
  function unwrap(result, name) {
16
21
  if (!result || result.ok !== true) throw new Error(`${name}: ${result?.error?.message ?? 'unavailable'}`)
@@ -58,6 +63,38 @@ window.__ModuleLoader__.load({
58
63
  return source ? `${t(source.layer)} · ${source.identity}` : t('sourceUnknown')
59
64
  }
60
65
 
66
+ // The official Host projects the Loader, not a health model: a failed fiber plus its diagnostic
67
+ // is the whole of what it still reports, and it is exactly what this page diagnoses.
68
+ function findingsOf(entries) {
69
+ const findings = []
70
+ for (const entry of entries) {
71
+ if (entry?.fiberPhase !== 'failed') continue
72
+ const entryId = String(entry.entryId ?? entry.moduleName ?? '')
73
+ findings.push({
74
+ id: `activation:${entryId}`,
75
+ code: 'plugin.activation-failed',
76
+ severity: 'error',
77
+ affectedEntryIds: entry.entryId === undefined ? [] : [entry.entryId],
78
+ remediationEntryIds: [],
79
+ evidence: {
80
+ name: entry.moduleName,
81
+ ...(typeof entry.diagnostic === 'string' && entry.diagnostic !== '' ? { detail: entry.diagnostic } : {}),
82
+ },
83
+ })
84
+ }
85
+ return findings
86
+ }
87
+
88
+ // One Loader projection serves both shapes: the official `{ entries, managementAvailable }`
89
+ // snapshot and the older `{ toolRegistrations, mcpClients }` inventory.
90
+ function readInventory(value) {
91
+ return {
92
+ entries: Array.isArray(value?.entries) ? value.entries : [],
93
+ managementAvailable: value?.managementAvailable !== false,
94
+ toolRegistrations: Array.isArray(value?.toolRegistrations) ? value.toolRegistrations : [],
95
+ }
96
+ }
97
+
61
98
  const SEVERITY_KEY = { error: 'severityError', warning: 'severityWarning', info: 'severityInfo' }
62
99
 
63
100
  function readStoredTab() {
@@ -229,19 +266,11 @@ window.__ModuleLoader__.load({
229
266
  }, h('span', null, item.label), item.count === undefined ? null : h('span', { style: styles.tabCount }, String(item.count)))))
230
267
  }
231
268
 
232
- function PluginsPanel({ pluginRows, findings, plugins, query, busy, preview, onToggle, onPreview, onApplyPreview, onCancelPreview, t }) {
269
+ function PluginsPanel({ pluginRows, findings, plugins, query, busy, canManage, onToggle, t }) {
233
270
  const name = row => row.meta?.title?.en ?? row.meta?.title?.zh ?? row.moduleName
234
271
  const severity = value => t(SEVERITY_KEY[value] ?? 'severityInfo')
235
272
  return h('div', { style: styles.page },
236
273
  h('p', { style: styles.description }, t('pluginsIntro')),
237
- preview ? h('section', { style: { ...styles.section, padding: 16 }, 'aria-label': t('repairPreview') },
238
- h('h2', { style: styles.sectionTitle }, t('repairPreview')),
239
- h('p', { style: styles.meta }, `${t('target')}: ${plugins.find(row => row.entryId === preview.targetEntryId)?.moduleName ?? preview.targetEntryId}`),
240
- h('p', { style: styles.meta }, `${t('effect')}: ${t('disablePlugin')}`),
241
- h('p', { style: styles.meta }, `${t('risk')}: ${t(preview.risk)} · ${t(preview.reversible ? 'reversible' : 'notReversible')}`),
242
- h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
243
- h('button', { type: 'button', style: { ...styles.button, ...styles.primary }, disabled: busy === preview.previewId, onClick: () => { void onApplyPreview() } }, t(preview.requiresConfirmation ? 'confirmRepair' : 'applyRepair')),
244
- h('button', { type: 'button', style: styles.button, onClick: onCancelPreview }, t('cancel')))) : null,
245
274
  h(Section, { id: 'findings', title: t('findingsTitle'), count: `${findings.length} ${t('items')}`, empty: t(query ? 'noMatches' : 'noRows') },
246
275
  findings.length ? h('ul', { style: styles.list }, findings.map(finding => {
247
276
  const severe = finding.severity === 'error'
@@ -255,11 +284,7 @@ window.__ModuleLoader__.load({
255
284
  finding.evidence?.name || finding.evidence?.serverName || finding.evidence?.packageName
256
285
  ? h('div', { style: styles.meta }, `${t('evidence')}: ${finding.evidence.name ?? finding.evidence.serverName ?? finding.evidence.packageName}`)
257
286
  : null,
258
- finding.remediationEntryIds.map(id => {
259
- const target = plugins.find(plugin => plugin.entryId === id)
260
- if (!target) return null
261
- return h('button', { key: id, type: 'button', style: styles.button, disabled: busy === finding.id, onClick: () => { void onPreview(finding, id) } }, t('previewRepair', { name: target.moduleName }))
262
- }))
287
+ finding.evidence?.detail ? h('p', { style: { ...styles.message, padding: '4px 0 0' } }, finding.evidence.detail) : null)
263
288
  })) : null),
264
289
  h(Section, { id: 'plugins', title: t('pluginsTitle'), count: `${pluginRows.length} ${t('items')}`, empty: t(query ? 'noMatches' : 'noRows') },
265
290
  pluginRows.length ? h('ul', { style: styles.list }, pluginRows.map(row => h('li', { key: row.entryId, style: styles.row },
@@ -269,7 +294,7 @@ window.__ModuleLoader__.load({
269
294
  h('div', { style: styles.meta }, h('span', null, row.entryId), h('span', null, t(row.fiberPhase ?? 'notRunning')), row.readOnlyReason ? h('span', null, t(row.readOnlyReason)) : null)),
270
295
  h('button', {
271
296
  type: 'button', style: { ...styles.button, ...(row.enabled ? styles.primary : {}) },
272
- 'aria-pressed': String(row.enabled), disabled: busy === row.entryId || row.readOnlyReason !== undefined,
297
+ 'aria-pressed': String(row.enabled), disabled: !canManage || busy === row.entryId || row.readOnlyReason !== undefined,
273
298
  onClick: () => { void onToggle(row) },
274
299
  }, t(row.enabled ? 'disable' : 'enable'))),
275
300
  row.diagnostic ? h('p', { style: styles.meta }, t('activationFailed')) : null))) : null))
@@ -318,30 +343,37 @@ window.__ModuleLoader__.load({
318
343
  rows.length ? h('ul', { style: styles.list }, rows.map(skillRow)) : null))
319
344
  }
320
345
 
321
- function McpPanel({ inventory, mcpRows, toolRows, needle, t }) {
322
- const owner = row => row.owner ? `${row.owner.moduleName} (${row.owner.entryId})` : '—'
346
+ // Tool ownership is the one diagnostic the MCP settings page does not carry: it answers
347
+ // "which plugin registered this tool", which belongs to plugin management, not to MCP setup.
348
+ function ToolsPanel({ tools, needle, rows, onRetry, t }) {
349
+ const scopeText = row => row.scope === 'agent' && row.agentId ? `${t('scoped')} · ${row.agentId}` : t('global')
350
+ const ownerText = row => {
351
+ const owner = row.owner
352
+ if (!owner) return t('ownerUnknown')
353
+ if (owner.kind === 'mcp') return `${t('ownerMcp')}: ${owner.serverName}`
354
+ const base = owner.entryId ? `${owner.moduleName} (${owner.entryId})` : owner.moduleName
355
+ return owner.inferred ? `${base} · ${t('ownerInferred')}` : base
356
+ }
357
+ const copy = tools?.kind === 'loading' ? t('loadingTools')
358
+ : tools?.kind === 'unavailable' ? t('toolInventoryUnavailable')
359
+ : tools?.kind === 'error' ? t('toolInventoryError')
360
+ : needle ? t('noMatches') : t('noRows')
361
+ const retryable = tools?.kind === 'error' || tools?.kind === 'unavailable'
323
362
  return h('div', { style: styles.page },
324
- h('p', { style: styles.description }, t('mcpIntro')),
325
- h(Section, { id: 'mcp', title: t('mcp'), count: `${mcpRows.length} ${t('items')}`, empty: t(needle ? 'noMatches' : 'noRows') },
326
- mcpRows.length ? h('ul', { style: styles.list }, mcpRows.map(row => h('li', { key: `${row.serverName}:${row.owner?.entryId ?? ''}`, style: styles.row },
327
- h('div', { style: styles.rowHead },
328
- h('h3', { style: styles.rowTitle }, row.serverName),
329
- h('span', { style: { ...styles.badge, ...(row.state === 'connected' ? {} : styles.warning) } }, t(row.state))),
330
- h('div', { style: styles.meta }, [
331
- row.transport ? `${t('transport')}: ${row.transport}` : null,
332
- row.source ? `${t('mcpSource')}: ${row.source}` : null,
333
- row.toolCount === undefined ? null : `${t('toolCount')}: ${row.toolCount}`,
334
- `${t('owner')}: ${owner(row)}`,
335
- ].filter(Boolean).join(' · ')),
336
- row.toolNames?.length ? h('div', { style: styles.meta }, `${t('toolNames')}: ${row.toolNames.join(', ')}`) : null))) : null),
337
- h(Section, { id: 'tools', title: t('tools'), count: `${toolRows.length} ${t('items')}`, empty: t(needle ? 'noMatches' : 'noRows') },
338
- toolRows.length ? h('ul', { style: styles.list }, toolRows.map(row => h('li', { key: `${row.name}:${row.owner?.entryId ?? ''}`, style: styles.row },
339
- h('h3', { style: styles.rowTitle }, row.name),
340
- h('div', { style: styles.meta }, `${t('owner')}: ${owner(row)} · ${t(row.scope)}`)))) : null),
341
- inventory ? null : h('p', { style: styles.message }, t('inventoryUnavailable')))
363
+ h('p', { style: styles.description }, t('toolsIntro')),
364
+ h('p', { style: styles.message }, t('toolsMcpNote')),
365
+ h(Section, {
366
+ id: 'tools', title: t('tools'), count: tools?.kind === 'ready' ? `${rows.length} ${t('items')}` : undefined,
367
+ empty: rows.length ? null : h('div', { style: { display: 'grid', gap: 10, justifyItems: 'start', padding: 16 } },
368
+ h('p', { style: { ...styles.message, padding: 0 } }, copy),
369
+ retryable ? h('button', { type: 'button', style: styles.button, onClick: () => { if (onRetry) onRetry() } }, t('retry')) : null),
370
+ }, rows.length ? h('ul', { style: styles.list }, rows.map(row => h('li', { key: `${row.name}:${row.scope}:${row.agentId ?? ''}`, style: styles.row },
371
+ h('h3', { style: styles.rowTitle }, row.name),
372
+ h('div', { style: styles.meta }, h('span', null, `${t('owner')}: ${ownerText(row)}`), h('span', null, scopeText(row))),
373
+ row.description ? h('p', { style: styles.muted }, row.description) : null))) : null))
342
374
  }
343
375
 
344
- function ManagerPage({ list, manager, forms, loadSkills, listMcpStatus, readSessionId, watchSessions, t }) {
376
+ function ManagerPage({ list, manager, forms, loadSkills, loadTools, readSessionId, watchSessions, t }) {
345
377
  const initialTab = readStoredTab()
346
378
  const [tab, setTab] = React.useState(initialTab)
347
379
  const [visited, setVisited] = React.useState([initialTab])
@@ -350,10 +382,10 @@ window.__ModuleLoader__.load({
350
382
  const [revision, setRevision] = React.useState(0)
351
383
  const [busy, setBusy] = React.useState('')
352
384
  const [notice, setNotice] = React.useState('')
353
- const [preview, setPreview] = React.useState(null)
354
385
  const [sessionId, setSessionId] = React.useState(() => typeof readSessionId === 'function' ? readSessionId() : undefined)
355
386
  const [skills, setSkills] = React.useState({ kind: 'loading' })
356
387
  const [skillsRevision, setSkillsRevision] = React.useState(0)
388
+ const [tools, setTools] = React.useState({ kind: 'idle' })
357
389
 
358
390
  // The catalog follows the active session: opening one (or switching) reloads it without a
359
391
  // manual refresh, which is what a Host that requires a live session for `skills/list` needs.
@@ -388,19 +420,24 @@ window.__ModuleLoader__.load({
388
420
  React.useEffect(() => {
389
421
  let live = true
390
422
  Promise.resolve().then(async () => {
391
- const [inventoryResult, pluginResult, healthResult, settingsResult, statusResult] = await Promise.allSettled([
423
+ const [inventoryResult, settingsResult] = await Promise.allSettled([
392
424
  list(),
393
- manager?.listPlugins ? manager.listPlugins() : Promise.reject(new Error('unavailable')),
394
- manager?.getHealthSnapshot ? manager.getHealthSnapshot() : Promise.reject(new Error('unavailable')),
395
425
  forms?.describe ? forms.describe().ensure().then(() => forms.describe().getSnapshot()) : Promise.reject(new Error('unavailable')),
396
- listMcpStatus ? listMcpStatus() : Promise.resolve(undefined),
397
426
  ])
398
427
  if (inventoryResult.status !== 'fulfilled') throw inventoryResult.reason
399
- const inventory = inventoryResult.value
400
- const plugins = pluginResult.status === 'fulfilled' ? unwrap(pluginResult.value, 'pluginManager.listPlugins') : []
401
- const health = healthResult.status === 'fulfilled' ? unwrap(healthResult.value, 'pluginManager.getHealthSnapshot') : undefined
428
+ const inventory = readInventory(inventoryResult.value)
429
+ // The official Host projects the Loader, so entries are the plugin list and a failed
430
+ // fiber is the finding; the older inventory's separate health snapshot no longer exists.
431
+ const plugins = inventory.entries.map(entry => ({
432
+ ...entry,
433
+ ...(inventory.managementAvailable ? {} : { readOnlyReason: entry.readOnlyReason ?? 'management-required' }),
434
+ }))
435
+ const health = {
436
+ pluginCount: plugins.length,
437
+ enabledCount: plugins.filter(row => row.enabled).length,
438
+ findings: findingsOf(plugins),
439
+ }
402
440
  const settings = settingsResult.status === 'fulfilled' ? settingsResult.value.view : undefined
403
- const mcpStatus = statusResult.status === 'fulfilled' ? statusResult.value : undefined
404
441
  const provenance = new Map()
405
442
  if (settings && manager?.getConfigProvenance) {
406
443
  await Promise.all(settings.namespaces.map(async view => {
@@ -415,12 +452,26 @@ window.__ModuleLoader__.load({
415
452
  }
416
453
  }))
417
454
  }
418
- if (live) setState({ kind: 'ready', snapshot: { inventory, plugins, health, settings, provenance, mcpStatus } })
455
+ if (live) setState({ kind: 'ready', snapshot: { inventory, plugins, health, settings, provenance } })
419
456
  }).catch(() => {
420
457
  if (live) setState(previous => ({ kind: 'error', snapshot: previous.snapshot }))
421
458
  })
422
459
  return () => { live = false }
423
- }, [list, manager, forms, listMcpStatus, revision])
460
+ }, [list, manager, forms, revision])
461
+
462
+ // The tool registry is session-wide Host state and the route scans package sources once, so
463
+ // it loads when the view is first opened, and again only when the page is refreshed.
464
+ React.useEffect(() => {
465
+ if (tab !== 'tools' || typeof loadTools !== 'function') return undefined
466
+ if (tools.kind !== 'idle' && tools.revision === revision) return undefined
467
+ let live = true
468
+ setTools({ kind: 'loading', revision })
469
+ Promise.resolve()
470
+ .then(() => loadTools())
471
+ .then(result => { if (live) setTools({ ...result, revision }) })
472
+ .catch(() => { if (live) setTools({ kind: 'error', revision }) })
473
+ return () => { live = false }
474
+ }, [loadTools, tab, revision, tools.kind, tools.revision])
424
475
 
425
476
  const refresh = () => {
426
477
  setState(current => ({ kind: 'loading', snapshot: current.snapshot }))
@@ -435,9 +486,10 @@ window.__ModuleLoader__.load({
435
486
  }
436
487
 
437
488
  const applyNotice = result => {
438
- setNotice(result.application === 'applied' ? t('changeApplied')
439
- : result.application === 'restart-required' ? t('restartRequired')
440
- : result.application === 'overridden' ? t('changeOverridden')
489
+ setNotice(result?.application === 'applied' ? t('changeApplied')
490
+ : result?.application === 'restart-required' ? t('restartRequired')
491
+ : result?.application === 'overridden' ? t('changeOverridden')
492
+ : result?.application === 'cancelled' ? t('changeCancelled')
441
493
  : t('changeFailed'))
442
494
  }
443
495
 
@@ -454,39 +506,6 @@ window.__ModuleLoader__.load({
454
506
  }
455
507
  }
456
508
 
457
- const makePreview = async (finding, targetEntryId) => {
458
- setBusy(finding.id)
459
- setPreview(null)
460
- try {
461
- const next = unwrap(await manager.previewRemediation({ findingId: finding.id, targetEntryId }), 'pluginManager.previewRemediation')
462
- if (next.requiresConfirmation) setPreview(next)
463
- else {
464
- applyNotice(unwrap(await manager.applyRemediation(next.previewId, false), 'pluginManager.applyRemediation'))
465
- refresh()
466
- }
467
- } catch (_error) {
468
- setNotice(t('previewOrRepairFailed'))
469
- } finally {
470
- setBusy('')
471
- }
472
- }
473
-
474
- const applyPreview = async () => {
475
- if (!preview) return
476
- setBusy(preview.previewId)
477
- try {
478
- applyNotice(unwrap(await manager.applyRemediation(preview.previewId, preview.requiresConfirmation), 'pluginManager.applyRemediation'))
479
- setPreview(null)
480
- refresh()
481
- } catch (_error) {
482
- setNotice(t('stalePreview'))
483
- setPreview(null)
484
- refresh()
485
- } finally {
486
- setBusy('')
487
- }
488
- }
489
-
490
509
  const current = state.snapshot
491
510
  const inventory = current?.inventory
492
511
  const plugins = current?.plugins ?? []
@@ -494,37 +513,21 @@ window.__ModuleLoader__.load({
494
513
  const settings = current?.settings
495
514
  const needle = query.trim().toLocaleLowerCase()
496
515
  const matches = values => !needle || values.filter(Boolean).some(value => String(value).toLocaleLowerCase().includes(needle))
497
- const pluginRows = plugins.filter(row => matches([row.moduleName, row.entryId, row.meta?.title, row.meta?.description]))
498
- const findings = (health?.findings ?? []).filter(row => matches([row.id, row.code, row.evidence?.name, row.evidence?.serverName, row.evidence?.packageName]))
499
- const toolRows = (inventory?.toolRegistrations ?? []).filter(row => matches([row.name, row.owner?.moduleName, row.owner?.entryId]))
500
- // The Host's own registry only reports the MCP servers it composes itself. Servers managed by
501
- // a companion package answer through `mcpClientStatus/list` instead, so both sources are merged
502
- // by server name: transport, source and tool counts survive even when the Host registry is empty.
503
- const mergedClients = new Map()
504
- for (const row of current?.mcpStatus ?? []) {
505
- mergedClients.set(row.serverName, {
506
- serverName: row.serverName, state: row.state, transport: row.transport, source: row.source,
507
- toolCount: row.toolCount, toolNames: (row.tools ?? []).map(tool => tool.name),
508
- })
509
- }
510
- for (const row of inventory?.mcpClients ?? []) {
511
- const previous = mergedClients.get(row.serverName) ?? {}
512
- mergedClients.set(row.serverName, {
513
- ...previous, ...row,
514
- transport: row.transport ?? previous.transport,
515
- source: row.source ?? previous.source,
516
- toolCount: row.toolCount ?? previous.toolCount ?? row.toolNames?.length,
517
- toolNames: row.toolNames ?? previous.toolNames,
518
- })
519
- }
520
- const mcpRows = [...mergedClients.values()]
521
- .filter(row => matches([row.serverName, row.state, row.transport, row.source, row.owner?.moduleName, ...(row.toolNames ?? [])]))
516
+ const pluginRows = plugins.filter(row => matches([row.moduleName, row.entryId, row.meta?.title?.en, row.meta?.title?.zh, row.meta?.description]))
517
+ const findings = (health?.findings ?? []).filter(row => matches([row.id, row.code, row.evidence?.name, row.evidence?.detail]))
518
+ // Legacy Hosts answered the inventory with registrations of their own; a Host served by this
519
+ // package answers the `/api` route instead, so either source fills the same rows.
520
+ const legacyRows = (inventory?.toolRegistrations ?? []).filter(row => matches([row.name, row.owner?.moduleName, row.owner?.entryId]))
521
+ const routeRows = tools.kind === 'ready' ? (tools.rows ?? []) : []
522
+ const toolRows = (routeRows.length > 0 ? routeRows : legacyRows).filter(row => matches([row.name, row.owner?.moduleName, row.owner?.entryId, row.owner?.serverName, row.agentId]))
523
+ const toolsView = tools.kind === 'ready' || legacyRows.length > 0 ? { kind: 'ready', rows: toolRows } : tools
524
+ const canManage = inventory !== undefined && inventory.managementAvailable && typeof manager?.setPluginEnabled === 'function'
522
525
 
523
526
  const tabs = [
524
527
  { id: 'plugins', label: t('tabs.plugins'), count: plugins.length },
525
528
  { id: 'config', label: t('tabs.config'), count: settings?.namespaces?.length },
526
529
  { id: 'skill', label: t('tabs.skill'), count: skills?.kind === 'ready' ? skills.items.length : undefined },
527
- { id: 'mcp', label: t('tabs.mcp'), count: mcpRows.length },
530
+ { id: 'tools', label: t('tabs.tools'), count: toolsView.kind === 'ready' ? toolRows.length : undefined },
528
531
  ]
529
532
 
530
533
  const panel = (id, children) => visited.includes(id) ? h('div', {
@@ -541,7 +544,7 @@ window.__ModuleLoader__.load({
541
544
  [health?.enabledCount ?? plugins.filter(row => row.enabled).length, 'enabled'],
542
545
  [health ? health.findings.length : '—', 'findings'],
543
546
  [skills?.kind === 'ready' ? skills.items.length : '—', 'skills'],
544
- [inventory ? mcpRows.length : '—', 'mcpStat'],
547
+ [toolsView.kind === 'ready' ? toolRows.length : '—', 'toolsStat'],
545
548
  ]
546
549
  const showStats = state.kind === 'ready' && current !== undefined
547
550
 
@@ -564,14 +567,13 @@ window.__ModuleLoader__.load({
564
567
  h('p', { style: styles.message }, t('error')),
565
568
  h('button', { type: 'button', style: styles.button, onClick: refresh }, t('retry'))) : null,
566
569
  notice ? h('p', { role: 'status', style: styles.message }, notice) : null,
567
- !health && state.kind === 'ready' ? h('p', { role: 'status', style: styles.message }, t('diagnosticsUnavailable')) : null,
568
570
  panel('plugins', h(PluginsPanel, {
569
- pluginRows, findings, plugins, query: needle, busy, preview,
570
- onToggle: toggle, onPreview: makePreview, onApplyPreview: applyPreview, onCancelPreview: () => { setPreview(null) }, t,
571
+ pluginRows, findings, plugins, query: needle, busy, canManage,
572
+ onToggle: toggle, t,
571
573
  })),
572
574
  panel('config', h(ConfigPanel, { settings, settingsReady: settings !== undefined, plugins, forms, provenance: current?.provenance, t })),
573
575
  panel('skill', h(SkillPanel, { skills, needle, onRetry: refresh, t })),
574
- panel('mcp', h(McpPanel, { inventory, mcpRows, toolRows, needle, t })))
576
+ panel('tools', h(ToolsPanel, { tools: toolsView, toolRows, rows: toolRows, needle, onRetry: refresh, t })))
575
577
  }
576
578
 
577
579
  return {
@@ -582,56 +584,56 @@ window.__ModuleLoader__.load({
582
584
  inject: ['slots', 'locale'],
583
585
  apply(ctx) {
584
586
  const zh = {
585
- tab: '插件管理', search: '搜索当前视图的插件、配置、Skill 或 MCP', refresh: '刷新', loading: '正在读取 Host 状态…', loadingShort: '读取中…',
586
- eyebrow: '插件健康与管理', heading: '插件管理', description: '查看插件状态与冲突,追踪配置来源,浏览 Skill 目录与 MCP 客户端,并通过受控操作修复问题。', summary: '当前状态', items: '项',
587
- viewsLabel: '管理视图', 'tabs.plugins': '插件', 'tabs.config': '配置', 'tabs.skill': 'Skill', 'tabs.mcp': 'MCP',
587
+ tab: '插件管理', search: '搜索当前视图的插件、配置、Skill 或工具', refresh: '刷新', loading: '正在读取 Host 状态…', loadingShort: '读取中…',
588
+ eyebrow: '插件健康与管理', heading: '插件管理', description: '查看插件状态与冲突,追踪配置来源,浏览 Skill 目录与工具注册归属,并通过受控操作修复问题。', summary: '当前状态', items: '项',
589
+ viewsLabel: '管理视图', 'tabs.plugins': '插件', 'tabs.config': '配置', 'tabs.skill': 'Skill', 'tabs.tools': '工具',
588
590
  pluginsIntro: '实时插件清单、健康诊断与启停操作。只列出当前 Profile 可寻址的插件。',
589
591
  configIntro: '按 Host schema 编辑非密钥配置,并查看每个字段的有效来源与被覆盖层。',
590
592
  skillIntro: '当前会话可用的 Skill 目录,按会话工作目录解析,并随会话切换自动刷新;模型可调用与仅用户可调用的条目分开标记。',
591
- mcpIntro: '已组合的 MCP 客户端连接状态与工具注册归属。',
592
- error: '无法读取运行时清单。', retry: '重试', noRows: '暂无记录。', noMatches: '没有匹配的记录。', diagnosticsUnavailable: '此 Harness Host 尚未提供诊断接口;当前显示可用的插件和注册清单。',
593
- inventoryUnavailable: '此 Host 未提供运行时清单接口,工具与 MCP 信息不可用。',
593
+ toolsIntro: '运行时工具注册清单,以及每个工具由哪个插件提供、作用于哪个范围。',
594
+ toolsMcpNote: 'MCP 服务器的添加与连接配置由 Host 的 MCP 设置页负责;这里只做插件侧的注册归属诊断,不再重复列出 MCP 服务器。',
595
+ error: '无法读取运行时清单。', retry: '重试', noRows: '暂无记录。', noMatches: '没有匹配的记录。',
596
+ loadingTools: '正在读取工具注册清单…', toolInventoryUnavailable: '此 Host 未提供工具注册清单路由(/api/wj/tool-inventory),工具视图不可用。', toolInventoryError: '无法读取工具注册清单。',
597
+ ownerUnknown: '未记录(Host 未暴露归属)', ownerMcp: 'MCP 服务器', ownerInferred: '推断',
594
598
  findingsTitle: '健康诊断', pluginsTitle: '插件', configurationTitle: '配置管理', plugins: '插件', enabled: '已启用', findings: '发现项', severity: '严重程度', affected: '相关插件', evidence: '证据',
595
599
  configEmpty: 'Host 未暴露可编辑的配置命名空间。', configUnavailable: '此 Host 未提供设置表单接口,配置视图不可用。',
596
600
  skillsTitle: 'Skill 目录', skillEmpty: '当前会话没有可用的 Skill。', skillUnsupported: '此 Host 未提供 skills 接口,Skill 目录不可用。', skillNoSession: '尚无可用会话。打开或切换会话后,这里会自动加载,无需刷新。', skillError: '无法读取 Skill 目录。', loadingSkills: '正在读取 Skill 目录…',
597
601
  skillModelInvocable: '模型可调用', skillUserOnly: '仅用户可调用', skillWhenToUse: '适用场景', skillPath: '指令文件',
598
- mcpStat: 'MCP', skills: 'Skill',
602
+ toolsStat: '工具', skills: 'Skill',
599
603
  'plugin.activation-failed': '插件启动失败', 'tool.duplicate-name': '工具名称重复', 'mcp.connection-failed': 'MCP 连接异常', 'mcp.duplicate-name': 'MCP 名称重复',
600
604
  'bundle.compatibility-rejected': '组合包版本不兼容', 'bundle.dependency-invalid': '所选依赖无效', severityError: '错误', severityWarning: '警告', severityInfo: '提示', warning: '警告', info: '提示',
601
605
  source: '配置来源', shadowed: '被覆盖来源', sourceUnknown: '未知(Host 未提供来源)', bundle: '组合包', profile: 'Profile', home: 'Home', invocation: '本次启动',
602
606
  save: '保存', reset: '恢复继承值', saved: '已保存', revisionConflict: '配置已被其他操作修改;草稿仍保留,请刷新后重试。', saveFailed: '保存失败,草稿已保留。', invalidNumber: '请输入有效数字。', loadingForm: '正在载入表单…', formUnavailable: '此配置表单当前不可用。', noSchemaFields: '没有可编辑的 schema 字段。', secretsHidden: '密钥字段已隐藏({count} 项)。',
603
- previewRepair: '诊断并修复 {name}', repairPreview: '修复预览', target: '目标', effect: '影响', disablePlugin: '关闭插件', risk: '风险', low: '低', high: '高', reversible: '可撤销', notReversible: '不可撤销', applyRepair: '执行修复', confirmRepair: '确认并执行', cancel: '取消', previewOrRepairFailed: '无法预览或执行此修复。', stalePreview: '修复预览已过期或状态已变化,请重新加载后再试。',
604
- changeApplied: '设置已保存并应用。', restartRequired: '设置已保存;重启后生效。', changeOverridden: '设置已保存,但被更高优先级配置覆盖。', changeFailed: 'Host 未能应用此更改。',
607
+ changeApplied: '设置已保存并应用。', restartRequired: '设置已保存;重启后生效。', changeOverridden: '设置已保存,但被更高优先级配置覆盖。', changeCancelled: 'Host 取消了此更改,未做修改。', changeFailed: 'Host 未能应用此更改。',
605
608
  enable: '启用', disable: '停用', disabled: '已停用', enabledTag: '已启用', disabledTag: '已停用', active: '运行中', failed: '失败', loadingPhase: '加载中', pending: '等待中', unloading: '卸载中', notRunning: '未运行',
606
- connecting: '连接中', disconnected: '已断开', transport: '传输方式', mcpSource: '连接来源', toolCount: '工具数',
607
609
  skillReadOnly: 'Skill 的启用与停用由 profile 的 skills 目录与指令文件决定;本 Host 未提供开关接口,因此这里只读展示当前会话可见的条目。',
608
- 'management-required': '管理服务受保护', unaddressable: '此条目无法通过当前 Profile 修改', activationFailed: '插件未能完成启动。', owner: '所属插件', tools: '工具注册', mcp: 'MCP 客户端', toolNames: '工具名称', global: '全局', scoped: '作用域', starting: '启动中', connected: '已连接', reconnecting: '正在重连', stopped: '已停止',
610
+ 'management-required': '管理服务受保护', unaddressable: '此条目无法通过当前 Profile 修改', activationFailed: '插件未能完成启动。', owner: '所属插件', tools: '工具注册', global: '全局', scoped: '作用域',
609
611
  }
610
612
  const en = {
611
- tab: 'Plugin management', search: 'Search the current view for plugins, settings, skills or MCP', refresh: 'Refresh', loading: 'Reading Host state…', loadingShort: 'Loading…',
612
- eyebrow: 'PLUGIN HEALTH AND MANAGEMENT', heading: 'Plugin management', description: 'Review plugin status and conflicts, trace configuration sources, browse the skill catalog and MCP clients, and repair issues through bounded actions.', summary: 'Current status', items: 'items',
613
- viewsLabel: 'Management views', 'tabs.plugins': 'Plugins', 'tabs.config': 'Configuration', 'tabs.skill': 'Skills', 'tabs.mcp': 'MCP',
613
+ tab: 'Plugin management', search: 'Search the current view for plugins, settings, skills or tools', refresh: 'Refresh', loading: 'Reading Host state…', loadingShort: 'Loading…',
614
+ eyebrow: 'PLUGIN HEALTH AND MANAGEMENT', heading: 'Plugin management', description: 'Review plugin status and conflicts, trace configuration sources, browse the skill catalog and tool ownership, and repair issues through bounded actions.', summary: 'Current status', items: 'items',
615
+ viewsLabel: 'Management views', 'tabs.plugins': 'Plugins', 'tabs.config': 'Configuration', 'tabs.skill': 'Skills', 'tabs.tools': 'Tools',
614
616
  pluginsIntro: 'Live plugin inventory, health findings and enable/disable actions. Only plugins addressable by the active profile are listed.',
615
617
  configIntro: 'Edit non-secret settings through the Host schema and see each field’s effective source and shadowed layers.',
616
618
  skillIntro: 'Skills available to the current session, resolved from its working directory and reloaded automatically when the session changes; model-invocable and user-only entries are marked separately.',
617
- mcpIntro: 'Composed MCP client connections and the owners of registered tools.',
618
- error: 'The runtime inventory could not be read.', retry: 'Retry', noRows: 'No records.', noMatches: 'No matching records.', diagnosticsUnavailable: 'This Harness Host does not expose diagnostics yet. Available plugin and registration inventories are still shown.',
619
- inventoryUnavailable: 'This Host does not expose the runtime inventory; tool and MCP details are unavailable.',
619
+ toolsIntro: 'Runtime tool registrations, with the plugin that provides each tool and the scope it applies to.',
620
+ toolsMcpNote: 'Adding and connecting MCP servers belongs to the Host’s MCP settings page; this view covers plugin-side ownership only and deliberately lists no MCP servers of its own.',
621
+ error: 'The runtime inventory could not be read.', retry: 'Retry', noRows: 'No records.', noMatches: 'No matching records.',
622
+ loadingTools: 'Reading the tool registry…', toolInventoryUnavailable: 'This Host does not serve the tool registry route (/api/wj/tool-inventory); the tool view is unavailable.', toolInventoryError: 'The tool registry could not be read.',
623
+ ownerUnknown: 'Not recorded (the Host exposes no owner)', ownerMcp: 'MCP server', ownerInferred: 'inferred',
620
624
  findingsTitle: 'Health findings', pluginsTitle: 'Plugins', configurationTitle: 'Configuration', plugins: 'plugins', enabled: 'enabled', findings: 'findings', severity: 'Severity', affected: 'Affected plugins', evidence: 'Evidence',
621
625
  configEmpty: 'The Host exposes no editable configuration namespaces.', configUnavailable: 'This Host does not expose settings forms; configuration is unavailable.',
622
626
  skillsTitle: 'Skill catalog', skillEmpty: 'The current session has no available skills.', skillUnsupported: 'This Host does not expose the skills interface; the catalog is unavailable.', skillNoSession: 'No session yet. Open or switch a session and this view loads automatically — no refresh needed.', skillError: 'The skill catalog could not be read.', loadingSkills: 'Reading the skill catalog…',
623
627
  skillModelInvocable: 'Model-invocable', skillUserOnly: 'User-only', skillWhenToUse: 'When to use', skillPath: 'Instruction file',
624
- mcpStat: 'MCP', skills: 'skills',
628
+ toolsStat: 'tools', skills: 'skills',
625
629
  'plugin.activation-failed': 'Plugin activation failed', 'tool.duplicate-name': 'Duplicate tool name', 'mcp.connection-failed': 'MCP connection issue', 'mcp.duplicate-name': 'Duplicate MCP name',
626
630
  'bundle.compatibility-rejected': 'Bundle version is incompatible', 'bundle.dependency-invalid': 'Selected dependency is invalid', severityError: 'Error', severityWarning: 'Warning', severityInfo: 'Info', warning: 'Warning', info: 'Info',
627
631
  source: 'Configuration source', shadowed: 'Shadowed sources', sourceUnknown: 'Unknown (Host did not provide a source)', bundle: 'Bundle', profile: 'Profile', home: 'Home', invocation: 'This launch',
628
632
  save: 'Save', reset: 'Reset to inherited value', saved: 'Saved', revisionConflict: 'Configuration changed elsewhere. Your draft is kept; refresh before retrying.', saveFailed: 'Save failed. Your draft is kept.', invalidNumber: 'Enter a valid number.', loadingForm: 'Loading form…', formUnavailable: 'This configuration form is unavailable.', noSchemaFields: 'No editable schema fields.', secretsHidden: '{count} secret fields are hidden.',
629
- previewRepair: 'Diagnose and repair {name}', repairPreview: 'Repair preview', target: 'Target', effect: 'Effect', disablePlugin: 'Disable plugin', risk: 'Risk', low: 'Low', high: 'High', reversible: 'Reversible', notReversible: 'Not reversible', applyRepair: 'Apply repair', confirmRepair: 'Confirm and apply', cancel: 'Cancel', previewOrRepairFailed: 'Could not preview or apply this repair.', stalePreview: 'The preview expired or state changed. Reload and preview the repair again.',
630
- changeApplied: 'The change was saved and applied.', restartRequired: 'The change was saved and will apply after restart.', changeOverridden: 'The change was saved but overridden by a higher-priority configuration.', changeFailed: 'The Host could not apply this change.',
633
+ changeApplied: 'The change was saved and applied.', restartRequired: 'The change was saved and will apply after restart.', changeOverridden: 'The change was saved but overridden by a higher-priority configuration.', changeCancelled: 'The Host cancelled this change; nothing was modified.', changeFailed: 'The Host could not apply this change.',
631
634
  enable: 'Enable', disable: 'Disable', disabled: 'Disabled', enabledTag: 'Enabled', disabledTag: 'Disabled', active: 'Active', failed: 'Failed', loadingPhase: 'Loading', pending: 'Pending', unloading: 'Unloading', notRunning: 'Not running',
632
- connecting: 'Connecting', disconnected: 'Disconnected', transport: 'Transport', mcpSource: 'Source', toolCount: 'Tools',
633
635
  skillReadOnly: 'Skills are enabled by the profile’s skills directories and instruction files; this Host exposes no toggle, so the catalog is read-only.',
634
- 'management-required': 'Management service is protected', unaddressable: 'This entry cannot be changed by the current profile', activationFailed: 'The plugin did not finish starting.', owner: 'Owner', tools: 'Tool registrations', mcp: 'MCP clients', toolNames: 'Tool names', global: 'Global', scoped: 'Scoped', starting: 'Starting', connected: 'Connected', reconnecting: 'Reconnecting', stopped: 'Stopped',
636
+ 'management-required': 'Management service is protected', unaddressable: 'This entry cannot be changed by the current profile', activationFailed: 'The plugin did not finish starting.', owner: 'Owner', tools: 'Tool registrations', global: 'Global', scoped: 'Scoped',
635
637
  }
636
638
  ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'plugin-manager-wj: dictionaries')
637
639
  const t = ctx.locale.bind(NS)
@@ -648,6 +650,24 @@ window.__ModuleLoader__.load({
648
650
  if (!inventory || typeof inventory.list !== 'function') throw new Error('pluginInventory.list: unavailable')
649
651
  return unwrap(await inventory.list(), 'pluginInventory.list')
650
652
  }
653
+ // The Host half publishes the tool registry on the shared authenticated `/api` channel:
654
+ // `ctx.remote` carries no tool namespace and a Client plugin cannot add one.
655
+ const loadTools = async () => {
656
+ if (typeof fetch !== 'function') return { kind: 'unavailable' }
657
+ let response
658
+ try {
659
+ response = await fetch(TOOL_INVENTORY_URL, { credentials: 'same-origin', headers: { accept: 'application/json' } })
660
+ } catch (_error) {
661
+ return { kind: 'error' }
662
+ }
663
+ if (!response || response.ok !== true) return { kind: 'unavailable' }
664
+ try {
665
+ const body = await response.json()
666
+ return { kind: 'ready', rows: Array.isArray(body?.tools) ? body.tools : [] }
667
+ } catch (_error) {
668
+ return { kind: 'error' }
669
+ }
670
+ }
651
671
  const forms = service('configForms')
652
672
 
653
673
  // The skill catalog is session-scoped (`skills/list`) and optional. Both services are read
@@ -696,18 +716,12 @@ window.__ModuleLoader__.load({
696
716
  }
697
717
  }
698
718
 
699
- // Servers managed by a companion package live outside the Host's own MCP registry and answer
700
- // through `mcpClientStatus/list`. It is optional, so a Host without it simply shows fewer rows.
701
- const listMcpStatus = async () => {
702
- const api = namespace('mcpClientStatus')
703
- if (!api || typeof api.list !== 'function') return undefined
704
- try { return unwrap(await api.list(), 'mcpClientStatus/list') } catch (_error) { return undefined }
705
- }
706
-
707
- ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
708
- name: 'settings.plugins.tab', id: 'wj-registration-inventory', order: 20,
719
+ // No `mcpClientStatus/list` probe lives here: the MCP settings bundle owns MCP server state
720
+ // and its page, and reading that remote from two pages is what made the two views conflict.
721
+ ctx.slots.inject('plugins.tab', () => ctx.slots.register({
722
+ name: 'plugins.tab', id: 'wj-registration-inventory', order: 20,
709
723
  label: () => t('tab'), locale: NS,
710
- inject: () => ({ list, manager: namespace('pluginManager'), forms, loadSkills, listMcpStatus, readSessionId: activeSessionId, watchSessions }),
724
+ inject: () => ({ list, manager: namespace('pluginManager'), forms, loadSkills, loadTools, readSessionId: activeSessionId, watchSessions }),
711
725
  }, ManagerPage))
712
726
  },
713
727
  }
package/index.js CHANGED
@@ -1,3 +1,294 @@
1
1
  // SPDX-License-Identifier: MIT
2
- /** Host half: the inventory page runs in the Web Client. */
3
- export function apply() {}
2
+ /**
3
+ * Host half: serve the runtime tool registry the Web Client cannot read directly.
4
+ *
5
+ * The Client half lives in `client.js` and runs in the browser. It can only read the Host through
6
+ * Remote namespaces, and the official Host exposes no tool registry there: `ctx.tools` is a Host
7
+ * service, and a third-party package cannot add a Remote namespace (the Client's `ctx.remote`
8
+ * table is a compiled allowlist). A plain authenticated Fetch route on the shared `/api` channel
9
+ * is the supported way for a package to hand its own Host-side data to its own Client half.
10
+ *
11
+ * Ownership is the one fact no Host service records: `ctx.tools` keeps definitions keyed by name
12
+ * and discards the registering context. The route therefore reports `owner.kind === 'mcp'` for
13
+ * MCP tool names (their names carry the server) and falls back to a package-source scan, which is
14
+ * marked `inferred` so the page never presents a guess as a Host fact.
15
+ */
16
+ import { readFileSync } from 'node:fs'
17
+ import { dirname, isAbsolute, join } from 'node:path'
18
+
19
+ /** Absolute path below the shared `/api` channel. */
20
+ export const TOOL_INVENTORY_PATH = '/api/wj/tool-inventory'
21
+
22
+ /** Do not read a single package bundle larger than this; a minified bundle above it is not scanned. */
23
+ const FILE_LIMIT_BYTES = 4 * 1024 * 1024
24
+
25
+ /** Total bytes the source scan may read for one snapshot. */
26
+ const TOTAL_LIMIT_BYTES = 64 * 1024 * 1024
27
+
28
+ /** Total package files the source scan may open for one snapshot. */
29
+ const FILE_BUDGET = 240
30
+
31
+ /** How long one computed snapshot is reused; the page refreshes on demand, not per keystroke. */
32
+ const CACHE_TTL_MS = 30_000
33
+
34
+ /** Keys in a package bundle that make a tool-name literal worth scanning for. */
35
+ const REGISTRATION_MARKERS = /tools\s*\.\s*register|defineTool|registerTool/
36
+
37
+ const TOOL_NAME_LITERAL = /\bname\s*:\s*(['"])([A-Za-z0-9_$.:-]{1,120})\1/g
38
+
39
+ /**
40
+ * Serve tool registrations over one authenticated GET route.
41
+ * @param ctx - Host context; `connection` is requested optionally so a Host without the shared
42
+ * channel keeps the plugin active and the page degrades to its own explanation.
43
+ */
44
+ export function apply(ctx) {
45
+ let cache
46
+
47
+ const snapshot = async () => {
48
+ const now = Date.now()
49
+ if (cache !== undefined && now - cache.at < CACHE_TTL_MS) return cache.value
50
+ const value = buildSnapshot(ctx)
51
+ cache = { at: now, value }
52
+ return value
53
+ }
54
+
55
+ // A Host that mounts no shared channel, or a route the channel refuses, must not fail this
56
+ // plugin's activation: the page already explains a missing route on its own.
57
+ try {
58
+ ctx.inject(['connection'], injected => {
59
+ if (typeof injected.connection?.fetch?.register !== 'function') return
60
+ injected.effect(() => {
61
+ try {
62
+ const dispose = injected.connection.fetch.register({
63
+ path: TOOL_INVENTORY_PATH,
64
+ methods: ['GET'],
65
+ requestBody: 'buffered',
66
+ fetch: async () => jsonResponse(await snapshot()),
67
+ })
68
+ return () => { void Promise.resolve(dispose).catch(() => {}) }
69
+ } catch (error) {
70
+ warn(injected, 'tool inventory route registration failed', error)
71
+ return undefined
72
+ }
73
+ }, 'plugin-manager-wj: tool inventory route')
74
+ })
75
+ } catch (error) {
76
+ warn(ctx, 'tool inventory route unavailable', error)
77
+ }
78
+ }
79
+
80
+ /**
81
+ * Build one snapshot of the live registry.
82
+ * @param ctx - Host context.
83
+ * @param options - test seams: `readFile`, `maxFiles`, `maxBytes`.
84
+ * @returns Tool rows with scope and best-effort owner, plus the scan limit that applied.
85
+ */
86
+ export function buildSnapshot(ctx, options = {}) {
87
+ const rows = collectTools(ctx)
88
+ const owners = ownersOf(ctx, rows.map(row => row.name), options)
89
+ const tools = rows.map(row => {
90
+ const owner = owners.get(row.name)
91
+ return owner === undefined ? row : { ...row, owner }
92
+ })
93
+ return {
94
+ version: 1,
95
+ generatedAt: new Date().toISOString(),
96
+ tools,
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Read every Tool schema visible to this Host, globally and in each live Agent scope.
102
+ * @param ctx - Host context with the `tools` service.
103
+ * @returns Rows in name order; a scoped registration that shadows a global one keeps both rows.
104
+ */
105
+ export function collectTools(ctx) {
106
+ const tools = optional(ctx, 'tools')
107
+ const rows = []
108
+ const seen = new Set()
109
+ const add = (schema, scope, agentId) => {
110
+ const toolName = schema?.name
111
+ if (typeof toolName !== 'string' || toolName.length === 0) return
112
+ const key = `${scope}:${agentId ?? ''}:${toolName}`
113
+ if (seen.has(key)) return
114
+ seen.add(key)
115
+ const base = { name: toolName, scope, ...(agentId === undefined ? {} : { agentId }) }
116
+ const description = typeof schema?.description === 'string' ? schema.description : undefined
117
+ rows.push(description === undefined ? base : { ...base, description })
118
+ }
119
+
120
+ for (const schema of schemasOf(tools, undefined)) add(schema, 'global')
121
+
122
+ for (const agent of listAgents(ctx)) {
123
+ const agentId = agentIdentity(agent)
124
+ if (agentId === undefined) continue
125
+ for (const schema of schemasOf(tools, agent)) add(schema, 'agent', agentId)
126
+ }
127
+
128
+ return rows.sort((left, right) => left.name.localeCompare(right.name))
129
+ }
130
+
131
+ /**
132
+ * Attribute each tool name to a provider where the Host makes that knowable.
133
+ * @param ctx - Host context.
134
+ * @param names - Live tool names.
135
+ * @param options - test seams for the package-source scan.
136
+ * @returns Name to owner map; absent names stay unattributed rather than guessed.
137
+ */
138
+ export function ownersOf(ctx, names, options = {}) {
139
+ const owners = new Map()
140
+ for (const toolName of names) {
141
+ const mcp = mcpOwner(toolName)
142
+ if (mcp !== undefined) owners.set(toolName, mcp)
143
+ }
144
+ const pending = names.filter(toolName => !owners.has(toolName))
145
+ if (pending.length === 0) return owners
146
+
147
+ for (const source of readPackageSources(ctx, options)) {
148
+ const declared = declaredToolNames(source.text)
149
+ if (declared.size === 0) continue
150
+ for (const toolName of pending) {
151
+ if (owners.has(toolName)) continue
152
+ if (!declared.has(toolName)) continue
153
+ owners.set(toolName, {
154
+ kind: 'package',
155
+ moduleName: source.moduleName,
156
+ ...(source.entryId === undefined ? {} : { entryId: source.entryId }),
157
+ inferred: true,
158
+ })
159
+ }
160
+ }
161
+ return owners
162
+ }
163
+
164
+ /**
165
+ * Recognize the MCP naming convention `mcp__<server>__<tool>`.
166
+ * @param toolName - Public tool name.
167
+ * @returns The MCP server owner, or undefined for a non-MCP name.
168
+ */
169
+ export function mcpOwner(toolName) {
170
+ const match = /^mcp__(.+?)__[A-Za-z0-9_]/.exec(toolName)
171
+ return match === null ? undefined : { kind: 'mcp', serverName: match[1] }
172
+ }
173
+
174
+ /**
175
+ * Collect every `name: '…'` literal from a bundle that registers tools.
176
+ * @param text - Package bundle source.
177
+ * @returns Declared names; empty when the bundle registers no tools at all.
178
+ */
179
+ export function declaredToolNames(text) {
180
+ const names = new Set()
181
+ if (typeof text !== 'string' || !REGISTRATION_MARKERS.test(text)) return names
182
+ TOOL_NAME_LITERAL.lastIndex = 0
183
+ let match
184
+ while ((match = TOOL_NAME_LITERAL.exec(text)) !== null) names.add(match[2])
185
+ return names
186
+ }
187
+
188
+ /**
189
+ * Read the entrypoint bundle of each loaded plugin package, within a fixed budget.
190
+ * @param ctx - Host context with `loader` and the optional `pluginPackages` service.
191
+ * @param options - test seams: `readFile`, `maxFiles`, `maxBytes`.
192
+ * @returns Entry id, module name and bundle text for every readable package.
193
+ */
194
+ export function readPackageSources(ctx, options = {}) {
195
+ const loader = optional(ctx, 'loader')
196
+ const packages = optional(ctx, 'pluginPackages')
197
+ const entries = typeof loader?.entries === 'function' ? loader.entries() : []
198
+ const readFile = options.readFile ?? readFileSync
199
+ const maxFiles = options.maxFiles ?? FILE_BUDGET
200
+ const maxBytes = options.maxBytes ?? TOTAL_LIMIT_BYTES
201
+
202
+ const sources = []
203
+ let files = 0
204
+ let bytes = 0
205
+
206
+ for (const entry of entries) {
207
+ if (files >= maxFiles || bytes >= maxBytes) break
208
+ const moduleName = entry?.options?.name
209
+ if (typeof moduleName !== 'string' || moduleName.length === 0) continue
210
+ const base = entry?.parent?.tree?.ctx?.baseUrl
211
+ let manifestPath
212
+ try {
213
+ manifestPath = packages?.packageOf?.(moduleName, base)?.manifestPath
214
+ } catch (_error) {
215
+ manifestPath = undefined
216
+ }
217
+ if (typeof manifestPath !== 'string') continue
218
+ try {
219
+ const manifest = JSON.parse(readFile(manifestPath, 'utf8'))
220
+ const main = typeof manifest?.main === 'string' && manifest.main.length > 0 ? manifest.main : 'index.js'
221
+ const file = isAbsolute(main) ? main : join(dirname(manifestPath), main)
222
+ const text = readFile(file, 'utf8')
223
+ if (typeof text !== 'string' || text.length === 0 || text.length > FILE_LIMIT_BYTES) continue
224
+ files += 1
225
+ bytes += text.length
226
+ sources.push({ entryId: entry.id, moduleName, text })
227
+ } catch (_error) {
228
+ // A package with an unreadable manifest or missing entrypoint simply cannot be scanned.
229
+ }
230
+ }
231
+
232
+ return sources
233
+ }
234
+
235
+ /** Read the Tool schemas for one scope; a Host without the service yields none. */
236
+ function schemasOf(tools, scope) {
237
+ if (typeof tools?.schemas !== 'function') return []
238
+ try {
239
+ const schemas = tools.schemas(scope)
240
+ return Array.isArray(schemas) ? schemas : []
241
+ } catch (_error) {
242
+ return []
243
+ }
244
+ }
245
+
246
+ /** Read the live Agents; a Host without the service yields none. */
247
+ function listAgents(ctx) {
248
+ const agents = optional(ctx, 'agents')
249
+ if (typeof agents?.list !== 'function') return []
250
+ try {
251
+ const rows = agents.list()
252
+ return Array.isArray(rows) ? rows : []
253
+ } catch (_error) {
254
+ return []
255
+ }
256
+ }
257
+
258
+ /** The stable identity of one live Agent, however that Agent object spells it. */
259
+ function agentIdentity(agent) {
260
+ const candidates = [agent?.id, agent?.session?.id, agent?.sessionId]
261
+ for (const candidate of candidates) {
262
+ if (typeof candidate === 'string' && candidate.length > 0) return candidate
263
+ }
264
+ return undefined
265
+ }
266
+
267
+ /** Read one optional Cordis service without turning a missing service into an activation failure. */
268
+ function optional(ctx, serviceName) {
269
+ try {
270
+ return ctx.get(serviceName)
271
+ } catch (_error) {
272
+ return undefined
273
+ }
274
+ }
275
+
276
+ /** Log through the Host logger when it is available; diagnostics never throw. */
277
+ function warn(ctx, message, error) {
278
+ try {
279
+ ctx.logger?.warn?.(`plugin-manager-wj: ${message}`, error)
280
+ } catch (_error) {
281
+ // A Host without a logger keeps the failure silent rather than failing activation.
282
+ }
283
+ }
284
+
285
+ /** One JSON response for the shared Fetch channel. */
286
+ function jsonResponse(value) {
287
+ return new Response(JSON.stringify(value), {
288
+ status: 200,
289
+ headers: {
290
+ 'content-type': 'application/json; charset=utf-8',
291
+ 'cache-control': 'no-store',
292
+ },
293
+ })
294
+ }
package/locale/en.json CHANGED
@@ -8,25 +8,23 @@
8
8
  "plugins": "Plugins",
9
9
  "config": "Configuration",
10
10
  "skill": "Skills",
11
- "mcp": "MCP"
11
+ "tools": "Tools"
12
12
  },
13
- "search": "Search the current view for plugins, settings, skills or MCP",
13
+ "search": "Search the current view for plugins, settings, skills or tools",
14
14
  "refresh": "Refresh",
15
15
  "loading": "Reading runtime state…",
16
16
  "error": "The runtime inventory could not be read.",
17
17
  "retry": "Retry",
18
- "empty": "There are no plugin, tool or MCP records yet.",
18
+ "empty": "There are no plugin or tool records yet.",
19
19
  "unsupported": "This Harness Host does not provide plugin management and runtime inventory. Upgrade Harness to manage plugins.",
20
20
  "tools": "Tool registrations",
21
- "mcp": "MCP clients",
21
+ "mcpNote": "Adding and connecting MCP servers belongs to the Host's MCP settings page; this page covers plugin-side ownership only.",
22
22
  "owner": "Owning plugin",
23
23
  "scope": "Scope",
24
24
  "global": "Global",
25
25
  "scoped": "Agent scope",
26
26
  "conditional": "Conditional",
27
27
  "unconditional": "Always registered",
28
- "serverState": "Connection state",
29
- "toolNames": "Tool names",
30
28
  "skills": "Skill catalog",
31
29
  "skillUnsupported": "This Host does not expose the skills interface; the catalog is unavailable.",
32
30
  "skillNoSession": "The catalog is resolved per session; open a session and refresh.",
package/locale/zh.json CHANGED
@@ -8,25 +8,23 @@
8
8
  "plugins": "插件",
9
9
  "config": "配置",
10
10
  "skill": "Skill",
11
- "mcp": "MCP"
11
+ "tools": "工具"
12
12
  },
13
- "search": "搜索当前视图的插件、配置、Skill 或 MCP",
13
+ "search": "搜索当前视图的插件、配置、Skill 或工具",
14
14
  "refresh": "刷新",
15
15
  "loading": "正在读取 Host 状态…",
16
16
  "error": "无法读取运行时清单。",
17
17
  "retry": "重试",
18
- "empty": "当前没有插件、工具或 MCP 记录。",
18
+ "empty": "当前没有插件或工具记录。",
19
19
  "unsupported": "当前 Harness Host 未提供插件管理和运行时清单,请升级 Harness 后管理插件。",
20
20
  "tools": "工具注册",
21
- "mcp": "MCP 客户端",
21
+ "mcpNote": "MCP 服务器的添加与连接由 Host 的 MCP 设置页负责;本页只做插件侧的注册归属诊断。",
22
22
  "owner": "所属插件",
23
23
  "scope": "作用域",
24
24
  "global": "全局",
25
25
  "scoped": "Agent 作用域",
26
26
  "conditional": "条件启用",
27
27
  "unconditional": "始终注册",
28
- "serverState": "连接状态",
29
- "toolNames": "工具名",
30
28
  "skills": "Skill 目录",
31
29
  "skillUnsupported": "此 Host 未提供 skills 接口,Skill 目录不可用。",
32
30
  "skillNoSession": "Skill 目录按会话解析;请先打开一个会话后刷新。",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tinyforge/dsh-plugin-manager-wj",
3
- "version": "1.3.4",
4
- "description": "Switchable plugin, configuration, skill and MCP views with health diagnostics, configuration provenance, and tool/MCP inventory for DeepSeek Harness.",
3
+ "version": "1.5.0",
4
+ "description": "Switchable plugin, configuration, skill and tool-ownership views with health diagnostics, configuration provenance, and tool inventory for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "scripts": { "test": "node --test" },