@jidekaixin2dian/dsh-toolgate 0.2.0 → 0.2.2
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 +38 -1
- package/README.en.md +4 -4
- package/README.md +5 -5
- package/lib/client.js +5 -5
- package/lib/gate-commands.js +31 -0
- package/lib/group-report.js +82 -0
- package/lib/groups.js +14 -6
- package/lib/index.js +82 -270
- package/lib/settings-store.js +66 -0
- package/lib/skills-runtime.js +14 -14
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
## 0.2.
|
|
3
|
+
## 0.2.2 — 2026-11-17
|
|
4
|
+
|
|
5
|
+
### 中文
|
|
6
|
+
|
|
7
|
+
- 设置保存成功后再更新生效状态;写入失败时保留完整旧设置。
|
|
8
|
+
- 设置页与模型工具共用分组、逐工具开关、预设和规则的修改流程,保留现有配置字段与核心工具保护。
|
|
9
|
+
- 分离设置存储、运行态和分组报表,补充失败路径回归与工程文档;意外入口加载错误直接使测试失败。
|
|
10
|
+
|
|
11
|
+
### English
|
|
12
|
+
|
|
13
|
+
- Apply settings only after persistence succeeds; failed writes retain the complete previous settings.
|
|
14
|
+
- Use the same commands for settings-page and model-tool changes to groups, per-tool switches, presets and rules, preserving configuration fields and core-tool protection.
|
|
15
|
+
- Separate settings storage, runtime state and group reporting, with failure-path regressions and architecture documentation. Unexpected entry-loading errors now fail tests.
|
|
16
|
+
|
|
17
|
+
## 0.2.1 — 2026-11-14
|
|
18
|
+
|
|
19
|
+
**为什么值得更新**:DSH 0.2.2 起多了一个 `apply_patch`(一次新增、修改、删除、移动多个文件),它和 `write`/`edit` 是同一类写盘工具,却没被保护名单覆盖。在逐工具开关里点掉它,模型就只剩单文件写入路径,README 里「任何配置都关不掉」这句承诺也就不成立了。
|
|
20
|
+
|
|
21
|
+
- 保护名单加入 `apply_patch`:与 `write`/`edit` 同级,`disabledTools`、规则、预设、会话覆盖都关不掉它。
|
|
22
|
+
- 回归宿主张新增 `0.2.2-rc.3` 并设为默认(`scripts/host.mjs`);Windows 本地跑通 11 项,浏览器用例按设计跳过(CI 里 `TOOLGATE_BROWSER=1` 会跑)。
|
|
23
|
+
|
|
24
|
+
**Why update**: DSH 0.2.2 added `apply_patch` (create, edit, delete and move several files in one call). It is a write-path tool like `write`/`edit` but sat outside the protected list, so one per-tool switch could hide it and quietly break the "no configuration can hide these" promise.
|
|
25
|
+
|
|
26
|
+
- Add `apply_patch` to `PROTECTED_TOOLS`; neither `disabledTools`, rules, presets, nor session overrides can hide it.
|
|
27
|
+
- Pin `0.2.2-rc.3` as the default regression host; 11 Windows host tests pass and the browser-only case skips by design.
|
|
28
|
+
|
|
29
|
+
## 0.2.0 — 2026-11-13
|
|
30
|
+
|
|
31
|
+
**为什么值得更新**:0.1.x 只能关 MCP / Skill / 记忆 / 定时这四类,ego、remote、watch、
|
|
32
|
+
团队这些真正占地方的工具一个都关不掉,只能每轮带着进 prompt。0.2.0 把它们变成可关的组,
|
|
33
|
+
`lite` 档在本机实测每轮省下约 1 万个 token 的工具 schema;同时修掉「按工具名隐藏其实
|
|
34
|
+
没生效」——那个问题会让新按钮看起来按了没用。
|
|
4
35
|
|
|
5
36
|
- 分组从写死改成**数据**:`DEFAULT_RULES` 自带 ego / memory / remote / watch /
|
|
6
37
|
schedule / team,`toolgate.json` 的 `rules` 可按 id 覆盖或新增;`core` 仍然不可隐藏。
|
|
@@ -15,6 +46,12 @@
|
|
|
15
46
|
toolgate/ask_user_question)不会被任何配置隐藏,避免把自己锁死。
|
|
16
47
|
- 会话级覆盖(`action=session`)沿用原有语义,参数改为按规则校验。
|
|
17
48
|
|
|
49
|
+
**Why update**: 0.1.x could only switch MCP / Skill / memory / schedule, so ego,
|
|
50
|
+
remote, watch and team tools — the ones that actually cost context — entered every
|
|
51
|
+
prompt. They are switchable groups now; the `lite` preset measured roughly 10k
|
|
52
|
+
fewer tool-schema tokens per turn here. It also fixes "hide by tool name does
|
|
53
|
+
nothing", which made the new switches look broken.
|
|
54
|
+
|
|
18
55
|
- Groups are data now: shipped `DEFAULT_RULES` plus per-id overrides in
|
|
19
56
|
`toolgate.json`; ungrouped tools stay in the un-hideable `core`.
|
|
20
57
|
- `deriveSuggestions()` proposes a group for any ≥3 tools sharing a prefix, so a
|
package/README.en.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**Bring only the tools you need into the next prompt.**
|
|
4
4
|
|
|
5
|
-
[中文](README.md) · [npm · 0.
|
|
5
|
+
[中文](README.md) · [npm · 0.2.2](https://www.npmjs.com/package/@jidekaixin2dian/dsh-toolgate/v/0.2.2) · [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
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
|
|
|
@@ -24,10 +24,10 @@ Requires **DSH >=0.2.1-rc.2 and Node >=24**. CI verifies DSH rc.2 / rc.3 / rc.4
|
|
|
24
24
|
|
|
25
25
|
Search for **dsh-toolgate**, author **jidekaixin2dian**, in the marketplace. Both npm and GitHub sources support version checks. Once the catalog recognizes the npm package it prefers npm; existing users can check under installed plugins. Catalog and registry data may take time to refresh.
|
|
26
26
|
|
|
27
|
-
|
|
27
|
+
Desktop users install, update and remove plugins through the in-app marketplace, restarting when prompted. Web/CLI users can stop the corresponding session and run this command for the `web` profile; repeat it to update:
|
|
28
28
|
|
|
29
29
|
```powershell
|
|
30
|
-
dsh plugin --profile
|
|
30
|
+
dsh plugin --profile web add @jidekaixin2dian/dsh-toolgate --registry=https://registry.npmjs.org
|
|
31
31
|
```
|
|
32
32
|
|
|
33
33
|
Offline packages are available in [Releases](https://github.com/jidekaixin2dian/dsh-toolgate/releases/latest). While Desktop owns a running profile, use its plugin manager and respect profile locks.
|
|
@@ -70,7 +70,7 @@ Existing `.tgz` or local installations can use the same command in the same prof
|
|
|
70
70
|
- Audit records are stored in `DSH_HOME/toolgate-audit.jsonl`. Management requires host authentication and the current profile, failing closed if either is missing.
|
|
71
71
|
- Plugin updates require an app restart; existing MCP configuration changes can hot reload through the host.
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
For Web/CLI removal, stop the corresponding session, run `dsh plugin --profile web remove @jidekaixin2dian/dsh-toolgate`, then restart the session.
|
|
74
74
|
|
|
75
75
|
## Downloads
|
|
76
76
|
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
**让下一轮 prompt 只带需要的工具。**
|
|
4
4
|
|
|
5
|
-
[English](README.en.md) · [npm · 0.2.
|
|
5
|
+
[English](README.en.md) · [npm · 0.2.2](https://www.npmjs.com/package/@jidekaixin2dian/dsh-toolgate/v/0.2.2) · [插件市场](https://awesome-dsh-plugin.com/p/jidekaixin2dian/dsh-toolgate/) · [下载](https://github.com/jidekaixin2dian/dsh-toolgate/releases/latest) · [更新记录](CHANGELOG.md)
|
|
6
6
|
|
|
7
7
|
Toolgate 为 DeepSeek Harness(DSH)提供统一的 MCP、Skill 和上下文预算设置页。按服务器隐藏当前用不到的工具定义,让下一轮 prompt 聚焦当前任务;需要时恢复,MCP 配置和连接保持。
|
|
8
8
|
|
|
@@ -28,7 +28,7 @@ Toolgate 为 DeepSeek Harness(DSH)提供统一的 MCP、Skill 和上下文
|
|
|
28
28
|
| 三档预设 | `lite` / `standard` / `full` 一键切换;预设永不隐藏 Skill 目录 |
|
|
29
29
|
| 逐工具开关 | `disabledTools` 精确隐藏单个工具,`status.groups[].tools` 返回每个工具名与 token 估算 |
|
|
30
30
|
| 分发守卫 | `restrict()` 只把 schema 从列表里摘掉,模型凭历史记忆仍可点名调用;新增的 `tools.guard()` 会在分发前二次拒绝,并说明是本会话还是全局闸门 |
|
|
31
|
-
| 保护名单 | `read/write/edit/glob/grep/pwsh/present/todo_write/toolgate/ask_user_question`
|
|
31
|
+
| 保护名单 | `read/write/edit/apply_patch/glob/grep/pwsh/present/todo_write/toolgate/ask_user_question` 任何配置都关不掉(`apply_patch` 是 DSH 0.2.2 起的多文件写入工具,与 write/edit 同级) |
|
|
32
32
|
|
|
33
33
|
也可以用工具本身操作:`toolgate action=status` 看分组,`action=preset preset=lite` 切档,`action=tools tools=[...]` 精确隐藏,`action=session disabled=[...]` 只改本会话,`action=reset` 取消会话覆盖。
|
|
34
34
|
|
|
@@ -38,10 +38,10 @@ Toolgate 为 DeepSeek Harness(DSH)提供统一的 MCP、Skill 和上下文
|
|
|
38
38
|
|
|
39
39
|
在插件市场搜索 **dsh-toolgate**,确认作者为 **jidekaixin2dian**。npm 与 GitHub 来源都支持版本检查;市场识别 npm 包后优先使用 npm,可在「已安装」中检查更新。目录与 registry 数据可能有同步延迟。
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
Desktop 用户在应用内插件市场安装、更新或卸载,按提示重启。Web/CLI 用户停止对应会话后,可对 `web` profile 执行以下命令;重复执行即可更新:
|
|
42
42
|
|
|
43
43
|
```powershell
|
|
44
|
-
dsh plugin --profile
|
|
44
|
+
dsh plugin --profile web add @jidekaixin2dian/dsh-toolgate --registry=https://registry.npmjs.org
|
|
45
45
|
```
|
|
46
46
|
|
|
47
47
|
离线安装包见 [Release](https://github.com/jidekaixin2dian/dsh-toolgate/releases/latest)。桌面端运行期间请使用其插件管理器,遵守 profile 锁。
|
|
@@ -86,7 +86,7 @@ toolgate action=reset
|
|
|
86
86
|
- 审计记录位于 `DSH_HOME/toolgate-audit.jsonl`。管理接口依赖宿主认证和当前 profile,缺失时拒绝访问。
|
|
87
87
|
- 插件本身更新需要重开 DSH;已有 MCP 配置变更可由宿主热重载。
|
|
88
88
|
|
|
89
|
-
|
|
89
|
+
Web/CLI 卸载:停止对应会话后执行 `dsh plugin --profile web remove @jidekaixin2dian/dsh-toolgate`,再重新启动会话。
|
|
90
90
|
|
|
91
91
|
## 下载情况
|
|
92
92
|
|
package/lib/client.js
CHANGED
|
@@ -470,7 +470,7 @@ const factory = (require) => {
|
|
|
470
470
|
}
|
|
471
471
|
apply(next)
|
|
472
472
|
}
|
|
473
|
-
const
|
|
473
|
+
const applyGroupSelection = (ids) => apply(ids)
|
|
474
474
|
const largest = groups.slice().sort((a, b) => b.tokens - a.tokens)[0]
|
|
475
475
|
|
|
476
476
|
return React.createElement('div', { className: 'cb-wrap' },
|
|
@@ -488,10 +488,10 @@ const factory = (require) => {
|
|
|
488
488
|
React.createElement('div', { className: 'cb-total' },
|
|
489
489
|
React.createElement('b', null, fmt(status.totals.saved)), React.createElement('span', null, '已节省(约 tokens)'))),
|
|
490
490
|
React.createElement('div', { className: 'cb-presets' },
|
|
491
|
-
React.createElement('button', { className: 'cb-btn primary', disabled: busy, onClick: () =>
|
|
492
|
-
React.createElement('button', { className: 'cb-btn', disabled: busy, onClick: () =>
|
|
493
|
-
largest ? React.createElement('button', { className: 'cb-btn', disabled: busy, onClick: () =>
|
|
494
|
-
React.createElement('button', { className: 'cb-btn', disabled: busy, onClick: () =>
|
|
491
|
+
React.createElement('button', { className: 'cb-btn primary', disabled: busy, onClick: () => applyGroupSelection([]) }, '全部显示'),
|
|
492
|
+
React.createElement('button', { className: 'cb-btn', disabled: busy, onClick: () => applyGroupSelection(['mcp']) }, '关闭全部 MCP'),
|
|
493
|
+
largest ? React.createElement('button', { className: 'cb-btn', disabled: busy, onClick: () => applyGroupSelection([largest.id]) }, '关闭最大组') : null,
|
|
494
|
+
React.createElement('button', { className: 'cb-btn', disabled: busy, onClick: () => applyGroupSelection(['mcp', 'skills', 'memory', 'schedule']) }, '精简模式'))),
|
|
495
495
|
React.createElement('div', { className: 'cb-card' },
|
|
496
496
|
React.createElement('div', { className: 'cb-row' },
|
|
497
497
|
React.createElement('div', { className: 'cb-row-main' },
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { normalizeDisabled, normalizeRule, normalizeToolList, PRESETS, PRESET_IDS } from './groups.js'
|
|
2
|
+
|
|
3
|
+
export function createGateCommands(store, { audit, invalidate }) {
|
|
4
|
+
const settings = store.settings
|
|
5
|
+
function commit(candidate, entry) {
|
|
6
|
+
store.commit(candidate)
|
|
7
|
+
audit(entry)
|
|
8
|
+
invalidate()
|
|
9
|
+
}
|
|
10
|
+
return {
|
|
11
|
+
setHiddenGroups(groups) {
|
|
12
|
+
const disabledGroups = normalizeDisabled(groups, settings.userRules)
|
|
13
|
+
commit({ ...settings, disabledGroups, preset: 'custom' }, { op: 'set', disabled: disabledGroups })
|
|
14
|
+
},
|
|
15
|
+
setHiddenTools(names) {
|
|
16
|
+
const disabledToolNames = normalizeToolList(names)
|
|
17
|
+
commit({ ...settings, disabledToolNames, preset: 'custom' }, { op: 'tools-set', tools: disabledToolNames })
|
|
18
|
+
},
|
|
19
|
+
selectPreset(value) {
|
|
20
|
+
const preset = String(value || '').trim().toLowerCase()
|
|
21
|
+
if (!PRESET_IDS.includes(preset)) throw new Error('unknown preset: ' + preset)
|
|
22
|
+
const disabledGroups = normalizeDisabled(PRESETS[preset], settings.userRules)
|
|
23
|
+
commit({ ...settings, disabledGroups, preset }, { op: 'preset', preset, disabled: disabledGroups })
|
|
24
|
+
},
|
|
25
|
+
replaceGroupingRules(value) {
|
|
26
|
+
const userRules = (Array.isArray(value) ? value : []).map(normalizeRule).filter(Boolean)
|
|
27
|
+
const disabledGroups = normalizeDisabled(settings.disabledGroups, userRules)
|
|
28
|
+
commit({ ...settings, userRules, disabledGroups }, { op: 'rules-set', rules: userRules.map(rule => rule.id) })
|
|
29
|
+
},
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { deriveSuggestions, groupOf, isDisabled, labelOf, normalizeRules, toolHidden, PRESET_IDS, PROTECTED_TOOLS } from './groups.js'
|
|
2
|
+
|
|
3
|
+
const CHARS_PER_TOKEN = 3.4
|
|
4
|
+
|
|
5
|
+
export function tokensOf(value) {
|
|
6
|
+
try {
|
|
7
|
+
return Math.max(1, Math.ceil(JSON.stringify(value).length / CHARS_PER_TOKEN))
|
|
8
|
+
} catch {
|
|
9
|
+
return 0
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function buildGroupReport({ schemas, globalSchemas, catalog, disabledGroups, disabledToolNames, userRules, preset }) {
|
|
14
|
+
const globalNames = new Set(globalSchemas.map(schema => schema.name))
|
|
15
|
+
// A session-scoped report must describe that session's gate, not the global
|
|
16
|
+
// one: `hidden` flags, `saved` tokens and the returned `disabled` list all
|
|
17
|
+
// follow the effective gate of the agent that asked.
|
|
18
|
+
const viewDisabled = disabledGroups
|
|
19
|
+
const groups = new Map()
|
|
20
|
+
const ensure = (id, toggle = true) => {
|
|
21
|
+
if (!groups.has(id)) {
|
|
22
|
+
groups.set(id, {
|
|
23
|
+
id, label: labelOf(id, userRules), count: 0, tokens: 0, hideableTokens: 0, toggle, tools: [],
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
return groups.get(id)
|
|
27
|
+
}
|
|
28
|
+
for (const schema of schemas) {
|
|
29
|
+
const group = groupOf(schema.name, userRules)
|
|
30
|
+
const entry = ensure(group, group !== 'core')
|
|
31
|
+
const tokens = tokensOf(schema)
|
|
32
|
+
entry.count += 1
|
|
33
|
+
entry.tokens += tokens
|
|
34
|
+
// Per-tool rows feed the "one button per tool" list; cap keeps the status
|
|
35
|
+
// payload small when a plugin registers dozens of tools.
|
|
36
|
+
if (entry.tools.length < 80) {
|
|
37
|
+
entry.tools.push({ name: schema.name, tokens, hidden: toolHidden(schema.name, viewDisabled, disabledToolNames, userRules) })
|
|
38
|
+
}
|
|
39
|
+
if (globalNames.has(schema.name)) entry.hideableTokens += tokens
|
|
40
|
+
}
|
|
41
|
+
let catalogTokens = 0
|
|
42
|
+
if (catalog.length > 0) {
|
|
43
|
+
const entry = ensure('skills')
|
|
44
|
+
entry.skillCount = catalog.length
|
|
45
|
+
const catalogBytes = catalog.reduce((sum, item) => {
|
|
46
|
+
return sum + String(item?.name || '').length + String(item?.description || '').length
|
|
47
|
+
}, 0)
|
|
48
|
+
catalogTokens = Math.ceil(catalogBytes / CHARS_PER_TOKEN)
|
|
49
|
+
// `skill` schema itself is already counted above; add catalog text.
|
|
50
|
+
entry.tokens += catalogTokens
|
|
51
|
+
if (globalNames.has('skill')) entry.hideableTokens += catalogTokens
|
|
52
|
+
}
|
|
53
|
+
const list = [...groups.values()].sort((a, b) => {
|
|
54
|
+
if (a.id === 'core') return 1
|
|
55
|
+
if (b.id === 'core') return -1
|
|
56
|
+
if (a.id.startsWith('mcp:') !== b.id.startsWith('mcp:')) return a.id.startsWith('mcp:') ? -1 : 1
|
|
57
|
+
return b.tokens - a.tokens
|
|
58
|
+
})
|
|
59
|
+
const full = list.reduce((sum, item) => sum + item.tokens, 0)
|
|
60
|
+
const saved = list.filter(item => isDisabled(item.id, viewDisabled))
|
|
61
|
+
.reduce((sum, item) => sum + item.hideableTokens, 0)
|
|
62
|
+
const scoped = schemas.filter(schema => !globalNames.has(schema.name)
|
|
63
|
+
&& schema.name.startsWith('mcp__')).length
|
|
64
|
+
const allNames = new Set(schemas.map(schema => schema.name))
|
|
65
|
+
return {
|
|
66
|
+
groups: list,
|
|
67
|
+
totals: { full, current: Math.max(0, full - saved), saved },
|
|
68
|
+
disabled: [...viewDisabled],
|
|
69
|
+
disabledTools: [...disabledToolNames],
|
|
70
|
+
// Names in the exact list that no longer exist: a typo, or a plugin that
|
|
71
|
+
// went away. Surfaced instead of failing silently.
|
|
72
|
+
unknownTools: disabledToolNames.filter(name => !allNames.has(name)),
|
|
73
|
+
preset: preset,
|
|
74
|
+
presets: PRESET_IDS,
|
|
75
|
+
rules: normalizeRules(userRules).map(rule => ({ id: rule.id, prefixes: rule.prefixes, ...(rule.exact ? { exact: rule.exact } : {}), ...(rule.label ? { label: rule.label } : {}) })),
|
|
76
|
+
suggestions: deriveSuggestions(schemas.map(schema => schema.name), userRules),
|
|
77
|
+
protectedTools: [...PROTECTED_TOOLS],
|
|
78
|
+
catalogTokens,
|
|
79
|
+
scoped,
|
|
80
|
+
skills: { count: catalog.length },
|
|
81
|
+
}
|
|
82
|
+
}
|
package/lib/groups.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// v0.2 — groups are data, not code:
|
|
5
5
|
// * `DEFAULT_RULES` ships the built-in buckets (ego / remote / watch / team …)
|
|
6
6
|
// * `toolgate.json` may add or override rules by id
|
|
7
|
-
// *
|
|
7
|
+
// * unmatched tools land in `core`; group toggles never hide this fallback bucket
|
|
8
8
|
// * `deriveSuggestions()` proposes groups for ungrouped prefixes, so a new
|
|
9
9
|
// plugin's tools show up as a suggestion instead of silently joining core
|
|
10
10
|
|
|
@@ -22,10 +22,13 @@ export const FIXED_LABELS = {
|
|
|
22
22
|
export const CORE_LABEL = '核心工具'
|
|
23
23
|
|
|
24
24
|
/** Never hideable, whatever the config says. Hiding pwsh or the tool itself
|
|
25
|
-
* locks the session out of its own escape hatch.
|
|
25
|
+
* locks the session out of its own escape hatch.
|
|
26
|
+
* `apply_patch` (DSH 0.2.2+) is the multi-file equivalent of write/edit, so it
|
|
27
|
+
* belongs to the same escape-hatch class: hiding it would leave the model with
|
|
28
|
+
* a "protected" write path that still cannot create or delete files. */
|
|
26
29
|
export const PROTECTED_TOOLS = Object.freeze([
|
|
27
|
-
'read', 'write', 'edit', 'glob', 'grep', 'pwsh', 'present',
|
|
28
|
-
'toolgate', 'ask_user_question',
|
|
30
|
+
'read', 'write', 'edit', 'apply_patch', 'glob', 'grep', 'pwsh', 'present',
|
|
31
|
+
'todo_write', 'toolgate', 'ask_user_question',
|
|
29
32
|
])
|
|
30
33
|
|
|
31
34
|
/**
|
|
@@ -182,10 +185,15 @@ export function matchesDisabled(toolName, disabled, rules) {
|
|
|
182
185
|
return isDisabled(groupOf(toolName, rules), disabled)
|
|
183
186
|
}
|
|
184
187
|
|
|
185
|
-
/**
|
|
188
|
+
/** Protection is independent of the fallback display group. */
|
|
189
|
+
export function isProtectedTool(toolName) {
|
|
190
|
+
return PROTECTED_TOOLS.includes(toolName)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** True when this tool is hidden by its group or exact name. */
|
|
186
194
|
export function toolHidden(toolName, disabled, disabledTools, rules) {
|
|
187
195
|
const name = String(toolName || '')
|
|
188
|
-
if (
|
|
196
|
+
if (isProtectedTool(name)) return false
|
|
189
197
|
if (Array.isArray(disabledTools) && disabledTools.includes(name)) return true
|
|
190
198
|
return matchesDisabled(name, disabled, rules)
|
|
191
199
|
}
|
package/lib/index.js
CHANGED
|
@@ -1,6 +1,3 @@
|
|
|
1
|
-
import fs from 'node:fs'
|
|
2
|
-
import path from 'node:path'
|
|
3
|
-
import { randomUUID } from 'node:crypto'
|
|
4
1
|
import z from '@deepseek-ai/schemastery'
|
|
5
2
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
6
3
|
|
|
@@ -9,20 +6,18 @@ export const inject = ['tools', 'skills', 'webServer']
|
|
|
9
6
|
export const Config = z.object({ allowSessionOverride: z.boolean().default(true) })
|
|
10
7
|
|
|
11
8
|
import {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
PRESETS, PRESET_IDS, PROTECTED_TOOLS,
|
|
9
|
+
isDisabled, isProtectedTool, normalizeDisabled, normalizeRules, shouldApplyGate, toolHidden,
|
|
10
|
+
PRESET_IDS,
|
|
15
11
|
} from './groups.js'
|
|
16
12
|
import { requestArgs } from './api-payload.js'
|
|
17
13
|
import { appendAudit } from './audit.js'
|
|
18
14
|
import { createMcpConfig, publicServers } from './mcp-config.js'
|
|
19
|
-
import { hostPaths } from './host-paths.js'
|
|
15
|
+
import { hostPaths, serviceOn } from './host-paths.js'
|
|
16
|
+
import { createSettingsStore } from './settings-store.js'
|
|
17
|
+
import { createGateCommands } from './gate-commands.js'
|
|
18
|
+
import { buildGroupReport, tokensOf } from './group-report.js'
|
|
20
19
|
import { installSkills } from './skills-runtime.js'
|
|
21
20
|
|
|
22
|
-
// Conservative, serialized-schema based estimate. It is deliberately labelled
|
|
23
|
-
// approximate in the UI; the real number comes from the provider tokenizer.
|
|
24
|
-
const CHARS_PER_TOKEN = 3.4
|
|
25
|
-
|
|
26
21
|
export async function apply(ctx, config = {}) {
|
|
27
22
|
// Prompt-injected traffic reaches the model tool; `false` lets a profile pin
|
|
28
23
|
// the global gate so only the authenticated settings page can change it.
|
|
@@ -42,13 +37,9 @@ export async function apply(ctx, config = {}) {
|
|
|
42
37
|
}
|
|
43
38
|
mcp = createMcpConfig(options)
|
|
44
39
|
} catch (error) { mcpError = '无法读取宿主 profile:' + error.message }
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
rules: [],
|
|
49
|
-
preset: 'custom',
|
|
50
|
-
disabledSkills: [],
|
|
51
|
-
skillRules: [],
|
|
40
|
+
const store = createSettingsStore(locations.home)
|
|
41
|
+
const settings = store.settings
|
|
42
|
+
const runtime = {
|
|
52
43
|
disposed: false,
|
|
53
44
|
timers: new Set(),
|
|
54
45
|
overrides: new Map(),
|
|
@@ -59,64 +50,10 @@ export async function apply(ctx, config = {}) {
|
|
|
59
50
|
// Counts/tokens for the full agent-visible tool set. The root tools view
|
|
60
51
|
// only contains global registrations; preset-scoped core tools are only
|
|
61
52
|
// visible through an agent, so the first real request records the full set.
|
|
62
|
-
|
|
53
|
+
referenceSchemas: null,
|
|
63
54
|
}
|
|
64
|
-
const stateFile = path.join(locations.home, 'toolgate.json')
|
|
65
55
|
const rootCtx = ctx
|
|
66
56
|
|
|
67
|
-
function loadState() {
|
|
68
|
-
const legacyFile = stateFile.replace(/toolgate\.json$/, 'context-budget.json')
|
|
69
|
-
for (const file of [stateFile, legacyFile]) {
|
|
70
|
-
try {
|
|
71
|
-
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
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'
|
|
77
|
-
state.disabledSkills = Array.isArray(parsed?.disabledSkills)
|
|
78
|
-
? parsed.disabledSkills.filter(name => typeof name === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))
|
|
79
|
-
: []
|
|
80
|
-
state.skillRules = Array.isArray(parsed?.skillRules) ? parsed.skillRules.filter(rule => rule && typeof rule.key === 'string' && typeof rule.identity === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(rule.name) && (rule.cwd === null || typeof rule.cwd === 'string')) : []
|
|
81
|
-
if (file !== stateFile) saveState()
|
|
82
|
-
return
|
|
83
|
-
} catch { /* try the legacy file, then reset */ }
|
|
84
|
-
}
|
|
85
|
-
state.disabled = []
|
|
86
|
-
state.disabledTools = []
|
|
87
|
-
state.rules = []
|
|
88
|
-
state.preset = 'custom'
|
|
89
|
-
state.disabledSkills = []
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
function saveState() {
|
|
93
|
-
const tmp = stateFile + '.' + randomUUID() + '.tmp'
|
|
94
|
-
try {
|
|
95
|
-
fs.mkdirSync(path.dirname(stateFile), { recursive: true })
|
|
96
|
-
fs.writeFileSync(tmp, JSON.stringify({
|
|
97
|
-
disabled: state.disabled,
|
|
98
|
-
disabledTools: state.disabledTools,
|
|
99
|
-
rules: state.rules,
|
|
100
|
-
preset: state.preset,
|
|
101
|
-
disabledSkills: state.disabledSkills,
|
|
102
|
-
skillRules: state.skillRules,
|
|
103
|
-
}, null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 })
|
|
104
|
-
fs.renameSync(tmp, stateFile)
|
|
105
|
-
} catch (err) {
|
|
106
|
-
throw new Error('无法保存 Toolgate 设置:' + (err?.message || err))
|
|
107
|
-
} finally {
|
|
108
|
-
if (fs.existsSync(tmp)) fs.unlinkSync(tmp)
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
function tokensOf(value) {
|
|
113
|
-
try {
|
|
114
|
-
return Math.max(1, Math.ceil(JSON.stringify(value).length / CHARS_PER_TOKEN))
|
|
115
|
-
} catch {
|
|
116
|
-
return 0
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
57
|
function fmt(n) {
|
|
121
58
|
const v = Number(n) || 0
|
|
122
59
|
if (v >= 10000) return (v / 10000).toFixed(1) + '万'
|
|
@@ -135,161 +72,91 @@ export async function apply(ctx, config = {}) {
|
|
|
135
72
|
}
|
|
136
73
|
|
|
137
74
|
async function groupReport(ctx, agent) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
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
|
-
}
|
|
151
|
-
return groups.get(id)
|
|
152
|
-
}
|
|
153
|
-
for (const schema of schemas) {
|
|
154
|
-
const group = groupOf(schema.name, state.rules)
|
|
155
|
-
const entry = ensure(group, group !== 'core')
|
|
156
|
-
const tokens = tokensOf(schema)
|
|
157
|
-
entry.count += 1
|
|
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
|
|
165
|
-
}
|
|
166
|
-
const catalog = await skillCatalog(ctx, agent)
|
|
167
|
-
let catalogTokens = 0
|
|
168
|
-
if (catalog.length > 0) {
|
|
169
|
-
const entry = ensure('skills')
|
|
170
|
-
entry.skillCount = catalog.length
|
|
171
|
-
const catalogBytes = catalog.reduce((sum, item) => {
|
|
172
|
-
return sum + String(item?.name || '').length + String(item?.description || '').length
|
|
173
|
-
}, 0)
|
|
174
|
-
catalogTokens = Math.ceil(catalogBytes / CHARS_PER_TOKEN)
|
|
175
|
-
// `skill` schema itself is already counted above; add catalog text.
|
|
176
|
-
entry.tokens += catalogTokens
|
|
177
|
-
if (globalNames.has('skill')) entry.hideableTokens += catalogTokens
|
|
178
|
-
}
|
|
179
|
-
const list = [...groups.values()].sort((a, b) => {
|
|
180
|
-
if (a.id === 'core') return 1
|
|
181
|
-
if (b.id === 'core') return -1
|
|
182
|
-
if (a.id.startsWith('mcp:') !== b.id.startsWith('mcp:')) return a.id.startsWith('mcp:') ? -1 : 1
|
|
183
|
-
return b.tokens - a.tokens
|
|
75
|
+
return buildGroupReport({
|
|
76
|
+
schemas: runtime.referenceSchemas || ctx.tools.schemas(),
|
|
77
|
+
globalSchemas: ctx.tools.schemas(),
|
|
78
|
+
catalog: await skillCatalog(ctx, agent),
|
|
79
|
+
disabledGroups: agent ? effectiveDisabled(agent) : settings.disabledGroups,
|
|
80
|
+
disabledToolNames: settings.disabledToolNames,
|
|
81
|
+
userRules: settings.userRules,
|
|
82
|
+
preset: settings.preset,
|
|
184
83
|
})
|
|
185
|
-
const full = list.reduce((sum, item) => sum + item.tokens, 0)
|
|
186
|
-
const saved = list.filter(item => isDisabled(item.id, viewDisabled))
|
|
187
|
-
.reduce((sum, item) => sum + item.hideableTokens, 0)
|
|
188
|
-
const scoped = schemas.filter(schema => !globalNames.has(schema.name)
|
|
189
|
-
&& schema.name.startsWith('mcp__')).length
|
|
190
|
-
const allNames = new Set(schemas.map(schema => schema.name))
|
|
191
|
-
return {
|
|
192
|
-
groups: list,
|
|
193
|
-
totals: { full, current: Math.max(0, full - saved), saved },
|
|
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],
|
|
204
|
-
catalogTokens,
|
|
205
|
-
scoped,
|
|
206
|
-
skills: { count: catalog.length },
|
|
207
|
-
}
|
|
208
84
|
}
|
|
209
85
|
|
|
210
86
|
function sessionIdOf(agent) {
|
|
211
87
|
return String(agent?.session?.id || agent?.sessionId || agent?.id || 'anonymous')
|
|
212
88
|
}
|
|
213
89
|
|
|
214
|
-
function serviceOn(agentCtx, service) {
|
|
215
|
-
try {
|
|
216
|
-
if (agentCtx && typeof agentCtx.get === 'function') return agentCtx.get(service)
|
|
217
|
-
return agentCtx?.[service]
|
|
218
|
-
} catch {
|
|
219
|
-
return undefined
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
|
|
223
90
|
function effectiveDisabled(agent) {
|
|
224
91
|
const sid = sessionIdOf(agent)
|
|
225
|
-
return
|
|
92
|
+
return runtime.overrides.has(sid) ? runtime.overrides.get(sid) : settings.disabledGroups
|
|
226
93
|
}
|
|
227
94
|
|
|
228
95
|
function applyToAgent(agent) {
|
|
229
96
|
const ag = agent?.agent ?? agent
|
|
230
|
-
if (
|
|
97
|
+
if (runtime.disposed || !ag || !ag.ctx) return
|
|
231
98
|
const sid = sessionIdOf(ag)
|
|
232
|
-
if (
|
|
99
|
+
if (runtime.stale) {
|
|
233
100
|
clearApplied()
|
|
234
|
-
|
|
101
|
+
runtime.stale = false
|
|
235
102
|
}
|
|
236
|
-
if (!
|
|
103
|
+
if (!runtime.referenceSchemas) {
|
|
237
104
|
try {
|
|
238
105
|
const visible = rootCtx.tools.schemas(ag)
|
|
239
|
-
if (Array.isArray(visible) && visible.length > 0)
|
|
106
|
+
if (Array.isArray(visible) && visible.length > 0) runtime.referenceSchemas = visible
|
|
240
107
|
} catch { /* tool view not ready yet */ }
|
|
241
108
|
} else {
|
|
242
109
|
try {
|
|
243
110
|
const visible = rootCtx.tools.schemas(ag)
|
|
244
|
-
if (Array.isArray(visible) && visible.length >
|
|
111
|
+
if (Array.isArray(visible) && visible.length > runtime.referenceSchemas.length) runtime.referenceSchemas = visible
|
|
245
112
|
} catch { /* tool view not ready yet */ }
|
|
246
113
|
}
|
|
247
114
|
const disabled = effectiveDisabled(ag)
|
|
248
|
-
const key = disabled.slice().sort().join(',') + '|' +
|
|
249
|
-
const previous =
|
|
115
|
+
const key = disabled.slice().sort().join(',') + '|' + settings.disabledToolNames.slice().sort().join(',') + '|' + normalizeRules(settings.userRules).length
|
|
116
|
+
const previous = runtime.applied.get(ag)
|
|
250
117
|
if (previous && previous.key === key) return
|
|
251
118
|
if (previous) {
|
|
252
|
-
|
|
253
|
-
try { previous.dispose() } catch { /* stale agent scope */ } finally {
|
|
254
|
-
|
|
119
|
+
runtime.applying = true
|
|
120
|
+
try { previous.dispose() } catch { /* stale agent scope */ } finally { runtime.applying = false }
|
|
121
|
+
runtime.applied.delete(ag)
|
|
255
122
|
}
|
|
256
123
|
// Both halves of the gate matter: an empty group list with a non-empty
|
|
257
124
|
// exact-tool list must still reach restrict(), otherwise the per-tool
|
|
258
125
|
// buttons update the file and change nothing in the prompt.
|
|
259
|
-
if (!shouldApplyGate(disabled,
|
|
260
|
-
|
|
126
|
+
if (!shouldApplyGate(disabled, settings.disabledToolNames)) {
|
|
127
|
+
runtime.errors.delete(sid)
|
|
261
128
|
return
|
|
262
129
|
}
|
|
263
130
|
const agentTools = serviceOn(ag.ctx, 'tools')
|
|
264
131
|
if (!agentTools || typeof agentTools.restrict !== 'function') {
|
|
265
|
-
|
|
132
|
+
runtime.errors.set(sid, 'agent ctx has no restrictable tools service')
|
|
266
133
|
return
|
|
267
134
|
}
|
|
268
135
|
const full = rootCtx.tools.schemas()
|
|
269
|
-
const deny = full.map(schema => schema.name).filter(n => toolHidden(n, disabled,
|
|
136
|
+
const deny = full.map(schema => schema.name).filter(n => toolHidden(n, disabled, settings.disabledToolNames, settings.userRules))
|
|
270
137
|
if (deny.length === 0) return
|
|
271
|
-
|
|
138
|
+
runtime.applying = true
|
|
272
139
|
try {
|
|
273
140
|
const dispose = agentTools.restrict({ deny })
|
|
274
|
-
|
|
275
|
-
|
|
141
|
+
runtime.applied.set(ag, { key, dispose })
|
|
142
|
+
runtime.errors.delete(sid)
|
|
276
143
|
} catch (err) {
|
|
277
|
-
|
|
144
|
+
runtime.errors.set(sid, String(err?.message || err))
|
|
278
145
|
} finally {
|
|
279
|
-
|
|
146
|
+
runtime.applying = false
|
|
280
147
|
}
|
|
281
148
|
}
|
|
282
149
|
|
|
283
150
|
function clearApplied() {
|
|
284
|
-
|
|
151
|
+
runtime.applying = true
|
|
285
152
|
try {
|
|
286
|
-
for (const entry of
|
|
153
|
+
for (const entry of runtime.applied.values()) {
|
|
287
154
|
try { entry.dispose() } catch { /* agent may already be gone */ }
|
|
288
155
|
}
|
|
289
|
-
|
|
290
|
-
|
|
156
|
+
runtime.applied.clear()
|
|
157
|
+
runtime.errors.clear()
|
|
291
158
|
} finally {
|
|
292
|
-
|
|
159
|
+
runtime.applying = false
|
|
293
160
|
}
|
|
294
161
|
}
|
|
295
162
|
|
|
@@ -307,7 +174,7 @@ export async function apply(ctx, config = {}) {
|
|
|
307
174
|
if (visible.some(schema => schema.name === 'skill')) current += full.catalogTokens
|
|
308
175
|
} catch { /* fall back to global estimate */ }
|
|
309
176
|
}
|
|
310
|
-
const overridden =
|
|
177
|
+
const overridden = runtime.overrides.has(sessionIdOf(agent))
|
|
311
178
|
const disabled = effectiveDisabled(agent)
|
|
312
179
|
const lines = []
|
|
313
180
|
lines.push('Toolgate' + (overridden ? '(本会话覆盖)' : ''))
|
|
@@ -347,19 +214,19 @@ export async function apply(ctx, config = {}) {
|
|
|
347
214
|
})
|
|
348
215
|
}
|
|
349
216
|
|
|
350
|
-
loadState()
|
|
351
217
|
ctx.effect(() => () => {
|
|
352
|
-
|
|
353
|
-
for (const timer of
|
|
354
|
-
|
|
218
|
+
runtime.disposed = true
|
|
219
|
+
for (const timer of runtime.timers) clearTimeout(timer)
|
|
220
|
+
runtime.timers.clear()
|
|
355
221
|
clearApplied()
|
|
356
|
-
|
|
357
|
-
|
|
222
|
+
runtime.overrides.clear()
|
|
223
|
+
runtime.referenceSchemas = null
|
|
358
224
|
})
|
|
359
|
-
const skillManager = installSkills(ctx,
|
|
225
|
+
const skillManager = installSkills(ctx, settings, locations, store.save)
|
|
360
226
|
const audit = entry => {
|
|
361
227
|
if (!appendAudit(locations.home, entry)) ctx.logger?.warn?.('Toolgate audit log write failed for %s', entry.op)
|
|
362
228
|
}
|
|
229
|
+
const commands = createGateCommands(store, { audit, invalidate: clearApplied })
|
|
363
230
|
const auditTarget = (op, args) => op === 'mcp-add' || op === 'mcp-edit'
|
|
364
231
|
? String(args.row?.id || args.row?.serverName || '')
|
|
365
232
|
: String(args.id || args.name || '')
|
|
@@ -411,13 +278,13 @@ export async function apply(ctx, config = {}) {
|
|
|
411
278
|
return '会话级覆盖已被宿主设置禁用(allowSessionOverride=false);全局工具闸门只能在 设置 → 工具闸门 中修改。\n\n' + await reportFor(agent)
|
|
412
279
|
}
|
|
413
280
|
if (action === 'reset') {
|
|
414
|
-
|
|
281
|
+
runtime.overrides.delete(sid)
|
|
415
282
|
applyToAgent(agent)
|
|
416
283
|
return '已恢复全局工具闸门。\n\n' + await reportFor(agent)
|
|
417
284
|
}
|
|
418
285
|
if (action === 'session') {
|
|
419
|
-
const disabled = normalizeDisabled(args.disabled,
|
|
420
|
-
|
|
286
|
+
const disabled = normalizeDisabled(args.disabled, settings.userRules)
|
|
287
|
+
runtime.overrides.set(sid, disabled)
|
|
421
288
|
applyToAgent(agent)
|
|
422
289
|
return '已应用本会话覆盖:' + (disabled.length ? disabled.join(', ') : '全部显示') +
|
|
423
290
|
'\n\n' + await reportFor(agent)
|
|
@@ -428,40 +295,16 @@ export async function apply(ctx, config = {}) {
|
|
|
428
295
|
return '未知预设 "' + name + '"。可选:' + PRESET_IDS.join(' / ') +
|
|
429
296
|
'\n\n' + await reportFor(agent)
|
|
430
297
|
}
|
|
431
|
-
|
|
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()
|
|
298
|
+
try { commands.selectPreset(name) } catch (error) { return '保存失败:' + (error?.message || error) }
|
|
444
299
|
applyToAgent(agent)
|
|
445
|
-
return '已切换到 ' + name + ' 档(全局):' + (
|
|
300
|
+
return '已切换到 ' + name + ' 档(全局):' + (settings.disabledGroups.length ? settings.disabledGroups.join(', ') : '全部显示') +
|
|
446
301
|
'\n\n' + await reportFor(agent)
|
|
447
302
|
}
|
|
448
303
|
if (action === 'tools') {
|
|
449
|
-
|
|
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()
|
|
304
|
+
try { commands.setHiddenTools(args.tools) } catch (error) { return '保存失败:' + (error?.message || error) }
|
|
462
305
|
applyToAgent(agent)
|
|
463
|
-
return '已隐藏 ' +
|
|
464
|
-
(
|
|
306
|
+
return '已隐藏 ' + settings.disabledToolNames.length + ' 个具体工具:' +
|
|
307
|
+
(settings.disabledToolNames.length ? settings.disabledToolNames.join(', ') : '无') +
|
|
465
308
|
'\n\n' + await reportFor(agent)
|
|
466
309
|
}
|
|
467
310
|
return 'Unknown action "' + action + '". Use status, session, reset, preset or tools.'
|
|
@@ -478,11 +321,11 @@ export async function apply(ctx, config = {}) {
|
|
|
478
321
|
const disposeGuard = ctx.tools.guard((execution) => {
|
|
479
322
|
const name = execution?.name
|
|
480
323
|
if (typeof name !== 'string' || name === '') return undefined
|
|
481
|
-
if (
|
|
324
|
+
if (isProtectedTool(name)) return undefined
|
|
482
325
|
const agent = execution?.agent
|
|
483
326
|
const disabled = effectiveDisabled(agent)
|
|
484
|
-
if (!toolHidden(name, disabled,
|
|
485
|
-
const scope =
|
|
327
|
+
if (!toolHidden(name, disabled, settings.disabledToolNames, settings.userRules)) return undefined
|
|
328
|
+
const scope = runtime.overrides.has(sessionIdOf(agent)) ? '本会话' : '全局'
|
|
486
329
|
return `"${name}" 已被 Toolgate 的${scope}闸门隐藏。用 toolgate action=status 查看分组与当前闸门,或在 设置 → 工具闸门 里打开它。`
|
|
487
330
|
})
|
|
488
331
|
ctx.effect(() => () => { try { disposeGuard?.() } catch { /* agent scope gone */ } })
|
|
@@ -507,12 +350,12 @@ export async function apply(ctx, config = {}) {
|
|
|
507
350
|
ctx.on('agent/created', (agent) => {
|
|
508
351
|
try { applyToAgent(agent) } catch { /* tools not installed yet */ }
|
|
509
352
|
const timer = setTimeout(() => {
|
|
510
|
-
|
|
353
|
+
runtime.timers.delete(timer)
|
|
511
354
|
try { applyToAgent(agent) } catch (err) {
|
|
512
355
|
console.warn('[dsh-toolgate] child apply failed:', err?.message || err)
|
|
513
356
|
}
|
|
514
357
|
}, 0)
|
|
515
|
-
|
|
358
|
+
runtime.timers.add(timer)
|
|
516
359
|
if (typeof timer?.unref === 'function') timer.unref()
|
|
517
360
|
})
|
|
518
361
|
|
|
@@ -527,17 +370,17 @@ export async function apply(ctx, config = {}) {
|
|
|
527
370
|
// restriction on the next step; ignore the events caused by our own
|
|
528
371
|
// restrict()/dispose() calls to avoid a churn loop.
|
|
529
372
|
ctx.on('tools/change', () => {
|
|
530
|
-
if (
|
|
531
|
-
|
|
532
|
-
|
|
373
|
+
if (runtime.applying) return
|
|
374
|
+
runtime.stale = true
|
|
375
|
+
runtime.referenceSchemas = null
|
|
533
376
|
})
|
|
534
377
|
|
|
535
378
|
ctx.on('agent/disposed', ({ agent }) => {
|
|
536
|
-
const applied =
|
|
537
|
-
if (applied) {
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
379
|
+
const applied = runtime.applied.get(agent)
|
|
380
|
+
if (applied) { runtime.applying = true; try { applied.dispose() } finally { runtime.applying = false } }
|
|
381
|
+
runtime.applied.delete(agent)
|
|
382
|
+
runtime.errors.delete(sessionIdOf(agent))
|
|
383
|
+
runtime.overrides.delete(sessionIdOf(agent))
|
|
541
384
|
})
|
|
542
385
|
|
|
543
386
|
const webServer = ctx.webServer ?? (() => { try { return ctx.get('webServer') } catch { return undefined } })()
|
|
@@ -570,46 +413,15 @@ export async function apply(ctx, config = {}) {
|
|
|
570
413
|
op = String(payload.op || '')
|
|
571
414
|
const args = requestArgs(payload)
|
|
572
415
|
if (op === 'status') return send(200, { ok: true, ...(await groupReport(ctx)),
|
|
573
|
-
applied: [...
|
|
574
|
-
if (op === 'set')
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
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()
|
|
416
|
+
applied: [...runtime.applied.keys()].map(sessionIdOf), errors: Object.fromEntries(runtime.errors) })
|
|
417
|
+
if (op === 'set') commands.setHiddenGroups(args.disabled)
|
|
418
|
+
else if (op === 'preset') {
|
|
419
|
+
const preset = String(args.preset || '').trim().toLowerCase()
|
|
420
|
+
if (!PRESET_IDS.includes(preset)) return send(400, { ok: false, error: 'unknown preset: ' + preset })
|
|
421
|
+
commands.selectPreset(preset)
|
|
422
|
+
} else if (op === 'tools-set') commands.setHiddenTools(args.tools)
|
|
423
|
+
else if (op === 'rules-set') commands.replaceGroupingRules(args.rules)
|
|
424
|
+
if (['set', 'preset', 'tools-set', 'rules-set'].includes(op)) {
|
|
613
425
|
return send(200, { ok: true, ...(await groupReport(ctx)) })
|
|
614
426
|
}
|
|
615
427
|
if (op.startsWith('mcp-')) {
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import { normalizeDisabled, normalizeRule, normalizeToolList, PRESET_IDS } from './groups.js'
|
|
5
|
+
|
|
6
|
+
function decodeSettings(value) {
|
|
7
|
+
const userRules = Array.isArray(value?.rules) ? value.rules.map(normalizeRule).filter(Boolean) : []
|
|
8
|
+
return {
|
|
9
|
+
disabledGroups: normalizeDisabled(value?.disabled, userRules),
|
|
10
|
+
disabledToolNames: normalizeToolList(value?.disabledTools),
|
|
11
|
+
userRules,
|
|
12
|
+
preset: PRESET_IDS.includes(value?.preset) ? value.preset : 'custom',
|
|
13
|
+
disabledSkills: Array.isArray(value?.disabledSkills)
|
|
14
|
+
? value.disabledSkills.filter(name => typeof name === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) : [],
|
|
15
|
+
skillRules: Array.isArray(value?.skillRules) ? value.skillRules.filter(rule => rule
|
|
16
|
+
&& typeof rule.key === 'string' && typeof rule.identity === 'string'
|
|
17
|
+
&& /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(rule.name)
|
|
18
|
+
&& (rule.cwd === null || typeof rule.cwd === 'string')) : [],
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Disk keys remain compatible with existing toolgate.json files.
|
|
23
|
+
function encodeSettings(settings) {
|
|
24
|
+
return {
|
|
25
|
+
disabled: settings.disabledGroups,
|
|
26
|
+
disabledTools: settings.disabledToolNames,
|
|
27
|
+
rules: settings.userRules,
|
|
28
|
+
preset: settings.preset,
|
|
29
|
+
disabledSkills: settings.disabledSkills,
|
|
30
|
+
skillRules: settings.skillRules,
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function createSettingsStore(home) {
|
|
35
|
+
const file = path.join(home, 'toolgate.json')
|
|
36
|
+
const settings = decodeSettings({})
|
|
37
|
+
function save(candidate = settings) {
|
|
38
|
+
const temporary = file + '.' + randomUUID() + '.tmp'
|
|
39
|
+
try {
|
|
40
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
41
|
+
fs.writeFileSync(temporary, JSON.stringify(encodeSettings(candidate), null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 })
|
|
42
|
+
fs.renameSync(temporary, file)
|
|
43
|
+
} catch (error) {
|
|
44
|
+
throw new Error('无法保存 Toolgate 设置:' + (error?.message || error))
|
|
45
|
+
} finally {
|
|
46
|
+
if (fs.existsSync(temporary)) fs.unlinkSync(temporary)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
for (const source of [file, path.join(home, 'context-budget.json')]) {
|
|
50
|
+
try {
|
|
51
|
+
const loaded = decodeSettings(JSON.parse(fs.readFileSync(source, 'utf8')))
|
|
52
|
+
if (source !== file) save(loaded)
|
|
53
|
+
Object.assign(settings, loaded)
|
|
54
|
+
break
|
|
55
|
+
} catch { /* unavailable or invalid settings retain defaults or the legacy source */ }
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
settings,
|
|
59
|
+
save,
|
|
60
|
+
commit(candidate) {
|
|
61
|
+
// Readers keep the same object; failed persistence never publishes new settings.
|
|
62
|
+
save(candidate)
|
|
63
|
+
Object.assign(settings, candidate)
|
|
64
|
+
},
|
|
65
|
+
}
|
|
66
|
+
}
|
package/lib/skills-runtime.js
CHANGED
|
@@ -6,7 +6,7 @@ const identity = skill => JSON.stringify([skill.name, skill.provider, skill.path
|
|
|
6
6
|
|
|
7
7
|
// Discovery remains the registry's job. The provider returns only previously
|
|
8
8
|
// resolved definitions, so it never recursively calls skills.get() from list().
|
|
9
|
-
export function installSkills(ctx,
|
|
9
|
+
export function installSkills(ctx, settings, locations, save) {
|
|
10
10
|
let control, disposed = false
|
|
11
11
|
const definitions = new Map()
|
|
12
12
|
const optionsFor = view => ({ ...(view.cwd ? { cwd: view.cwd } : {}), ...(view.scope ? { scope: view.scope } : {}) })
|
|
@@ -33,21 +33,21 @@ export function installSkills(ctx, state, locations, save) {
|
|
|
33
33
|
return true
|
|
34
34
|
}
|
|
35
35
|
const ready = (async () => {
|
|
36
|
-
for (const rule of
|
|
36
|
+
for (const rule of settings.skillRules) {
|
|
37
37
|
try { await resolve(rule, { cwd: rule.cwd || locations.workspace }) } catch { /* unavailable provider stays unresolved */ }
|
|
38
38
|
}
|
|
39
39
|
// Resolve legacy global names once; persist concrete identities instead of
|
|
40
40
|
// accidentally suppressing a different same-name project skill forever.
|
|
41
|
-
const migrated =
|
|
42
|
-
for (const name of
|
|
41
|
+
const migrated = settings.disabledSkills.length > 0
|
|
42
|
+
for (const name of settings.disabledSkills) {
|
|
43
43
|
const def = await ctx.skills.get(name, { cwd: locations.workspace || undefined })
|
|
44
44
|
if (!def || disposed) continue
|
|
45
45
|
const rule = { name, identity: identity(def), cwd: def.source.startsWith('project') ? projectRoot(locations.workspace) : null }
|
|
46
46
|
rule.key = JSON.stringify([rule.identity, rule.cwd])
|
|
47
|
-
if (!
|
|
47
|
+
if (!settings.skillRules.some(existing => existing.key === rule.key)) settings.skillRules.push(rule)
|
|
48
48
|
await resolve(rule, { cwd: rule.cwd || locations.workspace })
|
|
49
49
|
}
|
|
50
|
-
if (!disposed) { control.invalidate();
|
|
50
|
+
if (!disposed) { control.invalidate(); settings.disabledSkills = []; if (migrated) save() }
|
|
51
51
|
})()
|
|
52
52
|
// Keep initialization failures observable through list/write requests while
|
|
53
53
|
// preventing a provider failure from becoming an unhandled rejection.
|
|
@@ -58,7 +58,7 @@ export function installSkills(ctx, state, locations, save) {
|
|
|
58
58
|
refreshing = true
|
|
59
59
|
void ready.then(async () => {
|
|
60
60
|
let changed = false
|
|
61
|
-
for (const rule of
|
|
61
|
+
for (const rule of settings.skillRules) {
|
|
62
62
|
if (disposed || definitions.has(rule.key)) continue
|
|
63
63
|
changed = await resolve(rule, { cwd: rule.cwd || locations.workspace }) || changed
|
|
64
64
|
}
|
|
@@ -74,7 +74,7 @@ export function installSkills(ctx, state, locations, save) {
|
|
|
74
74
|
const row = source ? { ...summary, provider: source[1], path: source[2], source: source[3] } : summary
|
|
75
75
|
const global = await ctx.skills.get(row.name, { cwd: view.cwd })
|
|
76
76
|
const rootMatches = global?.provider === OVERRIDE ? !!cached : !!global && identity(global) === identity(row)
|
|
77
|
-
const rule =
|
|
77
|
+
const rule = settings.skillRules.find(rule => rule.identity === identity(row) && applies(rule, view))
|
|
78
78
|
rows.push({ name: row.name, description: row.description || '', provider: row.provider, path: row.path || null, source: row.source,
|
|
79
79
|
scope: row.source.startsWith('project') ? 'project' : 'user', disabled: !!rule,
|
|
80
80
|
toggleable: rootMatches, deletable: canDeleteSkill(row, { home: locations.home, cwd: view.projectRoot }),
|
|
@@ -99,17 +99,17 @@ export function installSkills(ctx, state, locations, save) {
|
|
|
99
99
|
const cwd = row.source.startsWith('project') ? view.projectRoot : null
|
|
100
100
|
const rule = { name: row.name, identity: identity(row), cwd }
|
|
101
101
|
rule.key = JSON.stringify([rule.identity, cwd])
|
|
102
|
-
const previousRules = [...
|
|
102
|
+
const previousRules = [...settings.skillRules]
|
|
103
103
|
const previousDefinition = definitions.get(rule.key)
|
|
104
104
|
if (args.enabled !== false) {
|
|
105
|
-
|
|
105
|
+
settings.skillRules = settings.skillRules.filter(existing => existing.key !== rule.key)
|
|
106
106
|
definitions.delete(rule.key)
|
|
107
|
-
} else if (!
|
|
107
|
+
} else if (!settings.skillRules.some(existing => existing.key === rule.key)) {
|
|
108
108
|
if (!await resolve(rule, view)) throw new Error('Skill 来源已变化,请刷新后重试')
|
|
109
|
-
|
|
109
|
+
settings.skillRules.push(rule)
|
|
110
110
|
}
|
|
111
111
|
try { save() } catch (error) {
|
|
112
|
-
|
|
112
|
+
settings.skillRules = previousRules
|
|
113
113
|
if (previousDefinition) definitions.set(rule.key, previousDefinition)
|
|
114
114
|
else definitions.delete(rule.key)
|
|
115
115
|
control.invalidate()
|
|
@@ -130,7 +130,7 @@ export function installSkills(ctx, state, locations, save) {
|
|
|
130
130
|
const { view, row } = await selected(args)
|
|
131
131
|
if (!row.deletable) throw new Error('仅可回收所选工作区或 DSH_HOME 下真实的 .dsh/skills 目录')
|
|
132
132
|
const removed = deleteSkill(row, { home: locations.home, cwd: view.projectRoot })
|
|
133
|
-
|
|
133
|
+
settings.skillRules = settings.skillRules.filter(rule => rule.identity !== identity(row))
|
|
134
134
|
for (const [key, cached] of definitions) if (cached.rule.identity === identity(row)) definitions.delete(key)
|
|
135
135
|
control.invalidate(); save()
|
|
136
136
|
return { removed, ...await rowsFor(view) }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jidekaixin2dian/dsh-toolgate",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
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",
|