@crocketc/dsh-capability-manager 0.1.1 → 0.3.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/src/host.js CHANGED
@@ -1,234 +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 (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
- }
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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[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 CHANGED
@@ -7,9 +7,10 @@ import { applyScopedToolVisibility, applySkillVisibility, groupForDefinition, in
7
7
  import { quoteMonthly } from './pricing.js'
8
8
  import { formatBudget, readInitial, sdkDeclarations } from './accounting.js'
9
9
  import { importSkill, searchSkills } from './discovery.js'
10
+ import { formatGitHubComparison } from './plugin-update.js'
10
11
 
11
12
  export const name = 'dsh-capability-manager'
12
- export const inject = ['connection', 'agentPresets', 'agents', 'workspaceRegistry', 'skills', 'tools', 'systemPrompt', 'agentDefaultModel', 'llm']
13
+ export const inject = ['connection', 'agentPresets', 'agents', 'workspaceRegistry', 'skills', 'tools', 'systemPrompt', 'agentDefaultModel', 'llm', 'pluginManager']
13
14
 
14
15
  const presetNames = { standard: '标准模式', ptc: 'PTC 模式', minimal: '极简模式', cordis: '创造模式', creative: '创造模式' }
15
16
  const globalHome = () => resolve(process.env.DSH_HOME?.trim() || join(homedir(), '.dsh'))
@@ -43,6 +44,15 @@ function validatedPolicy(draft, saved, tools, skills) {
43
44
  return { ...clean, importedSkills: saved.importedSkills }
44
45
  }
45
46
 
47
+ function categoryCountsFor(snapshot) {
48
+ const enabledTools = snapshot.tools.filter(row => row.enabled);
49
+ return {
50
+ tool: enabledTools.filter(row => row.group !== 'mcp').length,
51
+ mcp: enabledTools.filter(row => row.group === 'mcp').length,
52
+ skill: snapshot.skills.filter(row => row.enabled).length,
53
+ };
54
+ }
55
+
46
56
  export async function apply(ctx) {
47
57
  const home = globalHome()
48
58
  const store = await openPolicyStore(join(home, 'dsh-capability-manager.json'))
@@ -212,8 +222,8 @@ export async function apply(ctx) {
212
222
  if (save && !body.draft) throw makeError('缺少待保存的预设开关')
213
223
  const current = body.draft ? await preview(ctx, facts, draft, args, sdkDeclarations) : baseline
214
224
  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)
225
+ const budget = formatBudget({ ...current.measured, categoryCounts: categoryCountsFor(current) }, current.count)
226
+ const savedBudget = save ? budget : formatBudget({ ...baseline.measured, categoryCounts: categoryCountsFor(baseline) }, baseline.count)
217
227
  let pricing
218
228
  try {
219
229
  const present = !!model && ctx.llm.listProviders().some(provider => provider.id === model.provider)
@@ -228,6 +238,36 @@ export async function apply(ctx) {
228
238
  })
229
239
  }
230
240
 
241
+ async function pluginVersion() {
242
+ const packageName = '@crocketc/dsh-capability-manager'
243
+ const bundle = (await ctx.pluginManager.listBundles()).find(row => row.name === packageName)
244
+ if (!bundle) return { version: '0.3.0', status: 'unmanaged' }
245
+ if (bundle.update === 'registry') {
246
+ const listing = await ctx.pluginManager.listVersions(packageName)
247
+ if (listing.status !== 'listed') return { version: bundle.version, status: 'unavailable', source: 'npm' }
248
+ const update = listing.versions.find(row => row.bundle && !row.deprecated && !row.incompatible && !row.prerelease)
249
+ return { version: bundle.version, ...(update ? { update: update.version } : {}), status: 'checked', source: 'npm' }
250
+ }
251
+ if (bundle.update === 'git' && typeof bundle.source === 'string') {
252
+ const spec = bundle.source.replace(/^@[^@]+@/, '').replace(/^git\+/, '')
253
+ const match = spec.match(/^(?:github:|(?:https?|ssh):\/\/(?:git@)?github\.com\/)([A-Za-z0-9-]+)\/([A-Za-z0-9._-]+?)(?:\.git)?(?:[#?].*)?$/i)
254
+ if (!match) return { version: bundle.version, status: 'unsupported', source: 'git' }
255
+ const installed = spec.match(/[&#](?:commit=)?([0-9a-f]{40})(?=$|[&#])/i)?.[1]
256
+ if (!installed) return { version: bundle.version, status: 'unsupported', source: 'git' }
257
+ try {
258
+ const response = await fetch(`https://api.github.com/repos/${match[1]}/${match[2]}/compare/${installed}...HEAD`, {
259
+ headers: { accept: 'application/vnd.github+json', 'user-agent': 'dsh-capability-manager' },
260
+ })
261
+ if (!response.ok) return { version: bundle.version, status: 'unavailable', source: 'git' }
262
+ const comparison = await response.json()
263
+ return formatGitHubComparison(bundle.version, installed, comparison)
264
+ } catch {
265
+ return { version: bundle.version, status: 'unavailable', source: 'git' }
266
+ }
267
+ }
268
+ return { version: bundle.version, status: bundle.update ?? 'unsupported' }
269
+ }
270
+
231
271
  async function route(request) {
232
272
  if (request.headers.get('x-dsh-capability-manager') !== '1' ||
233
273
  !request.headers.get('content-type')?.startsWith('application/json')) {
@@ -240,6 +280,7 @@ export async function apply(ctx) {
240
280
  try { body = JSON.parse(data) } catch { throw makeError('无效的 JSON 请求') }
241
281
  if (!body || typeof body !== 'object') throw makeError('无效的请求数据')
242
282
  if (body.action === 'state' || body.action === 'save') return Response.json(await state(body, body.action === 'save'))
283
+ if (body.action === 'plugin-version') return Response.json(await pluginVersion())
243
284
  if (body.action === 'search') return Response.json({ results: await searchSkills(body.source, body.query) })
244
285
  if (body.action === 'import') {
245
286
  const workspace = body.target === 'workspace' && ctx.workspaceRegistry.get(body.workspaceId)
@@ -0,0 +1,13 @@
1
+ export function formatGitHubComparison(version, installed, comparison) {
2
+ const detail = '比较的是 GitHub 仓库默认分支 HEAD;DSH profile 未保留原始分支或标签。'
3
+ if (comparison?.base_commit?.sha?.toLowerCase() !== installed.toLowerCase()) {
4
+ return { version, status: 'unavailable', source: 'git', detail }
5
+ }
6
+ if (comparison?.status === 'identical') return { version, status: 'checked', source: 'git', detail }
7
+ const latest = comparison?.head_commit?.sha
8
+ if (comparison?.status === 'ahead' && Number.isInteger(comparison.ahead_by) && comparison.ahead_by > 0 &&
9
+ typeof latest === 'string' && /^[0-9a-f]{40}$/i.test(latest)) {
10
+ return { version, update: latest.slice(0, 7), status: 'checked', source: 'git', detail }
11
+ }
12
+ return { version, status: 'unavailable', source: 'git', detail }
13
+ }