dsh-plugin-capabilities 0.1.4 → 0.1.6

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.
Files changed (35) hide show
  1. package/README.md +4 -2
  2. package/lib/client.js +119 -24
  3. package/lib/client.js.map +4 -4
  4. package/lib/index.js +11 -2
  5. package/lib/index.js.map +4 -4
  6. package/package.json +2 -1
  7. package/skills/find-skills/LICENSE +21 -0
  8. package/skills/find-skills/SKILL.md +141 -0
  9. package/skills/skill-creator/LICENSE.txt +202 -0
  10. package/skills/skill-creator/SKILL.md +485 -0
  11. package/skills/skill-creator/agents/analyzer.md +274 -0
  12. package/skills/skill-creator/agents/comparator.md +202 -0
  13. package/skills/skill-creator/agents/grader.md +223 -0
  14. package/skills/skill-creator/assets/eval_review.html +146 -0
  15. package/skills/skill-creator/eval-viewer/generate_review.py +471 -0
  16. package/skills/skill-creator/eval-viewer/viewer.html +1325 -0
  17. package/skills/skill-creator/references/schemas.md +430 -0
  18. package/skills/skill-creator/scripts/__init__.py +0 -0
  19. package/skills/skill-creator/scripts/aggregate_benchmark.py +401 -0
  20. package/skills/skill-creator/scripts/generate_report.py +326 -0
  21. package/skills/skill-creator/scripts/improve_description.py +247 -0
  22. package/skills/skill-creator/scripts/package_skill.py +136 -0
  23. package/skills/skill-creator/scripts/quick_validate.py +103 -0
  24. package/skills/skill-creator/scripts/run_eval.py +310 -0
  25. package/skills/skill-creator/scripts/run_loop.py +328 -0
  26. package/skills/skill-creator/scripts/utils.py +47 -0
  27. package/src/client/CapabilitiesSection.tsx +102 -0
  28. package/src/client/McpTab.tsx +2 -0
  29. package/src/client/SkillsTab.tsx +2 -0
  30. package/src/client/css.ts +16 -2
  31. package/src/client/index.ts +15 -22
  32. package/src/client/locales.ts +2 -0
  33. package/src/index.ts +22 -6
  34. package/src/packaged-skills.test.ts +40 -0
  35. package/src/smoke.test.ts +8 -1
@@ -0,0 +1,328 @@
1
+ #!/usr/bin/env python3
2
+ """Run the eval + improve loop until all pass or max iterations reached.
3
+
4
+ Combines run_eval.py and improve_description.py in a loop, tracking history
5
+ and returning the best description found. Supports train/test split to prevent
6
+ overfitting.
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import random
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ import webbrowser
16
+ from pathlib import Path
17
+
18
+ from scripts.generate_report import generate_html
19
+ from scripts.improve_description import improve_description
20
+ from scripts.run_eval import find_project_root, run_eval
21
+ from scripts.utils import parse_skill_md
22
+
23
+
24
+ def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]:
25
+ """Split eval set into train and test sets, stratified by should_trigger."""
26
+ random.seed(seed)
27
+
28
+ # Separate by should_trigger
29
+ trigger = [e for e in eval_set if e["should_trigger"]]
30
+ no_trigger = [e for e in eval_set if not e["should_trigger"]]
31
+
32
+ # Shuffle each group
33
+ random.shuffle(trigger)
34
+ random.shuffle(no_trigger)
35
+
36
+ # Calculate split points
37
+ n_trigger_test = max(1, int(len(trigger) * holdout))
38
+ n_no_trigger_test = max(1, int(len(no_trigger) * holdout))
39
+
40
+ # Split
41
+ test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test]
42
+ train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:]
43
+
44
+ return train_set, test_set
45
+
46
+
47
+ def run_loop(
48
+ eval_set: list[dict],
49
+ skill_path: Path,
50
+ description_override: str | None,
51
+ num_workers: int,
52
+ timeout: int,
53
+ max_iterations: int,
54
+ runs_per_query: int,
55
+ trigger_threshold: float,
56
+ holdout: float,
57
+ model: str,
58
+ verbose: bool,
59
+ live_report_path: Path | None = None,
60
+ log_dir: Path | None = None,
61
+ ) -> dict:
62
+ """Run the eval + improvement loop."""
63
+ project_root = find_project_root()
64
+ name, original_description, content = parse_skill_md(skill_path)
65
+ current_description = description_override or original_description
66
+
67
+ # Split into train/test if holdout > 0
68
+ if holdout > 0:
69
+ train_set, test_set = split_eval_set(eval_set, holdout)
70
+ if verbose:
71
+ print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr)
72
+ else:
73
+ train_set = eval_set
74
+ test_set = []
75
+
76
+ history = []
77
+ exit_reason = "unknown"
78
+
79
+ for iteration in range(1, max_iterations + 1):
80
+ if verbose:
81
+ print(f"\n{'='*60}", file=sys.stderr)
82
+ print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr)
83
+ print(f"Description: {current_description}", file=sys.stderr)
84
+ print(f"{'='*60}", file=sys.stderr)
85
+
86
+ # Evaluate train + test together in one batch for parallelism
87
+ all_queries = train_set + test_set
88
+ t0 = time.time()
89
+ all_results = run_eval(
90
+ eval_set=all_queries,
91
+ skill_name=name,
92
+ description=current_description,
93
+ num_workers=num_workers,
94
+ timeout=timeout,
95
+ project_root=project_root,
96
+ runs_per_query=runs_per_query,
97
+ trigger_threshold=trigger_threshold,
98
+ model=model,
99
+ )
100
+ eval_elapsed = time.time() - t0
101
+
102
+ # Split results back into train/test by matching queries
103
+ train_queries_set = {q["query"] for q in train_set}
104
+ train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set]
105
+ test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set]
106
+
107
+ train_passed = sum(1 for r in train_result_list if r["pass"])
108
+ train_total = len(train_result_list)
109
+ train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total}
110
+ train_results = {"results": train_result_list, "summary": train_summary}
111
+
112
+ if test_set:
113
+ test_passed = sum(1 for r in test_result_list if r["pass"])
114
+ test_total = len(test_result_list)
115
+ test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total}
116
+ test_results = {"results": test_result_list, "summary": test_summary}
117
+ else:
118
+ test_results = None
119
+ test_summary = None
120
+
121
+ history.append({
122
+ "iteration": iteration,
123
+ "description": current_description,
124
+ "train_passed": train_summary["passed"],
125
+ "train_failed": train_summary["failed"],
126
+ "train_total": train_summary["total"],
127
+ "train_results": train_results["results"],
128
+ "test_passed": test_summary["passed"] if test_summary else None,
129
+ "test_failed": test_summary["failed"] if test_summary else None,
130
+ "test_total": test_summary["total"] if test_summary else None,
131
+ "test_results": test_results["results"] if test_results else None,
132
+ # For backward compat with report generator
133
+ "passed": train_summary["passed"],
134
+ "failed": train_summary["failed"],
135
+ "total": train_summary["total"],
136
+ "results": train_results["results"],
137
+ })
138
+
139
+ # Write live report if path provided
140
+ if live_report_path:
141
+ partial_output = {
142
+ "original_description": original_description,
143
+ "best_description": current_description,
144
+ "best_score": "in progress",
145
+ "iterations_run": len(history),
146
+ "holdout": holdout,
147
+ "train_size": len(train_set),
148
+ "test_size": len(test_set),
149
+ "history": history,
150
+ }
151
+ live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name))
152
+
153
+ if verbose:
154
+ def print_eval_stats(label, results, elapsed):
155
+ pos = [r for r in results if r["should_trigger"]]
156
+ neg = [r for r in results if not r["should_trigger"]]
157
+ tp = sum(r["triggers"] for r in pos)
158
+ pos_runs = sum(r["runs"] for r in pos)
159
+ fn = pos_runs - tp
160
+ fp = sum(r["triggers"] for r in neg)
161
+ neg_runs = sum(r["runs"] for r in neg)
162
+ tn = neg_runs - fp
163
+ total = tp + tn + fp + fn
164
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0
165
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0
166
+ accuracy = (tp + tn) / total if total > 0 else 0.0
167
+ print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr)
168
+ for r in results:
169
+ status = "PASS" if r["pass"] else "FAIL"
170
+ rate_str = f"{r['triggers']}/{r['runs']}"
171
+ print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr)
172
+
173
+ print_eval_stats("Train", train_results["results"], eval_elapsed)
174
+ if test_summary:
175
+ print_eval_stats("Test ", test_results["results"], 0)
176
+
177
+ if train_summary["failed"] == 0:
178
+ exit_reason = f"all_passed (iteration {iteration})"
179
+ if verbose:
180
+ print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr)
181
+ break
182
+
183
+ if iteration == max_iterations:
184
+ exit_reason = f"max_iterations ({max_iterations})"
185
+ if verbose:
186
+ print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr)
187
+ break
188
+
189
+ # Improve the description based on train results
190
+ if verbose:
191
+ print(f"\nImproving description...", file=sys.stderr)
192
+
193
+ t0 = time.time()
194
+ # Strip test scores from history so improvement model can't see them
195
+ blinded_history = [
196
+ {k: v for k, v in h.items() if not k.startswith("test_")}
197
+ for h in history
198
+ ]
199
+ new_description = improve_description(
200
+ skill_name=name,
201
+ skill_content=content,
202
+ current_description=current_description,
203
+ eval_results=train_results,
204
+ history=blinded_history,
205
+ model=model,
206
+ log_dir=log_dir,
207
+ iteration=iteration,
208
+ )
209
+ improve_elapsed = time.time() - t0
210
+
211
+ if verbose:
212
+ print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr)
213
+
214
+ current_description = new_description
215
+
216
+ # Find the best iteration by TEST score (or train if no test set)
217
+ if test_set:
218
+ best = max(history, key=lambda h: h["test_passed"] or 0)
219
+ best_score = f"{best['test_passed']}/{best['test_total']}"
220
+ else:
221
+ best = max(history, key=lambda h: h["train_passed"])
222
+ best_score = f"{best['train_passed']}/{best['train_total']}"
223
+
224
+ if verbose:
225
+ print(f"\nExit reason: {exit_reason}", file=sys.stderr)
226
+ print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr)
227
+
228
+ return {
229
+ "exit_reason": exit_reason,
230
+ "original_description": original_description,
231
+ "best_description": best["description"],
232
+ "best_score": best_score,
233
+ "best_train_score": f"{best['train_passed']}/{best['train_total']}",
234
+ "best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None,
235
+ "final_description": current_description,
236
+ "iterations_run": len(history),
237
+ "holdout": holdout,
238
+ "train_size": len(train_set),
239
+ "test_size": len(test_set),
240
+ "history": history,
241
+ }
242
+
243
+
244
+ def main():
245
+ parser = argparse.ArgumentParser(description="Run eval + improve loop")
246
+ parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file")
247
+ parser.add_argument("--skill-path", required=True, help="Path to skill directory")
248
+ parser.add_argument("--description", default=None, help="Override starting description")
249
+ parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers")
250
+ parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds")
251
+ parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations")
252
+ parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query")
253
+ parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold")
254
+ parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)")
255
+ parser.add_argument("--model", required=True, help="Model for improvement")
256
+ parser.add_argument("--verbose", action="store_true", help="Print progress to stderr")
257
+ parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)")
258
+ parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here")
259
+ args = parser.parse_args()
260
+
261
+ eval_set = json.loads(Path(args.eval_set).read_text())
262
+ skill_path = Path(args.skill_path)
263
+
264
+ if not (skill_path / "SKILL.md").exists():
265
+ print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
266
+ sys.exit(1)
267
+
268
+ name, _, _ = parse_skill_md(skill_path)
269
+
270
+ # Set up live report path
271
+ if args.report != "none":
272
+ if args.report == "auto":
273
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
274
+ live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html"
275
+ else:
276
+ live_report_path = Path(args.report)
277
+ # Open the report immediately so the user can watch
278
+ live_report_path.write_text("<html><body><h1>Starting optimization loop...</h1><meta http-equiv='refresh' content='5'></body></html>")
279
+ webbrowser.open(str(live_report_path))
280
+ else:
281
+ live_report_path = None
282
+
283
+ # Determine output directory (create before run_loop so logs can be written)
284
+ if args.results_dir:
285
+ timestamp = time.strftime("%Y-%m-%d_%H%M%S")
286
+ results_dir = Path(args.results_dir) / timestamp
287
+ results_dir.mkdir(parents=True, exist_ok=True)
288
+ else:
289
+ results_dir = None
290
+
291
+ log_dir = results_dir / "logs" if results_dir else None
292
+
293
+ output = run_loop(
294
+ eval_set=eval_set,
295
+ skill_path=skill_path,
296
+ description_override=args.description,
297
+ num_workers=args.num_workers,
298
+ timeout=args.timeout,
299
+ max_iterations=args.max_iterations,
300
+ runs_per_query=args.runs_per_query,
301
+ trigger_threshold=args.trigger_threshold,
302
+ holdout=args.holdout,
303
+ model=args.model,
304
+ verbose=args.verbose,
305
+ live_report_path=live_report_path,
306
+ log_dir=log_dir,
307
+ )
308
+
309
+ # Save JSON output
310
+ json_output = json.dumps(output, indent=2)
311
+ print(json_output)
312
+ if results_dir:
313
+ (results_dir / "results.json").write_text(json_output)
314
+
315
+ # Write final HTML report (without auto-refresh)
316
+ if live_report_path:
317
+ live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name))
318
+ print(f"\nReport: {live_report_path}", file=sys.stderr)
319
+
320
+ if results_dir and live_report_path:
321
+ (results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name))
322
+
323
+ if results_dir:
324
+ print(f"Results saved to: {results_dir}", file=sys.stderr)
325
+
326
+
327
+ if __name__ == "__main__":
328
+ main()
@@ -0,0 +1,47 @@
1
+ """Shared utilities for skill-creator scripts."""
2
+
3
+ from pathlib import Path
4
+
5
+
6
+
7
+ def parse_skill_md(skill_path: Path) -> tuple[str, str, str]:
8
+ """Parse a SKILL.md file, returning (name, description, full_content)."""
9
+ content = (skill_path / "SKILL.md").read_text()
10
+ lines = content.split("\n")
11
+
12
+ if lines[0].strip() != "---":
13
+ raise ValueError("SKILL.md missing frontmatter (no opening ---)")
14
+
15
+ end_idx = None
16
+ for i, line in enumerate(lines[1:], start=1):
17
+ if line.strip() == "---":
18
+ end_idx = i
19
+ break
20
+
21
+ if end_idx is None:
22
+ raise ValueError("SKILL.md missing frontmatter (no closing ---)")
23
+
24
+ name = ""
25
+ description = ""
26
+ frontmatter_lines = lines[1:end_idx]
27
+ i = 0
28
+ while i < len(frontmatter_lines):
29
+ line = frontmatter_lines[i]
30
+ if line.startswith("name:"):
31
+ name = line[len("name:"):].strip().strip('"').strip("'")
32
+ elif line.startswith("description:"):
33
+ value = line[len("description:"):].strip()
34
+ # Handle YAML multiline indicators (>, |, >-, |-)
35
+ if value in (">", "|", ">-", "|-"):
36
+ continuation_lines: list[str] = []
37
+ i += 1
38
+ while i < len(frontmatter_lines) and (frontmatter_lines[i].startswith(" ") or frontmatter_lines[i].startswith("\t")):
39
+ continuation_lines.append(frontmatter_lines[i].strip())
40
+ i += 1
41
+ description = " ".join(continuation_lines)
42
+ continue
43
+ else:
44
+ description = value.strip('"').strip("'")
45
+ i += 1
46
+
47
+ return name, description, content
@@ -0,0 +1,102 @@
1
+ /** Settings top-level “技能与 MCP” section: one nav entry beside 通用设置 and
2
+ * 模型, with the Skills and MCP pages as internal tabs. The two pages are the
3
+ * same components the Plugins section used to host — promoted a level instead
4
+ * of squeezed under 插件. Pure composition; data still arrives through the
5
+ * injected faces. */
6
+
7
+ import { useEffect, useId, useRef, useState } from 'react'
8
+ import type { ReactElement } from 'react'
9
+ import { CSS } from './css.ts'
10
+ import { McpTab } from './McpTab.tsx'
11
+ import type { McpInjected } from './McpTab.tsx'
12
+ import { SkillsTab } from './SkillsTab.tsx'
13
+ import type { SkillsInjected } from './SkillsTab.tsx'
14
+ import type { Translate } from './index.ts'
15
+
16
+ export function CapabilitiesSection(props: {
17
+ t: Translate
18
+ skills: SkillsInjected
19
+ mcp: McpInjected
20
+ }): ReactElement {
21
+ const { t, skills, mcp } = props
22
+ const tabsId = useId()
23
+ const tabRefs = useRef<Array<HTMLButtonElement | null>>([])
24
+ const rows = [
25
+ { id: 'skills', label: t('skillsTab') },
26
+ { id: 'mcp', label: t('mcpTab') },
27
+ ]
28
+ const [activeId, setActiveId] = useState('skills')
29
+ // The skills page mounts immediately; a tab mounts only when first
30
+ // selected, then stays mounted while hidden so editor drafts and outcome
31
+ // banners survive switching between the two views.
32
+ const [visitedIds, setVisitedIds] = useState<ReadonlySet<string>>(() => new Set(['skills']))
33
+
34
+ useEffect(() => {
35
+ setVisitedIds((previous) => {
36
+ if (previous.has(activeId)) return previous
37
+ return new Set([...previous, activeId])
38
+ })
39
+ }, [activeId])
40
+
41
+ return (
42
+ <div className="dpc-section">
43
+ <style>{CSS}</style>
44
+
45
+ <h2 className="dpc-heading">{t('sectionNav')}</h2>
46
+ <div className="dpc-tabs" role="tablist" aria-label={t('sectionNav')}>
47
+ {rows.map((row, index) => {
48
+ const selected = row.id === activeId
49
+ return (
50
+ <button
51
+ key={row.id}
52
+ ref={(element) => { tabRefs.current[index] = element }}
53
+ id={`${tabsId}-tab-${row.id}`}
54
+ type="button"
55
+ role="tab"
56
+ className="dpc-tab"
57
+ aria-selected={selected}
58
+ aria-controls={`${tabsId}-panel-${row.id}`}
59
+ data-active={selected ? 'true' : undefined}
60
+ tabIndex={selected ? 0 : -1}
61
+ onClick={() => { setActiveId(row.id) }}
62
+ onKeyDown={(event) => {
63
+ let nextIndex: number
64
+ switch (event.key) {
65
+ case 'ArrowRight': nextIndex = (index + 1) % rows.length; break
66
+ case 'ArrowLeft': nextIndex = (index - 1 + rows.length) % rows.length; break
67
+ case 'Home': nextIndex = 0; break
68
+ case 'End': nextIndex = rows.length - 1; break
69
+ default: return
70
+ }
71
+ event.preventDefault()
72
+ setActiveId(rows[nextIndex]?.id ?? 'skills')
73
+ tabRefs.current[nextIndex]?.focus()
74
+ }}
75
+ >
76
+ {row.label}
77
+ </button>
78
+ )
79
+ })}
80
+ </div>
81
+ {rows
82
+ .filter(row => row.id === activeId || visitedIds.has(row.id))
83
+ .map((row) => {
84
+ const selected = row.id === activeId
85
+ return (
86
+ <div
87
+ key={row.id}
88
+ id={`${tabsId}-panel-${row.id}`}
89
+ className="dpc-tabPanel"
90
+ role="tabpanel"
91
+ aria-labelledby={`${tabsId}-tab-${row.id}`}
92
+ hidden={!selected}
93
+ >
94
+ {row.id === 'skills'
95
+ ? <SkillsTab t={t} injected={skills} />
96
+ : <McpTab t={t} injected={mcp} />}
97
+ </div>
98
+ )
99
+ })}
100
+ </div>
101
+ )
102
+ }
@@ -320,6 +320,8 @@ export function McpTab(props: { t: Translate; injected: McpInjected }): ReactEle
320
320
  open={editor !== null}
321
321
  onClose={() => setEditor(null)}
322
322
  title={editor !== null && editor.id !== '' ? t('editServer') : t('addServer')}
323
+ className="dpc-modalForm"
324
+ contentClassName="dpc-modalScroll"
323
325
  >
324
326
  {editor !== null && (
325
327
  <div className="dpc-form">
@@ -213,6 +213,8 @@ export function SkillsTab(props: { t: Translate; injected: SkillsInjected }): Re
213
213
  open={editor !== null}
214
214
  onClose={() => setEditor(null)}
215
215
  title={editor === null ? '' : editor.mode === 'create' ? t('newSkill') : editor.mode === 'edit' ? t('editSkill') : t('viewSkill')}
216
+ className="dpc-modalForm"
217
+ contentClassName="dpc-modalScroll"
216
218
  >
217
219
  {editor !== null && (
218
220
  <div className="dpc-form">
package/src/client/css.ts CHANGED
@@ -4,6 +4,15 @@
4
4
 
5
5
  export const CSS = `
6
6
  .dpc-section{display:flex;flex-direction:column;gap:14px;width:100%;max-width:760px;color:var(--dsw-alias-label-primary)}
7
+ .dpc-heading{margin:0;font-size:18px;line-height:26px;font-weight:600}
8
+ /* Top-level section's internal tabs — same underline-tab look as the host's
9
+ Plugins section so the promoted placement still reads as one family. */
10
+ .dpc-tabs{display:flex;align-items:flex-end;gap:22px;border-bottom:1px solid var(--dsw-alias-border-l2);margin-top:2px}
11
+ .dpc-tab{position:relative;border:0;padding:7px 1px 9px;background:transparent;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:13px;line-height:20px;cursor:pointer}
12
+ .dpc-tab:hover,.dpc-tab[data-active='true']{color:var(--dsw-alias-label-primary)}
13
+ .dpc-tab[data-active='true']::after,.dpc-tab:focus-visible::after{position:absolute;right:0;bottom:-1px;left:0;height:2px;border-radius:2px 2px 0 0;background:var(--dsw-alias-label-primary);content:''}
14
+ .dpc-tab:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px;border-radius:2px;color:var(--dsw-alias-label-primary)}
15
+ .dpc-tabPanel{min-width:0;padding-top:2px}
7
16
  .dpc-head{display:flex;align-items:center;gap:8px}
8
17
  .dpc-head h3{margin:0;font-size:13px;line-height:20px;font-weight:600}
9
18
  .dpc-head>svg{flex:none;color:var(--dsw-alias-label-tertiary)}
@@ -37,8 +46,8 @@ export const CSS = `
37
46
  .dpc-label{display:flex;flex-direction:column;gap:4px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary)}
38
47
  .dpc-label>span:first-child{color:var(--dsw-alias-label-tertiary)}
39
48
  .dpc-input,.dpc-textarea,.dpc-select{width:100%;box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;padding:7px 10px;outline:none;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px}
40
- .dpc-textarea{min-height:120px;resize:vertical;font-family:var(--ds-font-family-code);line-height:1.5}
41
- .dpc-textarea[data-short='true']{min-height:64px}
49
+ .dpc-textarea{min-height:240px;resize:vertical;font-family:var(--ds-font-family-code);line-height:1.5}
50
+ .dpc-textarea[data-short='true']{min-height:96px}
42
51
  .dpc-input:focus-visible,.dpc-textarea:focus-visible,.dpc-select:focus-visible{border-color:var(--dsw-alias-state-business-primary);box-shadow:0 0 0 2px color-mix(in srgb,var(--dsw-alias-state-business-primary) 18%,transparent)}
43
52
  .dpc-checks{display:flex;gap:16px;font-size:13px;line-height:20px}
44
53
  .dpc-checks label{display:inline-flex;align-items:center;gap:6px;cursor:pointer}
@@ -47,6 +56,11 @@ export const CSS = `
47
56
  its own scroll so title, intro, and footer stay pinned. The doubled class
48
57
  beats the host dialog's module CSS regardless of injection order. */
49
58
  .dpc-modalWide.dpc-modalWide{width:min(680px,100%)}
59
+ /* Editor dialogs (new skill / server): 640px wide so markdown bodies and
60
+ command/arg/env lines stop wrapping mid-token; the content column scrolls
61
+ on short viewports instead of clipping past the dialog edge. */
62
+ .dpc-modalForm.dpc-modalForm{width:min(640px,100%)}
63
+ .dpc-modalScroll.dpc-modalScroll{max-height:calc(100vh - 160px);overflow-y:auto}
50
64
  .dpc-importScroll{display:flex;flex-direction:column;gap:14px;max-height:min(400px,52vh);overflow-y:auto;padding:2px 4px 2px 2px}
51
65
  .dpc-importGroup{display:flex;flex-direction:column;gap:8px}
52
66
  .dpc-importHead{display:flex;align-items:center;gap:8px;padding:0 2px}
@@ -1,9 +1,11 @@
1
- /** dsh-plugin-capabilities client entry: contributes the “技能/Skills” and
2
- * MCP” tabs into Settings Plugins. Calls the host routes with fetch. */
1
+ /** dsh-plugin-capabilities client entry: contributes the top-level
2
+ * “技能与 MCP” section into Settings (beside 通用设置/模型, with Skills and
3
+ * MCP as internal tabs). Calls the host routes with fetch. */
3
4
 
4
5
  import { createElement as h } from 'react'
5
- import { McpTab, type McpInjected, type McpRow } from './McpTab.tsx'
6
- import { SkillsTab, type SkillsInjected, type SkillRowView } from './SkillsTab.tsx'
6
+ import { CapabilitiesSection } from './CapabilitiesSection.tsx'
7
+ import type { McpInjected, McpRow } from './McpTab.tsx'
8
+ import type { SkillsInjected, SkillRowView } from './SkillsTab.tsx'
7
9
  import { zh, en } from './locales.ts'
8
10
 
9
11
  /** Locale dictionary namespace owned by this plugin. */
@@ -91,25 +93,16 @@ export function apply(ctx: CapabilitiesClientContext): void {
91
93
  desktop: window.dshDesktop !== undefined,
92
94
  }
93
95
 
94
- ctx.slots.inject('settings.plugins.tab', () => {
96
+ // One top-level nav entry (between 模型 and 插件), not a tab under the
97
+ // Plugins section — the section component owns its internal Skills/MCP
98
+ // tabs directly, so nothing registers into settings.plugins.tab anymore.
99
+ ctx.slots.inject('settings.section', () => {
95
100
  return ctx.slots.register({
96
- name: 'settings.plugins.tab',
97
- id: 'capabilities-skills',
98
- order: 30,
99
- label: () => t('skillsTab'),
101
+ name: 'settings.section',
102
+ id: 'capabilities',
103
+ order: 12,
104
+ label: () => t('sectionNav'),
100
105
  locale: NS,
101
- inject: () => skillsInjected,
102
- }, () => h(SkillsTab, { t, injected: skillsInjected }))
103
- })
104
-
105
- ctx.slots.inject('settings.plugins.tab', () => {
106
- return ctx.slots.register({
107
- name: 'settings.plugins.tab',
108
- id: 'capabilities-mcp',
109
- order: 40,
110
- label: () => t('mcpTab'),
111
- locale: NS,
112
- inject: () => mcpInjected,
113
- }, () => h(McpTab, { t, injected: mcpInjected }))
106
+ }, () => h(CapabilitiesSection, { t, skills: skillsInjected, mcp: mcpInjected }))
114
107
  })
115
108
  }
@@ -1,6 +1,7 @@
1
1
  /** zh/en dictionaries for the Settings capabilities tabs. */
2
2
 
3
3
  export const zh = {
4
+ sectionNav: '技能与 MCP',
4
5
  skillsTab: '技能',
5
6
  mcpTab: 'MCP',
6
7
  skillsTitle: '技能管理',
@@ -72,6 +73,7 @@ export const zh = {
72
73
  }
73
74
 
74
75
  export const en = {
76
+ sectionNav: 'Skills & MCP',
75
77
  skillsTab: 'Skills',
76
78
  mcpTab: 'MCP',
77
79
  skillsTitle: 'Skills',
package/src/index.ts CHANGED
@@ -4,6 +4,9 @@
4
4
  * catalog (the web composition deliberately leaves the host row to presets). */
5
5
 
6
6
  import type { Context } from '@deepseek-ai/cordis'
7
+ import { existsSync } from 'node:fs'
8
+ import { dirname, join } from 'node:path'
9
+ import { fileURLToPath } from 'node:url'
7
10
  import { agentSkillRoots } from './agents.ts'
8
11
  import { argvProfile, profileDir } from './profile.ts'
9
12
  import { mountCapabilitiesRoutes } from './routes.ts'
@@ -11,6 +14,16 @@ import type { CapabilitiesHost } from './types.ts'
11
14
 
12
15
  export const name = 'dsh-plugin-capabilities'
13
16
 
17
+ /**
18
+ * The package's own vendored skills (`skills/` at the package root — resolves
19
+ * identically from src/ under vitest and from lib/ when installed). Scanned as
20
+ * a custom root, so every session sees them through the registry's global
21
+ * layer while the files stay zero-copy and travel with plugin installs.
22
+ */
23
+ export function packagedSkillsDir(): string {
24
+ return join(dirname(fileURLToPath(import.meta.url)), '..', 'skills')
25
+ }
26
+
14
27
  /** Optional cordis.yml configuration; profile defaults to the booted one. */
15
28
  export interface Config {
16
29
  /** Profile whose patch layer holds the MCP rows; defaults to argv or `web`. */
@@ -31,17 +44,20 @@ export function apply(ctx: Context, config?: Config): void {
31
44
  // The web bundle disables the host-plane `skill-filesystem` row on
32
45
  // purpose (presets own per-session discovery). The Settings manager
33
46
  // mounts its own host-plane provider as a CHILD of this plugin: it dies
34
- // with us, registers into the registry's global layer, and preset layers
35
- // keep their semantics (nearest layer still wins duplicate names). Other
36
- // agents' skill roots (~/.claude/skills, ~/.codex/skills) join as custom
37
- // dirs zero-copy, live-synced both ways. A failed load only means an
38
- // empty catalog the routes keep serving.
47
+ // with us, registers into the registry's global layer (deployment-level
48
+ // providers are exactly what that layer is for agents read the merged
49
+ // catalog), and preset layers keep their semantics (nearest layer still
50
+ // wins duplicate names). Custom roots, in scan order: the package's own
51
+ // vendored skills (read-only, update with the plugin), then other agents'
52
+ // skill roots (~/.claude/skills, ~/.codex/skills) — zero-copy, live-synced
53
+ // both ways. A failed load only means an empty catalog — the routes keep
54
+ // serving.
39
55
  void (async () => {
40
56
  try {
41
57
  const mod = (await import('@deepseek-ai/dsh-skill-filesystem')) as unknown as
42
58
  (FilesystemSkillPlugin & { default?: FilesystemSkillPlugin })
43
59
  const plugin = mod.default ?? mod
44
- const roots = agentSkillRoots()
60
+ const roots = [packagedSkillsDir(), ...agentSkillRoots()].filter(dir => existsSync(dir))
45
61
  hostCtx.plugin(plugin, roots.length > 0 ? { customSkillDirs: roots } : {})
46
62
  } catch {
47
63
  // Unresolvable provider: skills list stays empty; MCP tab unaffected.