Repository navigation
feat(cli): ship workflow guides and expose dp skills offline
#6105
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
njzjz-bot
wants to merge
6
commits into
deepmodeling:master
Choose a base branch
from
njzjz-bot:agent-dot/bundled-skills-cli-20261024
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d1d3dd9
feat(cli): bundle offline workflow skills and contextual help
njzjz-bot 8c71c81
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 1b4a3d6
docs: describe bundled skills in Agent Skills guide
njzjz-bot 233ce34
fix(cli): report missing skills resources consistently
njzjz-bot 411bd60
test(packaging): smoke-test bundled CLI guides from installed wheels
njzjz-bot a6faf26
test(packaging): exercise bundled guides in Windows wheels
njzjz-bot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Read the public workflow guides shipped with this version of DeePMD-kit.""" | ||
|
|
||
| import argparse | ||
| import sys | ||
| from pathlib import ( | ||
| Path, | ||
| ) | ||
|
|
||
|
|
||
| def skill_root() -> Path: | ||
| """Locate installed resources or the adjacent development checkout.""" | ||
| package = Path(__file__).resolve().parent | ||
| bundled = package / "_skills" | ||
| if bundled.is_dir(): | ||
| return bundled | ||
| checkout = package.parent | ||
| if (checkout / "pyproject.toml").is_file() and (checkout / "skills").is_dir(): | ||
| return checkout / "skills" | ||
| raise ValueError("Bundled skills are missing; reinstall the package.") | ||
|
|
||
|
|
||
| def add_parser(subparsers: argparse._SubParsersAction) -> None: | ||
| """Register the offline skills commands on the application parser.""" | ||
| parser = subparsers.add_parser( | ||
| "skills", help="Read bundled workflow guides offline." | ||
| ) | ||
| actions = parser.add_subparsers(dest="skills_action", required=True) | ||
| actions.add_parser("list", help="List available workflow guides.") | ||
| read = actions.add_parser( | ||
| "read", help="Read a skill or one of its reference files." | ||
| ) | ||
| read.add_argument("name", help="Skill name from 'dp skills list'.") | ||
| read.add_argument( | ||
| "path", nargs="?", default="SKILL.md", help="Relative reference path." | ||
| ) | ||
|
|
||
|
|
||
| def read_skill(name: str, path: str = "SKILL.md") -> str: | ||
| """Read a public text resource without executing it or following escaping paths.""" | ||
| root = skill_root().resolve() | ||
| if not name or name in (".", "..") or any(c in name for c in "/\\\0"): | ||
| raise ValueError("invalid skill name") | ||
| parts = path.split("/") | ||
| if ( | ||
| not path | ||
| or any(c in path for c in "\\\0:") | ||
| or any(p in ("", ".", "..") for p in parts) | ||
| ): | ||
| raise ValueError("reference path must stay within the skill") | ||
| skill = (root / name).resolve() | ||
| if skill.parent != root or not (skill / "SKILL.md").is_file(): | ||
| raise ValueError(f"unknown skill: {name}") | ||
| target = skill.joinpath(*parts).resolve() | ||
| if not target.is_relative_to(skill) or not target.is_file(): | ||
| raise ValueError(f"unknown skill reference: {path}") | ||
| try: | ||
| return target.read_bytes().decode("utf-8") | ||
| except UnicodeDecodeError as exc: | ||
| raise ValueError("skill reference is not UTF-8 text") from exc | ||
|
|
||
|
|
||
| def run(args: argparse.Namespace) -> None: | ||
| """Write the requested guide to stdout; report invalid references as CLI errors.""" | ||
| try: | ||
| if args.skills_action == "list": | ||
| root = skill_root().resolve() | ||
| for path in sorted(root.glob("*/SKILL.md")): | ||
| if path.parent.resolve().parent == root: | ||
| sys.stdout.write(path.parent.name + "\n") | ||
| return | ||
| content = read_skill(args.name, args.path) | ||
| except (ValueError, OSError) as exc: | ||
| sys.stderr.write(f"dp skills: {exc}\n") | ||
| raise SystemExit(2) from exc | ||
| sys.stdout.write(content) | ||
|
|
||
|
|
||
| def workflow_help(name: str) -> str: | ||
| """Point help readers to an available, version-matched workflow guide.""" | ||
| try: | ||
| available = skill_root().joinpath(name, "SKILL.md").is_file() | ||
| except (ValueError, OSError): | ||
| return "" | ||
| if not available: | ||
| return "" | ||
| return f"Workflow guide (read first): dp skills read {name}" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Discoverable workflow guidance belongs to help, not command output.""" | ||
|
|
||
| import contextlib | ||
| import io | ||
| import unittest | ||
| from unittest.mock import ( | ||
| patch, | ||
| ) | ||
|
|
||
| from deepmd.main import ( | ||
| main_parser, | ||
| ) | ||
| from deepmd.skills import ( | ||
| workflow_help, | ||
| ) | ||
|
|
||
|
|
||
| class TestSkillHelp(unittest.TestCase): | ||
| def test_contextual_help(self) -> None: | ||
| for command, skill in {"train": "deepmd-train"}.items(): | ||
| with self.subTest(command=command): | ||
| output = io.StringIO() | ||
| with ( | ||
| contextlib.redirect_stdout(output), | ||
| self.assertRaises(SystemExit) as result, | ||
| ): | ||
| main_parser().parse_args( | ||
| ([command] if command else []) + ["--help"] | ||
| ) | ||
| self.assertEqual(result.exception.code, 0) | ||
| self.assertIn(f"dp skills read {skill}", output.getvalue()) | ||
| self.assertIn( | ||
| "dp train input.json --restart model.ckpt", output.getvalue() | ||
| ) | ||
|
|
||
| def test_missing_guide_has_no_pointer(self) -> None: | ||
| self.assertEqual(workflow_help("not-a-bundled-skill"), "") | ||
| with patch( | ||
| "deepmd.skills.skill_root", side_effect=ValueError("missing resources") | ||
| ): | ||
| self.assertEqual(workflow_help("deepmd-train"), "") |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| # SPDX-License-Identifier: LGPL-3.0-or-later | ||
| """Tests for offline, version-matched workflow discovery.""" | ||
|
|
||
| import contextlib | ||
| import io | ||
| import os | ||
| import subprocess | ||
| import sys | ||
| import tempfile | ||
| import unittest | ||
| from pathlib import ( | ||
| Path, | ||
| ) | ||
| from unittest.mock import ( | ||
| patch, | ||
| ) | ||
|
|
||
| from deepmd.main import ( | ||
| main_parser, | ||
| parse_args, | ||
| ) | ||
| from deepmd.skills import ( | ||
| read_skill, | ||
| run, | ||
| skill_root, | ||
| ) | ||
|
|
||
|
|
||
| class TestSkills(unittest.TestCase): | ||
| def test_list_and_read(self) -> None: | ||
| output = io.StringIO() | ||
| with contextlib.redirect_stdout(output): | ||
| run(parse_args(["skills", "list"])) | ||
| self.assertIn("deepmd-train", output.getvalue().splitlines()) | ||
| expected = (skill_root() / "deepmd-train" / "SKILL.md").read_bytes() | ||
| self.assertEqual(read_skill("deepmd-train").encode(), expected) | ||
|
|
||
| def test_help_and_legacy_parser(self) -> None: | ||
| self.assertIn("skills", main_parser().format_help()) | ||
| args = parse_args(["train", "input.json"]) | ||
| self.assertEqual(args.INPUT, "input.json") | ||
|
|
||
| def test_invalid_paths(self) -> None: | ||
| for name, path in [ | ||
| ("../deepmd-train", "SKILL.md"), | ||
| ("missing", "SKILL.md"), | ||
| ("deepmd-train", "../README.md"), | ||
| ("deepmd-train", "/etc/passwd"), | ||
| ("deepmd-train", "..\\README.md"), | ||
| ("deepmd-train", "C:/file"), | ||
| ("deepmd-train", "SKILL.md\0"), | ||
| ]: | ||
| with self.subTest(name=name, path=path), self.assertRaises(ValueError): | ||
| read_skill(name, path) | ||
|
|
||
| def test_symlink_escape(self) -> None: | ||
| with tempfile.TemporaryDirectory() as tmp: | ||
| root = Path(tmp) | ||
| skill = root / "skills" / "guide" | ||
| skill.mkdir(parents=True) | ||
| (skill / "SKILL.md").write_text("guide", encoding="utf-8") | ||
| outside = root / "private.txt" | ||
| outside.write_text("private", encoding="utf-8") | ||
| (skill / "escape.md").symlink_to(outside) | ||
| with patch("deepmd.skills.skill_root", return_value=root / "skills"): | ||
| with self.assertRaises(ValueError): | ||
| read_skill("guide", "escape.md") | ||
|
|
||
| def test_cli_leaves_home_untouched(self) -> None: | ||
| with tempfile.TemporaryDirectory() as home: | ||
| result = subprocess.run( | ||
| [sys.executable, "-m", "deepmd", "skills", "list"], | ||
| env={**os.environ, "HOME": home}, | ||
| capture_output=True, | ||
| text=True, | ||
| check=True, | ||
| ) | ||
| self.assertIn("deepmd-train", result.stdout) | ||
| self.assertEqual(list(Path(home).iterdir()), []) | ||
|
|
||
| def test_no_backend_import(self) -> None: | ||
| code = ( | ||
| "import sys; " | ||
| "sys.modules.update({name: None for name in " | ||
| "('tensorflow', 'torch', 'jax', 'paddle')}); " | ||
| "from deepmd.main import main; main(['skills', 'list'])" | ||
| ) | ||
| subprocess.run([sys.executable, "-c", code], check=True, capture_output=True) | ||
|
|
||
| def test_missing_resources_are_cli_errors(self) -> None: | ||
| for command in [["skills", "list"], ["skills", "read", "deepmd-train"]]: | ||
| args = parse_args(command) | ||
| for error in [ValueError("missing guides"), OSError("guides inaccessible")]: | ||
| output, errors = io.StringIO(), io.StringIO() | ||
| with ( | ||
| self.subTest(command=command, error=error), | ||
| patch("deepmd.skills.skill_root", side_effect=error), | ||
| contextlib.redirect_stdout(output), | ||
| contextlib.redirect_stderr(errors), | ||
| self.assertRaises(SystemExit) as raised, | ||
| ): | ||
| run(args) | ||
| self.assertEqual(raised.exception.code, 2) | ||
| self.assertEqual(output.getvalue(), "") | ||
| self.assertIn(f"dp skills: {error}", errors.getvalue()) | ||
| self.assertNotIn("Traceback", errors.getvalue()) | ||
|
|
||
| def test_resource_locations(self) -> None: | ||
| with tempfile.TemporaryDirectory() as tmp: | ||
| root = Path(tmp) | ||
| package = root / "deepmd" | ||
| package.mkdir() | ||
| with patch("deepmd.skills.__file__", str(package / "skills.py")): | ||
| with self.assertRaisesRegex(ValueError, "reinstall"): | ||
| skill_root() | ||
| (root / "pyproject.toml").touch() | ||
| with self.assertRaisesRegex(ValueError, "reinstall"): | ||
| skill_root() | ||
| (root / "skills").mkdir() | ||
| self.assertEqual(skill_root(), (root / "skills").resolve()) | ||
| bundled = package / "_skills" | ||
| bundled.mkdir() | ||
| self.assertEqual(skill_root(), bundled.resolve()) | ||
|
|
||
| def test_resource_locations_through_symlink(self) -> None: | ||
| with tempfile.TemporaryDirectory() as tmp: | ||
| root = Path(tmp) | ||
| actual, alias = root / "actual", root / "alias" | ||
| actual.mkdir() | ||
| try: | ||
| alias.symlink_to(actual, target_is_directory=True) | ||
| except (OSError, NotImplementedError) as exc: | ||
| self.skipTest(f"Directory symlinks are unavailable: {exc}") | ||
| with patch("tempfile.tempdir", str(alias)): | ||
| self.test_resource_locations() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.