@crocketc/dsh-capability-manager 0.0.0-stage → 0.1.1

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/src/host.js ADDED
@@ -0,0 +1,234 @@
1
+ import { estimateTextTokens, measureInitialRequest } from './measurement.js'
2
+ import { reservedTools, skillEnabled, toolEnabled } from './policy.js'
3
+ import { excludedRuntimeSection } from './accounting.js'
4
+
5
+ const builtinTools = new Set((
6
+ 'bash pwsh shell fs read write edit apply_patch glob grep ls list_files read_file write_file edit_file ' +
7
+ 'read_image search_files skill todo_write schedule sleep web_search web_fetch ask_user_question ' +
8
+ 'exit_plan_mode enter_plan_mode subagent subagent_fork subagent_control workflow present_files ' +
9
+ 'working_directory jobs job_start job_wait job_list job_kill job_output get_goal create_goal update_goal ' +
10
+ 'run_code session_query plan_mode plan document read_document create_document load_workspace_dependencies ' +
11
+ 'str_replace_editor wait_agent list_agents send_message interrupt_agent list_subagent_models present cordis_inspect lsp ' +
12
+ 'session_send_message list_workspace list_session schedule_create schedule_list schedule_view schedule_edit ' +
13
+ 'team_task_create team_task_list team_task_get team_task_update terminal_open terminal_send terminal_read terminal_signal terminal_close ' +
14
+ 'plugin_manager cordis_inspect_list cordis_inspect_query office_render office_convert office_recalculate'
15
+ ).split(' '))
16
+
17
+ export function groupOf(name) {
18
+ if (name.startsWith('mcp__')) return 'mcp'
19
+ return builtinTools.has(name) ? 'builtin' : 'unknown'
20
+ }
21
+
22
+ export function originOf(group) {
23
+ return group === 'builtin' ? 'dsh' : group
24
+ }
25
+
26
+ function projected(definition) {
27
+ const { name, description, parameters, deferLoading } = definition
28
+ return { name, description, parameters, ...(deferLoading === true ? { deferLoading } : {}) }
29
+ }
30
+
31
+ function labelForTool(name, group) {
32
+ if (group === 'mcp') return name.split('__')[1]
33
+ if (group === 'builtin') return '内置工具'
34
+ return group === 'plugin' ? '插件工具' : '来源未知'
35
+ }
36
+
37
+ export function groupForDefinition(definition) {
38
+ const known = groupOf(definition.name)
39
+ if (known !== 'unknown') return known
40
+ if (definition.source?.kind === 'plugin' || typeof definition.plugin === 'string') return 'plugin'
41
+ return 'unknown'
42
+ }
43
+
44
+ export function isWorkspaceSkill(skill) {
45
+ return skill.source?.startsWith('project-') === true
46
+ }
47
+
48
+ export function readDefinitions(api, scope) {
49
+ if (typeof api.definitions === 'function') return [...api.definitions(scope)]
50
+ const root = api.selectRoot(scope)
51
+ return typeof root.bindings === 'function'
52
+ ? [...root.bindings(scope), ...api.getAll(scope)]
53
+ : [...api.getAll(scope)]
54
+ }
55
+
56
+ export function applyScopedToolVisibility(api, policyForScope) {
57
+ // RC5 uses the same view for discovery, step admission and direct execution.
58
+ // Its native restriction only applies to inherited registrations.
59
+ if (typeof api.view !== 'function') return () => {}
60
+ const original = api.view
61
+ function view(scope) {
62
+ const result = original.call(this, scope)
63
+ const denied = policyForScope(scope)?.disabledTools
64
+ if (!denied?.length) return result
65
+ for (const name of denied) {
66
+ result.visible.delete(name)
67
+ result.registrations.delete(name)
68
+ }
69
+ return result
70
+ }
71
+ api.view = view
72
+ return () => {
73
+ if (api.view === view) api.view = original
74
+ }
75
+ }
76
+
77
+ export function applySkillVisibility(registry, policyForScope) {
78
+ const originals = Object.fromEntries(['get', 'list', 'snapshot'].map(name => [name, registry[name]]))
79
+ const replacements = {
80
+ get: async function (name, options) {
81
+ const policy = policyForScope(options?.scope)
82
+ if (policy && !skillEnabled(policy, name)) return undefined
83
+ return originals.get.call(this, name, options)
84
+ },
85
+ list: async function (options) {
86
+ const policy = policyForScope(options?.scope)
87
+ const value = await originals.list.call(this, options)
88
+ return policy ? value.filter(skill => skillEnabled(policy, skill.name)) : value
89
+ },
90
+ snapshot: async function (options) {
91
+ const policy = policyForScope(options?.scope)
92
+ const value = await originals.snapshot.call(this, options)
93
+ return policy ? { ...value, skills: value.skills.filter(skill => skillEnabled(policy, skill.name)) } : value
94
+ },
95
+ }
96
+ for (const name of Object.keys(replacements)) registry[name] = replacements[name]
97
+ return () => {
98
+ for (const name of Object.keys(replacements)) {
99
+ if (registry[name] === replacements[name]) registry[name] = originals[name]
100
+ }
101
+ }
102
+ }
103
+
104
+ const catalogRequest = { header: { reason: 'initial', startsSeries: true }, turn: 0, step: 0 }
105
+
106
+ export function textOf(section, variables) {
107
+ return section.interpolate === false
108
+ ? section.text
109
+ : section.text.replace(/{{([a-z][a-z0-9_]*)}}/g, (_, key) => variables[key] ?? '')
110
+ }
111
+
112
+ function skillLine(skill) {
113
+ const description = skill.description.replace(/\s+/g, ' ').trim()
114
+ const short = description.length > 500 ? description.slice(0, 497) + '...' : description
115
+ return '- `' + skill.name + '`: ' + short.replace(/[&<>]/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[char]) + '\n'
116
+ }
117
+
118
+ function initialSkillCatalog(lines) {
119
+ return [
120
+ '<system-reminder>',
121
+ 'A skill is a reusable set of task-specific instructions. The following skills are available in this session:',
122
+ '',
123
+ '<available_skills>',
124
+ ...lines.map(line => line.trimEnd()),
125
+ '</available_skills>',
126
+ '',
127
+ 'If the user names a skill, or the task clearly matches a skill\'s description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill\'s instructions until it has been loaded.',
128
+ 'A user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.',
129
+ '</system-reminder>',
130
+ ].join('\n')
131
+ }
132
+
133
+ export async function inspectPreset(ctx, scope, cwd, model) {
134
+ const api = ctx.tools
135
+ const legacy = typeof api.definitions === 'function'
136
+ const defaults = readDefinitions(api, scope)
137
+ const root = legacy ? api.selectExecutor(scope) : api.selectRoot(scope)
138
+ const ptcSection = root.sections?.find(section => section.name === 'tools:sdk')
139
+ const ptc = !!ptcSection || typeof root.renderSdk === 'function'
140
+ const runCode = ptc ? (legacy ? root.describe(defaults).schemas : api.getAll(scope).map(projected))
141
+ .find(tool => tool.name === 'run_code') : undefined
142
+ const skills = await ctx.skills.list({ scope, cwd })
143
+ return { legacy, defaults, ptc, ptcSection, runCode, skills, scope, model }
144
+ }
145
+
146
+ export async function preview(ctx, facts, policy, globalDefinitions, declarations) {
147
+ const { legacy, defaults, ptcSection, ptc, runCode, skills, scope, model } = facts
148
+ const defaultByName = new Map(defaults.map(tool => [tool.name, tool]))
149
+ const fixed = name => reservedTools.has(name)
150
+ const selected = new Map(defaults.filter(tool => fixed(tool.name) || toolEnabled(policy, tool.name, true)).map(tool => [tool.name, tool]))
151
+ const exposed = [...selected.values()].filter(tool => !tool.deferLoading)
152
+ const map = new Map(exposed.map(tool => [tool.name, tool]))
153
+ const legacySet = { view: key => key === scope ? map : new Map() }
154
+ const transport = defaultByName.get('run_code')
155
+ const step = { agent: scope, declarations: ptc ? [transport] : exposed, declares: tool => tool === transport || map.get(tool.name) === tool }
156
+ const assembly = await ctx.systemPrompt.assemble({
157
+ scope, modelSelection: model, ...(legacy ? { toolSet: legacySet } : { toolStep: step }),
158
+ })
159
+ const tools = new Map()
160
+ const groups = new Map()
161
+ for (const tool of [...defaults, ...globalDefinitions]) {
162
+ if (tools.has(tool.name)) continue
163
+ const group = groupForDefinition(tool)
164
+ groups.set(tool.name, group)
165
+ const available = defaultByName.has(tool.name)
166
+ tools.set(tool.name, {
167
+ name: tool.name, description: tool.description, group, source: labelForTool(tool.name, group),
168
+ available, defaultEnabled: available, enabled: selected.has(tool.name), fixed: available && fixed(tool.name),
169
+ reason: available ? undefined : '当前预设无法单独挂载此工具',
170
+ tokens: estimateTextTokens(JSON.stringify(projected(tool))) + 4,
171
+ })
172
+ }
173
+ if (runCode && !tools.has(runCode.name)) {
174
+ tools.set(runCode.name, {
175
+ ...runCode, group: 'builtin', source: 'PTC 入口', available: true, defaultEnabled: true, enabled: true, fixed: true,
176
+ tokens: estimateTextTokens(JSON.stringify(runCode)) + 4,
177
+ })
178
+ groups.set(runCode.name, 'builtin')
179
+ }
180
+ for (const row of tools.values()) {
181
+ if (ptc && row.name !== 'run_code' && ptcSection) {
182
+ const tool = defaultByName.get(row.name) ?? globalDefinitions.find(item => item.name === row.name)
183
+ if (tool) {
184
+ const fragments = declarations(ptcSection.text([tool]), groups)
185
+ row.tokens = estimateTextTokens(fragments.map(part => part.text).join(''))
186
+ }
187
+ }
188
+ }
189
+ const skillRows = skills.map(skill => {
190
+ const workspace = isWorkspaceSkill(skill)
191
+ const available = defaultByName.has('skill') && (skill.invocation?.modelInvocable !== false || skill.invocation?.userInvocable !== false)
192
+ return {
193
+ name: skill.name, description: skill.description, group: workspace ? 'workspace' : 'global',
194
+ source: skill.source, workspace, available, modelInvocable: skill.invocation?.modelInvocable !== false,
195
+ defaultEnabled: available && !policy.importedSkills.includes(skill.name), enabled: available && skillEnabled(policy, skill.name),
196
+ tokens: estimateTextTokens(skillLine(skill)),
197
+ line: skillLine(skill),
198
+ }
199
+ })
200
+ const visibleSkills = selected.has('skill') ? skillRows.filter(skill => skill.enabled && skill.modelInvocable) : []
201
+ const systemParts = []
202
+ let sdkText
203
+ for (const section of assembly.sections) {
204
+ const text = textOf(section, assembly.variables)
205
+ if (section.name === 'tools:sdk') sdkText = text
206
+ else systemParts.push({ kind: section.name.startsWith('tool') ? 'tool-prompt' : 'base-system', text })
207
+ }
208
+ const contexts = assembly.contexts.filter(section => !excludedRuntimeSection(section.name))
209
+ .map(section => textOf(section, assembly.variables)).filter(Boolean)
210
+ if (contexts.length) systemParts.push({ kind: 'automatic',
211
+ text: `<system-reminder>\nThe following information describes your current session:\n\n${contexts.join('\n\n')}\n</system-reminder>`,
212
+ })
213
+ if (visibleSkills.length) systemParts.push({ kind: 'skill-catalog', text: initialSkillCatalog(visibleSkills.map(skill => skill.line)) })
214
+ const fragments = sdkText ? declarations(sdkText, groups) : []
215
+ const sdkTools = [...new Set(fragments.map(fragment => fragment.name))]
216
+ const schemas = ptc ? (runCode ? [runCode] : []) : assembly.tools
217
+ const measured = measureInitialRequest({
218
+ request: catalogRequest, promptParts: systemParts,
219
+ tools: [
220
+ ...schemas.map(schema => ({ name: schema.name, source: originOf(groups.get(schema.name) ?? 'unknown'),
221
+ mode: schema.name === 'run_code' ? 'run-code' : 'native', schema })),
222
+ ...sdkTools.map(name => ({ name, source: originOf(groups.get(name) ?? 'unknown'), mode: 'ptc' })),
223
+ ],
224
+ ...(sdkText ? { ptcSdk: { text: sdkText, declarations: fragments } } : {}),
225
+ })
226
+ measured.prompt.workspaceSkillCatalogTokens = estimateTextTokens(visibleSkills.filter(skill => skill.workspace)
227
+ .map(skill => skill.line.trimEnd()).join('\n'))
228
+ for (const row of measured.toolRows) if (tools.has(row.name)) tools.get(row.name).tokens = row.tokens
229
+ return {
230
+ measured, tools: [...tools.values()], groups,
231
+ skills: skillRows.map(({ line, modelInvocable, workspace, ...row }) => row),
232
+ count: selected.size + Number(Boolean(runCode) && !selected.has('run_code')) + skillRows.filter(skill => skill.enabled).length,
233
+ }
234
+ }
package/src/index.js ADDED
@@ -0,0 +1,273 @@
1
+ import { homedir } from 'node:os'
2
+ import { join, resolve } from 'node:path'
3
+ import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
4
+ import { randomUUID } from 'node:crypto'
5
+ import { openPolicyStore } from './policy.js'
6
+ import { applyScopedToolVisibility, applySkillVisibility, groupForDefinition, inspectPreset, isWorkspaceSkill, preview, readDefinitions, textOf } from './host.js'
7
+ import { quoteMonthly } from './pricing.js'
8
+ import { formatBudget, readInitial, sdkDeclarations } from './accounting.js'
9
+ import { importSkill, searchSkills } from './discovery.js'
10
+
11
+ export const name = 'dsh-capability-manager'
12
+ export const inject = ['connection', 'agentPresets', 'agents', 'workspaceRegistry', 'skills', 'tools', 'systemPrompt', 'agentDefaultModel', 'llm']
13
+
14
+ const presetNames = { standard: '标准模式', ptc: 'PTC 模式', minimal: '极简模式', cordis: '创造模式', creative: '创造模式' }
15
+ const globalHome = () => resolve(process.env.DSH_HOME?.trim() || join(homedir(), '.dsh'))
16
+
17
+ async function usingPreset(ctx, id, read) {
18
+ const lease = await ctx.agentPresets.acquireScope(id)
19
+ try {
20
+ return await read(lease.key)
21
+ } finally {
22
+ await lease[Symbol.asyncDispose]()
23
+ }
24
+ }
25
+
26
+ function makeError(message, status = 400) {
27
+ return Object.assign(new Error(message), { status })
28
+ }
29
+
30
+ function validatedPolicy(draft, saved, tools, skills) {
31
+ if (!draft || typeof draft !== 'object') throw makeError('提交后才能保存预设')
32
+ const clean = {}
33
+ for (const [field, rows] of [
34
+ ['disabledTools', tools], ['enabledTools', tools], ['disabledSkills', skills], ['enabledSkills', skills],
35
+ ]) {
36
+ if (!Array.isArray(draft[field]) || draft[field].length > 10_000 ||
37
+ draft[field].some(value => typeof value !== 'string' || !value || value.length > 256)) {
38
+ throw makeError('无效的能力清单')
39
+ }
40
+ const editable = new Set(rows.filter(row => row.available && !row.fixed).map(row => row.name))
41
+ clean[field] = [...new Set([...saved[field].filter(value => !editable.has(value)), ...draft[field].filter(value => editable.has(value))])]
42
+ }
43
+ return { ...clean, importedSkills: saved.importedSkills }
44
+ }
45
+
46
+ export async function apply(ctx) {
47
+ const home = globalHome()
48
+ const store = await openPolicyStore(join(home, 'dsh-capability-manager.json'))
49
+ const policies = new WeakMap()
50
+ const firstSystemSections = new WeakMap()
51
+ const collected = new WeakSet()
52
+ const recording = new Map()
53
+ const recordsDir = join(home, 'capability-manager-first-requests')
54
+ const settingRestrictions = new WeakMap()
55
+ const removedOnDispose = new Set()
56
+ const refreshSkillMethods = applySkillVisibility(ctx.skills, scope => policies.get(scope))
57
+ const restoreToolView = applyScopedToolVisibility(ctx.tools, scope => policies.get(scope))
58
+ ctx.effect(() => () => {
59
+ refreshSkillMethods()
60
+ restoreToolView()
61
+ for (const dispose of removedOnDispose) dispose()
62
+ }, 'capability-manager.runtime')
63
+
64
+ function bind(agent) {
65
+ const presetId = ctx.agentPresets.composedPreset(agent.ctx)
66
+ const previous = settingRestrictions.get(agent)
67
+ if (previous) {
68
+ previous()
69
+ settingRestrictions.delete(agent)
70
+ }
71
+ if (!presetId) {
72
+ policies.delete(agent)
73
+ return
74
+ }
75
+ const policy = store.get(presetId)
76
+ const names = ctx.tools.view?.(agent)?.restrictableNames ?? new Set(readDefinitions(ctx.tools, agent).map(tool => tool.name))
77
+ const deny = policy.disabledTools.filter(tool => names.has(tool))
78
+ if (deny.length) {
79
+ const releaseMask = agent.ctx.tools.restrict({ deny })
80
+ const dispose = () => {
81
+ removedOnDispose.delete(dispose)
82
+ releaseMask()
83
+ }
84
+ removedOnDispose.add(dispose)
85
+ settingRestrictions.set(agent, dispose)
86
+ }
87
+ policies.set(agent, policy)
88
+ }
89
+
90
+ ctx.on('agent/created', ({ agent, source }) => {
91
+ if (source === 'startup' || source === 'clear') bind(agent)
92
+ })
93
+ ctx.on('agent-preset/selected', id => {
94
+ const agent = ctx.agents.get(id)
95
+ if (agent) bind(agent)
96
+ })
97
+ ctx.on('agent/disposed', ({ agent }) => {
98
+ const dispose = agent && settingRestrictions.get(agent)
99
+ if (dispose) dispose()
100
+ })
101
+ ctx.on('system-prompt/assemble', async (presentation, { scope }, next) => {
102
+ const result = await next()
103
+ if (scope && policies.has(scope) && !collected.has(scope) && !firstSystemSections.has(scope)) {
104
+ firstSystemSections.set(scope, result.sections.map(section => ({
105
+ name: section.name, text: textOf(section, result.variables),
106
+ })).filter(section => section.text))
107
+ }
108
+ return result
109
+ })
110
+ const recordPath = id => typeof id === 'string' && /^session-[a-z0-9-]{8,120}$/i.test(id)
111
+ ? join(recordsDir, `${id}.json`) : undefined
112
+
113
+ ctx.on('session/event', (session, event) => {
114
+ if (event.type !== 'assistant/message' || session.header.isSeeded || !recordPath(session.id)) return
115
+ const agent = ctx.agents.get(session.id)
116
+ if (!agent || !policies.has(agent) || collected.has(agent) || recording.has(session.id)) return
117
+ const task = recordFirstRequest(agent, session)
118
+ recording.set(session.id, task)
119
+ void task.catch(error => ctx.logger.warn(`Agent capability record: ${String(error)}`))
120
+ .finally(() => recording.delete(session.id))
121
+ })
122
+
123
+ async function recordFirstRequest(agent, session) {
124
+ const sections = firstSystemSections.get(agent)
125
+ const groups = new Map(readDefinitions(ctx.tools, agent).map(tool => [tool.name, groupForDefinition(tool)]))
126
+ const workspace = ctx.workspaceRegistry.list().find(row => row.sessionIds.includes(session.id))
127
+ const workspaceSkillNames = new Set((await ctx.skills.list({ scope: agent, cwd: session.header.cwd }))
128
+ .filter(isWorkspaceSkill).map(skill => skill.name))
129
+ const measured = readInitial(session.ownEvents(), {
130
+ presetId: session.header.agentPreset ?? ctx.agentPresets.composedPreset(agent.ctx),
131
+ workspaceId: workspace?.id ?? '',
132
+ groupByName: groups, firstSystemSections: sections, workspaceSkillNames,
133
+ baseSectionNames: sections?.filter(section => !section.name.startsWith('tool')).map(section => section.name)
134
+ ?? ['harness:identity', 'deployment:persona-prefix', 'deployment:persona-suffix'],
135
+ })
136
+ if (!measured) return
137
+ const record = {
138
+ presetId: measured.presetId, workspaceId: measured.workspaceId,
139
+ model: measured.request.model, provider: measured.request.provider,
140
+ inputTokens: measured.measured.totals.providerUsageInputTokens,
141
+ budget: formatBudget(measured, measured.count),
142
+ }
143
+ await mkdir(recordsDir, { recursive: true })
144
+ const file = recordPath(session.id)
145
+ const temporary = `${file}.${randomUUID()}.tmp`
146
+ try {
147
+ await writeFile(temporary, JSON.stringify(record), { flag: 'wx' })
148
+ await rename(temporary, file)
149
+ } finally {
150
+ await rm(temporary, { force: true })
151
+ }
152
+ collected.add(agent)
153
+ firstSystemSections.delete(agent)
154
+ return record
155
+ }
156
+
157
+ async function getRecord(id) {
158
+ const file = recordPath(id)
159
+ if (!file) return undefined
160
+ try {
161
+ const pending = recording.get(id)
162
+ if (pending) return await pending
163
+ return JSON.parse(await readFile(file, 'utf8'))
164
+ } catch (error) {
165
+ if (error.code !== 'ENOENT') ctx.logger.warn(`Agent capability record read: ${String(error)}`)
166
+ return undefined
167
+ }
168
+ }
169
+
170
+ async function state(body, save = false) {
171
+ const all = await ctx.agentPresets.list()
172
+ const presets = all.map(preset => ({
173
+ id: preset.id, name: preset.name ?? presetNames[preset.id] ?? preset.id,
174
+ available: !preset.broken, reason: preset.broken,
175
+ }))
176
+ const allWorkspaces = ctx.workspaceRegistry.list()
177
+ const workspaces = allWorkspaces.map(workspace => ({ id: workspace.id, name: workspace.title }))
178
+ const activeWorkspace = allWorkspaces.find(workspace => workspace.sessionIds.includes(body.sessionId))
179
+ const workspaceId = body.workspaceId ?? activeWorkspace?.id ?? ''
180
+ const workspace = allWorkspaces.find(row => row.id === workspaceId)
181
+ if (workspaceId && !workspace) throw makeError('所选工作区不存在')
182
+ const presetId = body.presetId || ctx.agentPresets.defaultId || presets.find(preset => preset.available)?.id || ''
183
+ const preset = presets.find(row => row.id === presetId)
184
+ if (body.presetId && !preset) throw makeError('所选 Agent 预设不存在')
185
+ const policy = store.get(presetId)
186
+ const shell = { presets, presetId, workspaces, workspaceId, policy }
187
+ const emptyBudget = { count: 0, capability: 0, total: 0, breakdown: [] }
188
+ if (!preset?.available) {
189
+ if (save) throw makeError(preset?.reason ?? '当前没有可用的 Agent 预设')
190
+ return { ...shell, tools: [], skills: [], budget: emptyBudget, savedBudget: emptyBudget,
191
+ pricing: { status: '默认模型不可用' } }
192
+ }
193
+
194
+ let model
195
+ let pricingError = false
196
+ try { model = ctx.agentDefaultModel.currentSelection() } catch { pricingError = true }
197
+ const otherTools = new Map()
198
+ const addTools = tools => {
199
+ for (const tool of tools) if (!otherTools.has(tool.name) && tool.name !== 'run_code') otherTools.set(tool.name, tool)
200
+ }
201
+ try { addTools(readDefinitions(ctx.tools)) } catch { /* Web profiles can have no unscoped executor. */ }
202
+ await Promise.all(presets.filter(row => row.available && row.id !== presetId).map(row =>
203
+ usingPreset(ctx, row.id, scope => addTools(readDefinitions(ctx.tools, scope))).catch(error => {
204
+ ctx.logger.debug(`Capability inventory for ${row.id}: ${String(error)}`)
205
+ }),
206
+ ))
207
+ return usingPreset(ctx, presetId, async scope => {
208
+ const args = [...otherTools.values()]
209
+ const facts = await inspectPreset(ctx, scope, workspace?.path, model)
210
+ const baseline = await preview(ctx, facts, policy, args, sdkDeclarations)
211
+ const draft = body.draft ? validatedPolicy(body.draft, policy, baseline.tools, baseline.skills) : policy
212
+ if (save && !body.draft) throw makeError('缺少待保存的预设开关')
213
+ const current = body.draft ? await preview(ctx, facts, draft, args, sdkDeclarations) : baseline
214
+ if (save) await store.save(presetId, draft)
215
+ const budget = formatBudget(current.measured, current.count)
216
+ const savedBudget = save ? budget : formatBudget(baseline.measured, baseline.count)
217
+ let pricing
218
+ try {
219
+ const present = !!model && ctx.llm.listProviders().some(provider => provider.id === model.provider)
220
+ pricing = pricingError ? { status: '无法读取默认模型' } : quoteMonthly(model, budget.capability - savedBudget.capability, budget.total, present)
221
+ } catch {
222
+ pricing = { status: '无法读取默认模型' }
223
+ }
224
+
225
+ const actual = await getRecord(body.sessionId)
226
+ return { ...shell, policy: save ? store.get(presetId) : policy, tools: current.tools, skills: current.skills,
227
+ budget, savedBudget, pricing, actual }
228
+ })
229
+ }
230
+
231
+ async function route(request) {
232
+ if (request.headers.get('x-dsh-capability-manager') !== '1' ||
233
+ !request.headers.get('content-type')?.startsWith('application/json')) {
234
+ return Response.json({ error: '无效的插件请求' }, { status: 403 })
235
+ }
236
+ try {
237
+ const data = await request.text()
238
+ if (data.length > 1_048_576) throw makeError('请求内容过长', 413)
239
+ let body
240
+ try { body = JSON.parse(data) } catch { throw makeError('无效的 JSON 请求') }
241
+ if (!body || typeof body !== 'object') throw makeError('无效的请求数据')
242
+ if (body.action === 'state' || body.action === 'save') return Response.json(await state(body, body.action === 'save'))
243
+ if (body.action === 'search') return Response.json({ results: await searchSkills(body.source, body.query) })
244
+ if (body.action === 'import') {
245
+ const workspace = body.target === 'workspace' && ctx.workspaceRegistry.get(body.workspaceId)
246
+ if (body.target !== 'global' && !workspace) throw makeError('请先选定要导入的工作区')
247
+ const destination = workspace ? join(workspace.path, '.dsh', 'skills') : join(home, 'skills')
248
+ const imported = await importSkill(body.selection, destination, async skillName => {
249
+ const all = await ctx.agentPresets.list()
250
+ const contexts = workspace ? [workspace.path] : [undefined, ...ctx.workspaceRegistry.list().map(row => row.path)]
251
+ for (const preset of all.filter(item => !item.broken)) {
252
+ await usingPreset(ctx, preset.id, async scope => {
253
+ for (const cwd of contexts) {
254
+ const existing = await ctx.skills.list({ cwd, scope })
255
+ if (existing.some(skill => skill.name === skillName)) throw makeError('DSH 已识别到同名技能', 409)
256
+ }
257
+ })
258
+ }
259
+ }, (skillName, publish) => store.registerImport(skillName, publish))
260
+ return Response.json(imported)
261
+ }
262
+ throw makeError('未知的插件操作')
263
+ } catch (error) {
264
+ const status = error.status ?? (error.code === 'EEXIST' ? 409 : 500)
265
+ if (status === 500) ctx.logger.warn(`Agent capability manager: ${String(error)}`)
266
+ return Response.json({ error: error.message ?? String(error) }, { status })
267
+ }
268
+ }
269
+
270
+ ctx.effect(() => ctx.connection.fetch.register({
271
+ path: '/api/dsh-capability-manager', methods: ['POST'], requestBody: 'buffered', fetch: route,
272
+ }), 'capability-manager.http')
273
+ }