dsh-skill-pool 0.0.0-stage → 0.3.7

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/rules.js ADDED
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Session-scope resolution for the single global pool.
3
+ *
4
+ * Every pool member carries two independent filters — Agent modes and
5
+ * workspaces — and both must admit the session (AND). An empty filter admits
6
+ * everything, so a freshly added member is active everywhere by default.
7
+ *
8
+ * Pure functions only: the same helpers serve the Host gate and the panel's
9
+ * preview.
10
+ *
11
+ * @module dsh-skill-pool/rules
12
+ */
13
+
14
+ /** Prefix of every MCP tool registered by `dsh-mcp-client`. */
15
+ export const MCP_TOOL_PREFIX = 'mcp__'
16
+
17
+ /**
18
+ * Normalize a path for comparison (forward slashes, no trailing slash).
19
+ * @param {unknown} value - candidate path.
20
+ * @returns {string} comparable path, or ''.
21
+ */
22
+ export function comparablePath(value) {
23
+ if (typeof value !== 'string') return ''
24
+ let path = value.trim().replace(/\\/g, '/')
25
+ if (path.length === 0) return ''
26
+ path = path.replace(/\/{2,}/g, '/')
27
+ while (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1)
28
+ return path
29
+ }
30
+
31
+ /**
32
+ * Whether two paths name the same directory.
33
+ * @param {unknown} left - first path.
34
+ * @param {unknown} right - second path.
35
+ * @returns {boolean} equality after lexical normalization.
36
+ */
37
+ export function samePath(left, right) {
38
+ const a = comparablePath(left)
39
+ const b = comparablePath(right)
40
+ return a.length > 0 && a === b
41
+ }
42
+
43
+ /**
44
+ * Whether `child` sits inside `parent` (or is `parent` itself).
45
+ * @param {unknown} child - candidate descendant path.
46
+ * @param {unknown} parent - candidate ancestor path.
47
+ * @returns {boolean} whether the descendant relationship holds.
48
+ */
49
+ export function isUnder(child, parent) {
50
+ const a = comparablePath(child)
51
+ const b = comparablePath(parent)
52
+ if (a.length === 0 || b.length === 0) return false
53
+ if (a === b) return true
54
+ return a.startsWith(b.endsWith('/') ? b : `${b}/`)
55
+ }
56
+
57
+ /**
58
+ * Group key of one source record: the repository when it has one, else the
59
+ * import itself. Empty when the record names neither.
60
+ *
61
+ * @param {{project?: string, id?: string}|null|undefined} source - source record.
62
+ * @returns {string} `repo:<project>`, `import:<id>`, or ''.
63
+ */
64
+ export function groupKeyOfSource(source) {
65
+ if (source === null || typeof source !== 'object') return ''
66
+ const project = typeof source.project === 'string' ? source.project.trim() : ''
67
+ if (project.length > 0) return `repo:${project}`
68
+ const id = typeof source.id === 'string' ? source.id.trim() : ''
69
+ return id.length > 0 ? `import:${id}` : ''
70
+ }
71
+
72
+ /**
73
+ * Group key of one pool member, following its source.
74
+ *
75
+ * @param {object} state - normalized document.
76
+ * @param {{sourceId?: string}|null|undefined} member - pool member.
77
+ * @returns {string} group key, or '' when the member has no source.
78
+ */
79
+ export function groupKeyOfMember(state, member) {
80
+ if (member === null || typeof member !== 'object') return ''
81
+ const sourceId = typeof member.sourceId === 'string' ? member.sourceId : ''
82
+ if (sourceId.length === 0) return ''
83
+ const sources = state?.sources
84
+ if (sources === null || typeof sources !== 'object') return ''
85
+ return groupKeyOfSource(sources[sourceId])
86
+ }
87
+
88
+ /**
89
+ * The group record one member belongs to, if any.
90
+ *
91
+ * @param {object} state - normalized document.
92
+ * @param {{sourceId?: string}|null|undefined} member - pool member.
93
+ * @returns {object|undefined} group record.
94
+ */
95
+ export function groupOfMember(state, member) {
96
+ const key = groupKeyOfMember(state, member)
97
+ if (key.length === 0) return undefined
98
+ const groups = state?.groups
99
+ if (groups === null || typeof groups !== 'object') return undefined
100
+ const group = groups[key]
101
+ return group !== null && typeof group === 'object' ? group : undefined
102
+ }
103
+
104
+ /**
105
+ * Resolve one member's effective scope after group inheritance.
106
+ *
107
+ * `modesFrom` / `workspacesFrom` are `group` (inherit) or `self` (this member's
108
+ * own list); the store normalizes them, so a member without one keeps its own
109
+ * list. A missing group falls back to the member's own list.
110
+ *
111
+ * @param {object} state - normalized document.
112
+ * @param {{modes?: string[], workspaces?: string[], modesFrom?: string, workspacesFrom?: string}} member - pool member.
113
+ * @returns {{modes: string[], workspaces: string[]}} effective scope.
114
+ */
115
+ export function effectiveScope(state, member) {
116
+ const group = groupOfMember(state, member)
117
+ const ownModes = Array.isArray(member?.modes) ? member.modes : []
118
+ const ownWorkspaces = Array.isArray(member?.workspaces) ? member.workspaces : []
119
+ const inheritModes = member?.modesFrom === 'group' && group !== undefined
120
+ const inheritWorkspaces = member?.workspacesFrom === 'group' && group !== undefined
121
+ return {
122
+ modes: inheritModes && Array.isArray(group.modes) ? group.modes : ownModes,
123
+ workspaces: inheritWorkspaces && Array.isArray(group.workspaces) ? group.workspaces : ownWorkspaces,
124
+ }
125
+ }
126
+
127
+ /**
128
+ * Whether one member is switched on, taking its group's switch into account.
129
+ *
130
+ * A disabled group disables every member without touching their own flag, so
131
+ * turning the repository back on restores exactly the previous per-member state.
132
+ *
133
+ * @param {object} state - normalized document.
134
+ * @param {{enabled?: boolean, sourceId?: string}} member - pool member.
135
+ * @returns {boolean} whether the member may be active.
136
+ */
137
+ export function effectiveEnabled(state, member) {
138
+ if (member?.enabled === false) return false
139
+ const group = groupOfMember(state, member)
140
+ return group === undefined ? true : group.enabled !== false
141
+ }
142
+
143
+ /**
144
+ * Whether one member's scope admits a session.
145
+ *
146
+ * `allModes` / `allWorkspaces` drop one dimension entirely: the panel's "all"
147
+ * preview option asks "what would be visible if this dimension did not filter",
148
+ * which is not the same as passing an empty mode or cwd.
149
+ *
150
+ * @param {{modes?: string[], workspaces?: string[]}|null|undefined} entry - pool member scope.
151
+ * @param {{mode?: string, cwd?: string, allModes?: boolean, allWorkspaces?: boolean}} target - session identity.
152
+ * @returns {boolean} whether both filters admit the session.
153
+ */
154
+ export function scopeMatches(entry, { mode, cwd, allModes, allWorkspaces } = {}) {
155
+ if (entry === null || typeof entry !== 'object') return false
156
+ const modes = Array.isArray(entry.modes) ? entry.modes : []
157
+ const workspaces = Array.isArray(entry.workspaces) ? entry.workspaces : []
158
+ if (allModes !== true && modes.length > 0) {
159
+ const targetMode = typeof mode === 'string' ? mode : ''
160
+ if (!modes.includes(targetMode)) return false
161
+ }
162
+ if (allWorkspaces !== true && workspaces.length > 0) {
163
+ const targetPath = comparablePath(cwd)
164
+ if (targetPath.length === 0) return false
165
+ if (!workspaces.some((workspace) => isUnder(targetPath, workspace))) return false
166
+ }
167
+ return true
168
+ }
169
+
170
+ /**
171
+ * Whether one pool member is active for a session (present, enabled, admitted).
172
+ * @param {{enabled?: boolean, modes?: string[], workspaces?: string[]}|null|undefined} entry - pool member scope.
173
+ * @param {{mode?: string, cwd?: string}} target - session identity.
174
+ * @returns {boolean} whether the member is active.
175
+ */
176
+ export function itemActive(entry, target = {}) {
177
+ if (entry === null || typeof entry !== 'object') return false
178
+ if (entry.enabled === false) return false
179
+ return scopeMatches(entry, target)
180
+ }
181
+
182
+ /**
183
+ * Resolve the pool for one session.
184
+ *
185
+ * @param {object} state - normalized document.
186
+ * @param {{mode?: string, cwd?: string, allModes?: boolean, allWorkspaces?: boolean}} target - session identity.
187
+ * @returns {{gated: boolean, skills: string[], mcpServers: string[],
188
+ * gateSkills: boolean, gateMcp: boolean}} resolved pool.
189
+ */
190
+ export function resolvePool(state, { mode, cwd, allModes, allWorkspaces } = {}) {
191
+ const settings = state?.settings ?? {}
192
+ const empty = { gated: false, skills: [], mcpServers: [], gateSkills: false, gateMcp: false }
193
+ if (settings.enabled === false) return empty
194
+
195
+ const target = { mode, cwd, allModes, allWorkspaces }
196
+ const skillsMap = state?.skills !== null && typeof state?.skills === 'object' ? state.skills : {}
197
+ const mcpMap = state?.mcp !== null && typeof state?.mcp === 'object' ? state.mcp : {}
198
+
199
+ const skills = Object.entries(skillsMap)
200
+ .filter(([, entry]) =>
201
+ itemActive(
202
+ { ...entry, ...effectiveScope(state, entry), enabled: effectiveEnabled(state, entry) },
203
+ target,
204
+ ),
205
+ )
206
+ .map(([name]) => name)
207
+ .sort()
208
+ const mcpServers = Object.entries(mcpMap)
209
+ .filter(([, entry]) => itemActive({ ...entry, enabled: effectiveEnabled(state, entry) }, target))
210
+ .map(([name]) => name)
211
+ .sort()
212
+
213
+ // Gate each namespace only when that namespace has pool members: importing a
214
+ // single MCP server must not hide every skill, and vice versa.
215
+ //
216
+ // Skills need no switch of their own in v3: the pool owns its library, so
217
+ // "member or not" is already the whole decision. MCP keeps `mcpGate` because
218
+ // its members are Loader-managed servers that may exist outside the pool.
219
+ const hasSkillMembers = Object.keys(skillsMap).length > 0
220
+ const hasMcpMembers = Object.keys(mcpMap).length > 0
221
+ const gateSkills = hasSkillMembers
222
+ const gateMcp = hasMcpMembers && settings.mcpGate !== false
223
+ return {
224
+ gated: gateSkills || gateMcp,
225
+ skills: hasSkillMembers ? skills : [],
226
+ mcpServers: hasMcpMembers ? mcpServers : [],
227
+ gateSkills,
228
+ gateMcp,
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Parse the MCP Server name out of one public tool name.
234
+ * @param {unknown} toolName - model-facing tool name such as `mcp__qcc__search`.
235
+ * @returns {string} server name, or '' when the name is not an MCP tool.
236
+ */
237
+ export function mcpServerOf(toolName) {
238
+ if (typeof toolName !== 'string' || !toolName.startsWith(MCP_TOOL_PREFIX)) return ''
239
+ const rest = toolName.slice(MCP_TOOL_PREFIX.length)
240
+ const separator = rest.indexOf('__')
241
+ const server = separator >= 0 ? rest.slice(0, separator) : rest
242
+ return server.trim()
243
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Canonical `<skill_content>` rendering.
3
+ *
4
+ * This mirrors `renderSkillContent` from `@deepseek-ai/dsh-skill` byte for byte,
5
+ * because the scoped replacement `skill` tool must present the same shape the
6
+ * model already knows from the native loader: a user-explicit `/name` invocation
7
+ * and a tool load must stay indistinguishable. Copied instead of imported so the
8
+ * plugin keeps working when the package's internal path changes.
9
+ *
10
+ * @module dsh-skill-pool/skill-content
11
+ */
12
+
13
+ /** Escape one value embedded in a double-quoted markup attribute. */
14
+ export function escapeAttr(value) {
15
+ return String(value).replaceAll('&', '&amp;').replaceAll('"', '&quot;').replaceAll('<', '&lt;')
16
+ }
17
+
18
+ /** Escape model-facing prose embedded inside skill markup. */
19
+ export function escapeText(value) {
20
+ return String(value).replaceAll('&', '&amp;').replaceAll('<', '&lt;')
21
+ }
22
+
23
+ /**
24
+ * Render the resource guidance lines for one skill body.
25
+ * @param {object} skill - loaded skill definition.
26
+ * @returns {string[]} guidance lines.
27
+ */
28
+ export function renderResourceHint(skill) {
29
+ const base = skill?.resourceBase
30
+ if (base === undefined || base === null) {
31
+ return [
32
+ `Resources for this skill are managed by provider "${escapeText(skill?.provider ?? 'unknown')}".`,
33
+ 'Load referenced resources only as needed.',
34
+ ]
35
+ }
36
+ switch (base.kind) {
37
+ case 'directory':
38
+ return [
39
+ `Base directory for this skill: ${escapeText(base.path)}`,
40
+ 'Resolve relative paths mentioned by this skill against the base directory before using them. Load referenced resources only as needed.',
41
+ ]
42
+ case 'url':
43
+ return [
44
+ `Base URL for this skill: ${escapeText(base.url)}`,
45
+ 'Resolve relative URLs mentioned by this skill against the base URL before using them. Load referenced resources only as needed.',
46
+ ]
47
+ case 'opaque':
48
+ return [
49
+ `Resources for this skill: ${escapeText(base.description)}`,
50
+ 'Load referenced resources only as needed.',
51
+ ]
52
+ default:
53
+ return [
54
+ `Resources for this skill are managed by provider "${escapeText(skill?.provider ?? 'unknown')}".`,
55
+ 'Load referenced resources only as needed.',
56
+ ]
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Render one loaded skill for the model.
62
+ * @param {{name: string, provider: string, resourceBase?: object, content: string}} skill - loaded skill.
63
+ * @returns {string} complete `<skill_content>` block.
64
+ */
65
+ export function renderSkillContent(skill) {
66
+ const resourceHint = renderResourceHint(skill)
67
+ return [
68
+ `<skill_content name="${escapeAttr(skill.name)}">`,
69
+ '<skill_resources>',
70
+ ...resourceHint,
71
+ '</skill_resources>',
72
+ '',
73
+ '<skill_instructions>',
74
+ skill.content,
75
+ '</skill_instructions>',
76
+ '</skill_content>',
77
+ ].join('\n')
78
+ }