@dev-sergeev/datalab-kit 0.1.5 → 0.1.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.
Files changed (30) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +30 -8
  3. package/THIRD_PARTY_NOTICES.md +4 -1
  4. package/dist/extension.js +4 -2
  5. package/dist/install.d.ts +2 -2
  6. package/dist/install.js +14 -12
  7. package/dist/skills.d.ts +2 -0
  8. package/dist/skills.js +54 -0
  9. package/docs/adr/0002-package-delivery.md +5 -5
  10. package/package.json +40 -13
  11. package/skills/init/SKILL.md +31 -0
  12. package/skills/skill-creator/LICENSE.txt +202 -0
  13. package/skills/skill-creator/SKILL.md +610 -0
  14. package/skills/skill-creator/agents/analyzer.md +291 -0
  15. package/skills/skill-creator/agents/comparator.md +213 -0
  16. package/skills/skill-creator/agents/grader.md +234 -0
  17. package/skills/skill-creator/assets/eval_review.html +146 -0
  18. package/skills/skill-creator/eval-viewer/generate_review.py +453 -0
  19. package/skills/skill-creator/eval-viewer/viewer.html +1329 -0
  20. package/skills/skill-creator/references/schemas.md +521 -0
  21. package/skills/skill-creator/scripts/__init__.py +0 -0
  22. package/skills/skill-creator/scripts/aggregate_benchmark.py +415 -0
  23. package/skills/skill-creator/scripts/generate_report.py +329 -0
  24. package/skills/skill-creator/scripts/improve_description.py +225 -0
  25. package/skills/skill-creator/scripts/package_skill.py +136 -0
  26. package/skills/skill-creator/scripts/pi_runtime.py +177 -0
  27. package/skills/skill-creator/scripts/quick_validate.py +107 -0
  28. package/skills/skill-creator/scripts/run_eval.py +215 -0
  29. package/skills/skill-creator/scripts/run_loop.py +334 -0
  30. package/skills/skill-creator/scripts/utils.py +41 -0
@@ -0,0 +1,334 @@
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
+ Changed by Datalab Kit: Pi model syntax and termination cleanup.
9
+ Upstream: anthropics/skills
10
+ dbd4588f9e1033efb41dad4bef2f7947c8993d44 (Apache-2.0).
11
+ """
12
+
13
+ import argparse
14
+ import json
15
+ import random
16
+ import sys
17
+ import tempfile
18
+ import time
19
+ import webbrowser
20
+ from pathlib import Path
21
+
22
+ from scripts.generate_report import generate_html
23
+ from scripts.improve_description import improve_description
24
+ from scripts.pi_runtime import interrupt_on_termination
25
+ from scripts.run_eval import find_project_root, run_eval
26
+ from scripts.utils import parse_skill_md
27
+
28
+
29
+ def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]:
30
+ """Split eval set into train and test sets, stratified by should_trigger."""
31
+ random.seed(seed)
32
+
33
+ # Separate by should_trigger
34
+ trigger = [e for e in eval_set if e["should_trigger"]]
35
+ no_trigger = [e for e in eval_set if not e["should_trigger"]]
36
+
37
+ # Shuffle each group
38
+ random.shuffle(trigger)
39
+ random.shuffle(no_trigger)
40
+
41
+ # Calculate split points
42
+ n_trigger_test = max(1, int(len(trigger) * holdout))
43
+ n_no_trigger_test = max(1, int(len(no_trigger) * holdout))
44
+
45
+ # Split
46
+ test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test]
47
+ train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:]
48
+
49
+ return train_set, test_set
50
+
51
+
52
+ def run_loop(
53
+ eval_set: list[dict],
54
+ skill_path: Path,
55
+ description_override: str | None,
56
+ num_workers: int,
57
+ timeout: int,
58
+ max_iterations: int,
59
+ runs_per_query: int,
60
+ trigger_threshold: float,
61
+ holdout: float,
62
+ model: str,
63
+ verbose: bool,
64
+ live_report_path: Path | None = None,
65
+ log_dir: Path | None = None,
66
+ ) -> dict:
67
+ """Run the eval + improvement loop."""
68
+ project_root = find_project_root()
69
+ name, original_description, content = parse_skill_md(skill_path)
70
+ current_description = description_override or original_description
71
+
72
+ # Split into train/test if holdout > 0
73
+ if holdout > 0:
74
+ train_set, test_set = split_eval_set(eval_set, holdout)
75
+ if verbose:
76
+ print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr)
77
+ else:
78
+ train_set = eval_set
79
+ test_set = []
80
+
81
+ history = []
82
+ exit_reason = "unknown"
83
+
84
+ for iteration in range(1, max_iterations + 1):
85
+ if verbose:
86
+ print(f"\n{'='*60}", file=sys.stderr)
87
+ print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr)
88
+ print(f"Description: {current_description}", file=sys.stderr)
89
+ print(f"{'='*60}", file=sys.stderr)
90
+
91
+ # Evaluate train + test together in one batch for parallelism
92
+ all_queries = train_set + test_set
93
+ t0 = time.time()
94
+ all_results = run_eval(
95
+ eval_set=all_queries,
96
+ skill_name=name,
97
+ description=current_description,
98
+ num_workers=num_workers,
99
+ timeout=timeout,
100
+ project_root=project_root,
101
+ runs_per_query=runs_per_query,
102
+ trigger_threshold=trigger_threshold,
103
+ model=model,
104
+ )
105
+ eval_elapsed = time.time() - t0
106
+
107
+ # Split results back into train/test by matching queries
108
+ train_queries_set = {q["query"] for q in train_set}
109
+ train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set]
110
+ test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set]
111
+
112
+ train_passed = sum(1 for r in train_result_list if r["pass"])
113
+ train_total = len(train_result_list)
114
+ train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total}
115
+ train_results = {"results": train_result_list, "summary": train_summary}
116
+
117
+ if test_set:
118
+ test_passed = sum(1 for r in test_result_list if r["pass"])
119
+ test_total = len(test_result_list)
120
+ test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total}
121
+ test_results = {"results": test_result_list, "summary": test_summary}
122
+ else:
123
+ test_results = None
124
+ test_summary = None
125
+
126
+ history.append({
127
+ "iteration": iteration,
128
+ "description": current_description,
129
+ "train_passed": train_summary["passed"],
130
+ "train_failed": train_summary["failed"],
131
+ "train_total": train_summary["total"],
132
+ "train_results": train_results["results"],
133
+ "test_passed": test_summary["passed"] if test_summary else None,
134
+ "test_failed": test_summary["failed"] if test_summary else None,
135
+ "test_total": test_summary["total"] if test_summary else None,
136
+ "test_results": test_results["results"] if test_results else None,
137
+ # For backward compat with report generator
138
+ "passed": train_summary["passed"],
139
+ "failed": train_summary["failed"],
140
+ "total": train_summary["total"],
141
+ "results": train_results["results"],
142
+ })
143
+
144
+ # Write live report if path provided
145
+ if live_report_path:
146
+ partial_output = {
147
+ "original_description": original_description,
148
+ "best_description": current_description,
149
+ "best_score": "in progress",
150
+ "iterations_run": len(history),
151
+ "holdout": holdout,
152
+ "train_size": len(train_set),
153
+ "test_size": len(test_set),
154
+ "history": history,
155
+ }
156
+ live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name))
157
+
158
+ if verbose:
159
+ def print_eval_stats(label, results, elapsed):
160
+ pos = [r for r in results if r["should_trigger"]]
161
+ neg = [r for r in results if not r["should_trigger"]]
162
+ tp = sum(r["triggers"] for r in pos)
163
+ pos_runs = sum(r["runs"] for r in pos)
164
+ fn = pos_runs - tp
165
+ fp = sum(r["triggers"] for r in neg)
166
+ neg_runs = sum(r["runs"] for r in neg)
167
+ tn = neg_runs - fp
168
+ total = tp + tn + fp + fn
169
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0
170
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0
171
+ accuracy = (tp + tn) / total if total > 0 else 0.0
172
+ print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr)
173
+ for r in results:
174
+ status = "PASS" if r["pass"] else "FAIL"
175
+ rate_str = f"{r['triggers']}/{r['runs']}"
176
+ print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr)
177
+
178
+ print_eval_stats("Train", train_results["results"], eval_elapsed)
179
+ if test_summary:
180
+ print_eval_stats("Test ", test_results["results"], 0)
181
+
182
+ if train_summary["failed"] == 0:
183
+ exit_reason = f"all_passed (iteration {iteration})"
184
+ if verbose:
185
+ print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr)
186
+ break
187
+
188
+ if iteration == max_iterations:
189
+ exit_reason = f"max_iterations ({max_iterations})"
190
+ if verbose:
191
+ print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr)
192
+ break
193
+
194
+ # Improve the description based on train results
195
+ if verbose:
196
+ print(f"\nImproving description...", file=sys.stderr)
197
+
198
+ t0 = time.time()
199
+ # Strip test scores from history so improvement model can't see them
200
+ blinded_history = [
201
+ {k: v for k, v in h.items() if not k.startswith("test_")}
202
+ for h in history
203
+ ]
204
+ new_description = improve_description(
205
+ skill_name=name,
206
+ skill_content=content,
207
+ current_description=current_description,
208
+ eval_results=train_results,
209
+ history=blinded_history,
210
+ model=model,
211
+ log_dir=log_dir,
212
+ iteration=iteration,
213
+ )
214
+ improve_elapsed = time.time() - t0
215
+
216
+ if verbose:
217
+ print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr)
218
+
219
+ current_description = new_description
220
+
221
+ # Find the best iteration by TEST score (or train if no test set)
222
+ if test_set:
223
+ best = max(history, key=lambda h: h["test_passed"] or 0)
224
+ best_score = f"{best['test_passed']}/{best['test_total']}"
225
+ else:
226
+ best = max(history, key=lambda h: h["train_passed"])
227
+ best_score = f"{best['train_passed']}/{best['train_total']}"
228
+
229
+ if verbose:
230
+ print(f"\nExit reason: {exit_reason}", file=sys.stderr)
231
+ print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr)
232
+
233
+ return {
234
+ "exit_reason": exit_reason,
235
+ "original_description": original_description,
236
+ "best_description": best["description"],
237
+ "best_score": best_score,
238
+ "best_train_score": f"{best['train_passed']}/{best['train_total']}",
239
+ "best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None,
240
+ "final_description": current_description,
241
+ "iterations_run": len(history),
242
+ "holdout": holdout,
243
+ "train_size": len(train_set),
244
+ "test_size": len(test_set),
245
+ "history": history,
246
+ }
247
+
248
+
249
+ def main():
250
+ parser = argparse.ArgumentParser(description="Run eval + improve loop")
251
+ parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file")
252
+ parser.add_argument("--skill-path", required=True, help="Path to skill directory")
253
+ parser.add_argument("--description", default=None, help="Override starting description")
254
+ parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers")
255
+ parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds")
256
+ parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations")
257
+ parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query")
258
+ parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold")
259
+ parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)")
260
+ parser.add_argument("--model", required=True, help="Pi model provider/id[:thinking] for evaluation and improvement")
261
+ parser.add_argument("--verbose", action="store_true", help="Print progress to stderr")
262
+ parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)")
263
+ parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here")
264
+ args = parser.parse_args()
265
+
266
+ eval_set = json.loads(Path(args.eval_set).read_text())
267
+ skill_path = Path(args.skill_path)
268
+
269
+ if not (skill_path / "SKILL.md").exists():
270
+ print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
271
+ sys.exit(1)
272
+
273
+ name, _, _ = parse_skill_md(skill_path)
274
+
275
+ # Set up live report path
276
+ if args.report != "none":
277
+ if args.report == "auto":
278
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
279
+ live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html"
280
+ else:
281
+ live_report_path = Path(args.report)
282
+ # Open the report immediately so the user can watch
283
+ live_report_path.write_text("<html><body><h1>Starting optimization loop...</h1><meta http-equiv='refresh' content='5'></body></html>")
284
+ webbrowser.open(str(live_report_path))
285
+ else:
286
+ live_report_path = None
287
+
288
+ # Determine output directory (create before run_loop so logs can be written)
289
+ if args.results_dir:
290
+ timestamp = time.strftime("%Y-%m-%d_%H%M%S")
291
+ results_dir = Path(args.results_dir) / timestamp
292
+ results_dir.mkdir(parents=True, exist_ok=True)
293
+ else:
294
+ results_dir = None
295
+
296
+ log_dir = results_dir / "logs" if results_dir else None
297
+
298
+ output = run_loop(
299
+ eval_set=eval_set,
300
+ skill_path=skill_path,
301
+ description_override=args.description,
302
+ num_workers=args.num_workers,
303
+ timeout=args.timeout,
304
+ max_iterations=args.max_iterations,
305
+ runs_per_query=args.runs_per_query,
306
+ trigger_threshold=args.trigger_threshold,
307
+ holdout=args.holdout,
308
+ model=args.model,
309
+ verbose=args.verbose,
310
+ live_report_path=live_report_path,
311
+ log_dir=log_dir,
312
+ )
313
+
314
+ # Save JSON output
315
+ json_output = json.dumps(output, indent=2)
316
+ print(json_output)
317
+ if results_dir:
318
+ (results_dir / "results.json").write_text(json_output)
319
+
320
+ # Write final HTML report (without auto-refresh)
321
+ if live_report_path:
322
+ live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name))
323
+ print(f"\nReport: {live_report_path}", file=sys.stderr)
324
+
325
+ if results_dir and live_report_path:
326
+ (results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name))
327
+
328
+ if results_dir:
329
+ print(f"Results saved to: {results_dir}", file=sys.stderr)
330
+
331
+
332
+ if __name__ == "__main__":
333
+ with interrupt_on_termination():
334
+ main()
@@ -0,0 +1,41 @@
1
+ """Shared utilities for skill-creator scripts.
2
+
3
+ Changed by Datalab Kit: parse Pi skill frontmatter as YAML, including quoted
4
+ and multiline descriptions. Upstream: anthropics/skills
5
+ dbd4588f9e1033efb41dad4bef2f7947c8993d44 (Apache-2.0).
6
+ """
7
+
8
+ from pathlib import Path
9
+
10
+ import yaml
11
+
12
+
13
+
14
+ def parse_skill_md(skill_path: Path) -> tuple[str, str, str]:
15
+ """Parse a SKILL.md file, returning (name, description, full_content)."""
16
+ content = (skill_path / "SKILL.md").read_text()
17
+ lines = content.split("\n")
18
+
19
+ if lines[0].strip() != "---":
20
+ raise ValueError("SKILL.md missing frontmatter (no opening ---)")
21
+
22
+ end_idx = None
23
+ for i, line in enumerate(lines[1:], start=1):
24
+ if line.strip() == "---":
25
+ end_idx = i
26
+ break
27
+
28
+ if end_idx is None:
29
+ raise ValueError("SKILL.md missing frontmatter (no closing ---)")
30
+
31
+ frontmatter = yaml.safe_load("\n".join(lines[1:end_idx]))
32
+ if not isinstance(frontmatter, dict):
33
+ raise ValueError("SKILL.md frontmatter must be a YAML mapping")
34
+ name = frontmatter.get("name", "")
35
+ description = frontmatter.get("description", "")
36
+ if not isinstance(name, str) or not name.strip():
37
+ raise ValueError("SKILL.md requires a non-empty string name")
38
+ if not isinstance(description, str) or not description.strip():
39
+ raise ValueError("SKILL.md requires a non-empty string description")
40
+
41
+ return name, description, content