From 6b88702f0cef39467db752dc411fb55395757790 Mon Sep 17 00:00:00 2001 From: jabrailkhalil Date: Fri, 20 Nov 2026 01:05:37 +0300 Subject: [PATCH] fix(middleware): align skills discovery and catalog ownership --- packages/genkit-middleware/README.md | 7 +- .../src/genkit_middleware/_skills.py | 17 +- .../genkit-middleware/tests/skills_test.py | 156 +++++++++++++++++- 3 files changed, 173 insertions(+), 7 deletions(-) diff --git a/packages/genkit-middleware/README.md b/packages/genkit-middleware/README.md index 31c63458a..f205c2608 100644 --- a/packages/genkit-middleware/README.md +++ b/packages/genkit-middleware/README.md @@ -193,7 +193,12 @@ print(response.text) # => Sure. Loaded python-expert. What are you working on? ``` -Each direct subdirectory of a skill path that holds a `SKILL.md` is a skill, named after the directory (`skills/python-expert/SKILL.md` is `python-expert`). Frontmatter `description` shows up in the catalog; frontmatter `name` doesn't rename the skill: +By default, `Skills()` scans `.agents/skills` and then `skills`. Set `skill_paths` +to replace these defaults, or set it to `[]` to disable discovery. + +Each direct subdirectory of a skill path that holds a `SKILL.md` is a skill, named +after the directory (`skills/python-expert/SKILL.md` is `python-expert`). Frontmatter +`description` shows up in the catalog. Frontmatter `name` does not rename the skill: ```markdown --- diff --git a/packages/genkit-middleware/src/genkit_middleware/_skills.py b/packages/genkit-middleware/src/genkit_middleware/_skills.py index ceb373f94..bf64e9918 100644 --- a/packages/genkit-middleware/src/genkit_middleware/_skills.py +++ b/packages/genkit-middleware/src/genkit_middleware/_skills.py @@ -48,6 +48,8 @@ logger = get_logger(__name__) _SKILLS_MARKER = 'skills-instructions' +_SKILLS_TOOL_METADATA_KEY = 'skillsActivationTool' +_USE_SKILL_TOOL_NAME = 'use_skill' _MISSING_DESCRIPTION = 'No description provided.' _SKILL_FILE_NAME = 'SKILL.md' @@ -74,7 +76,7 @@ class _UseSkillInput(PydanticBaseModel): class SkillsConfig(GenkitConfig): """Directories to scan for skill folders containing ``SKILL.md``.""" - skill_paths: list[str] = Field(default_factory=lambda: ['skills']) + skill_paths: list[str] = Field(default_factory=lambda: ['.agents/skills', 'skills']) def _single_line(value: str) -> str: @@ -263,6 +265,7 @@ def _build_skills_prompt(self, skills: dict[str, dict[str, str]]) -> str: 'You have access to a library of skills that serve as specialized instructions/personas.', 'Strongly prefer to use them when working on anything related to them.', 'Only use them once to load the context.', + f"Call the {_USE_SKILL_TOOL_NAME} tool with a skill's name to load its instructions.", 'Here are the available skills:', ] for skill_name in sorted(skills.keys()): @@ -283,7 +286,10 @@ def _inject_skills_prompt(self, options: GenerateActionOptions, prompt_text: str system_idx = i break - marker_meta: dict[str, Any] = {_SKILLS_MARKER: True} + marker_meta: dict[str, Any] = { + _SKILLS_MARKER: True, + _SKILLS_TOOL_METADATA_KEY: _USE_SKILL_TOOL_NAME, + } new_part = Part.from_text(prompt_text, metadata=marker_meta) if system_idx is not None: @@ -291,8 +297,9 @@ def _inject_skills_prompt(self, options: GenerateActionOptions, prompt_text: str new_content = [] replaced = False for part in msg.content: - meta = part.metadata if part.text is not None else None - if isinstance(meta, dict) and meta.get(_SKILLS_MARKER): + meta = part.metadata if part.text is not None and isinstance(part.metadata, dict) else None + owner = meta.get(_SKILLS_TOOL_METADATA_KEY) if meta else None + if meta and meta.get(_SKILLS_MARKER) and (not isinstance(owner, str) or owner == _USE_SKILL_TOOL_NAME): new_content.append(new_part) replaced = True else: @@ -328,7 +335,7 @@ async def use_skill(input: _UseSkillInput) -> str: logger.warning('skill could not be read', skill=skill_name, path=info['path'], error=str(exc)) return f'Failed to read skill "{_catalog_text(skill_name)}".' - return [Tool(use_skill, description='Load a skill by name.')] + return [Tool(use_skill, name=_USE_SKILL_TOOL_NAME, description='Load a skill by name.')] async def wrap_generate( self, diff --git a/packages/genkit-middleware/tests/skills_test.py b/packages/genkit-middleware/tests/skills_test.py index 672dfa850..53c1f309b 100644 --- a/packages/genkit-middleware/tests/skills_test.py +++ b/packages/genkit-middleware/tests/skills_test.py @@ -22,7 +22,7 @@ import pytest from genkit_middleware import Skills -from genkit import ModelResponse +from genkit import Message, ModelResponse, Part, Role from genkit.middleware import GenerateHookParams, MiddlewareContext from genkit.model import GenerateActionOptions @@ -34,6 +34,160 @@ def _make_params() -> GenerateHookParams: ) +def _write_skill(path: Path, content: str = 'Skill instructions.') -> None: + path.mkdir(parents=True) + (path / 'SKILL.md').write_text(content, encoding='utf-8') + + +@pytest.mark.parametrize('paths', [['.agents/skills'], ['skills'], ['.agents/skills', 'skills']]) +def test_skills_default_paths(tmp_path, monkeypatch, paths) -> None: + monkeypatch.chdir(tmp_path) + for index, path in enumerate(paths): + _write_skill(tmp_path / path / f'skill-{index}') + + scanned = Skills()._scan_skills() + + assert set(scanned) == {f'skill-{index}' for index in range(len(paths))} + + +def test_skills_default_paths_later_directory_wins(tmp_path, monkeypatch) -> None: + monkeypatch.chdir(tmp_path) + _write_skill(tmp_path / '.agents/skills/shared', 'Agent instructions.') + _write_skill(tmp_path / 'skills/shared', 'Project instructions.') + + scanned = Skills()._scan_skills() + + assert set(scanned) == {'shared'} + assert Path(scanned['shared']['path']) == tmp_path / 'skills/shared/SKILL.md' + + +@pytest.mark.parametrize('paths', [['custom'], []]) +def test_skills_explicit_paths_replace_defaults(tmp_path, monkeypatch, paths) -> None: + monkeypatch.chdir(tmp_path) + _write_skill(tmp_path / '.agents/skills/agent') + _write_skill(tmp_path / 'skills/project') + _write_skill(tmp_path / 'custom/explicit') + + scanned = Skills(skill_paths=paths)._scan_skills() + + assert set(scanned) == ({'explicit'} if paths else set()) + + +@pytest.mark.asyncio +@pytest.mark.parametrize('has_system_message', [False, True]) +async def test_skills_catalog_names_activation_tool(tmp_path, ctx, has_system_message) -> None: + _write_skill(tmp_path / 'poetry') + skills = Skills(skill_paths=[str(tmp_path)]) + params = _make_params() + if has_system_message: + params.options.messages.append(Message(role=Role.SYSTEM, content=[Part.from_text('System instructions.')])) + params.options.messages.append(Message(role=Role.USER, content=[Part.from_text('Write a poem.')])) + original = params.model_copy(deep=True) + tool = skills.tools(ctx)[0] + + async def next_fn(updated, ctx): + system = updated.options.messages[0] + assert system.role == Role.SYSTEM + catalog = system.content[-1] + assert catalog.text is not None + assert f"Call the {tool.name} tool with a skill's name to load its instructions." in catalog.text + assert catalog.metadata == {'skills-instructions': True, 'skillsActivationTool': tool.name} + assert ' - poetry\n' in catalog.text + if has_system_message: + assert system.content[0] == original.options.messages[0].content[0] + assert updated.options.messages[1:] == original.options.messages[-1:] + return ModelResponse(message=None) + + await skills.wrap_generate(params, ctx, next_fn) + assert params == original + + +@pytest.mark.parametrize( + 'owner_metadata', + [ + {}, + {'skillsActivationTool': 'use_skill'}, + {'skillsActivationTool': None}, + {'skillsActivationTool': False}, + {'skillsActivationTool': 123}, + {'skillsActivationTool': []}, + {'skillsActivationTool': {}}, + ], + ids=['legacy', 'same-owner', 'null', 'boolean', 'number', 'list', 'object'], +) +def test_skills_refreshes_owned_and_legacy_catalogs(owner_metadata) -> None: + skills = Skills() + options = GenerateActionOptions( + messages=[ + Message( + role=Role.SYSTEM, + content=[ + Part.from_text('System instructions.'), + Part.from_text('Old catalog.', metadata={'skills-instructions': True, **owner_metadata}), + ], + ), + ], + ) + original = options.model_copy(deep=True) + + updated = skills._inject_skills_prompt(options, 'Updated catalog.') + updated = skills._inject_skills_prompt(updated, 'Latest catalog.') + + assert options == original + assert len(updated.messages[0].content) == 2 + assert updated.messages[0].content[0] == original.messages[0].content[0] + assert updated.messages[0].content[1].text == 'Latest catalog.' + assert updated.messages[0].content[1].metadata == { + 'skills-instructions': True, + 'skillsActivationTool': 'use_skill', + } + + +@pytest.mark.parametrize('owner', ['', 'other_use_skill']) +def test_skills_preserves_foreign_catalogs(owner) -> None: + skills = Skills() + options = GenerateActionOptions( + messages=[ + Message( + role=Role.SYSTEM, + content=[ + Part.from_text('System instructions.'), + Part.from_text( + 'Foreign catalog.', metadata={'skills-instructions': True, 'skillsActivationTool': owner} + ), + ], + ), + ], + ) + original = options.model_copy(deep=True) + + updated = skills._inject_skills_prompt(options, 'New catalog.') + updated = skills._inject_skills_prompt(updated, 'Updated catalog.') + + assert options == original + assert len(updated.messages[0].content) == 3 + assert updated.messages[0].content[:2] == original.messages[0].content + assert updated.messages[0].content[2].text == 'Updated catalog.' + assert updated.messages[0].content[2].metadata == { + 'skills-instructions': True, + 'skillsActivationTool': 'use_skill', + } + + +@pytest.mark.asyncio +async def test_skills_unknown_name_lists_available_skills(tmp_path, ctx) -> None: + _write_skill(tmp_path / 'zebra') + _write_skill(tmp_path / 'poetry', 'Write a poem.') + skills = Skills(skill_paths=[str(tmp_path)]) + tool = skills.tools(ctx)[0] + + unknown = await tool(input={'skill_name': 'missing'}) + assert unknown == 'Unknown skill "missing". Available skills: poetry, zebra' + + known = await tool(input={'skill_name': 'poetry'}) + assert known == 'Write a poem.' + + @pytest.mark.asyncio async def test_skills_no_paths(ctx: MiddlewareContext) -> None: """Test that middleware works with no skill paths."""