dsh-capability-switch 0.0.0-stage → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/imports.js ADDED
@@ -0,0 +1,120 @@
1
+ import { promises as fs } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { parse as parseToml } from 'smol-toml'
5
+ import { createHash } from 'node:crypto'
6
+
7
+ function object(value) {
8
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
9
+ }
10
+
11
+ function strings(value) {
12
+ return object(value) ? Object.fromEntries(Object.entries(value).filter(([, item]) => typeof item === 'string')) : {}
13
+ }
14
+
15
+ function normalizeStandard(name, value, source) {
16
+ if (!object(value)) throw new Error('配置项必须是对象')
17
+ const kind = value.transport || value.type || (value.url ? 'streamable-http' : 'stdio')
18
+ if (['http', 'streamable-http', 'sse'].includes(kind)) {
19
+ if (!String(value.url || '').trim()) throw new Error('HTTP MCP 缺少 URL')
20
+ return {
21
+ name, transport: 'streamable-http', url: String(value.url || ''), headers: strings(value.headers),
22
+ command: '', args: [], env: {}, cwd: '', enabled: value.enabled !== false && value.disabled !== true, sources: [source],
23
+ }
24
+ }
25
+ if (kind !== 'stdio') throw new Error(`暂不支持 ${String(kind)} 传输`)
26
+ if (!String(value.command || '').trim()) throw new Error('stdio MCP 缺少启动命令')
27
+ return {
28
+ name, transport: 'stdio', command: String(value.command || ''),
29
+ args: Array.isArray(value.args) ? value.args.map(String) : [],
30
+ env: strings(value.env), cwd: String(value.cwd || ''), url: '', headers: {},
31
+ enabled: value.enabled !== false && value.disabled !== true, sources: [source],
32
+ }
33
+ }
34
+
35
+ function normalizeOpenCode(name, value, source) {
36
+ if (!object(value)) throw new Error('配置项必须是对象')
37
+ if (value.type === 'remote') {
38
+ return normalizeStandard(name, { ...value, type: 'http' }, source)
39
+ }
40
+ if (value.type !== 'local') throw new Error('OpenCode MCP 仅支持 local 或 remote')
41
+ const command = Array.isArray(value.command) ? value.command.map(String) : []
42
+ return normalizeStandard(name, {
43
+ type: 'stdio', command: command[0] || '', args: command.slice(1),
44
+ env: value.environment, enabled: value.enabled,
45
+ }, source)
46
+ }
47
+
48
+ function normalizeCodex(name, value, source) {
49
+ if (!object(value)) throw new Error('配置项必须是表')
50
+ return normalizeStandard(name, {
51
+ type: value.url ? 'http' : 'stdio', command: value.command, args: value.args,
52
+ env: value.env, cwd: value.cwd, url: value.url, headers: value.http_headers,
53
+ enabled: value.enabled,
54
+ }, source)
55
+ }
56
+
57
+ function definitions(baseHome) {
58
+ return [
59
+ { id: 'claude-code', label: 'Claude Code', path: join(baseHome, '.claude.json'), format: 'json', pick: data => data.mcpServers, normalize: normalizeStandard },
60
+ { id: 'codex', label: 'Codex', path: join(baseHome, '.codex', 'config.toml'), format: 'toml', pick: data => data.mcp_servers, normalize: normalizeCodex },
61
+ { id: 'gemini', label: 'Gemini CLI', path: join(baseHome, '.gemini', 'settings.json'), format: 'json', pick: data => data.mcpServers, normalize: normalizeStandard },
62
+ { id: 'opencode', label: 'OpenCode', path: join(baseHome, '.config', 'opencode', 'opencode.json'), format: 'json', pick: data => data.mcp, normalize: normalizeOpenCode },
63
+ { id: 'cursor', label: 'Cursor', path: join(baseHome, '.cursor', 'mcp.json'), format: 'json', pick: data => data.mcpServers, normalize: normalizeStandard },
64
+ ]
65
+ }
66
+
67
+ /** Read supported user-level application configs without modifying them. */
68
+ export async function scanMcpApps(baseHome = homedir()) {
69
+ const servers = []
70
+ const sources = []
71
+ for (const definition of definitions(baseHome)) {
72
+ const source = { id: definition.id, label: definition.label, path: definition.path }
73
+ try {
74
+ const text = await fs.readFile(definition.path, 'utf8')
75
+ const data = definition.format === 'toml' ? parseToml(text) : JSON.parse(text)
76
+ if (!object(data)) throw new Error('配置文件根节点必须是对象')
77
+ const entries = definition.pick(data)
78
+ if (entries !== undefined && !object(entries)) throw new Error('MCP 配置节点必须是对象')
79
+ const names = []
80
+ for (const [name, value] of Object.entries(entries || {})) {
81
+ try {
82
+ servers.push(definition.normalize(name, value, { id: source.id, label: source.label, path: source.path }))
83
+ names.push(name)
84
+ } catch (error) {
85
+ sources.push({ ...source, name, error: error.message })
86
+ }
87
+ }
88
+ sources.push({ ...source, count: names.length })
89
+ } catch (error) {
90
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') sources.push({ ...source, error: error.message })
91
+ }
92
+ }
93
+ return { servers, sources }
94
+ }
95
+
96
+ export function mcpFingerprint(row) {
97
+ const canonical = JSON.stringify([
98
+ row.name, row.transport, row.command, row.args, row.cwd, row.url,
99
+ Object.entries(row.env || {}).sort(([left], [right]) => left.localeCompare(right)),
100
+ Object.entries(row.headers || {}).sort(([left], [right]) => left.localeCompare(right)),
101
+ ])
102
+ return createHash('sha256').update(canonical).digest('hex')
103
+ }
104
+
105
+ /** Merge only identical same-name entries; conflicting sources remain separate choices. */
106
+ export function groupMcpImports(rows) {
107
+ const groups = new Map()
108
+ for (const row of rows) {
109
+ const fingerprint = mcpFingerprint(row)
110
+ const key = row.name + '\0' + fingerprint
111
+ const existing = groups.get(key)
112
+ if (existing) existing.sources.push(...row.sources)
113
+ else groups.set(key, { ...row, fingerprint, sources: [...row.sources] })
114
+ }
115
+ const counts = new Map()
116
+ for (const row of groups.values()) counts.set(row.name, (counts.get(row.name) || 0) + 1)
117
+ return [...groups.values()]
118
+ .map(row => ({ ...row, conflict: counts.get(row.name) > 1 }))
119
+ .sort((a, b) => a.name.localeCompare(b.name) || a.sources[0].id.localeCompare(b.sources[0].id))
120
+ }
package/lib/index.js ADDED
@@ -0,0 +1,320 @@
1
+ import { promises as fs } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
4
+ import { listSkills, listProjectSkills, readSkill, createSkill, updateSkill, toggleSkill, deleteSkill, syncAgentSkills, previewAgentSkillSync, installSkillTakeover, invalidateSkillCatalog, dshHome } from './skills.js'
5
+ import { listMcp, saveMcp, toggleMcp, deleteMcp, testMcp, restartMcp, listMcpImports, importMcp } from './mcp.js'
6
+ import { createUpdateManager } from './update.js'
7
+
8
+ export const name = 'capability-switch'
9
+ export const inject = ['tools', 'skills']
10
+
11
+ const BASE = '/__dsh-capability-switch'
12
+ const MAX_BODY = 1024 * 1024
13
+
14
+ export function normalizePreferences(value = {}) {
15
+ return {
16
+ sidebarVisible: true,
17
+ sidebarLabel: '技能与MCP',
18
+ defaultTab: value.defaultTab === 'mcp' ? 'mcp' : 'skills',
19
+ showDescriptions: true,
20
+ compactRows: true,
21
+ }
22
+ }
23
+
24
+ function requestRejection(scope, req) {
25
+ const connection = scope.get('connection')
26
+ if (!connection || typeof connection.requestRejection !== 'function') return 403
27
+ try {
28
+ return connection.requestRejection(req) ?? undefined
29
+ } catch {
30
+ return 403
31
+ }
32
+ }
33
+
34
+ function send(res, status, payload) {
35
+ res.statusCode = status
36
+ res.setHeader('content-type', 'application/json; charset=utf-8')
37
+ res.setHeader('cache-control', 'no-store')
38
+ res.end(JSON.stringify(payload))
39
+ }
40
+
41
+ function readJson(req) {
42
+ return new Promise((resolve, reject) => {
43
+ const chunks = []
44
+ let size = 0
45
+ req.on('data', chunk => {
46
+ size += chunk.length
47
+ if (size > MAX_BODY) { reject(new Error('请求体超过 1 MiB')); req.destroy(); return }
48
+ chunks.push(chunk)
49
+ })
50
+ req.on('end', () => {
51
+ const text = Buffer.concat(chunks).toString('utf8')
52
+ if (!text.trim()) return resolve({})
53
+ try { resolve(JSON.parse(text)) } catch { reject(new Error('请求体不是合法 JSON')) }
54
+ })
55
+ req.on('error', reject)
56
+ })
57
+ }
58
+
59
+ function currentProfile(ctx) {
60
+ const fromEnvironment = process.env.DSH_PROFILE?.trim()
61
+ if (fromEnvironment) return fromEnvironment
62
+ const documentPath = ctx.get('configEditor')?.documentPath
63
+ if (typeof documentPath !== 'string' || !documentPath) return null
64
+ return basename(dirname(documentPath))
65
+ }
66
+
67
+ function workspaceRows(ctx) {
68
+ const registry = ctx.get('workspaceRegistry')
69
+ if (!registry) return []
70
+ try {
71
+ return registry.list().map(workspace => ({
72
+ id: workspace.id,
73
+ path: workspace.path,
74
+ title: workspace.title,
75
+ }))
76
+ } catch {
77
+ return []
78
+ }
79
+ }
80
+
81
+ function expandHome(value) {
82
+ if (value === '~') return homedir()
83
+ if (value.startsWith('~/') || value.startsWith('~\\')) return join(homedir(), value.slice(2))
84
+ return value
85
+ }
86
+
87
+ async function createWorkspace(ctx, input = {}) {
88
+ const name = String(input.name || '').trim()
89
+ if (!name || name === '.' || name === '..' || /[\\/]/.test(name)) {
90
+ throw new Error('工作区名称不能包含路径分隔符')
91
+ }
92
+ const rawParent = String(input.parent || '').trim() || join(homedir(), 'Documents')
93
+ const parent = resolve(expandHome(rawParent))
94
+ if (!isAbsolute(expandHome(rawParent))) throw new Error('工作区父目录必须是绝对路径')
95
+ const target = resolve(parent, name)
96
+ if (dirname(target) !== parent) throw new Error('工作区路径不合法')
97
+ await fs.mkdir(target, { recursive: true })
98
+ const registry = ctx.get('workspaceRegistry')
99
+ if (!registry) throw new Error('当前 DSH 未提供工作区注册服务')
100
+ const workspace = await registry.create(target, String(input.title || name).trim() || name)
101
+ return { ok: true, workspace: { id: workspace.id, path: workspace.path, title: workspace.title }, workspaces: workspaceRows(ctx) }
102
+ }
103
+
104
+ async function resolveSessionCwd(ctx, sessionId) {
105
+ if (typeof sessionId !== 'string' || !sessionId) return null
106
+ const agent = ctx.get('agents')?.get(sessionId)
107
+ const workingDirectory = ctx.get('workingDirectory')
108
+ if (agent && workingDirectory) {
109
+ try { return await workingDirectory.ensure(agent) } catch { return null }
110
+ }
111
+ const sessionQuery = ctx.get('sessionQuery')
112
+ if (!sessionQuery) return null
113
+ try {
114
+ const observation = await sessionQuery.observeSession(sessionId)
115
+ try {
116
+ return observation.projections?.values?.workingDirectory || observation.header?.cwd || null
117
+ } finally {
118
+ await observation[Symbol.asyncDispose]?.()
119
+ }
120
+ } catch {
121
+ return null
122
+ }
123
+ }
124
+
125
+ function requestSessionId(req) {
126
+ const value = req.headers?.['x-dsh-session-id']
127
+ return Array.isArray(value) ? value[0] : value
128
+ }
129
+
130
+ async function currentAgentCwd(ctx) {
131
+ const agent = ctx.get('agents')?.currentInitiator?.()
132
+ const workingDirectory = ctx.get('workingDirectory')
133
+ if (!agent || !workingDirectory) return null
134
+ try { return await workingDirectory.ensure(agent) } catch { return null }
135
+ }
136
+
137
+ function isRegisteredWorkspace(ctx, cwd) {
138
+ if (typeof cwd !== 'string' || !cwd.trim()) return false
139
+ const requested = resolve(cwd)
140
+ return workspaceRows(ctx).some(workspace => resolve(workspace.path) === requested)
141
+ }
142
+
143
+ function projectCreateCwd(ctx, body, sessionCwd) {
144
+ if (body.scope !== 'project') return undefined
145
+ return isRegisteredWorkspace(ctx, body.cwd) ? resolve(body.cwd) : sessionCwd
146
+ }
147
+
148
+ function requestedWorkspaceCwd(ctx, requestedCwd, sessionCwd) {
149
+ return isRegisteredWorkspace(ctx, requestedCwd) ? resolve(requestedCwd) : sessionCwd
150
+ }
151
+
152
+ async function state(ctx, prefs, cwd, includeWorkspaces = true, updates = null) {
153
+ let mcp = []
154
+ let mcpError
155
+ try { mcp = await listMcp(ctx) } catch (error) { mcpError = error.message }
156
+ const skills = await listSkills(cwd)
157
+ const workspaces = workspaceRows(ctx)
158
+ const currentWorkspacePath = typeof cwd === 'string' && cwd.trim() ? resolve(cwd) : null
159
+ const currentWorkspace = workspaces.find(workspace => resolve(workspace.path) === currentWorkspacePath)
160
+ for (const row of skills) {
161
+ if (row.scope !== 'project') continue
162
+ if (currentWorkspace?.id !== undefined) row.workspaceId = currentWorkspace.id
163
+ row.workspaceTitle = currentWorkspace?.title || basename(currentWorkspacePath || '')
164
+ row.workspacePath = currentWorkspacePath
165
+ }
166
+ const otherWorkspaces = includeWorkspaces
167
+ ? workspaces.filter(workspace => !currentWorkspacePath || resolve(workspace.path) !== currentWorkspacePath)
168
+ : []
169
+ const otherResults = await Promise.all(otherWorkspaces.map(async workspace => {
170
+ try {
171
+ return { workspace, rows: await listProjectSkills(workspace.path) }
172
+ } catch (error) {
173
+ return { workspace, error: error?.message || String(error) }
174
+ }
175
+ }))
176
+ const skillWarnings = []
177
+ for (const result of otherResults) {
178
+ if (result.error) {
179
+ skillWarnings.push({ workspaceId: result.workspace.id, workspaceTitle: result.workspace.title, workspacePath: result.workspace.path, error: result.error })
180
+ continue
181
+ }
182
+ for (const row of result.rows) {
183
+ skills.push({
184
+ ...row,
185
+ workspaceId: result.workspace.id,
186
+ workspaceTitle: result.workspace.title,
187
+ workspacePath: result.workspace.path,
188
+ writable: row.writable,
189
+ crossWorkspace: true,
190
+ ...(row.writable ? {} : { readOnlyReason: 'other-workspace-readonly' }),
191
+ })
192
+ }
193
+ }
194
+ return {
195
+ ok: true, skills, mcp, skillWarnings, ...(mcpError === undefined ? {} : { mcpError }),
196
+ prefs, ...(updates ? { update: updates.status() } : {}),
197
+ dshHome: dshHome(), home: homedir(), userSkillsRoot: join(dshHome(), 'skills'), profile: currentProfile(ctx),
198
+ workspace: currentWorkspacePath,
199
+ workspaces,
200
+ }
201
+ }
202
+
203
+ function tool(ctx, prefs, updates) {
204
+ const mutateSkill = async operation => {
205
+ const result = await operation()
206
+ invalidateSkillCatalog(ctx)
207
+ return result
208
+ }
209
+ return {
210
+ name: 'capability_manager',
211
+ description: '管理 DSH 的 Skills、工作区与 MCP。list 查看;workspace_create 新建并注册工作区;skill_create/update/toggle/delete 管理用户级和项目级技能,skill_create 用 scope 选择 user 或 project,project 写入所选已注册工作区的 .agents/skills,省略工作区时使用当前 Agent 工作区;同步默认创建软链接,也可用 mode=copy 创建独立副本;软链接删除只移除 DSH 链接并保留 Agent 源文件;skill_sync_preview/skill_sync 预览并同步 Agent 目录;mcp_save/toggle/delete/test/restart 管理当前 profile 的 MCP,mcp_import_list/mcp_import 预览并从其他应用导入。删除必须 confirm=true。',
212
+ parameters: {
213
+ type: 'object',
214
+ properties: {
215
+ action: { type: 'string', enum: ['list', 'workspace_create', 'skill_read', 'skill_create', 'skill_update', 'skill_toggle', 'skill_delete', 'skill_sync_preview', 'skill_sync', 'mcp_save', 'mcp_toggle', 'mcp_delete', 'mcp_test', 'mcp_restart', 'mcp_import_list', 'mcp_import'] },
216
+ cwd: { type: 'string', description: '项目技能所在工作区;必须是已注册工作区,省略时使用当前 Agent 工作目录' },
217
+ scope: { type: 'string', enum: ['user', 'project'], description: 'skill_create 的技能范围,默认 user;project 写入所选或当前工作区的 .agents/skills' },
218
+ path: { type: 'string', description: '技能入口文件路径' },
219
+ text: { type: 'string', description: '完整 SKILL.md 内容' },
220
+ name: { type: 'string', description: '技能名、MCP 名称或新工作区名称' },
221
+ parent: { type: 'string', description: 'workspace_create 的父目录,默认 ~/Documents' },
222
+ selections: { type: 'array', items: { type: 'string' }, description: 'mcp_import 要导入的预览条目 ID 列表;预览后配置变化会拒绝导入' },
223
+ names: { type: 'array', items: { type: 'string' }, description: 'skill_sync 要同步的技能名称列表;省略同步预览中的全部变更' },
224
+ mode: { type: 'string', enum: ['symlink', 'copy'], description: 'skill_sync 模式:默认 symlink 软链接,copy 复制独立副本' },
225
+ description: { type: 'string', description: '技能描述' },
226
+ body: { type: 'string', description: '技能正文' },
227
+ enabled: { type: 'boolean' },
228
+ confirm: { type: 'boolean' },
229
+ server: { type: 'object', description: 'mcp_save 的完整服务器配置' },
230
+ },
231
+ required: ['action'],
232
+ },
233
+ output: {
234
+ schema: { type: 'object' },
235
+ render: (_args, value) => [{ type: 'text', text: JSON.stringify(value, null, 2) }],
236
+ },
237
+ execute: async args => {
238
+ const trustedCwd = await currentAgentCwd(ctx)
239
+ const requestedCwd = isRegisteredWorkspace(ctx, args.cwd) ? resolve(args.cwd) : trustedCwd
240
+ switch (args.action) {
241
+ case 'list': return await state(ctx, prefs, trustedCwd, true, updates)
242
+ case 'workspace_create': return await createWorkspace(ctx, { name: args.name, parent: args.parent })
243
+ case 'skill_read': return await readSkill(args.path, requestedCwd)
244
+ case 'skill_create': return await mutateSkill(() => createSkill({ ...args, cwd: projectCreateCwd(ctx, args, requestedCwd) }))
245
+ case 'skill_update': return await mutateSkill(() => updateSkill(args.path, args.text, requestedCwd))
246
+ case 'skill_toggle': return await mutateSkill(() => toggleSkill(args.path, args.enabled === true, requestedCwd))
247
+ case 'skill_delete': return await mutateSkill(() => deleteSkill(args.path, args.confirm, requestedCwd))
248
+ case 'skill_sync_preview': return await previewAgentSkillSync(args.mode)
249
+ case 'skill_sync': return await mutateSkill(() => syncAgentSkills(undefined, args.names, args.mode))
250
+ case 'mcp_save': return await saveMcp(ctx, { ...(args.server || {}), name: args.name || args.server?.name })
251
+ case 'mcp_toggle': return await toggleMcp(ctx, args.name, args.enabled)
252
+ case 'mcp_delete': return await deleteMcp(ctx, args.name, args.confirm)
253
+ case 'mcp_test': return await testMcp(ctx, args.name)
254
+ case 'mcp_restart': return await restartMcp(ctx, args.name)
255
+ case 'mcp_import_list': return await listMcpImports(ctx)
256
+ case 'mcp_import': return await importMcp(ctx, args.selections, undefined, args.enabled === true)
257
+ default: throw new Error('未知 action')
258
+ }
259
+ },
260
+ }
261
+ }
262
+
263
+ export function apply(ctx, config = {}) {
264
+ const prefs = normalizePreferences(config)
265
+ const updates = createUpdateManager(ctx)
266
+ ctx.effect(() => installSkillTakeover(ctx), 'capability-switch: DSH skill takeover')
267
+ invalidateSkillCatalog(ctx)
268
+ ctx.effect(() => ctx.tools.register(tool(ctx, prefs, updates)), 'capability-switch: agent tool')
269
+ ctx.effect(() => updates.start(), 'capability-switch: auto update')
270
+
271
+ const routes = [
272
+ ['GET', '/state', async (_req, url, sessionCwd) => await state(ctx, prefs, sessionCwd || url.searchParams.get('cwd'), url.searchParams.get('workspaces') !== '0', updates)],
273
+ ['GET', '/skill', async (_req, url, sessionCwd) => await readSkill(url.searchParams.get('path'), requestedWorkspaceCwd(ctx, url.searchParams.get('cwd'), sessionCwd))],
274
+ ['POST', '/skill/create', async (body, _url, sessionCwd) => await createSkill({ ...body, cwd: projectCreateCwd(ctx, body, sessionCwd) })],
275
+ ['POST', '/workspace/create', async body => await createWorkspace(ctx, body)],
276
+ ['POST', '/skill/update', async (body, _url, sessionCwd) => await updateSkill(body.path, body.text, requestedWorkspaceCwd(ctx, body.cwd, sessionCwd))],
277
+ ['POST', '/skill/toggle', async (body, _url, sessionCwd) => await toggleSkill(body.path, body.enabled === true, requestedWorkspaceCwd(ctx, body.cwd, sessionCwd))],
278
+ ['POST', '/skill/delete', async (body, _url, sessionCwd) => await deleteSkill(body.path, body.confirm, requestedWorkspaceCwd(ctx, body.cwd, sessionCwd))],
279
+ ['GET', '/skill/sync-preview', async (_req, url) => await previewAgentSkillSync(url.searchParams.get('mode') || 'symlink')],
280
+ ['POST', '/skill/sync', async body => await syncAgentSkills(undefined, body.names, body.mode || 'symlink')],
281
+ ['GET', '/mcp/imports', async () => await listMcpImports(ctx)],
282
+ ['POST', '/mcp/import', async body => await importMcp(ctx, body.selections, undefined, body.enabled === true)],
283
+ ['POST', '/mcp/save', async body => await saveMcp(ctx, body)],
284
+ ['POST', '/mcp/toggle', async body => await toggleMcp(ctx, body.name, body.enabled)],
285
+ ['POST', '/mcp/delete', async body => await deleteMcp(ctx, body.name, body.confirm)],
286
+ ['POST', '/mcp/test', async body => await testMcp(ctx, body.name)],
287
+ ['POST', '/mcp/restart', async body => await restartMcp(ctx, body.name)],
288
+ ['POST', '/update/config', async body => await updates.setAutoUpdate(body.autoUpdate === true)],
289
+ ['POST', '/update/check', async () => await updates.check()],
290
+ ['POST', '/update/apply', async body => await updates.apply(body.version)],
291
+ ]
292
+
293
+ const skillMutationPaths = new Set(['/skill/create', '/skill/update', '/skill/toggle', '/skill/delete', '/skill/sync'])
294
+ const sessionPaths = new Set(['/state', '/skill', '/skill/create', '/skill/update', '/skill/toggle', '/skill/delete'])
295
+ const register = (webServer, scope) => {
296
+ for (const [method, suffix, handler] of routes) {
297
+ scope.effect(() => webServer.register({
298
+ kind: 'exact', path: BASE + suffix,
299
+ handler: async (req, res) => {
300
+ const rejection = requestRejection(scope, req)
301
+ if (rejection !== undefined) return send(res, rejection, { ok: false, error: 'DSH 连接鉴权拒绝' })
302
+ if ((req.method || 'GET').toUpperCase() !== method) return send(res, 405, { ok: false, error: '请求方法不匹配' })
303
+ try {
304
+ const url = new URL(req.url || BASE + suffix, 'http://127.0.0.1')
305
+ const sessionCwd = sessionPaths.has(suffix) ? await resolveSessionCwd(scope, requestSessionId(req)) : null
306
+ const payload = await handler(method === 'POST' ? await readJson(req) : req, url, sessionCwd)
307
+ if (skillMutationPaths.has(suffix)) invalidateSkillCatalog(scope)
308
+ send(res, 200, payload?.ok === true ? payload : { ok: true, ...(payload || {}) })
309
+ } catch (error) {
310
+ send(res, 400, { ok: false, error: error?.message || String(error) })
311
+ }
312
+ },
313
+ }), 'capability-switch: ' + method + ' ' + suffix)
314
+ }
315
+ }
316
+
317
+ const webServer = ctx.get('webServer')
318
+ if (webServer) register(webServer, ctx)
319
+ else ctx.inject(['webServer'], scope => register(scope.webServer, scope))
320
+ }