@jidekaixin2dian/dsh-toolgate 0.1.8 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0 — 2026-11-13(本地构建,未发布 / local build, unpublished)
4
+
5
+ - 分组从写死改成**数据**:`DEFAULT_RULES` 自带 ego / memory / remote / watch /
6
+ schedule / team,`toolgate.json` 的 `rules` 可按 id 覆盖或新增;`core` 仍然不可隐藏。
7
+ - 新增 `deriveSuggestions()`:没归组的工具若共享同一前缀(≥3 个,如 `job_*`)会作为
8
+ 「建议分组」出现在设置页的 status 里,点一下即可变成规则——插件不再需要为每个新包改代码。
9
+ - 新增三档预设 `lite` / `standard` / `full`(`op: preset`),预设永不隐藏 `skills`。
10
+ - 新增**逐工具**开关:`disabledTools` + `op: tools-set`,`groupReport().groups[].tools`
11
+ 返回每个工具名与 token 估算,供 UI 渲染独立按钮。
12
+ - 新增**dispatch guard**:`restrict()` 只从列表里摘掉 schema,模型凭历史记忆仍可点名调用;
13
+ 现在 `tools.guard()` 会二次拦截并给出可读理由(按会话/全局分别提示)。
14
+ - 保护名单 `PROTECTED_TOOLS`(read/write/edit/glob/grep/pwsh/present/todo_write/
15
+ toolgate/ask_user_question)不会被任何配置隐藏,避免把自己锁死。
16
+ - 会话级覆盖(`action=session`)沿用原有语义,参数改为按规则校验。
17
+
18
+ - Groups are data now: shipped `DEFAULT_RULES` plus per-id overrides in
19
+ `toolgate.json`; ungrouped tools stay in the un-hideable `core`.
20
+ - `deriveSuggestions()` proposes a group for any ≥3 tools sharing a prefix, so a
21
+ new plugin shows up as a suggestion instead of requiring a code change.
22
+ - Presets `lite` / `standard` / `full`; presets never hide `skills`.
23
+ - Per-tool switches via `disabledTools` / `op: tools-set`, with per-tool rows and
24
+ token estimates in the status payload.
25
+ - A dispatch guard (`tools.guard()`) refuses hidden tools that a model names from
26
+ history, with a scope-aware reason string.
27
+ - `PROTECTED_TOOLS` keeps the escape hatches (read/write/pwsh/toolgate/…) visible
28
+ under every configuration.
29
+
3
30
  ## 0.1.8 — 2026-11-06
4
31
 
5
32
  - 默认固定宿主升级到 DSH rc.5,兼容验证扩展到 **0.2.2-rc.1**(2026-11-04 发布;
package/README.en.md CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  **Bring only the tools you need into the next prompt.**
4
4
 
5
- [中文](README.md) · [npm](https://www.npmjs.com/package/@jidekaixin2dian/dsh-toolgate/v/0.1.7) · [Marketplace](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-toolgate/) · [Download](https://github.com/jidekaixin2dian/dsh-toolgate/releases/latest) · [Changelog](CHANGELOG.md)
5
+ [中文](README.md) · [npm · 0.1.8](https://www.npmjs.com/package/@jidekaixin2dian/dsh-toolgate/v/0.1.8) · [Marketplace](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-toolgate/) · [Download](https://github.com/jidekaixin2dian/dsh-toolgate/releases/latest) · [Changelog](CHANGELOG.md)
6
6
 
7
- Toolgate is an MCP server, skill and context-budget management plugin for DeepSeek Harness (DSH). Have many MCP servers installed but only a few relevant to the task? Hide tool definitions by server in one settings page and restore them when needed; configuration stays in place and MCP processes keep running.
7
+ Toolgate brings MCP servers, skills and context budgets into one DeepSeek Harness (DSH) settings page. Hide tool definitions by server to focus the next prompt on the current task, then restore them when needed. MCP configuration and connections stay in place.
8
8
 
9
9
  ![Tool grouping illustration; example counts are not measured savings](assets/readme-schema-v2.svg)
10
10
 
11
- ## Three jobs, one settings page
11
+ ## Hide tool definitions without disconnecting MCP
12
12
 
13
13
  | Tab | What it does |
14
14
  |---|---|
@@ -16,15 +16,7 @@ Toolgate is an MCP server, skill and context-budget management plugin for DeepSe
16
16
  | MCP servers | Add, edit, enable, disable and remove stdio or streamable-http servers |
17
17
  | Skills | Search, create and toggle by Session workspace; move eligible local skills to trash |
18
18
 
19
- For example, hide MCP tool groups unrelated to a coding task to change the tool definitions supplied with the next prompt, then restore them when needed. The page estimates tokens from schema and description length; the estimate is not a measurement of cost or speed. Settings-page budgets apply to all sessions and subagents; permitted session overrides affect only that session.
20
-
21
- ## Downloads
22
-
23
- | GitHub release assets · all releases | npm 0.1.5 · past 7 days |
24
- |---|---|
25
- | [**471 downloads**](https://api.github.com/repos/jidekaixin2dian/dsh-toolgate/releases?per_page=100) | [**126 downloads**](https://api.npmjs.org/versions/@jidekaixin2dian%2Fdsh-toolgate/last-week) |
26
-
27
- Snapshot: **2026-10-29**. GitHub counts release-asset requests, including checksums; npm counts downloads of the named version. Requests can include repeat installs and automation, so these are not unique-user counts and the two columns are not added together. Click a number for its live source.
19
+ Hide tool groups unrelated to the current task and restore them in one click when needed. MCP configuration and running processes stay in place; the next prompt receives the updated tool list. The page estimates tokens from schema and description length; the estimate is not a measurement of cost or speed. Settings-page budgets apply to all sessions and subagents; permitted session overrides affect only that session.
28
20
 
29
21
  ## Install and update
30
22
 
@@ -80,6 +72,14 @@ Existing `.tgz` or local installations can use the same command in the same prof
80
72
 
81
73
  To remove, quit DSH, run `dsh plugin --profile desktop remove @jidekaixin2dian/dsh-toolgate`, then reopen it.
82
74
 
75
+ ## Downloads
76
+
77
+ | GitHub archives | npm | Combined |
78
+ |---:|---:|---:|
79
+ | [467](https://api.github.com/repos/jidekaixin2dian/dsh-toolgate/releases?per_page=100) | [679](https://api.npmjs.org/downloads/point/2026-10-28:2026-11-04/@jidekaixin2dian%2Fdsh-toolgate) | **1,146 requests** |
80
+
81
+ Snapshot: 2026-11-06; npm data through 2026-11-04. GitHub counts installation archives; npm excludes `0.0.0-stage`. Includes repeat installs and automation, not unique users.
82
+
83
83
  [Development and verification](https://github.com/jidekaixin2dian/dsh-toolgate/blob/main/docs/development.md) · [Security](SECURITY.md) · [Issues](https://github.com/jidekaixin2dian/dsh-toolgate/issues)
84
84
 
85
85
  MIT · Independent community plugin, not affiliated with DeepSeek.
package/README.md CHANGED
@@ -2,13 +2,13 @@
2
2
 
3
3
  **让下一轮 prompt 只带需要的工具。**
4
4
 
5
- [English](README.en.md) · [npm](https://www.npmjs.com/package/@jidekaixin2dian/dsh-toolgate/v/0.1.7) · [插件市场](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-toolgate/) · [下载](https://github.com/jidekaixin2dian/dsh-toolgate/releases/latest) · [更新记录](CHANGELOG.md)
5
+ [English](README.en.md) · [npm · 0.2.0](https://www.npmjs.com/package/@jidekaixin2dian/dsh-toolgate/v/0.2.0) · [插件市场](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-toolgate/) · [下载](https://github.com/jidekaixin2dian/dsh-toolgate/releases/latest) · [更新记录](CHANGELOG.md)
6
6
 
7
- Toolgate 是 DeepSeek Harness(DSH)的 MCP、Skill 和上下文预算管理插件。装了很多 MCP,却只有少数工具与当前任务有关?在同一个设置页按服务器隐藏不需要的工具定义,需要时再恢复;配置保留,MCP 进程继续运行。
7
+ Toolgate 为 DeepSeek Harness(DSH)提供统一的 MCP、Skill 和上下文预算设置页。按服务器隐藏当前用不到的工具定义,让下一轮 prompt 聚焦当前任务;需要时恢复,MCP 配置和连接保持。
8
8
 
9
9
  ![工具分组示意,示例数量不代表实测节省](assets/readme-schema-v2.svg)
10
10
 
11
- ## 一处管理三件事
11
+ ## 隐藏工具定义,MCP 保持连接
12
12
 
13
13
  | 页面 | 你可以做什么 |
14
14
  |---|---|
@@ -16,15 +16,21 @@ Toolgate 是 DeepSeek Harness(DSH)的 MCP、Skill 和上下文预算管理
16
16
  | MCP 服务器 | 新增、编辑、启停、删除服务器;支持 stdio 与 streamable-http |
17
17
  | Skills | 按会话工作区搜索、新建、启停;可删除的本地 Skill 移到回收目录 |
18
18
 
19
- 例如,可以在写代码时隐藏与任务无关的 MCP 工具组,下一轮再交给模型的工具定义就会变化;需要时恢复。页面按工具 schema 和描述长度估算 token,占用与实际费用或速度不是同一指标。设置页预算作用于所有会话和子代理,允许的会话覆盖只影响当前会话。
19
+ 按组隐藏当前任务用不到的工具,需要时一键恢复。配置和运行中的 MCP 保留,下一轮 prompt 使用调整后的工具列表。页面按工具 schema 和描述长度估算 token,占用与实际费用或速度不是同一指标。设置页预算作用于所有会话和子代理,允许的会话覆盖只影响当前会话。
20
20
 
21
- ## 下载情况
21
+ ## 0.2.0:分组是数据,不是写死的表
22
22
 
23
- | GitHub Release 资源 · 历史累计 | npm 0.1.5 · 近 7 日 |
23
+ | 能力 | 说明 |
24
24
  |---|---|
25
- | [**471 次下载**](https://api.github.com/repos/jidekaixin2dian/dsh-toolgate/releases?per_page=100) | [**126 次下载**](https://api.npmjs.org/versions/@jidekaixin2dian%2Fdsh-toolgate/last-week) |
25
+ | 自动分组 | 工具按注册名自动归组(`ego_`、`mnemon_`、`remote_`、`watch_`、`schedule_`、`team_task_`、`mcp__<服务器>__*`);没归组的留在「核心工具」,不可隐藏 |
26
+ | 建议分组 | 「核心工具」里有 ≥3 个工具共享同一前缀(例如 `job_list` / `job_output` / `job_kill`)时,作为建议出现在状态里,一键变成规则 |
27
+ | 自定义规则 | `toolgate.json` 的 `rules: [{ id, prefixes, exact?, label? }]` 可新增分组,或按 id 覆盖内置分组的前缀 |
28
+ | 三档预设 | `lite` / `standard` / `full` 一键切换;预设永不隐藏 Skill 目录 |
29
+ | 逐工具开关 | `disabledTools` 精确隐藏单个工具,`status.groups[].tools` 返回每个工具名与 token 估算 |
30
+ | 分发守卫 | `restrict()` 只把 schema 从列表里摘掉,模型凭历史记忆仍可点名调用;新增的 `tools.guard()` 会在分发前二次拒绝,并说明是本会话还是全局闸门 |
31
+ | 保护名单 | `read/write/edit/glob/grep/pwsh/present/todo_write/toolgate/ask_user_question` 任何配置都关不掉 |
26
32
 
27
- 统计快照:**2026-10-29**。GitHub 包含安装包、校验文件等资源请求;npm 仅统计表中版本。下载可能包含重复安装和自动化请求,不代表独立用户数,两列不相加。点击数字可查看实时来源。
33
+ 也可以用工具本身操作:`toolgate action=status` 看分组,`action=preset preset=lite` 切档,`action=tools tools=[...]` 精确隐藏,`action=session disabled=[...]` 只改本会话,`action=reset` 取消会话覆盖。
28
34
 
29
35
  ## 安装与更新
30
36
 
@@ -82,6 +88,14 @@ toolgate action=reset
82
88
 
83
89
  卸载:退出 DSH 后执行 `dsh plugin --profile desktop remove @jidekaixin2dian/dsh-toolgate`,再重新打开。
84
90
 
91
+ ## 下载情况
92
+
93
+ | GitHub 安装包 | npm | 合计 |
94
+ |---:|---:|---:|
95
+ | [467](https://api.github.com/repos/jidekaixin2dian/dsh-toolgate/releases?per_page=100) | [679](https://api.npmjs.org/downloads/point/2026-10-28:2026-11-04/@jidekaixin2dian%2Fdsh-toolgate) | **1,146 次** |
96
+
97
+ 统计于 2026-11-06;npm 数据截至 2026-11-04。GitHub 仅计安装包,npm 排除 `0.0.0-stage`。下载包含重复安装与自动化请求,不是独立用户数。
98
+
85
99
  [开发与验证](https://github.com/jidekaixin2dian/dsh-toolgate/blob/main/docs/development.md) · [安全说明](SECURITY.md) · [反馈问题](https://github.com/jidekaixin2dian/dsh-toolgate/issues)
86
100
 
87
101
  MIT · 独立社区插件,与 DeepSeek 官方无隶属关系。
package/lib/groups.js CHANGED
@@ -1,13 +1,112 @@
1
1
  // Pure grouping rules. Kept dependency-free so node --test can exercise them
2
2
  // without loading the DSH host or @deepseek-ai/dsh-tools.
3
+ //
4
+ // v0.2 — groups are data, not code:
5
+ // * `DEFAULT_RULES` ships the built-in buckets (ego / remote / watch / team …)
6
+ // * `toolgate.json` may add or override rules by id
7
+ // * anything left over still lands in `core`, which is never hideable
8
+ // * `deriveSuggestions()` proposes groups for ungrouped prefixes, so a new
9
+ // plugin's tools show up as a suggestion instead of silently joining core
10
+
11
+ /** Reserved buckets whose labels are fixed regardless of rules. */
3
12
  export const FIXED_LABELS = {
4
13
  skills: 'Skill 目录',
5
14
  memory: '记忆工具',
6
15
  schedule: '定时任务',
16
+ ego: 'Ego 浏览器',
17
+ remote: '远程会话',
18
+ watch: '仓库巡检',
19
+ team: '团队任务',
20
+ job: '后台作业',
7
21
  }
8
22
  export const CORE_LABEL = '核心工具'
9
23
 
10
- export function groupOf(toolName) {
24
+ /** Never hideable, whatever the config says. Hiding pwsh or the tool itself
25
+ * locks the session out of its own escape hatch. */
26
+ export const PROTECTED_TOOLS = Object.freeze([
27
+ 'read', 'write', 'edit', 'glob', 'grep', 'pwsh', 'present', 'todo_write',
28
+ 'toolgate', 'ask_user_question',
29
+ ])
30
+
31
+ /**
32
+ * Shipped rules. Order matters: first match wins, so a more specific prefix
33
+ * belongs above a broader one. `exact` matches the whole tool name.
34
+ * @type {ReadonlyArray<{id: string, prefixes: string[], exact?: string[]}>}
35
+ */
36
+ export const DEFAULT_RULES = Object.freeze([
37
+ Object.freeze({ id: 'ego', prefixes: ['ego_'] }),
38
+ Object.freeze({ id: 'memory', prefixes: ['mnemon_'] }),
39
+ Object.freeze({ id: 'remote', prefixes: ['remote_'] }),
40
+ Object.freeze({ id: 'watch', prefixes: ['watch_'] }),
41
+ Object.freeze({ id: 'schedule', prefixes: ['schedule_'] }),
42
+ Object.freeze({ id: 'team', prefixes: ['team_task_'] }),
43
+ ])
44
+
45
+ /** One-tap configurations. `skills` is never hidden by a preset. */
46
+ export const PRESETS = Object.freeze({
47
+ full: Object.freeze([]),
48
+ standard: Object.freeze(['ego', 'watch', 'remote']),
49
+ lite: Object.freeze(['ego', 'watch', 'remote', 'team', 'schedule', 'memory']),
50
+ })
51
+
52
+ export const PRESET_IDS = Object.freeze(Object.keys(PRESETS))
53
+
54
+ const ID_RE = /^[a-z0-9][a-z0-9:_-]{0,39}$/
55
+ const MCP_ID_RE = /^mcp:[a-z0-9_-]{1,32}$/
56
+ const RESERVED_IDS = new Set(['skills', 'memory', 'schedule', 'mcp'])
57
+
58
+ function cleanStrings(value, limit = 8) {
59
+ if (!Array.isArray(value)) return []
60
+ const out = []
61
+ for (const raw of value) {
62
+ const text = String(raw || '').trim()
63
+ if (!text || text.length > 64) continue
64
+ if (!out.includes(text)) out.push(text)
65
+ if (out.length >= limit) break
66
+ }
67
+ return out
68
+ }
69
+
70
+ /** Validate one user rule. Returns null when it would be unsafe or unusable. */
71
+ export function normalizeRule(rule) {
72
+ if (!rule || typeof rule !== 'object') return null
73
+ const id = String(rule.id || '').trim().toLowerCase()
74
+ if (!ID_RE.test(id) || id === 'core') return null
75
+ const prefixes = cleanStrings(rule.prefixes).filter(prefix => /^[A-Za-z0-9_.:-]+$/.test(prefix))
76
+ const exact = cleanStrings(rule.exact).filter(name => /^[A-Za-z0-9_.:-]+$/.test(name))
77
+ if (prefixes.length === 0 && exact.length === 0) return null
78
+ const label = typeof rule.label === 'string' && rule.label.trim() !== ''
79
+ ? rule.label.trim().slice(0, 48)
80
+ : undefined
81
+ return { id, prefixes, exact, ...(label ? { label } : {}) }
82
+ }
83
+
84
+ /**
85
+ * Merge shipped rules with user rules. A user rule with the same id replaces
86
+ * the shipped one in place, so ordering stays stable and overrides are obvious.
87
+ */
88
+ export function normalizeRules(rules) {
89
+ const user = (Array.isArray(rules) ? rules : []).map(normalizeRule).filter(Boolean)
90
+ const merged = []
91
+ for (const base of DEFAULT_RULES) {
92
+ const override = user.find(rule => rule.id === base.id)
93
+ merged.push(Object.freeze(override ? { ...base, ...override } : { ...base }))
94
+ }
95
+ for (const rule of user) {
96
+ if (!merged.some(entry => entry.id === rule.id)) merged.push(Object.freeze(rule))
97
+ }
98
+ return merged
99
+ }
100
+
101
+ /** Every id that may appear in a `disabled` list. */
102
+ export function knownGroupIds(rules) {
103
+ const ids = new Set(RESERVED_IDS)
104
+ ids.add('mcp')
105
+ for (const rule of normalizeRules(rules)) ids.add(rule.id)
106
+ return ids
107
+ }
108
+
109
+ export function groupOf(toolName, rules) {
11
110
  const n = String(toolName || '')
12
111
  if (n.startsWith('mcp__')) {
13
112
  const rest = n.slice(5)
@@ -16,34 +115,49 @@ export function groupOf(toolName) {
16
115
  return 'mcp:' + (server.toLowerCase().replace(/[^a-z0-9_-]/g, '_').slice(0, 32) || 'other')
17
116
  }
18
117
  if (n === 'skill') return 'skills'
19
- if (n.startsWith('mnemon_')) return 'memory'
20
- if (n.startsWith('schedule_')) return 'schedule'
118
+ for (const rule of normalizeRules(rules)) {
119
+ if (rule.exact && rule.exact.includes(n)) return rule.id
120
+ for (const prefix of rule.prefixes) {
121
+ if (n.startsWith(prefix)) return rule.id
122
+ }
123
+ }
21
124
  return 'core'
22
125
  }
23
126
 
24
- export function labelOf(group) {
127
+ export function labelOf(group, rules) {
25
128
  if (group === 'core') return CORE_LABEL
26
129
  if (group.startsWith('mcp:')) return 'MCP · ' + group.slice(4)
27
- return FIXED_LABELS[group] || group
130
+ if (FIXED_LABELS[group]) return FIXED_LABELS[group]
131
+ const rule = normalizeRules(rules).find(entry => entry.id === group)
132
+ return rule?.label || group
28
133
  }
29
134
 
30
- export function normalizeDisabled(value) {
135
+ export function normalizeDisabled(value, rules) {
31
136
  if (!Array.isArray(value)) return []
137
+ const known = knownGroupIds(rules)
32
138
  const out = new Set()
33
139
  for (const raw of value) {
34
140
  let id = String(raw || '').trim().toLowerCase()
35
141
  // Migrate the pre-market fixed groups to generic MCP server ids.
36
142
  if (id === 'rea') id = 'mcp:rea'
37
143
  if (id === 'mcp_other') id = 'mcp:other'
38
- if (id === 'mcp') {
39
- out.add('mcp')
40
- continue
41
- }
42
- if (/^mcp:[a-z0-9_-]{1,32}$/.test(id)) {
43
- out.add(id)
44
- continue
45
- }
46
- if (Object.hasOwn(FIXED_LABELS, id)) out.add(id)
144
+ if (id === 'mcp') { out.add('mcp'); continue }
145
+ if (MCP_ID_RE.test(id)) { out.add(id); continue }
146
+ if (known.has(id)) out.add(id)
147
+ }
148
+ return [...out]
149
+ }
150
+
151
+ /** Exact tool names to hide, validated and de-duplicated. */
152
+ export function normalizeToolList(value) {
153
+ if (!Array.isArray(value)) return []
154
+ const out = new Set()
155
+ for (const raw of value) {
156
+ if (typeof raw !== 'string') continue
157
+ const name = raw.trim()
158
+ if (!/^[A-Za-z0-9_.:-]{1,64}$/.test(name)) continue
159
+ if (PROTECTED_TOOLS.includes(name)) continue
160
+ out.add(name)
47
161
  }
48
162
  return [...out]
49
163
  }
@@ -53,7 +167,53 @@ export function isDisabled(group, disabled) {
53
167
  return disabled.includes(group) || (group.startsWith('mcp:') && disabled.includes('mcp'))
54
168
  }
55
169
 
56
- export function matchesDisabled(toolName, disabled) {
57
- return isDisabled(groupOf(toolName), disabled)
170
+ /**
171
+ * Whether a gate is worth applying at all. Both halves count: a session that
172
+ * disables no group but names individual tools must still be restricted, and
173
+ * forgetting this is exactly how the per-tool switch once became a no-op.
174
+ */
175
+ export function shouldApplyGate(disabled, disabledTools) {
176
+ const groups = Array.isArray(disabled) ? disabled.length : 0
177
+ const tools = Array.isArray(disabledTools) ? disabledTools.length : 0
178
+ return groups > 0 || tools > 0
58
179
  }
59
180
 
181
+ export function matchesDisabled(toolName, disabled, rules) {
182
+ return isDisabled(groupOf(toolName, rules), disabled)
183
+ }
184
+
185
+ /** True when this tool must not reach the model: group off or listed by name. */
186
+ export function toolHidden(toolName, disabled, disabledTools, rules) {
187
+ const name = String(toolName || '')
188
+ if (PROTECTED_TOOLS.includes(name)) return false
189
+ if (Array.isArray(disabledTools) && disabledTools.includes(name)) return true
190
+ return matchesDisabled(name, disabled, rules)
191
+ }
192
+
193
+ /**
194
+ * Propose groups for tools still sitting in `core`. A prefix shared by at
195
+ * least `min` tools is a real cluster, not a coincidence: `job_list`,
196
+ * `job_output`, `job_kill` → `job`. Suggestions are advisory only; the user
197
+ * turns one into a rule from the settings page.
198
+ */
199
+ export function deriveSuggestions(toolNames, rules, min = 3) {
200
+ const taken = new Set(normalizeRules(rules).map(rule => rule.id))
201
+ const buckets = new Map()
202
+ for (const name of Array.isArray(toolNames) ? toolNames : []) {
203
+ if (typeof name !== 'string' || name === '') continue
204
+ if (groupOf(name, rules) !== 'core') continue
205
+ const cut = name.indexOf('_')
206
+ if (cut < 2) continue
207
+ const prefix = name.slice(0, cut) + '_'
208
+ if (!buckets.has(prefix)) buckets.set(prefix, [])
209
+ buckets.get(prefix).push(name)
210
+ }
211
+ const out = []
212
+ for (const [prefix, names] of buckets) {
213
+ if (names.length < min) continue
214
+ const id = prefix.slice(0, -1).toLowerCase()
215
+ if (!ID_RE.test(id) || taken.has(id)) continue
216
+ out.push({ id, prefixes: [prefix], tools: names.slice(0, 12), count: names.length })
217
+ }
218
+ return out.sort((a, b) => b.count - a.count)
219
+ }
package/lib/index.js CHANGED
@@ -8,7 +8,11 @@ export const name = 'dsh-toolgate'
8
8
  export const inject = ['tools', 'skills', 'webServer']
9
9
  export const Config = z.object({ allowSessionOverride: z.boolean().default(true) })
10
10
 
11
- import { groupOf, isDisabled, labelOf, matchesDisabled, normalizeDisabled } from './groups.js'
11
+ import {
12
+ deriveSuggestions, groupOf, isDisabled, labelOf, matchesDisabled, normalizeDisabled,
13
+ normalizeRule, normalizeRules, normalizeToolList, shouldApplyGate, toolHidden,
14
+ PRESETS, PRESET_IDS, PROTECTED_TOOLS,
15
+ } from './groups.js'
12
16
  import { requestArgs } from './api-payload.js'
13
17
  import { appendAudit } from './audit.js'
14
18
  import { createMcpConfig, publicServers } from './mcp-config.js'
@@ -40,6 +44,9 @@ export async function apply(ctx, config = {}) {
40
44
  } catch (error) { mcpError = '无法读取宿主 profile:' + error.message }
41
45
  const state = {
42
46
  disabled: [],
47
+ disabledTools: [],
48
+ rules: [],
49
+ preset: 'custom',
43
50
  disabledSkills: [],
44
51
  skillRules: [],
45
52
  disposed: false,
@@ -62,7 +69,11 @@ export async function apply(ctx, config = {}) {
62
69
  for (const file of [stateFile, legacyFile]) {
63
70
  try {
64
71
  const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
65
- state.disabled = normalizeDisabled(parsed?.disabled)
72
+ // Rules first: they decide which ids `disabled` may legitimately name.
73
+ state.rules = Array.isArray(parsed?.rules) ? parsed.rules.map(normalizeRule).filter(Boolean) : []
74
+ state.disabled = normalizeDisabled(parsed?.disabled, state.rules)
75
+ state.disabledTools = normalizeToolList(parsed?.disabledTools)
76
+ state.preset = PRESET_IDS.includes(parsed?.preset) ? parsed.preset : 'custom'
66
77
  state.disabledSkills = Array.isArray(parsed?.disabledSkills)
67
78
  ? parsed.disabledSkills.filter(name => typeof name === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))
68
79
  : []
@@ -72,6 +83,9 @@ export async function apply(ctx, config = {}) {
72
83
  } catch { /* try the legacy file, then reset */ }
73
84
  }
74
85
  state.disabled = []
86
+ state.disabledTools = []
87
+ state.rules = []
88
+ state.preset = 'custom'
75
89
  state.disabledSkills = []
76
90
  }
77
91
 
@@ -81,6 +95,9 @@ export async function apply(ctx, config = {}) {
81
95
  fs.mkdirSync(path.dirname(stateFile), { recursive: true })
82
96
  fs.writeFileSync(tmp, JSON.stringify({
83
97
  disabled: state.disabled,
98
+ disabledTools: state.disabledTools,
99
+ rules: state.rules,
100
+ preset: state.preset,
84
101
  disabledSkills: state.disabledSkills,
85
102
  skillRules: state.skillRules,
86
103
  }, null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 })
@@ -120,17 +137,31 @@ export async function apply(ctx, config = {}) {
120
137
  async function groupReport(ctx, agent) {
121
138
  const schemas = state.bestSchemas || ctx.tools.schemas()
122
139
  const globalNames = new Set(ctx.tools.schemas().map(schema => schema.name))
140
+ // A session-scoped report must describe that session's gate, not the global
141
+ // one: `hidden` flags, `saved` tokens and the returned `disabled` list all
142
+ // follow the effective gate of the agent that asked.
143
+ const viewDisabled = agent ? effectiveDisabled(agent) : state.disabled
123
144
  const groups = new Map()
124
145
  const ensure = (id, toggle = true) => {
125
- if (!groups.has(id)) groups.set(id, { id, label: labelOf(id), count: 0, tokens: 0, hideableTokens: 0, toggle })
146
+ if (!groups.has(id)) {
147
+ groups.set(id, {
148
+ id, label: labelOf(id, state.rules), count: 0, tokens: 0, hideableTokens: 0, toggle, tools: [],
149
+ })
150
+ }
126
151
  return groups.get(id)
127
152
  }
128
153
  for (const schema of schemas) {
129
- const group = groupOf(schema.name)
154
+ const group = groupOf(schema.name, state.rules)
130
155
  const entry = ensure(group, group !== 'core')
156
+ const tokens = tokensOf(schema)
131
157
  entry.count += 1
132
- entry.tokens += tokensOf(schema)
133
- if (globalNames.has(schema.name)) entry.hideableTokens += tokensOf(schema)
158
+ entry.tokens += tokens
159
+ // Per-tool rows feed the "one button per tool" list; cap keeps the status
160
+ // payload small when a plugin registers dozens of tools.
161
+ if (entry.tools.length < 80) {
162
+ entry.tools.push({ name: schema.name, tokens, hidden: toolHidden(schema.name, viewDisabled, state.disabledTools, state.rules) })
163
+ }
164
+ if (globalNames.has(schema.name)) entry.hideableTokens += tokens
134
165
  }
135
166
  const catalog = await skillCatalog(ctx, agent)
136
167
  let catalogTokens = 0
@@ -152,14 +183,24 @@ export async function apply(ctx, config = {}) {
152
183
  return b.tokens - a.tokens
153
184
  })
154
185
  const full = list.reduce((sum, item) => sum + item.tokens, 0)
155
- const saved = list.filter(item => isDisabled(item.id, state.disabled))
186
+ const saved = list.filter(item => isDisabled(item.id, viewDisabled))
156
187
  .reduce((sum, item) => sum + item.hideableTokens, 0)
157
188
  const scoped = schemas.filter(schema => !globalNames.has(schema.name)
158
189
  && schema.name.startsWith('mcp__')).length
190
+ const allNames = new Set(schemas.map(schema => schema.name))
159
191
  return {
160
192
  groups: list,
161
193
  totals: { full, current: Math.max(0, full - saved), saved },
162
- disabled: [...state.disabled],
194
+ disabled: [...viewDisabled],
195
+ disabledTools: [...state.disabledTools],
196
+ // Names in the exact list that no longer exist: a typo, or a plugin that
197
+ // went away. Surfaced instead of failing silently.
198
+ unknownTools: state.disabledTools.filter(name => !allNames.has(name)),
199
+ preset: state.preset,
200
+ presets: PRESET_IDS,
201
+ rules: normalizeRules(state.rules).map(rule => ({ id: rule.id, prefixes: rule.prefixes, ...(rule.exact ? { exact: rule.exact } : {}), ...(rule.label ? { label: rule.label } : {}) })),
202
+ suggestions: deriveSuggestions(schemas.map(schema => schema.name), state.rules),
203
+ protectedTools: [...PROTECTED_TOOLS],
163
204
  catalogTokens,
164
205
  scoped,
165
206
  skills: { count: catalog.length },
@@ -204,7 +245,7 @@ export async function apply(ctx, config = {}) {
204
245
  } catch { /* tool view not ready yet */ }
205
246
  }
206
247
  const disabled = effectiveDisabled(ag)
207
- const key = disabled.slice().sort().join(',')
248
+ const key = disabled.slice().sort().join(',') + '|' + state.disabledTools.slice().sort().join(',') + '|' + normalizeRules(state.rules).length
208
249
  const previous = state.applied.get(ag)
209
250
  if (previous && previous.key === key) return
210
251
  if (previous) {
@@ -212,7 +253,10 @@ export async function apply(ctx, config = {}) {
212
253
  try { previous.dispose() } catch { /* stale agent scope */ } finally { state.applying = false }
213
254
  state.applied.delete(ag)
214
255
  }
215
- if (disabled.length === 0) {
256
+ // Both halves of the gate matter: an empty group list with a non-empty
257
+ // exact-tool list must still reach restrict(), otherwise the per-tool
258
+ // buttons update the file and change nothing in the prompt.
259
+ if (!shouldApplyGate(disabled, state.disabledTools)) {
216
260
  state.errors.delete(sid)
217
261
  return
218
262
  }
@@ -222,7 +266,7 @@ export async function apply(ctx, config = {}) {
222
266
  return
223
267
  }
224
268
  const full = rootCtx.tools.schemas()
225
- const deny = full.map(schema => schema.name).filter(n => matchesDisabled(n, disabled))
269
+ const deny = full.map(schema => schema.name).filter(n => toolHidden(n, disabled, state.disabledTools, state.rules))
226
270
  if (deny.length === 0) return
227
271
  state.applying = true
228
272
  try {
@@ -323,22 +367,34 @@ export async function apply(ctx, config = {}) {
323
367
  const tool = defineTool({
324
368
  name: 'toolgate',
325
369
  description: [
326
- 'Inspect or shrink this session context by hiding tool groups (MCP/Skill/memory/schedule).',
370
+ 'Inspect or shrink this session context by hiding tool groups or single tools.',
371
+ 'Groups are discovered from the tools that actually registered (ego, remote, watch, team, schedule, memory, skills, mcp:<server>, …),',
372
+ 'plus any custom rule in toolgate.json; anything ungrouped stays in core and cannot be hidden.',
327
373
  'This changes the very next request, is reversible, and does not restart MCP processes.',
328
- 'Use action=status first. Use action=session with disabled groups for a session-only override,',
329
- 'or action=reset to fall back to the global setting. Global settings live in Settings > Toolgate.',
374
+ 'Use action=status first. action=session/disabled applies a session-only override, action=reset drops it,',
375
+ 'action=preset with lite|standard|full switches the global gate, and action=tools with exact names hides individual tools.',
376
+ 'Global settings live in Settings > Toolgate.',
330
377
  ...(allowSessionOverride ? [] : ['Session overrides are disabled by the host; only action=status is available.']),
331
378
  ].join(' '),
332
379
  parameters: {
333
380
  action: {
334
381
  type: 'string',
335
382
  required: true,
336
- description: 'status | session | reset',
383
+ description: 'status | session | reset | preset | tools',
337
384
  },
338
385
  disabled: {
339
386
  type: 'array',
340
387
  items: { type: 'string' },
341
- description: 'Groups to hide: mcp:<server>, mcp (all MCP), skills, memory, schedule. Empty means show all.',
388
+ description: 'Groups to hide: ego, memory, remote, watch, schedule, team, skills, mcp:<server>, mcp (all MCP), or a custom rule id. Empty means show all.',
389
+ },
390
+ preset: {
391
+ type: 'string',
392
+ description: 'With action=preset: lite | standard | full.',
393
+ },
394
+ tools: {
395
+ type: 'array',
396
+ items: { type: 'string' },
397
+ description: 'With action=tools: exact tool names to hide globally. Protected tools (read/write/pwsh/toolgate/…) are ignored.',
342
398
  },
343
399
  },
344
400
  output: {
@@ -360,17 +416,81 @@ export async function apply(ctx, config = {}) {
360
416
  return '已恢复全局工具闸门。\n\n' + await reportFor(agent)
361
417
  }
362
418
  if (action === 'session') {
363
- const disabled = normalizeDisabled(args.disabled)
419
+ const disabled = normalizeDisabled(args.disabled, state.rules)
364
420
  state.overrides.set(sid, disabled)
365
421
  applyToAgent(agent)
366
422
  return '已应用本会话覆盖:' + (disabled.length ? disabled.join(', ') : '全部显示') +
367
423
  '\n\n' + await reportFor(agent)
368
424
  }
369
- return 'Unknown action "' + action + '". Use status, session or reset.'
425
+ if (action === 'preset') {
426
+ const name = String(args.preset || '').trim().toLowerCase()
427
+ if (!PRESET_IDS.includes(name)) {
428
+ return '未知预设 "' + name + '"。可选:' + PRESET_IDS.join(' / ') +
429
+ '\n\n' + await reportFor(agent)
430
+ }
431
+ const previous = state.disabled
432
+ const previousPreset = state.preset
433
+ state.disabled = normalizeDisabled(PRESETS[name], state.rules)
434
+ state.preset = name
435
+ try {
436
+ saveState()
437
+ } catch (error) {
438
+ state.disabled = previous
439
+ state.preset = previousPreset
440
+ return '保存失败:' + (error?.message || error)
441
+ }
442
+ audit({ op: 'preset', preset: name, disabled: [...state.disabled] })
443
+ clearApplied()
444
+ applyToAgent(agent)
445
+ return '已切换到 ' + name + ' 档(全局):' + (state.disabled.length ? state.disabled.join(', ') : '全部显示') +
446
+ '\n\n' + await reportFor(agent)
447
+ }
448
+ if (action === 'tools') {
449
+ const previous = state.disabledTools
450
+ const previousPreset = state.preset
451
+ state.disabledTools = normalizeToolList(args.tools)
452
+ state.preset = 'custom'
453
+ try {
454
+ saveState()
455
+ } catch (error) {
456
+ state.disabledTools = previous
457
+ state.preset = previousPreset
458
+ return '保存失败:' + (error?.message || error)
459
+ }
460
+ audit({ op: 'tools-set', tools: [...state.disabledTools] })
461
+ clearApplied()
462
+ applyToAgent(agent)
463
+ return '已隐藏 ' + state.disabledTools.length + ' 个具体工具:' +
464
+ (state.disabledTools.length ? state.disabledTools.join(', ') : '无') +
465
+ '\n\n' + await reportFor(agent)
466
+ }
467
+ return 'Unknown action "' + action + '". Use status, session, reset, preset or tools.'
370
468
  },
371
469
  })
372
470
  ctx.tools.register(tool)
373
471
 
472
+ // `restrict()` only removes a schema from the model-facing list; a model that
473
+ // replays a name from history still reaches dispatch. The guard makes the
474
+ // switch a gate instead of a hint, and it is evaluated per calling agent so a
475
+ // session override stays session-scoped.
476
+ try {
477
+ if (typeof ctx.tools.guard === 'function') {
478
+ const disposeGuard = ctx.tools.guard((execution) => {
479
+ const name = execution?.name
480
+ if (typeof name !== 'string' || name === '') return undefined
481
+ if (PROTECTED_TOOLS.includes(name)) return undefined
482
+ const agent = execution?.agent
483
+ const disabled = effectiveDisabled(agent)
484
+ if (!toolHidden(name, disabled, state.disabledTools, state.rules)) return undefined
485
+ const scope = state.overrides.has(sessionIdOf(agent)) ? '本会话' : '全局'
486
+ return `"${name}" 已被 Toolgate 的${scope}闸门隐藏。用 toolgate action=status 查看分组与当前闸门,或在 设置 → 工具闸门 里打开它。`
487
+ })
488
+ ctx.effect(() => () => { try { disposeGuard?.() } catch { /* agent scope gone */ } })
489
+ }
490
+ } catch (error) {
491
+ ctx.logger?.warn?.('dsh-toolgate: dispatch guard unavailable (%s)', String(error?.message || error))
492
+ }
493
+
374
494
  // Every request passes here before prompt assembly. Applying the restriction
375
495
  // in this hook means the schemas disappear without touching any config or
376
496
  // restarting the MCP client process.
@@ -453,12 +573,45 @@ export async function apply(ctx, config = {}) {
453
573
  applied: [...state.applied.keys()].map(sessionIdOf), errors: Object.fromEntries(state.errors) })
454
574
  if (op === 'set') {
455
575
  const previous = state.disabled
456
- state.disabled = normalizeDisabled(args.disabled)
576
+ state.disabled = normalizeDisabled(args.disabled, state.rules)
577
+ state.preset = 'custom'
457
578
  try { saveState() } catch (error) { state.disabled = previous; throw error }
458
579
  audit({ op, disabled: [...state.disabled] })
459
580
  clearApplied()
460
581
  return send(200, { ok: true, ...(await groupReport(ctx)) })
461
582
  }
583
+ if (op === 'preset') {
584
+ const name = String(args.preset || '').trim().toLowerCase()
585
+ if (!PRESET_IDS.includes(name)) return send(400, { ok: false, error: 'unknown preset: ' + name })
586
+ const previous = state.disabled
587
+ const previousPreset = state.preset
588
+ state.disabled = normalizeDisabled(PRESETS[name], state.rules)
589
+ state.preset = name
590
+ try { saveState() } catch (error) { state.disabled = previous; state.preset = previousPreset; throw error }
591
+ audit({ op, preset: name, disabled: [...state.disabled] })
592
+ clearApplied()
593
+ return send(200, { ok: true, ...(await groupReport(ctx)) })
594
+ }
595
+ if (op === 'tools-set') {
596
+ const previous = state.disabledTools
597
+ const previousPreset = state.preset
598
+ state.disabledTools = normalizeToolList(args.tools)
599
+ state.preset = 'custom'
600
+ try { saveState() } catch (error) { state.disabledTools = previous; state.preset = previousPreset; throw error }
601
+ audit({ op, tools: [...state.disabledTools] })
602
+ clearApplied()
603
+ return send(200, { ok: true, ...(await groupReport(ctx)) })
604
+ }
605
+ if (op === 'rules-set') {
606
+ const previous = state.rules
607
+ state.rules = (Array.isArray(args.rules) ? args.rules : []).map(normalizeRule).filter(Boolean)
608
+ // A rule that disappears must not leave an unusable id in `disabled`.
609
+ state.disabled = normalizeDisabled(state.disabled, state.rules)
610
+ try { saveState() } catch (error) { state.rules = previous; throw error }
611
+ audit({ op, rules: state.rules.map(rule => rule.id) })
612
+ clearApplied()
613
+ return send(200, { ok: true, ...(await groupReport(ctx)) })
614
+ }
462
615
  if (op.startsWith('mcp-')) {
463
616
  if (!mcp) return send(503, { ok: false, error: mcpError || 'current profile unavailable' })
464
617
  const operations = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jidekaixin2dian/dsh-toolgate",
3
- "version": "0.1.8",
3
+ "version": "0.2.0",
4
4
  "description": "Manage MCP servers and skills in one place; hide or restore groups of tool definitions to control what enters the next prompt.",
5
5
  "icon": "icon.svg",
6
6
  "type": "module",
@@ -64,9 +64,7 @@
64
64
  },
65
65
  "peerDependencies": {
66
66
  "@deepseek-ai/cordis-plugin-include": "*",
67
- "@deepseek-ai/dsh-app-boot": "*",
68
- "@deepseek-ai/dsh-tools": ">=0.2.0-rc.1 <0.2.1-0 || >=0.2.1-rc.1 <0.3.0-0",
69
- "@deepseek-ai/schemastery": "*"
67
+ "@deepseek-ai/dsh-app-boot": "*"
70
68
  },
71
69
  "license": "MIT",
72
70
  "dependencies": {