@jidekaixin2dian/dsh-toolgate 0.0.0-stage → 0.1.5
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 +71 -0
- package/LICENSE +21 -0
- package/README.en.md +71 -0
- package/README.md +73 -3
- package/README.zh.md +6 -0
- package/SECURITY.md +16 -0
- package/assets/readme-schema-v2.svg +18 -0
- package/cordis.patch.yml +6 -0
- package/icon.svg +10 -0
- package/lib/api-payload.js +10 -0
- package/lib/audit.js +25 -0
- package/lib/client.js +516 -0
- package/lib/config-files.js +73 -0
- package/lib/groups.js +59 -0
- package/lib/host-paths.js +39 -0
- package/lib/index.js +501 -0
- package/lib/mcp-config.js +239 -0
- package/lib/skills-config.js +86 -0
- package/lib/skills-runtime.js +139 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +103 -6
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import os from 'node:os'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
|
|
5
|
+
export function projectRoot(cwd) {
|
|
6
|
+
if (!cwd) return undefined
|
|
7
|
+
const original = path.resolve(cwd)
|
|
8
|
+
for (let current = original; ; current = path.dirname(current)) {
|
|
9
|
+
if (fs.existsSync(path.join(current, '.git'))) return current
|
|
10
|
+
if (path.dirname(current) === current) return original
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function serviceOn(ctx, name) {
|
|
15
|
+
try { return ctx?.get?.(name) ?? ctx?.[name] } catch { return undefined }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function hostPaths(ctx) {
|
|
19
|
+
const profile = serviceOn(ctx, 'profileContext')
|
|
20
|
+
const homePath = serviceOn(ctx, 'dshHomePath')
|
|
21
|
+
const home = profile?.home || (typeof homePath === 'function' ? homePath() : undefined)
|
|
22
|
+
|| process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
23
|
+
return { home: path.resolve(home), profileDir: profile?.dir || process.env.DSH_TOOLGATE_PROFILE_DIR,
|
|
24
|
+
profilePatch: profile?.patchPath, workspace: profile?.cwd || serviceOn(ctx, 'workingDirectory')?.defaultDirectory || null }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function skillView(ctx, args = {}) {
|
|
28
|
+
const agents = serviceOn(ctx, 'agents')?.list?.() || []
|
|
29
|
+
const directory = serviceOn(ctx, 'workingDirectory')
|
|
30
|
+
const sessions = agents.filter(agent => agent?.session).map(agent => ({
|
|
31
|
+
id: String(agent.session.id), label: String(agent.session.id),
|
|
32
|
+
cwd: directory?.get?.(agent.session) || agent.session.header?.cwd || null, agent,
|
|
33
|
+
}))
|
|
34
|
+
const selected = args.sessionId ? sessions.find(row => row.id === args.sessionId) : undefined
|
|
35
|
+
if (args.sessionId && !selected) throw new Error('所选会话已不存在,请刷新后重选')
|
|
36
|
+
const cwd = selected?.cwd || (!args.sessionId ? hostPaths(ctx).workspace : null)
|
|
37
|
+
return { cwd: cwd ? path.resolve(cwd) : undefined, projectRoot: projectRoot(cwd), scope: selected?.agent, sessionId: selected?.id || null,
|
|
38
|
+
sessions: sessions.map(({ agent: _agent, ...row }) => row) }
|
|
39
|
+
}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { randomUUID } from 'node:crypto'
|
|
4
|
+
import z from '@deepseek-ai/schemastery'
|
|
5
|
+
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
6
|
+
|
|
7
|
+
export const name = 'dsh-toolgate'
|
|
8
|
+
export const inject = ['tools', 'skills', 'webServer']
|
|
9
|
+
export const Config = z.object({ allowSessionOverride: z.boolean().default(true) })
|
|
10
|
+
|
|
11
|
+
import { groupOf, isDisabled, labelOf, matchesDisabled, normalizeDisabled } from './groups.js'
|
|
12
|
+
import { requestArgs } from './api-payload.js'
|
|
13
|
+
import { appendAudit } from './audit.js'
|
|
14
|
+
import { createMcpConfig, publicServers } from './mcp-config.js'
|
|
15
|
+
import { hostPaths } from './host-paths.js'
|
|
16
|
+
import { installSkills } from './skills-runtime.js'
|
|
17
|
+
|
|
18
|
+
// Conservative, serialized-schema based estimate. It is deliberately labelled
|
|
19
|
+
// approximate in the UI; the real number comes from the provider tokenizer.
|
|
20
|
+
const CHARS_PER_TOKEN = 3.4
|
|
21
|
+
|
|
22
|
+
export async function apply(ctx, config = {}) {
|
|
23
|
+
// Prompt-injected traffic reaches the model tool; `false` lets a profile pin
|
|
24
|
+
// the global gate so only the authenticated settings page can change it.
|
|
25
|
+
const allowSessionOverride = config.allowSessionOverride !== false
|
|
26
|
+
const locations = hostPaths(ctx)
|
|
27
|
+
let mcp, mcpError
|
|
28
|
+
try {
|
|
29
|
+
const profile = serviceOn(ctx, 'profileContext')
|
|
30
|
+
const options = { ...locations }
|
|
31
|
+
if (profile) {
|
|
32
|
+
const [{ readBundlePatches }, { applyEntryPatches }] = await Promise.all([
|
|
33
|
+
import('@deepseek-ai/dsh-app-boot'), import('@deepseek-ai/cordis-plugin-include'),
|
|
34
|
+
])
|
|
35
|
+
options.basePatches = () => readBundlePatches('dsh', profile)
|
|
36
|
+
options.overlays = profile.overlays
|
|
37
|
+
options.compose = applyEntryPatches
|
|
38
|
+
}
|
|
39
|
+
mcp = createMcpConfig(options)
|
|
40
|
+
} catch (error) { mcpError = '无法读取宿主 profile:' + error.message }
|
|
41
|
+
const state = {
|
|
42
|
+
disabled: [],
|
|
43
|
+
disabledSkills: [],
|
|
44
|
+
skillRules: [],
|
|
45
|
+
disposed: false,
|
|
46
|
+
timers: new Set(),
|
|
47
|
+
overrides: new Map(),
|
|
48
|
+
applied: new Map(),
|
|
49
|
+
errors: new Map(),
|
|
50
|
+
applying: false,
|
|
51
|
+
stale: false,
|
|
52
|
+
// Counts/tokens for the full agent-visible tool set. The root tools view
|
|
53
|
+
// only contains global registrations; preset-scoped core tools are only
|
|
54
|
+
// visible through an agent, so the first real request records the full set.
|
|
55
|
+
bestSchemas: null,
|
|
56
|
+
}
|
|
57
|
+
const stateFile = path.join(locations.home, 'toolgate.json')
|
|
58
|
+
const rootCtx = ctx
|
|
59
|
+
|
|
60
|
+
function loadState() {
|
|
61
|
+
const legacyFile = stateFile.replace(/toolgate\.json$/, 'context-budget.json')
|
|
62
|
+
for (const file of [stateFile, legacyFile]) {
|
|
63
|
+
try {
|
|
64
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
65
|
+
state.disabled = normalizeDisabled(parsed?.disabled)
|
|
66
|
+
state.disabledSkills = Array.isArray(parsed?.disabledSkills)
|
|
67
|
+
? parsed.disabledSkills.filter(name => typeof name === 'string' && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name))
|
|
68
|
+
: []
|
|
69
|
+
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')) : []
|
|
70
|
+
if (file !== stateFile) saveState()
|
|
71
|
+
return
|
|
72
|
+
} catch { /* try the legacy file, then reset */ }
|
|
73
|
+
}
|
|
74
|
+
state.disabled = []
|
|
75
|
+
state.disabledSkills = []
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function saveState() {
|
|
79
|
+
const tmp = stateFile + '.' + randomUUID() + '.tmp'
|
|
80
|
+
try {
|
|
81
|
+
fs.mkdirSync(path.dirname(stateFile), { recursive: true })
|
|
82
|
+
fs.writeFileSync(tmp, JSON.stringify({
|
|
83
|
+
disabled: state.disabled,
|
|
84
|
+
disabledSkills: state.disabledSkills,
|
|
85
|
+
skillRules: state.skillRules,
|
|
86
|
+
}, null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 })
|
|
87
|
+
fs.renameSync(tmp, stateFile)
|
|
88
|
+
} catch (err) {
|
|
89
|
+
throw new Error('无法保存 Toolgate 设置:' + (err?.message || err))
|
|
90
|
+
} finally {
|
|
91
|
+
if (fs.existsSync(tmp)) fs.unlinkSync(tmp)
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function tokensOf(value) {
|
|
96
|
+
try {
|
|
97
|
+
return Math.max(1, Math.ceil(JSON.stringify(value).length / CHARS_PER_TOKEN))
|
|
98
|
+
} catch {
|
|
99
|
+
return 0
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function fmt(n) {
|
|
104
|
+
const v = Number(n) || 0
|
|
105
|
+
if (v >= 10000) return (v / 10000).toFixed(1) + '万'
|
|
106
|
+
return String(Math.round(v))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function skillCatalog(ctx, agent) {
|
|
110
|
+
try {
|
|
111
|
+
const skills = ctx.get?.('skills') ?? ctx.skills
|
|
112
|
+
if (!skills || typeof skills.list !== 'function') return []
|
|
113
|
+
const list = await Promise.resolve(skills.list({ ...(agent ? { cwd: serviceOn(ctx, 'workingDirectory')?.get?.(agent.session), scope: agent } : locations.workspace ? { cwd: locations.workspace } : {}) }))
|
|
114
|
+
return Array.isArray(list) ? list : []
|
|
115
|
+
} catch {
|
|
116
|
+
return []
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async function groupReport(ctx, agent) {
|
|
121
|
+
const schemas = state.bestSchemas || ctx.tools.schemas()
|
|
122
|
+
const globalNames = new Set(ctx.tools.schemas().map(schema => schema.name))
|
|
123
|
+
const groups = new Map()
|
|
124
|
+
const ensure = (id, toggle = true) => {
|
|
125
|
+
if (!groups.has(id)) groups.set(id, { id, label: labelOf(id), count: 0, tokens: 0, hideableTokens: 0, toggle })
|
|
126
|
+
return groups.get(id)
|
|
127
|
+
}
|
|
128
|
+
for (const schema of schemas) {
|
|
129
|
+
const group = groupOf(schema.name)
|
|
130
|
+
const entry = ensure(group, group !== 'core')
|
|
131
|
+
entry.count += 1
|
|
132
|
+
entry.tokens += tokensOf(schema)
|
|
133
|
+
if (globalNames.has(schema.name)) entry.hideableTokens += tokensOf(schema)
|
|
134
|
+
}
|
|
135
|
+
const catalog = await skillCatalog(ctx, agent)
|
|
136
|
+
let catalogTokens = 0
|
|
137
|
+
if (catalog.length > 0) {
|
|
138
|
+
const entry = ensure('skills')
|
|
139
|
+
entry.skillCount = catalog.length
|
|
140
|
+
const catalogBytes = catalog.reduce((sum, item) => {
|
|
141
|
+
return sum + String(item?.name || '').length + String(item?.description || '').length
|
|
142
|
+
}, 0)
|
|
143
|
+
catalogTokens = Math.ceil(catalogBytes / CHARS_PER_TOKEN)
|
|
144
|
+
// `skill` schema itself is already counted above; add catalog text.
|
|
145
|
+
entry.tokens += catalogTokens
|
|
146
|
+
if (globalNames.has('skill')) entry.hideableTokens += catalogTokens
|
|
147
|
+
}
|
|
148
|
+
const list = [...groups.values()].sort((a, b) => {
|
|
149
|
+
if (a.id === 'core') return 1
|
|
150
|
+
if (b.id === 'core') return -1
|
|
151
|
+
if (a.id.startsWith('mcp:') !== b.id.startsWith('mcp:')) return a.id.startsWith('mcp:') ? -1 : 1
|
|
152
|
+
return b.tokens - a.tokens
|
|
153
|
+
})
|
|
154
|
+
const full = list.reduce((sum, item) => sum + item.tokens, 0)
|
|
155
|
+
const saved = list.filter(item => isDisabled(item.id, state.disabled))
|
|
156
|
+
.reduce((sum, item) => sum + item.hideableTokens, 0)
|
|
157
|
+
const scoped = schemas.filter(schema => !globalNames.has(schema.name)
|
|
158
|
+
&& schema.name.startsWith('mcp__')).length
|
|
159
|
+
return {
|
|
160
|
+
groups: list,
|
|
161
|
+
totals: { full, current: Math.max(0, full - saved), saved },
|
|
162
|
+
disabled: [...state.disabled],
|
|
163
|
+
catalogTokens,
|
|
164
|
+
scoped,
|
|
165
|
+
skills: { count: catalog.length },
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function sessionIdOf(agent) {
|
|
170
|
+
return String(agent?.session?.id || agent?.sessionId || agent?.id || 'anonymous')
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function serviceOn(agentCtx, service) {
|
|
174
|
+
try {
|
|
175
|
+
if (agentCtx && typeof agentCtx.get === 'function') return agentCtx.get(service)
|
|
176
|
+
return agentCtx?.[service]
|
|
177
|
+
} catch {
|
|
178
|
+
return undefined
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function effectiveDisabled(agent) {
|
|
183
|
+
const sid = sessionIdOf(agent)
|
|
184
|
+
return state.overrides.has(sid) ? state.overrides.get(sid) : state.disabled
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function applyToAgent(agent) {
|
|
188
|
+
const ag = agent?.agent ?? agent
|
|
189
|
+
if (state.disposed || !ag || !ag.ctx) return
|
|
190
|
+
const sid = sessionIdOf(ag)
|
|
191
|
+
if (state.stale) {
|
|
192
|
+
clearApplied()
|
|
193
|
+
state.stale = false
|
|
194
|
+
}
|
|
195
|
+
if (!state.bestSchemas) {
|
|
196
|
+
try {
|
|
197
|
+
const visible = rootCtx.tools.schemas(ag)
|
|
198
|
+
if (Array.isArray(visible) && visible.length > 0) state.bestSchemas = visible
|
|
199
|
+
} catch { /* tool view not ready yet */ }
|
|
200
|
+
} else {
|
|
201
|
+
try {
|
|
202
|
+
const visible = rootCtx.tools.schemas(ag)
|
|
203
|
+
if (Array.isArray(visible) && visible.length > state.bestSchemas.length) state.bestSchemas = visible
|
|
204
|
+
} catch { /* tool view not ready yet */ }
|
|
205
|
+
}
|
|
206
|
+
const disabled = effectiveDisabled(ag)
|
|
207
|
+
const key = disabled.slice().sort().join(',')
|
|
208
|
+
const previous = state.applied.get(ag)
|
|
209
|
+
if (previous && previous.key === key) return
|
|
210
|
+
if (previous) {
|
|
211
|
+
state.applying = true
|
|
212
|
+
try { previous.dispose() } catch { /* stale agent scope */ } finally { state.applying = false }
|
|
213
|
+
state.applied.delete(ag)
|
|
214
|
+
}
|
|
215
|
+
if (disabled.length === 0) {
|
|
216
|
+
state.errors.delete(sid)
|
|
217
|
+
return
|
|
218
|
+
}
|
|
219
|
+
const agentTools = serviceOn(ag.ctx, 'tools')
|
|
220
|
+
if (!agentTools || typeof agentTools.restrict !== 'function') {
|
|
221
|
+
state.errors.set(sid, 'agent ctx has no restrictable tools service')
|
|
222
|
+
return
|
|
223
|
+
}
|
|
224
|
+
const full = rootCtx.tools.schemas()
|
|
225
|
+
const deny = full.map(schema => schema.name).filter(n => matchesDisabled(n, disabled))
|
|
226
|
+
if (deny.length === 0) return
|
|
227
|
+
state.applying = true
|
|
228
|
+
try {
|
|
229
|
+
const dispose = agentTools.restrict({ deny })
|
|
230
|
+
state.applied.set(ag, { key, dispose })
|
|
231
|
+
state.errors.delete(sid)
|
|
232
|
+
} catch (err) {
|
|
233
|
+
state.errors.set(sid, String(err?.message || err))
|
|
234
|
+
} finally {
|
|
235
|
+
state.applying = false
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function clearApplied() {
|
|
240
|
+
state.applying = true
|
|
241
|
+
try {
|
|
242
|
+
for (const entry of state.applied.values()) {
|
|
243
|
+
try { entry.dispose() } catch { /* agent may already be gone */ }
|
|
244
|
+
}
|
|
245
|
+
state.applied.clear()
|
|
246
|
+
state.errors.clear()
|
|
247
|
+
} finally {
|
|
248
|
+
state.applying = false
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async function reportFor(agent) {
|
|
253
|
+
const full = await groupReport(rootCtx, agent)
|
|
254
|
+
let current = full.totals.full
|
|
255
|
+
let currentCount = rootCtx.tools.schemas().length
|
|
256
|
+
if (agent?.ctx) {
|
|
257
|
+
try {
|
|
258
|
+
const visible = rootCtx.tools.schemas(agent)
|
|
259
|
+
currentCount = visible.length
|
|
260
|
+
current = 0
|
|
261
|
+
for (const schema of visible) current += tokensOf(schema)
|
|
262
|
+
// Preserve the full skill-catalog estimate when `skill` is still visible.
|
|
263
|
+
if (visible.some(schema => schema.name === 'skill')) current += full.catalogTokens
|
|
264
|
+
} catch { /* fall back to global estimate */ }
|
|
265
|
+
}
|
|
266
|
+
const overridden = state.overrides.has(sessionIdOf(agent))
|
|
267
|
+
const disabled = effectiveDisabled(agent)
|
|
268
|
+
const lines = []
|
|
269
|
+
lines.push('Toolgate' + (overridden ? '(本会话覆盖)' : ''))
|
|
270
|
+
lines.push('完整: ' + fmt(full.totals.full) + ' tokens / ' + fullCount(full) + ' 个工具')
|
|
271
|
+
lines.push('当前: ' + fmt(current) + ' tokens / ' + currentCount + ' 个工具')
|
|
272
|
+
lines.push('节省: ' + fmt(Math.max(0, full.totals.full - current)) + ' tokens')
|
|
273
|
+
lines.push('隐藏: ' + (disabled.length ? disabled.join(', ') : '无'))
|
|
274
|
+
lines.push('')
|
|
275
|
+
for (const g of full.groups) {
|
|
276
|
+
lines.push('- ' + g.id + ' (' + g.label + '): ' + g.count + ' 个,约 ' + fmt(g.tokens) + ' tokens' + (isDisabled(g.id, disabled) ? ' [已隐藏]' : ''))
|
|
277
|
+
}
|
|
278
|
+
lines.push('')
|
|
279
|
+
lines.push(allowSessionOverride
|
|
280
|
+
? '用 action=session + disabled=[...] 只改本会话;action=reset 恢复默认。'
|
|
281
|
+
: '会话级覆盖已被宿主设置禁用,请在 设置 → 工具闸门 修改全局闸门。')
|
|
282
|
+
return lines.join('\n')
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function fullCount(report) {
|
|
286
|
+
return report.groups.reduce((sum, g) => sum + g.count, 0)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function readBody(req, limit = 64 * 1024) {
|
|
290
|
+
return new Promise((resolve, reject) => {
|
|
291
|
+
const chunks = []
|
|
292
|
+
let size = 0, exceeded = false
|
|
293
|
+
req.on('data', chunk => {
|
|
294
|
+
if (exceeded) return
|
|
295
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
296
|
+
size += buffer.length
|
|
297
|
+
if (size > limit) { exceeded = true; chunks.length = 0; reject(Object.assign(new Error('body too large'), { status: 413 })); return }
|
|
298
|
+
chunks.push(buffer)
|
|
299
|
+
})
|
|
300
|
+
req.on('end', () => { if (!exceeded) resolve(Buffer.concat(chunks).toString('utf8')) })
|
|
301
|
+
req.on('error', reject)
|
|
302
|
+
req.on('aborted', () => reject(new Error('request aborted')))
|
|
303
|
+
})
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
loadState()
|
|
307
|
+
ctx.effect(() => () => {
|
|
308
|
+
state.disposed = true
|
|
309
|
+
for (const timer of state.timers) clearTimeout(timer)
|
|
310
|
+
state.timers.clear()
|
|
311
|
+
clearApplied()
|
|
312
|
+
state.overrides.clear()
|
|
313
|
+
state.bestSchemas = null
|
|
314
|
+
})
|
|
315
|
+
const skillManager = installSkills(ctx, state, locations, saveState)
|
|
316
|
+
const audit = entry => {
|
|
317
|
+
if (!appendAudit(locations.home, entry)) ctx.logger?.warn?.('Toolgate audit log write failed for %s', entry.op)
|
|
318
|
+
}
|
|
319
|
+
const auditTarget = (op, args) => op === 'mcp-add' || op === 'mcp-edit'
|
|
320
|
+
? String(args.row?.id || args.row?.serverName || '')
|
|
321
|
+
: String(args.id || args.name || '')
|
|
322
|
+
|
|
323
|
+
const tool = defineTool({
|
|
324
|
+
name: 'toolgate',
|
|
325
|
+
description: [
|
|
326
|
+
'Inspect or shrink this session context by hiding tool groups (MCP/Skill/memory/schedule).',
|
|
327
|
+
'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.',
|
|
330
|
+
...(allowSessionOverride ? [] : ['Session overrides are disabled by the host; only action=status is available.']),
|
|
331
|
+
].join(' '),
|
|
332
|
+
parameters: {
|
|
333
|
+
action: {
|
|
334
|
+
type: 'string',
|
|
335
|
+
required: true,
|
|
336
|
+
description: 'status | session | reset',
|
|
337
|
+
},
|
|
338
|
+
disabled: {
|
|
339
|
+
type: 'array',
|
|
340
|
+
items: { type: 'string' },
|
|
341
|
+
description: 'Groups to hide: mcp:<server>, mcp (all MCP), skills, memory, schedule. Empty means show all.',
|
|
342
|
+
},
|
|
343
|
+
},
|
|
344
|
+
output: {
|
|
345
|
+
schema: { type: 'string' },
|
|
346
|
+
render: (_args, value) => [{ type: 'text', text: String(value) }],
|
|
347
|
+
},
|
|
348
|
+
async execute(args, exec) {
|
|
349
|
+
const agent = exec.agent
|
|
350
|
+
if (!agent) return 'No active agent context; toolgate only works inside a session.'
|
|
351
|
+
const action = String(args.action || 'status').trim().toLowerCase()
|
|
352
|
+
const sid = sessionIdOf(agent)
|
|
353
|
+
if (action === 'status') return reportFor(agent)
|
|
354
|
+
if (!allowSessionOverride && (action === 'session' || action === 'reset')) {
|
|
355
|
+
return '会话级覆盖已被宿主设置禁用(allowSessionOverride=false);全局工具闸门只能在 设置 → 工具闸门 中修改。\n\n' + await reportFor(agent)
|
|
356
|
+
}
|
|
357
|
+
if (action === 'reset') {
|
|
358
|
+
state.overrides.delete(sid)
|
|
359
|
+
applyToAgent(agent)
|
|
360
|
+
return '已恢复全局工具闸门。\n\n' + await reportFor(agent)
|
|
361
|
+
}
|
|
362
|
+
if (action === 'session') {
|
|
363
|
+
const disabled = normalizeDisabled(args.disabled)
|
|
364
|
+
state.overrides.set(sid, disabled)
|
|
365
|
+
applyToAgent(agent)
|
|
366
|
+
return '已应用本会话覆盖:' + (disabled.length ? disabled.join(', ') : '全部显示') +
|
|
367
|
+
'\n\n' + await reportFor(agent)
|
|
368
|
+
}
|
|
369
|
+
return 'Unknown action "' + action + '". Use status, session or reset.'
|
|
370
|
+
},
|
|
371
|
+
})
|
|
372
|
+
ctx.tools.register(tool)
|
|
373
|
+
|
|
374
|
+
// Every request passes here before prompt assembly. Applying the restriction
|
|
375
|
+
// in this hook means the schemas disappear without touching any config or
|
|
376
|
+
// restarting the MCP client process.
|
|
377
|
+
ctx.on('agent/pre-step', (agent, next) => {
|
|
378
|
+
try { applyToAgent(agent) } catch (err) {
|
|
379
|
+
console.warn('[dsh-toolgate] apply failed:', err?.message || err)
|
|
380
|
+
}
|
|
381
|
+
return typeof next === 'function' ? next() : undefined
|
|
382
|
+
})
|
|
383
|
+
|
|
384
|
+
// Workflow/subagent creation can begin its first step before a pre-step
|
|
385
|
+
// listener attached at the root has run. Apply once at creation too, then
|
|
386
|
+
// re-check on the next tick when the child's tool scope is fully installed.
|
|
387
|
+
ctx.on('agent/created', (agent) => {
|
|
388
|
+
try { applyToAgent(agent) } catch { /* tools not installed yet */ }
|
|
389
|
+
const timer = setTimeout(() => {
|
|
390
|
+
state.timers.delete(timer)
|
|
391
|
+
try { applyToAgent(agent) } catch (err) {
|
|
392
|
+
console.warn('[dsh-toolgate] child apply failed:', err?.message || err)
|
|
393
|
+
}
|
|
394
|
+
}, 0)
|
|
395
|
+
state.timers.add(timer)
|
|
396
|
+
if (typeof timer?.unref === 'function') timer.unref()
|
|
397
|
+
})
|
|
398
|
+
|
|
399
|
+
// Last-resort catch for workflow children whose first step is already in
|
|
400
|
+
// flight when creation handlers run. `applyToAgent` is idempotent per key.
|
|
401
|
+
ctx.on('agent/status', (agent) => {
|
|
402
|
+
try { applyToAgent(agent) } catch { /* not a scoped agent event */ }
|
|
403
|
+
})
|
|
404
|
+
|
|
405
|
+
// Dynamic MCP managers (community dsh-mcp-manager, lazy-mcp) add/remove
|
|
406
|
+
// agent-scoped tools at runtime. Rebuild the baseline and re-apply the
|
|
407
|
+
// restriction on the next step; ignore the events caused by our own
|
|
408
|
+
// restrict()/dispose() calls to avoid a churn loop.
|
|
409
|
+
ctx.on('tools/change', () => {
|
|
410
|
+
if (state.applying) return
|
|
411
|
+
state.stale = true
|
|
412
|
+
state.bestSchemas = null
|
|
413
|
+
})
|
|
414
|
+
|
|
415
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
416
|
+
const applied = state.applied.get(agent)
|
|
417
|
+
if (applied) { state.applying = true; try { applied.dispose() } finally { state.applying = false } }
|
|
418
|
+
state.applied.delete(agent)
|
|
419
|
+
state.errors.delete(sessionIdOf(agent))
|
|
420
|
+
state.overrides.delete(sessionIdOf(agent))
|
|
421
|
+
})
|
|
422
|
+
|
|
423
|
+
const webServer = ctx.webServer ?? (() => { try { return ctx.get('webServer') } catch { return undefined } })()
|
|
424
|
+
if (webServer) {
|
|
425
|
+
ctx.effect(() => webServer.register({
|
|
426
|
+
kind: 'exact',
|
|
427
|
+
path: '/dsh-toolgate/api',
|
|
428
|
+
handler: async (req, res) => {
|
|
429
|
+
const send = (code, value) => {
|
|
430
|
+
res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' })
|
|
431
|
+
res.end(JSON.stringify(value))
|
|
432
|
+
}
|
|
433
|
+
const header = (name) => {
|
|
434
|
+
const value = req.headers?.[name]
|
|
435
|
+
return Array.isArray(value) ? value[0] ?? '' : value ?? ''
|
|
436
|
+
}
|
|
437
|
+
// `op` lives outside the try so the failure audit below can name it.
|
|
438
|
+
let op = ''
|
|
439
|
+
try {
|
|
440
|
+
const connection = serviceOn(ctx, 'connection')
|
|
441
|
+
if (typeof connection?.requestRejection !== 'function') return send(503, { ok: false, error: 'host authentication unavailable' })
|
|
442
|
+
const rejection = connection.requestRejection(req)
|
|
443
|
+
if (rejection !== undefined) return send(rejection, { ok: false, error: 'request rejected by host authentication' })
|
|
444
|
+
if (String(req.method || '').toUpperCase() !== 'POST') return send(405, { ok: false, error: 'method not allowed' })
|
|
445
|
+
if (header('x-dsh-plugin') !== 'dsh-toolgate') return send(403, { ok: false, error: 'missing plugin gate header' })
|
|
446
|
+
if (!/^application\/json(?:\s*;|$)/i.test(header('content-type'))) return send(415, { ok: false, error: 'expected application/json' })
|
|
447
|
+
let payload
|
|
448
|
+
try { payload = JSON.parse(await readBody(req)) } catch (error) { return send(error.status || 400, { ok: false, error: error.status === 413 ? 'request body too large' : 'invalid JSON body' }) }
|
|
449
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return send(400, { ok: false, error: 'expected JSON object' })
|
|
450
|
+
op = String(payload.op || '')
|
|
451
|
+
const args = requestArgs(payload)
|
|
452
|
+
if (op === 'status') return send(200, { ok: true, ...(await groupReport(ctx)),
|
|
453
|
+
applied: [...state.applied.keys()].map(sessionIdOf), errors: Object.fromEntries(state.errors) })
|
|
454
|
+
if (op === 'set') {
|
|
455
|
+
const previous = state.disabled
|
|
456
|
+
state.disabled = normalizeDisabled(args.disabled)
|
|
457
|
+
try { saveState() } catch (error) { state.disabled = previous; throw error }
|
|
458
|
+
audit({ op, disabled: [...state.disabled] })
|
|
459
|
+
clearApplied()
|
|
460
|
+
return send(200, { ok: true, ...(await groupReport(ctx)) })
|
|
461
|
+
}
|
|
462
|
+
if (op.startsWith('mcp-')) {
|
|
463
|
+
if (!mcp) return send(503, { ok: false, error: mcpError || 'current profile unavailable' })
|
|
464
|
+
const operations = {
|
|
465
|
+
'mcp-list': () => mcp.listServers(),
|
|
466
|
+
'mcp-add': () => mcp.addServer(args.row),
|
|
467
|
+
'mcp-edit': () => mcp.editServer(args.row),
|
|
468
|
+
'mcp-remove': () => mcp.removeServer(args.id),
|
|
469
|
+
'mcp-enabled': () => mcp.setServerEnabled(args.id, args.enabled !== false),
|
|
470
|
+
}
|
|
471
|
+
if (!operations[op]) return send(400, { ok: false, error: 'unknown operation' })
|
|
472
|
+
try {
|
|
473
|
+
const result = operations[op]()
|
|
474
|
+
if (op !== 'mcp-list') audit({ op, id: auditTarget(op, args) })
|
|
475
|
+
return send(200, { ok: true, ...publicServers(result) })
|
|
476
|
+
} catch (error) {
|
|
477
|
+
audit({ op, id: auditTarget(op, args), error: String(error?.message || error) })
|
|
478
|
+
return send(400, { ok: false, error: error.message })
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
const skillsOps = { 'skills-list': 'list', 'skill-toggle': 'toggle', 'skill-create': 'create', 'skill-delete': 'delete' }
|
|
482
|
+
if (skillsOps[op]) {
|
|
483
|
+
try {
|
|
484
|
+
const result = await skillManager[skillsOps[op]](args)
|
|
485
|
+
if (op !== 'skills-list') audit({ op, name: String(args.name || ''), ...(op === 'skill-toggle' ? { enabled: args.enabled !== false } : {}) })
|
|
486
|
+
return send(200, { ok: true, ...result })
|
|
487
|
+
} catch (error) {
|
|
488
|
+
audit({ op, name: String(args.name || ''), error: String(error?.message || error) })
|
|
489
|
+
return send(400, { ok: false, error: error.message })
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return send(400, { ok: false, error: 'unknown operation: ' + op })
|
|
493
|
+
} catch (err) {
|
|
494
|
+
audit({ op: String(op || ''), error: String(err?.message || err) })
|
|
495
|
+
send(500, { ok: false, error: String(err?.message || err) })
|
|
496
|
+
}
|
|
497
|
+
},
|
|
498
|
+
}), 'dsh-toolgate: api route')
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|