@crocketc/dsh-capability-manager 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +107 -3
- package/cordis.patch.yml +3 -0
- package/data/catalog.json +22495 -0
- package/package.json +16 -4
- package/src/accounting.js +337 -0
- package/src/client.js +407 -0
- package/src/discovery.js +214 -0
- package/src/host.js +253 -0
- package/src/index.js +273 -0
- package/src/measurement.js +232 -0
- package/src/policy.js +84 -0
- package/src/pricing.js +39 -0
- package/src/vendor/LICENSE +21 -0
- package/src/vendor/pricing-validation.cjs +95 -0
- package/src/vendor/pricing.cjs +669 -0
package/src/host.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
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 (mcpServerOf(name)) 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 mcpServerOf(name) {
|
|
32
|
+
if (typeof name !== 'string') return undefined
|
|
33
|
+
const match = /^mcp__(.+?)__(.+)$/.exec(name)
|
|
34
|
+
return match?.[1]
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function pluginLabel(definition) {
|
|
38
|
+
const source = definition.source
|
|
39
|
+
const label = typeof source === 'object' && source !== null && source.kind === 'plugin'
|
|
40
|
+
? source.plugin ?? source.name ?? source.id
|
|
41
|
+
: source?.plugin
|
|
42
|
+
return typeof label === 'string' && label.trim() ? label.trim()
|
|
43
|
+
: typeof definition.plugin === 'string' && definition.plugin.trim() ? definition.plugin.trim()
|
|
44
|
+
: '插件工具'
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function labelForTool(name, group, definition) {
|
|
48
|
+
if (group === 'mcp') return mcpServerOf(name)
|
|
49
|
+
if (group === 'builtin') return '内置工具'
|
|
50
|
+
return group === 'plugin' ? pluginLabel(definition) : '来源未知'
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function groupForDefinition(definition) {
|
|
54
|
+
const known = groupOf(definition.name)
|
|
55
|
+
if (known !== 'unknown') return known
|
|
56
|
+
const sourcePlugin = definition.source?.plugin
|
|
57
|
+
if (definition.source?.kind === 'plugin'
|
|
58
|
+
|| (typeof sourcePlugin === 'string' && sourcePlugin.trim())
|
|
59
|
+
|| (typeof definition.plugin === 'string' && definition.plugin.trim())) return 'plugin'
|
|
60
|
+
return 'unknown'
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function isWorkspaceSkill(skill) {
|
|
64
|
+
return skill.source?.startsWith('project-') === true
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function readDefinitions(api, scope) {
|
|
68
|
+
if (typeof api.definitions === 'function') return [...api.definitions(scope)]
|
|
69
|
+
const root = api.selectRoot(scope)
|
|
70
|
+
return typeof root.bindings === 'function'
|
|
71
|
+
? [...root.bindings(scope), ...api.getAll(scope)]
|
|
72
|
+
: [...api.getAll(scope)]
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function applyScopedToolVisibility(api, policyForScope) {
|
|
76
|
+
// RC5 uses the same view for discovery, step admission and direct execution.
|
|
77
|
+
// Its native restriction only applies to inherited registrations.
|
|
78
|
+
if (typeof api.view !== 'function') return () => {}
|
|
79
|
+
const original = api.view
|
|
80
|
+
function view(scope) {
|
|
81
|
+
const result = original.call(this, scope)
|
|
82
|
+
const denied = policyForScope(scope)?.disabledTools
|
|
83
|
+
if (!denied?.length) return result
|
|
84
|
+
for (const name of denied) {
|
|
85
|
+
result.visible.delete(name)
|
|
86
|
+
result.registrations.delete(name)
|
|
87
|
+
}
|
|
88
|
+
return result
|
|
89
|
+
}
|
|
90
|
+
api.view = view
|
|
91
|
+
return () => {
|
|
92
|
+
if (api.view === view) api.view = original
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function applySkillVisibility(registry, policyForScope) {
|
|
97
|
+
const originals = Object.fromEntries(['get', 'list', 'snapshot'].map(name => [name, registry[name]]))
|
|
98
|
+
const replacements = {
|
|
99
|
+
get: async function (name, options) {
|
|
100
|
+
const policy = policyForScope(options?.scope)
|
|
101
|
+
if (policy && !skillEnabled(policy, name)) return undefined
|
|
102
|
+
return originals.get.call(this, name, options)
|
|
103
|
+
},
|
|
104
|
+
list: async function (options) {
|
|
105
|
+
const policy = policyForScope(options?.scope)
|
|
106
|
+
const value = await originals.list.call(this, options)
|
|
107
|
+
return policy ? value.filter(skill => skillEnabled(policy, skill.name)) : value
|
|
108
|
+
},
|
|
109
|
+
snapshot: async function (options) {
|
|
110
|
+
const policy = policyForScope(options?.scope)
|
|
111
|
+
const value = await originals.snapshot.call(this, options)
|
|
112
|
+
return policy ? { ...value, skills: value.skills.filter(skill => skillEnabled(policy, skill.name)) } : value
|
|
113
|
+
},
|
|
114
|
+
}
|
|
115
|
+
for (const name of Object.keys(replacements)) registry[name] = replacements[name]
|
|
116
|
+
return () => {
|
|
117
|
+
for (const name of Object.keys(replacements)) {
|
|
118
|
+
if (registry[name] === replacements[name]) registry[name] = originals[name]
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const catalogRequest = { header: { reason: 'initial', startsSeries: true }, turn: 0, step: 0 }
|
|
124
|
+
|
|
125
|
+
export function textOf(section, variables) {
|
|
126
|
+
return section.interpolate === false
|
|
127
|
+
? section.text
|
|
128
|
+
: section.text.replace(/{{([a-z][a-z0-9_]*)}}/g, (_, key) => variables[key] ?? '')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function skillLine(skill) {
|
|
132
|
+
const description = skill.description.replace(/\s+/g, ' ').trim()
|
|
133
|
+
const short = description.length > 500 ? description.slice(0, 497) + '...' : description
|
|
134
|
+
return '- `' + skill.name + '`: ' + short.replace(/[&<>]/g, char => ({ '&': '&', '<': '<', '>': '>' })[char]) + '\n'
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function initialSkillCatalog(lines) {
|
|
138
|
+
return [
|
|
139
|
+
'<system-reminder>',
|
|
140
|
+
'A skill is a reusable set of task-specific instructions. The following skills are available in this session:',
|
|
141
|
+
'',
|
|
142
|
+
'<available_skills>',
|
|
143
|
+
...lines.map(line => line.trimEnd()),
|
|
144
|
+
'</available_skills>',
|
|
145
|
+
'',
|
|
146
|
+
'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.',
|
|
147
|
+
'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.',
|
|
148
|
+
'</system-reminder>',
|
|
149
|
+
].join('\n')
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export async function inspectPreset(ctx, scope, cwd, model) {
|
|
153
|
+
const api = ctx.tools
|
|
154
|
+
const legacy = typeof api.definitions === 'function'
|
|
155
|
+
const defaults = readDefinitions(api, scope)
|
|
156
|
+
const root = legacy ? api.selectExecutor(scope) : api.selectRoot(scope)
|
|
157
|
+
const ptcSection = root.sections?.find(section => section.name === 'tools:sdk')
|
|
158
|
+
const ptc = !!ptcSection || typeof root.renderSdk === 'function'
|
|
159
|
+
const runCode = ptc ? (legacy ? root.describe(defaults).schemas : api.getAll(scope).map(projected))
|
|
160
|
+
.find(tool => tool.name === 'run_code') : undefined
|
|
161
|
+
const skills = await ctx.skills.list({ scope, cwd })
|
|
162
|
+
return { legacy, defaults, ptc, ptcSection, runCode, skills, scope, model }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export async function preview(ctx, facts, policy, globalDefinitions, declarations) {
|
|
166
|
+
const { legacy, defaults, ptcSection, ptc, runCode, skills, scope, model } = facts
|
|
167
|
+
const defaultByName = new Map(defaults.map(tool => [tool.name, tool]))
|
|
168
|
+
const fixed = name => reservedTools.has(name)
|
|
169
|
+
const selected = new Map(defaults.filter(tool => fixed(tool.name) || toolEnabled(policy, tool.name, true)).map(tool => [tool.name, tool]))
|
|
170
|
+
const exposed = [...selected.values()].filter(tool => !tool.deferLoading)
|
|
171
|
+
const map = new Map(exposed.map(tool => [tool.name, tool]))
|
|
172
|
+
const legacySet = { view: key => key === scope ? map : new Map() }
|
|
173
|
+
const transport = defaultByName.get('run_code')
|
|
174
|
+
const step = { agent: scope, declarations: ptc ? [transport] : exposed, declares: tool => tool === transport || map.get(tool.name) === tool }
|
|
175
|
+
const assembly = await ctx.systemPrompt.assemble({
|
|
176
|
+
scope, modelSelection: model, ...(legacy ? { toolSet: legacySet } : { toolStep: step }),
|
|
177
|
+
})
|
|
178
|
+
const tools = new Map()
|
|
179
|
+
const groups = new Map()
|
|
180
|
+
for (const tool of [...defaults, ...globalDefinitions]) {
|
|
181
|
+
if (tools.has(tool.name)) continue
|
|
182
|
+
const group = groupForDefinition(tool)
|
|
183
|
+
groups.set(tool.name, group)
|
|
184
|
+
const available = defaultByName.has(tool.name)
|
|
185
|
+
tools.set(tool.name, {
|
|
186
|
+
name: tool.name, description: tool.description, group, source: labelForTool(tool.name, group, tool),
|
|
187
|
+
available, defaultEnabled: available, enabled: selected.has(tool.name), fixed: available && fixed(tool.name),
|
|
188
|
+
reason: available ? undefined : '当前预设无法单独挂载此工具',
|
|
189
|
+
tokens: estimateTextTokens(JSON.stringify(projected(tool))) + 4,
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
if (runCode && !tools.has(runCode.name)) {
|
|
193
|
+
tools.set(runCode.name, {
|
|
194
|
+
...runCode, group: 'builtin', source: 'PTC 入口', available: true, defaultEnabled: true, enabled: true, fixed: true,
|
|
195
|
+
tokens: estimateTextTokens(JSON.stringify(runCode)) + 4,
|
|
196
|
+
})
|
|
197
|
+
groups.set(runCode.name, 'builtin')
|
|
198
|
+
}
|
|
199
|
+
for (const row of tools.values()) {
|
|
200
|
+
if (ptc && row.name !== 'run_code' && ptcSection) {
|
|
201
|
+
const tool = defaultByName.get(row.name) ?? globalDefinitions.find(item => item.name === row.name)
|
|
202
|
+
if (tool) {
|
|
203
|
+
const fragments = declarations(ptcSection.text([tool]), groups)
|
|
204
|
+
row.tokens = estimateTextTokens(fragments.map(part => part.text).join(''))
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const skillRows = skills.map(skill => {
|
|
209
|
+
const workspace = isWorkspaceSkill(skill)
|
|
210
|
+
const available = defaultByName.has('skill') && (skill.invocation?.modelInvocable !== false || skill.invocation?.userInvocable !== false)
|
|
211
|
+
return {
|
|
212
|
+
name: skill.name, description: skill.description, group: workspace ? 'workspace' : 'global',
|
|
213
|
+
source: skill.source, workspace, available, modelInvocable: skill.invocation?.modelInvocable !== false,
|
|
214
|
+
defaultEnabled: available && !policy.importedSkills.includes(skill.name), enabled: available && skillEnabled(policy, skill.name),
|
|
215
|
+
tokens: estimateTextTokens(skillLine(skill)),
|
|
216
|
+
line: skillLine(skill),
|
|
217
|
+
}
|
|
218
|
+
})
|
|
219
|
+
const visibleSkills = selected.has('skill') ? skillRows.filter(skill => skill.enabled && skill.modelInvocable) : []
|
|
220
|
+
const systemParts = []
|
|
221
|
+
let sdkText
|
|
222
|
+
for (const section of assembly.sections) {
|
|
223
|
+
const text = textOf(section, assembly.variables)
|
|
224
|
+
if (section.name === 'tools:sdk') sdkText = text
|
|
225
|
+
else systemParts.push({ kind: section.name.startsWith('tool') ? 'tool-prompt' : 'base-system', text })
|
|
226
|
+
}
|
|
227
|
+
const contexts = assembly.contexts.filter(section => !excludedRuntimeSection(section.name))
|
|
228
|
+
.map(section => textOf(section, assembly.variables)).filter(Boolean)
|
|
229
|
+
if (contexts.length) systemParts.push({ kind: 'automatic',
|
|
230
|
+
text: `<system-reminder>\nThe following information describes your current session:\n\n${contexts.join('\n\n')}\n</system-reminder>`,
|
|
231
|
+
})
|
|
232
|
+
if (visibleSkills.length) systemParts.push({ kind: 'skill-catalog', text: initialSkillCatalog(visibleSkills.map(skill => skill.line)) })
|
|
233
|
+
const fragments = sdkText ? declarations(sdkText, groups) : []
|
|
234
|
+
const sdkTools = [...new Set(fragments.map(fragment => fragment.name))]
|
|
235
|
+
const schemas = ptc ? (runCode ? [runCode] : []) : assembly.tools
|
|
236
|
+
const measured = measureInitialRequest({
|
|
237
|
+
request: catalogRequest, promptParts: systemParts,
|
|
238
|
+
tools: [
|
|
239
|
+
...schemas.map(schema => ({ name: schema.name, source: originOf(groups.get(schema.name) ?? 'unknown'),
|
|
240
|
+
mode: schema.name === 'run_code' ? 'run-code' : 'native', schema })),
|
|
241
|
+
...sdkTools.map(name => ({ name, source: originOf(groups.get(name) ?? 'unknown'), mode: 'ptc' })),
|
|
242
|
+
],
|
|
243
|
+
...(sdkText ? { ptcSdk: { text: sdkText, declarations: fragments } } : {}),
|
|
244
|
+
})
|
|
245
|
+
measured.prompt.workspaceSkillCatalogTokens = estimateTextTokens(visibleSkills.filter(skill => skill.workspace)
|
|
246
|
+
.map(skill => skill.line.trimEnd()).join('\n'))
|
|
247
|
+
for (const row of measured.toolRows) if (tools.has(row.name)) tools.get(row.name).tokens = row.tokens
|
|
248
|
+
return {
|
|
249
|
+
measured, tools: [...tools.values()], groups,
|
|
250
|
+
skills: skillRows.map(({ line, modelInvocable, workspace, ...row }) => row),
|
|
251
|
+
count: selected.size + Number(Boolean(runCode) && !selected.has('run_code')) + skillRows.filter(skill => skill.enabled).length,
|
|
252
|
+
}
|
|
253
|
+
}
|
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
|
+
}
|