dsh-agent-control-center 0.4.0 → 0.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.
@@ -1,7 +1,7 @@
1
1
  # 兼容性与降级(DSH 版本 / 能力矩阵)
2
2
 
3
3
  > 实现:`lib/core/compat.js`(纯函数 + 一次版本探测);测试:`tests/compat.test.mjs`。
4
- > 目标宿主:DSH `0.2.2-rc.5`(`/opt/dsh-0222`)。本文件描述**已经发生的事实**与**可复算的判定规则**,不描述期望。
4
+ > 目标宿主:DSH `0.2.2-rc.5`(`/opt/dsh-0222`)与 `0.2.3-alpha.3`(`/opt/dsh-0233`,v0.4.1 起)。本文件描述**已经发生的事实**与**可复算的判定规则**,不描述期望。
5
5
  > 证据标签沿用 `docs/01-CONTRACT.md` §5:`VERIFIED`(本机实测观察)、`SOURCE-CONFIRMED`(读到宿主源码/类型)、`INFERRED`(由源码推定未实测)、`UNKNOWN`。
6
6
 
7
7
  ---
@@ -58,8 +58,8 @@
58
58
  |---|---|---|
59
59
  | `MIN_SUPPORTED` | `0.2.0` | 兼容层愿意推理的最低版本。**低于** `DECLARED_MIN`(`0.2.1-rc.1`)是有意的:宿主自身会用 `engines.dsh` 拦掉,但版本豁免/源码运行仍要让插件给出结论而不是假设 |
60
60
  | `DECLARED_MIN` | `0.2.1-rc.1` | `package.json` 的 `engines.dsh` / `dsh.compatibility.dsh` 下限(与 `package.json` 的一致性有测试) |
61
- | `TESTED` | `['0.2.2-rc.5']` | 真正跑过/推导过能力矩阵的版本 |
62
- | `MAX_TESTED` | `0.2.2-rc.5` | 由 `TESTED` 推导(最大值),`full` 只可能出现在这段区间 |
61
+ | `TESTED` | `['0.2.2-rc.5', '0.2.3-alpha.3']` | 真正跑过/推导过能力矩阵的版本 |
62
+ | `MAX_TESTED` | `0.2.3-alpha.3` | 由 `TESTED` 推导(最大值),`full` 只可能出现在这段区间 |
63
63
  | `DECLARED_MAX` | `0.3.0`(**不含**) | `package.json` 声明的上限;`>= 0.3.0` 属于新一代 API,未测 |
64
64
 
65
65
  ### 已测/未测矩阵
@@ -69,7 +69,8 @@
69
69
  | `0.1.x` | INFERRED | `unsupported` | true | 低于 `MIN_SUPPORTED`,`version-below-minimum` |
70
70
  | `0.2.0` | INFERRED(无实测) | `degraded` | false | `version-below-declared` + `version-untested`;只在宿主版本豁免时可出现 |
71
71
  | `0.2.1-rc.1` ~ `0.2.1-rc.x` | 声明下限,**未实测** | `degraded` | false | `version-untested`;能力矩阵推定与 0.2.2 同构(INFERRED) |
72
- | `0.2.2-rc.5` | **VERIFIED**(本机 `/opt/dsh-0222`) | `full`(21/21 能力齐全时) | false | 唯一 `full` 区间 |
72
+ | `0.2.2-rc.5` | **VERIFIED**(`/opt/dsh-0222`) | `full`(21/21 能力齐全时) | false | v0.1.0–v0.4.0 的验收基线 |
73
+ | `0.2.3-alpha.3` | **VERIFIED**(`/opt/dsh-0233`,v0.4.1) | `full`(21/21 能力齐全,12 模块 11 FULL + recovery PARTIAL) | false | 见 §7 的 API 漂移表 |
73
74
  | `0.2.2`(正式)/`0.2.3-alpha.1` | 未实测,在声明范围内 | `degraded` | false | `version-above-tested`:可能含新 API,写入仍允许 |
74
75
  | `0.3.0+` | **UNKNOWN** | `degraded` | **true** | `version-above-declared`:跨代,默认只读 |
75
76
 
@@ -200,3 +201,21 @@
200
201
  | `0.3.0` 只读策略可能过于保守 | 跨代默认只读 | 实测 0.3.x 后按 §7.4 抬 `MAX_TESTED`/`DECLARED_MAX`,只读自动解除 |
201
202
  | 版本来源依赖 `profileContext` 形状 | 宿主改字段名→退回 `argv`;两者皆失→只读 | 新增来源只需在 `detectVersion` 候选中加一项并补测试 |
202
203
  | `DSH_INSTALL_DIR` 在本机不存在 | 现有 `f-diagnostics`/`h-overview` 显示版本未知 | 接线时优先用 `createCompatibility`(内部首选 `profileContext`),并考虑把两个模块改为读兼容层结论 |
204
+
205
+ ---
206
+
207
+ ## 7. `0.2.3-alpha.3` 的 API 漂移与适配(v0.4.1)
208
+
209
+ 0.2.3 改了两处本插件实际读取的宿主 API。两处都不是破坏性的语义变化,只是**改名**;适配后 `evaluate()` 在 `0.2.3-alpha.3` 上给出 `level:'full'、tested:true、readOnly:false`。
210
+
211
+ | 能力 | 0.2.2 | 0.2.3 | 适配位置 |
212
+ |---|---|---|---|
213
+ | `tools` | `definitions(scope)` + `schemas(scope)` | `getAll(scope)` + `get(name, scope)`(`schemas()` 不再公开) | `lib/core/tools-view.js`(`readDefinitions` / `readSchemaProjection` / `isExecutable`);`caps.js` 的 `ALTERNATES` 接受任一完整方法族 |
214
+ | `connection` | `requestRejection(request)` → `401 \| 403 \| undefined` | `admit(request)` → `{ rejection } \| { peer }` | `lib/core/http.js`(`rejectionOf()` 两条分支,`{peer}` 视为放行);`caps.js` 的 `ALTERNATES` 同样接受两族 |
215
+
216
+ 规则与取舍:
217
+
218
+ 1. **只有整族齐全才算 present**。半套(例如只有 `getAll` 没有 `get`)判为缺失并把两族名字都写进 `detail`,避免“看起来能用、实际半坏”。
219
+ 2. **`schemas()` 缺失是降级而非阻断**。它只用于“模型面投影核对”这一诊断项;`tools.schemaProjection` 会标 `available:false` 并给出原因,工具清单照常工作。
220
+ 3. **`executable()` → `get()` 的语义差**。`executable(name, scope)` 表示“带 `when` 条件的工具不算可执行”;`get(name, scope)` 只表示“该作用域能看到”。因此 `isExecutable()` 优先用 `executable()`,没有时才退回 `get()`,且 `get()` 抛错(同名多定义)时返回 `null`(未知),不猜。
221
+ 4. **`admit()` 的放行分支**。`{ peer }` 表示通过;`{ rejection: 401 | 403 }` 转成对应状态码;其它异常值按 `403`。`admit()` 抛错时退回本插件的兜底判定(Host 头白名单 + 回环)。
@@ -42,7 +42,7 @@ DSH Web GUI (browser)
42
42
 
43
43
  ### 2.1 入口 `index.js`
44
44
 
45
- - 导出:`name`、`VERSION`(`0.4.0`,与 `package.json` 同步)、`HTTP_PREFIX`(`/__agent-control-center`)、`inject = []`、`apply(ctx, rawConfig)`。
45
+ - 导出:`name`、`VERSION`(`0.5.0`,与 `package.json` 同步)、`HTTP_PREFIX`(`/__agent-control-center`)、`inject = []`、`apply(ctx, rawConfig)`。
46
46
  - `inject = []` 是硬约束:**任何宿主服务缺失都不阻止插件激活**,只让对应模块降级为 PARTIAL/BLOCKED。
47
47
  - 启动序列(`apply`):
48
48
  1. `normalizeConfig(rawConfig)`:未知字段/类型错误/越界 → **加载期直接抛错**(fail loud,不做静默兜底);
@@ -24,13 +24,30 @@
24
24
 
25
25
  **局限必须记住**:静态扫描只覆盖构建产物里的字面量,运行时动态生成 id 的插件会漏检;本插件自己的 bundle 若以 `link:` 安装在 `$DSH_HOME` 之外(被路径围栏拒绝读取),则改用插件内常量 `agent-control-center` 补一行并标 `scanned:false`。
26
26
 
27
+ ## 声明 vs 运行时(漂移)
28
+
29
+ `health.drift()` 比较 **profile 声明的插件行** 与 **Loader 实际运行状态**,证据来自两个宿主服务:
30
+
31
+ | 证据 | 服务 | 能证明什么 |
32
+ |---|---|---|
33
+ | 每行是否启用、运行时相位、启动错误 | `pluginManager.listPlugins()` | 声明为启用却不在 `active`、声明停用却仍在跑、启动失败 |
34
+ | 哪些行能被 profile patch 寻址 | `configEditor.entries()` | 行是否受本 profile 的 patch 管辖(`include:` 前缀会被归一) |
35
+ | 声明了但装不上的 bundle | `pluginManager.listBundles()` | `availability:'missing'` 的 bundle |
36
+
37
+ **不解析 `cordis.patch.yml`**:该文件可能含插件密钥,路径围栏按设计拒绝读取。因此「声明」一侧取自上面两个服务的投影,响应里的 `note` 明说这一点,不会假装读到了 YAML。
38
+
39
+ 漂移类型:`enabled-not-running`、`disabled-but-running`、`startup-failed`(唯一映射到 `error` 级)、`declared-not-installed`。bundle 检查需要显式 `includeBundles:true`(读取每个安装位置要数秒,页面把它做成一个按钮)。
40
+
41
+ 真机(0.2.3-alpha.3,2026-11-29):225 行 / 222 行受 profile 管辖 / 3 行由 bundle 或安装自带提供;开启 bundle 检查后发现 **2 条真实漂移**:`@deepseek-ai/dsh-subagent-claude-code` 与 `@deepseek-ai/dsh-subagent-codex` 声明在 profile 里但安装目录中不存在(`availability=missing`)。
42
+
27
43
  ## API
28
44
 
29
45
  - `health.plugins()` → `{available, source:'pluginManager', items:[{entryId,moduleName,patchId,readOnlyReason}], anomalies:[{kind,detail}]}`
30
46
  - `health.settings()` → `{available, namespaces:[{ns,revision,autoGenerate,hasValue,secretKeys}], own:{ns:'acc',declared,enabled}, redactionVerified, note}`
31
47
  - `health.sections()` → `{available, method:'static-scan', scanned:{packages,files}, sections:[{id,owner,file}], conflicts:[{kind,id,owners,suggestion}], own, note}`
32
48
  - `health.compat()` → `{available, level, version, readOnly, reasons, source}`
33
- - `health.summary()` → `{generatedAt, plugins:{total,anomalies}, settings:{...}, sections:{count,conflicts}, compat:{level,readOnly}, worst:{severity,id}}`
49
+ - `health.drift()` → `{available, rows:[{entryId,moduleName,enabled,fiberPhase,addressable,inProfile}], mountedRows, inProfileRows, bundlesChecked, self, drifts:[{kind,id,detail,suggestion}], notes, note}`
50
+ - `health.summary()` → `{generatedAt, plugins:{total,anomalies}, settings:{...}, sections:{count,conflicts}, drift:{rows,mounted,count}, compat:{level,readOnly}, worst:{severity,id}}`
34
51
 
35
52
  ## 真机观察(accverify,2026-11-29,12 模块)
36
53
 
@@ -0,0 +1,47 @@
1
+ # 逐页浏览回归报告(12 页,真实 Chrome,accverify)
2
+
3
+ > 数据来源:本轮子代理在 17:36–17:51 于运行实例上采集的 `regression-data.json` / `probe_interact.json` / `extra-results.json`,其进程在环境重启后中断,报告由 lead 从原始数据重建。**不含逐页完整交互清单**(见「未覆盖」)。
4
+
5
+ ## 首屏
6
+
7
+ | 页面 | 首屏 ms | 文本字符 | 出现 Loading | 错误态块 |
8
+ | --- | --- | --- | --- | --- |
9
+ | Overview | 334 | 1483 | False | 0 |
10
+ | AGENTS.md | 1576 | 1143 | True | 0 |
11
+ | Tools | 5712 | 4262 | True | 0 |
12
+ | Sessions | 2460 | 6423 | True | 0 |
13
+ | Usage | 405 | 2368 | True | 0 |
14
+ | Agent info | 708 | 1067 | True | 0 |
15
+ | Instruction preview | 2168 | 60137 | True | 0 |
16
+ | Templates | 402 | 1636 | True | 0 |
17
+ | Diagnostics | 2395 | 9616 | True | 0 |
18
+ | Export | 922 | 3251 | True | 0 |
19
+ | Restart & Resume | 343 | 663 | False | 0 |
20
+ | tools_esc | None | None | None | None |
21
+ | health_extra | None | 0 | None | None |
22
+
23
+ 12 页全部 0 错误态块;慢页:Tools 5.7 s(对应 `tools.list` 实测 5.4 s)、Instruction 2.2 s、Diagnostics 2.4 s、Sessions 2.5 s。
24
+
25
+ ## 交互证据(已采集到的部分)
26
+
27
+ - Sessions:Archived 切换后列表由 50 行变为 8/8 行;勾选一行出现 `1 selected` 工具条;展开一行出现详情。
28
+ - Agent info:Presets 视图由 1 行变 4 行;Export 视图渲染 `{schemaVersion, exportedAt, presets, agents, models}` 且声明不含密钥。
29
+ - Instruction preview:会话下拉 51 个选项;选中后进入 `by session` 视图(2,554 字符);Compare 视图 2,654 字符。
30
+ - Templates:进入模板详情(2,390 字符);Apply 打开确认对话框并出现 diff(3,670 字符)。
31
+ - Diagnostics:4 个统计卡(Error 0 / Warning 2 / Unknown 1 / OK 19);点 Warning 过滤生效;展开「Most severe」组可读到证据切片。
32
+ - Health check:1,118 ms 进入、20,982 字符、就绪态。
33
+
34
+ ## 发现的问题
35
+
36
+ | 级别 | 页面 | 现象 | 判断 |
37
+ | --- | --- | --- | --- |
38
+ | S2 | Tools | 首屏 5.7 s;`tools.list` 实测 **5,407 ms**,`tools.summary` 2,366 ms(357 个会话下冷启动) | 真实性能问题:首次扫描历史无上限,需分页/时间窗或预热缓存 |
39
+ | S3 | Sessions | 脚本按「Activity statistics」tab 定位超时 | 脚本假设错误:该页只有 All chats / Archived 两个 tab,统计是区块;非产品问题 |
40
+ | S3 | Diagnostics | `collapsed_evidence_present=false`(脚本期望默认折叠) | 默认展开,脚本断言方向错;非产品问题 |
41
+ | S3 | Tools | `tools_read_cold` 记录 95 s 且 ok=false | 与 `tools.callers` 方法不存在(`not_found`)相关,属脚本调用错误方法;非产品问题 |
42
+ | S4 | 全部 | 无 console error / pageerror | 通过 |
43
+
44
+ ## 未覆盖(诚实缺口)
45
+
46
+ - Overview 的卡片跳转、AGENTS.md 的选中刷新、Usage 的日期切换、Restart & Resume 的扫描:脚本在环境重启后中断,未采到结果。
47
+ - 截图 23 张(`01-overview.png` … `12-*`)在 `/tmp/ux/regress/`,未逐张目视复核。
package/index.js CHANGED
@@ -15,7 +15,7 @@ import { createRegistry } from './lib/core/registry.js'
15
15
 
16
16
  export const name = 'dsh-agent-control-center'
17
17
  /** Plugin version, mirrored in package.json. */
18
- export const VERSION = '0.4.0'
18
+ export const VERSION = '0.5.0'
19
19
  /** Browser transport prefix. The client fetches it document-relative. */
20
20
  export const HTTP_PREFIX = '/__agent-control-center'
21
21
 
package/lib/core/caps.js CHANGED
@@ -14,7 +14,9 @@ const REQUIRED = Object.freeze({
14
14
  workspaceRegistry: ['list', 'archiveSession', 'unarchiveSession'],
15
15
  workspaceController: ['archiveSession', 'unarchiveSession'],
16
16
  workspaceFiles: ['read', 'stat', 'list'],
17
- tools: ['definitions', 'schemas'],
17
+ // Host 0.2.3 replaced `definitions()` / `schemas()` with `getAll()` / `get()`.
18
+ // `tools` counts as present when either API family is complete (see ALTERNATES).
19
+ tools: ['getAll', 'get'],
18
20
  settings: ['describe'],
19
21
  credentials: ['listRecords'],
20
22
  configEditor: ['entries'],
@@ -25,11 +27,23 @@ const REQUIRED = Object.freeze({
25
27
  pluginManager: ['listPlugins', 'listBundles'],
26
28
  storage: ['form'],
27
29
  webServer: ['register'],
28
- connection: ['requestRejection'],
30
+ connection: ['admit'], // 0.2.3 replaced `requestRejection()`; see ALTERNATES
29
31
  commands: ['list'],
30
32
  systemPrompt: [],
31
33
  })
32
34
 
35
+ /**
36
+ * Alternative method families for one capability. A capability is present when
37
+ * any family is fully available, so a host that renamed its API is still read.
38
+ * The legacy 0.2.x tools surface (`definitions` + `schemas`) and the 0.2.3 one
39
+ * (`getAll` + `get`) are both accepted; `methods` reports whichever matched.
40
+ * @type {Record<string, readonly (readonly string[])[]>}
41
+ */
42
+ const ALTERNATES = Object.freeze({
43
+ tools: Object.freeze([['getAll', 'get'], ['definitions', 'schemas']]),
44
+ connection: Object.freeze([['admit'], ['requestRejection']]),
45
+ })
46
+
33
47
  /**
34
48
  * @param {{ ctx: { get(name: string): unknown }, log?: (message: string) => void }} options
35
49
  */
@@ -54,12 +68,19 @@ export function createCaps(options) {
54
68
  if (known === undefined) return { present: false, methods: [], detail: '未知能力' }
55
69
  const service = read(name)
56
70
  if (service === undefined || service === null) return { present: false, methods: [], detail: '宿主未提供该服务' }
57
- const methods = []
58
- for (const method of known) {
59
- const value = /** @type {Record<string, unknown>} */ (service)[method]
60
- if (typeof value === 'function') methods.push(method)
61
- }
62
71
  if (known.length === 0) return { present: true, methods: [], detail: '' }
72
+ const table = /** @type {Record<string, unknown>} */ (service)
73
+ const has = (/** @type {string} */ method) => typeof table[method] === 'function'
74
+ const alternates = ALTERNATES[name]
75
+ if (alternates !== undefined) {
76
+ // One whole family must be there; a half-renamed host counts as absent.
77
+ const family = alternates.find((candidate) => candidate.every(has)) ?? null
78
+ if (family === null) {
79
+ return { present: false, methods: [], detail: `缺少方法族:${alternates.map((candidate) => candidate.join(' + ')).join(' 或 ')}` }
80
+ }
81
+ return { present: true, methods: [...family], detail: '' }
82
+ }
83
+ const methods = known.filter(has)
63
84
  const missing = known.filter((method) => !methods.includes(method))
64
85
  return {
65
86
  present: methods.length > 0,
@@ -28,12 +28,14 @@ import path from 'node:path'
28
28
  export const MIN_SUPPORTED = '0.2.0'
29
29
 
30
30
  /** DSH versions the plugin has actually been exercised against. */
31
- export const TESTED = Object.freeze(['0.2.2-rc.5'])
31
+ export const TESTED = Object.freeze([
32
+ '0.2.2-rc.5',
33
+ // Exercised end to end on 0.2.3-alpha.3: the tools registry surface was renamed
34
+ // (`definitions`/`schemas` → `getAll`/`get`) and `connection.requestRejection`
35
+ // became `admit(request)`; both are read through adapters now.
36
+ '0.2.3-alpha.3',
37
+ ])
32
38
 
33
- /** Highest measured DSH version; versions above it run degraded, never blocked. */
34
- export const MAX_TESTED = TESTED.reduce((highest, version) =>
35
- compareVersions(version, highest) > 0 ? version : highest,
36
- )
37
39
 
38
40
  /** Lower bound declared in `package.json` (`dsh.compatibility.dsh` / `engines.dsh`). */
39
41
  export const DECLARED_MIN = '0.2.1-rc.1'
@@ -262,6 +264,15 @@ export function compareVersions(a, b) {
262
264
  return 0
263
265
  }
264
266
 
267
+ /**
268
+ * Highest measured DSH version; versions above it run degraded, never blocked.
269
+ * Computed after {@link compareVersions} exists so a multi-entry {@link TESTED}
270
+ * list does not compare versions before the parser is initialised.
271
+ */
272
+ export const MAX_TESTED = TESTED.reduce((highest, version) =>
273
+ compareVersions(version, highest) > 0 ? version : highest,
274
+ )
275
+
265
276
  /* ------------------------------------------------------------------------- */
266
277
  /* Capability normalization */
267
278
  /* ------------------------------------------------------------------------- */
package/lib/core/http.js CHANGED
@@ -133,7 +133,7 @@ function fallbackRejection(request) {
133
133
  * prefix: string,
134
134
  * version: string,
135
135
  * log: (message: string) => void,
136
- * getConnection?: () => { requestRejection?: (request: unknown) => 401 | 403 | undefined } | undefined,
136
+ * getConnection?: () => { requestRejection?: (request: unknown) => 401 | 403 | undefined, admit?: (request: unknown) => { rejection?: unknown } | unknown } | undefined,
137
137
  * dispatch: (method: string, params: Record<string, unknown>, context: object) => Promise<unknown>,
138
138
  * health: () => unknown,
139
139
  * onRejected?: (info: { path: string, method: string, status: 401 | 403, address: string }) => void,
@@ -148,6 +148,9 @@ export function createHttp(options) {
148
148
  /** @param {import('node:http').IncomingMessage} request @returns {401 | 403 | undefined} */
149
149
  function rejectionOf(request) {
150
150
  const connection = options.getConnection?.()
151
+ // 0.2.2 exposed `requestRejection(request)`; 0.2.3 replaced it with
152
+ // `admit(request)`, which answers `{ rejection }` for a refusal and a peer
153
+ // for an admitted request.
151
154
  if (connection !== undefined && typeof connection.requestRejection === 'function') {
152
155
  try {
153
156
  return connection.requestRejection(request)
@@ -156,6 +159,19 @@ export function createHttp(options) {
156
159
  return fallbackRejection(request)
157
160
  }
158
161
  }
162
+ if (connection !== undefined && typeof connection.admit === 'function') {
163
+ try {
164
+ const admission = connection.admit(request)
165
+ if (admission !== null && typeof admission === 'object' && 'rejection' in admission) {
166
+ const status = /** @type {{ rejection?: unknown }} */ (admission).rejection
167
+ return status === 401 || status === 403 ? status : 403
168
+ }
169
+ return undefined
170
+ } catch (error) {
171
+ log(`connection.admit failed: ${String(error?.message ?? error)}`)
172
+ return fallbackRejection(request)
173
+ }
174
+ }
159
175
  return fallbackRejection(request)
160
176
  }
161
177
 
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Tool registry reads across host API generations.
3
+ *
4
+ * DSH 0.2.2 exposed `definitions(scope)` and `schemas(scope)`; 0.2.3 replaced
5
+ * them with `get(name, scope)` / `getAll(scope)` and dropped the schema
6
+ * projection from the public surface. Modules read through this adapter so a
7
+ * renamed host API degrades one diagnostic, never a whole module.
8
+ *
9
+ * @module dsh-agent-control-center/core/tools-view
10
+ */
11
+
12
+ /**
13
+ * @param {any} tools host `tools` service (already checked for existence)
14
+ * @returns {'getAll' | 'definitions' | null} the family this host speaks
15
+ */
16
+ export function toolsApiKind(tools) {
17
+ if (typeof tools?.getAll === 'function') return 'getAll'
18
+ if (typeof tools?.definitions === 'function') return 'definitions'
19
+ return null
20
+ }
21
+
22
+ /**
23
+ * Read one registry view: the unscoped view when `scope` is omitted, otherwise
24
+ * the view that scope sees.
25
+ *
26
+ * @param {any} tools host `tools` service
27
+ * @param {unknown} [scope] Agent object or preset scope key
28
+ * @returns {{ ok: boolean, definitions: readonly unknown[], detail?: string }}
29
+ */
30
+ export function readDefinitions(tools, scope) {
31
+ if (toolsApiKind(tools) === 'getAll') {
32
+ const definitions = scope === undefined ? tools.getAll() : tools.getAll(scope)
33
+ return { ok: true, definitions: Array.isArray(definitions) ? definitions : [] }
34
+ }
35
+ if (toolsApiKind(tools) === 'definitions') {
36
+ const definitions = scope === undefined ? tools.definitions() : tools.definitions(scope)
37
+ return { ok: true, definitions: Array.isArray(definitions) ? definitions : [] }
38
+ }
39
+ return { ok: false, definitions: [], detail: '宿主 tools 服务既没有 getAll() 也没有 definitions()' }
40
+ }
41
+
42
+ /**
43
+ * Project the model-facing schema list, when the host still exposes it.
44
+ *
45
+ * @param {any} tools host `tools` service
46
+ * @returns {{ available: boolean, count: number | null, reason: string | null }}
47
+ */
48
+ export function readSchemaProjection(tools) {
49
+ if (typeof tools?.schemas !== 'function') {
50
+ return {
51
+ available: false,
52
+ count: null,
53
+ reason: '宿主 tools 服务没有 schemas()(0.2.3 起该投影不再公开),无法核对模型面投影',
54
+ }
55
+ }
56
+ try {
57
+ const schemas = tools.schemas()
58
+ return { available: true, count: Array.isArray(schemas) ? schemas.length : null, reason: null }
59
+ } catch (error) {
60
+ return { available: false, count: null, reason: String(/** @type {any} */ (error)?.message ?? error).slice(0, 200) }
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Whether one name is executable for a scope. The host expresses `when`-gated
66
+ * tools as a `get()`/`executable()` miss; without either method the answer is
67
+ * unknown rather than assumed.
68
+ *
69
+ * @param {any} tools host `tools` service
70
+ * @param {string} name tool name
71
+ * @param {unknown} [scope] Agent object or preset scope key
72
+ * @returns {boolean | null} true = executable, false = registered but gated, null = unknown
73
+ */
74
+ export function isExecutable(tools, name, scope) {
75
+ if (typeof tools?.executable === 'function') {
76
+ try {
77
+ return tools.executable(name, scope) !== undefined
78
+ } catch {
79
+ return null
80
+ }
81
+ }
82
+ if (typeof tools?.get === 'function') {
83
+ try {
84
+ return (scope === undefined ? tools.get(name) : tools.get(name, scope)) !== undefined
85
+ } catch {
86
+ // `get()` throws for an ambiguous name; that is a registry conflict, not
87
+ // a statement about execution.
88
+ return null
89
+ }
90
+ }
91
+ return null
92
+ }
@@ -21,6 +21,7 @@
21
21
  * @module dsh-agent-control-center/modules/tools
22
22
  */
23
23
  import { createCache, resolveCacheTtlMs, scheduleWarmup, withCacheMeta } from '../core/cache.js'
24
+ import { isExecutable, readDefinitions, readSchemaProjection, toolsApiKind } from '../core/tools-view.js'
24
25
 
25
26
  /** List descriptions are truncated; `tools.detail` carries the full text. */
26
27
  const DESCRIPTION_LIMIT = 240
@@ -206,12 +207,7 @@ export default function createModule(core) {
206
207
  * @param {unknown} scope
207
208
  */
208
209
  function readView(tools, scope) {
209
- if (scope === undefined) {
210
- const definitions = tools.definitions()
211
- return { ok: true, definitions: Array.isArray(definitions) ? definitions : [] }
212
- }
213
- const definitions = tools.definitions(scope)
214
- return { ok: true, definitions: Array.isArray(definitions) ? definitions : [] }
210
+ return readDefinitions(tools, scope)
215
211
  }
216
212
 
217
213
  /** @param {string} name @param {{ inGlobal: boolean, scopes: string[] }} checks */
@@ -240,8 +236,8 @@ export default function createModule(core) {
240
236
  */
241
237
  async function registrySnapshot(options = {}) {
242
238
  const tools = service('tools')
243
- if (tools === undefined || typeof tools.definitions !== 'function') {
244
- return unavailable('宿主未提供 tools 服务(或缺少 definitions 方法)', '工具清单只能来自宿主工具注册表;本模块不做磁盘推断')
239
+ if (tools === undefined || toolsApiKind(tools) === null) {
240
+ return unavailable('宿主未提供 tools 服务(或缺少 getAll/definitions 方法)', '工具清单只能来自宿主工具注册表;本模块不做磁盘推断')
245
241
  }
246
242
  const globalView = readView(tools, undefined)
247
243
  const globalByName = new Map()
@@ -251,17 +247,7 @@ export default function createModule(core) {
251
247
  }
252
248
  }
253
249
 
254
- let schemaProjection = { available: true, count: null, reason: null }
255
- if (typeof tools.schemas === 'function') {
256
- try {
257
- const schemas = tools.schemas()
258
- schemaProjection = { available: true, count: Array.isArray(schemas) ? schemas.length : null, reason: null }
259
- } catch (error) {
260
- schemaProjection = { available: false, count: null, reason: util.redact(String(error?.message ?? error), 200) }
261
- }
262
- } else {
263
- schemaProjection = { available: false, count: null, reason: '宿主 tools 服务没有 schemas(),无法核对模型面投影' }
264
- }
250
+ const schemaProjection = readSchemaProjection(tools)
265
251
 
266
252
  const agentsService = service('agents')
267
253
  let liveAgents = []
@@ -448,6 +434,32 @@ export default function createModule(core) {
448
434
  * `maxSessions` and a soft deadline and reports every truncation.
449
435
  * @param {{ from: number, to: number, maxSessions: number, timeBudgetMs: number, sampleLimit: number }} options
450
436
  */
437
+ /**
438
+ * Fold results keyed by the scan bounds. The page issues summary + list +
439
+ * detail in sequence; without this memo each one re-reads the same sessions.
440
+ */
441
+ const historyMemo = new Map()
442
+
443
+ /** @param {{ from: number, to: number, maxSessions: number, timeBudgetMs: number, sampleLimit: number, refresh?: boolean }} options */
444
+ async function sharedHistory(options) {
445
+ const key = `${options.from}|${options.to}|${options.maxSessions}|${options.timeBudgetMs}|${options.sampleLimit}`
446
+ const ttl = typeof core.config?.cacheTtlMs === 'number' ? core.config.cacheTtlMs : 60 * 1000
447
+ const entry = historyMemo.get(key)
448
+ const now = Date.now()
449
+ if (options.refresh !== true && entry !== undefined && now - entry.at < ttl) {
450
+ return withCacheMeta({ value: entry.value, cached: true, ageMs: now - entry.at })
451
+ }
452
+ const value = await aggregateHistory(options)
453
+ // A degraded block is worth keeping too: the next request avoids the
454
+ // failure path without pretending it succeeded.
455
+ historyMemo.set(key, { at: Date.now(), value })
456
+ if (historyMemo.size > 24) {
457
+ const oldest = [...historyMemo.entries()].sort((left, right) => left[1].at - right[1].at)[0]
458
+ if (oldest !== undefined) historyMemo.delete(oldest[0])
459
+ }
460
+ return withCacheMeta({ value, cached: false, ageMs: 0 })
461
+ }
462
+
451
463
  async function aggregateHistory(options) {
452
464
  const query = service('sessionQuery')
453
465
  if (query === undefined || typeof query.listSessions !== 'function' || typeof query.readSession !== 'function') {
@@ -664,6 +676,10 @@ export default function createModule(core) {
664
676
  totals: history.totals,
665
677
  errorState: history.errorState,
666
678
  failuresWithoutIdentity: history.failuresWithoutIdentity,
679
+ // Freshness of the shared history fold (the way to force a re-read is
680
+ // `refresh: true` on the request).
681
+ cached: history.cached === true,
682
+ cacheAgeMs: typeof history.cacheAgeMs === 'number' ? history.cacheAgeMs : 0,
667
683
  }
668
684
  }
669
685
 
@@ -706,13 +722,8 @@ export default function createModule(core) {
706
722
  const visible = view.names.has(name)
707
723
  if (!visible) return { id: view.id, available: true, visible: false, conditional: null }
708
724
  let conditional = null
709
- if (typeof registry.tools.executable === 'function') {
710
- try {
711
- conditional = registry.tools.executable(name, view.agent) === undefined
712
- } catch {
713
- conditional = null
714
- }
715
- }
725
+ const executable = isExecutable(registry.tools, name, view.agent)
726
+ if (executable !== null) conditional = executable === false
716
727
  const shadowed = globalDefinition !== undefined && view.names.get(name) !== globalDefinition
717
728
  return { id: view.id, available: true, visible: true, conditional, shadowed }
718
729
  })
@@ -825,6 +836,8 @@ export default function createModule(core) {
825
836
  return {
826
837
  maxSessions: util.numParam(params, 'maxSessions', { min: 1, max: 200, fallback: DEFAULTS.maxSessions }),
827
838
  timeBudgetMs: util.numParam(params, 'timeBudgetMs', { min: 100, max: 20000, fallback: DEFAULTS.timeBudgetMs }),
839
+ // The host cache serves repeat reads; an explicit refresh re-reads sessions.
840
+ refresh: util.boolParam(params, 'refresh', false),
828
841
  }
829
842
  }
830
843
 
@@ -861,12 +874,13 @@ export default function createModule(core) {
861
874
  }
862
875
  const current = resolveCurrentAgent(registry.agentViews, agentId)
863
876
  const history = includeHistory
864
- ? await aggregateHistory({
877
+ ? await sharedHistory({
865
878
  from: window.from,
866
879
  to: window.to,
867
880
  maxSessions: historyOptions.maxSessions,
868
881
  timeBudgetMs: historyOptions.timeBudgetMs,
869
882
  sampleLimit: 5,
883
+ refresh: historyOptions.refresh,
870
884
  })
871
885
  : unavailable('按参数关闭了历史调用统计(includeHistory=false)')
872
886
 
@@ -924,12 +938,13 @@ export default function createModule(core) {
924
938
  return { available: false, reason: registry.reason, hint: registry.hint, name }
925
939
  }
926
940
  const current = resolveCurrentAgent(registry.agentViews, agentId)
927
- const history = await aggregateHistory({
941
+ const history = await sharedHistory({
928
942
  from: window.from,
929
943
  to: window.to,
930
944
  maxSessions: historyOptions.maxSessions,
931
945
  timeBudgetMs: historyOptions.timeBudgetMs,
932
946
  sampleLimit,
947
+ refresh: historyOptions.refresh,
933
948
  })
934
949
  const known = registry.globalByName.has(name)
935
950
  || registry.agentViews.some((view) => view.available && view.names.has(name))
@@ -937,19 +952,24 @@ export default function createModule(core) {
937
952
  || (history.available === true && history.byTool.has(name))
938
953
  if (!known) throw core.errors.notFound(`工具不存在:${name}`, { hint: '注册表与历史事件中都没有该名称' })
939
954
 
940
- const definition = registry.globalByName.get(name)
955
+ const globalDefinition = registry.globalByName.get(name)
956
+ const scopedDefinition = globalDefinition === undefined
957
+ ? [...registry.agentViews, ...registry.presetViews]
958
+ .filter((view) => view.available === true && view.names instanceof Map)
959
+ .map((view) => view.names.get(name))
960
+ .find((candidate) => candidate !== undefined && candidate !== null)
961
+ : undefined
962
+ const definition = globalDefinition === undefined ? scopedDefinition : globalDefinition
963
+ const schemaSource = globalDefinition !== undefined ? 'global' : definition === undefined ? null : 'scoped'
941
964
  const inspected = definition === undefined ? null : inspectDefinition(definition)
942
965
  const item = buildItem(name, registry, { history, current, includePresets })
943
966
  const agentVisibility = registry.agentViews.map((view) => {
944
967
  if (!view.available) return { id: view.id, available: false, visible: null, reason: view.reason }
945
968
  const visible = view.names.has(name)
946
969
  let conditional = null
947
- if (visible && typeof registry.tools.executable === 'function') {
948
- try {
949
- conditional = registry.tools.executable(name, view.agent) === undefined
950
- } catch {
951
- conditional = null
952
- }
970
+ if (visible) {
971
+ const executable = isExecutable(registry.tools, name, view.agent)
972
+ if (executable !== null) conditional = executable === false
953
973
  }
954
974
  return {
955
975
  id: view.id,
@@ -1011,8 +1031,12 @@ export default function createModule(core) {
1011
1031
  source: item.source,
1012
1032
  registered: item.registered,
1013
1033
  registeredWhere: item.registeredWhere,
1034
+ // Where the schema came from: the global registry, a scoped view, or
1035
+ // nowhere (a name seen only in history has no definition to read).
1036
+ schemaSource,
1037
+ definitionAvailable: inspected !== null,
1014
1038
  definition: inspected === null
1015
- ? unavailable('当前注册表中没有该名称,定义不可读(仅存在于历史事件)')
1039
+ ? unavailable('该名称只出现在历史事件里,全局与 Scoped 注册视图都没有它的定义,因此 schema 不可读')
1016
1040
  : {
1017
1041
  available: true,
1018
1042
  descriptionLength: inspected.descriptionLength,
@@ -1200,8 +1224,8 @@ export default function createModule(core) {
1200
1224
  },
1201
1225
  probe: () => {
1202
1226
  const tools = service('tools')
1203
- if (tools === undefined || typeof tools.definitions !== 'function') {
1204
- return { state: 'BLOCKED', detail: '宿主未提供 tools 服务(definitions)' }
1227
+ if (tools === undefined || toolsApiKind(tools) === null) {
1228
+ return { state: 'BLOCKED', detail: '宿主未提供 tools 服务(getAll/definitions)' }
1205
1229
  }
1206
1230
  const query = service('sessionQuery')
1207
1231
  if (query === undefined || typeof query.listSessions !== 'function' || typeof query.readSession !== 'function') {