diff --git a/nanobot/agent/plugins.py b/nanobot/agent/plugins.py index 5713108b9..b08928bfe 100644 --- a/nanobot/agent/plugins.py +++ b/nanobot/agent/plugins.py @@ -25,6 +25,16 @@ _MCP_SERVER_FIELDS = {"type", "command", "args", "env", "cwd"} _MAX_LOGO_BYTES = 256 * 1024 +@dataclass(frozen=True, slots=True) +class AgentPluginSkill: + """A skill document captured from the approved package fingerprint.""" + + name: str + path: Path + content: str + metadata: dict[str, object] + + @dataclass(frozen=True, slots=True) class _PackageSnapshot: root: Path @@ -81,25 +91,45 @@ def _installed_plugins(workspace: Path) -> list[AgentPlugin]: def enabled_agent_plugin_skills(workspace: Path) -> list[tuple[str, Path]]: """Verify and return skills from plugins the user has explicitly enabled.""" - skills: list[tuple[str, Path]] = [] + return [(skill.name, skill.path) for skill in enabled_agent_plugin_skill_documents(workspace)] + + +def enabled_agent_plugin_skill_documents(workspace: Path) -> list[AgentPluginSkill]: + """Return documents using the same bytes that passed package activation.""" + skills: list[AgentPluginSkill] = [] packages: list[_PackageSnapshot] = [] for plugin in _installed_plugins(workspace): - plugin_skills = _discover_plugin_skills(plugin.name, plugin.root) - fingerprint = _enabled_package_fingerprint(workspace, plugin) + skill_files = _plugin_skill_files(plugin.name, plugin.root) + documents: dict[Path, bytes | None] = {path: None for _name, path in skill_files} + fingerprint = _enabled_package_fingerprint(workspace, plugin, documents=documents) if fingerprint is None: continue + plugin_skills: list[AgentPluginSkill] = [] + for name, path in skill_files: + raw = documents[path] + try: + content = raw.decode("utf-8").replace("\r\n", "\n").replace("\r", "\n") if raw is not None else "" + except UnicodeError: + content = "" + metadata = parse_skill_metadata(content) + if metadata is None or not valid_skill_metadata(metadata, name): + logger.warning("Ignoring Agent Plugin '{}' skill '{}': invalid metadata", plugin.name, name) + continue + plugin_skills.append(AgentPluginSkill(name, path, content, metadata)) skills.extend(plugin_skills) if plugin_skills: packages.append( _PackageSnapshot( root=plugin.root, fingerprint=fingerprint, - skill_dirs=tuple(path.parent for _name, path in plugin_skills), + skill_dirs=tuple(skill.path.parent for skill in plugin_skills), ) ) key = _skill_cache_key(workspace) - _SKILL_CACHE[key] = _SkillCacheEntry(tuple(skills), tuple(packages)) + _SKILL_CACHE[key] = _SkillCacheEntry( + tuple((skill.name, skill.path) for skill in skills), tuple(packages) + ) return skills @@ -156,7 +186,9 @@ def _invalidate_skill_cache(workspace: Path) -> None: _SKILL_CACHE.pop(_skill_cache_key(workspace), None) -def _package_fingerprint(root: Path) -> str | None: +def _package_fingerprint( + root: Path, *, documents: dict[Path, bytes | None] | None = None, +) -> str | None: """Hash package paths, link targets, and file contents.""" digest = sha256() try: @@ -167,8 +199,11 @@ def _package_fingerprint(root: Path) -> str | None: digest.update(b"\0link\0") digest.update(candidate.readlink().as_posix().encode()) elif candidate.is_file(): + content = candidate.read_bytes() digest.update(b"\0file\0") - digest.update(candidate.read_bytes()) + digest.update(content) + if documents is not None and candidate in documents: + documents[candidate] = content elif candidate.is_dir(): digest.update(b"\0dir\0") else: @@ -413,14 +448,16 @@ def _plugin_data_dir(workspace: Path, name: str, *, create: bool) -> Path: return current -def _enabled_package_fingerprint(workspace: Path, plugin: AgentPlugin) -> str | None: +def _enabled_package_fingerprint( + workspace: Path, plugin: AgentPlugin, *, documents: dict[Path, bytes | None] | None = None, +) -> str | None: """Return the content fingerprint when this exact package is enabled.""" marker = _plugin_data_dir(workspace, plugin.name, create=False) / "enabled" try: if not marker.is_file(): return None current = marker.read_text(encoding="utf-8") - activation = _activation_marker(plugin) + activation = _activation_marker(plugin, documents=documents) if activation is None: marker.unlink(missing_ok=True) _invalidate_skill_cache(workspace) @@ -447,9 +484,11 @@ def _enabled(workspace: Path, plugin: AgentPlugin) -> bool: return _enabled_package_fingerprint(workspace, plugin) is not None -def _activation_marker(plugin: AgentPlugin) -> str | None: +def _activation_marker( + plugin: AgentPlugin, *, documents: dict[Path, bytes | None] | None = None, +) -> str | None: """Bind activation to one immutable package snapshot.""" - fingerprint = _package_fingerprint(plugin.root) + fingerprint = _package_fingerprint(plugin.root, documents=documents) if fingerprint is None: return None return json.dumps( @@ -459,7 +498,7 @@ def _activation_marker(plugin: AgentPlugin) -> str | None: ) -def _discover_plugin_skills(plugin_name: str, plugin_root: Path) -> list[tuple[str, Path]]: +def _plugin_skill_files(plugin_name: str, plugin_root: Path) -> list[tuple[str, Path]]: skills_root = _contained(plugin_root / "skills", plugin_root, directory=True) if skills_root is None: return [] @@ -472,13 +511,6 @@ def _discover_plugin_skills(plugin_name: str, plugin_root: Path) -> list[tuple[s skill_file = _contained(skill_root / "SKILL.md", plugin_root) if skill_file is None: continue - try: - metadata = parse_skill_metadata(skill_file.read_text(encoding="utf-8")) - except (OSError, UnicodeError): - metadata = None - if metadata is None or not valid_skill_metadata(metadata, candidate.name): - logger.warning("Ignoring Agent Plugin '{}' skill '{}': invalid metadata", plugin_name, candidate.name) - continue skills.append((candidate.name, skill_file)) return skills diff --git a/nanobot/agent/skills.py b/nanobot/agent/skills.py index 750cdcd5a..cc19ae238 100644 --- a/nanobot/agent/skills.py +++ b/nanobot/agent/skills.py @@ -121,32 +121,37 @@ class SkillsLoader: return skills def _discover_skills(self) -> list[dict[str, str]]: - from nanobot.agent.plugins import enabled_agent_plugin_skills + from nanobot.agent.plugins import enabled_agent_plugin_skill_documents - plugin_skills = enabled_agent_plugin_skills(self.workspace) + plugin_skills = enabled_agent_plugin_skill_documents(self.workspace) + disabled = set(self.disabled_skills) + if disabled: + for legacy, canonical in self._skill_aliases().items(): + if legacy in disabled or canonical in disabled: + disabled.update((legacy, canonical)) skills = self._skill_entries_from_dir(self.workspace_skills, "workspace") seen_names = {entry["name"] for entry in skills} - for name, path in plugin_skills: - if name in seen_names: + snapshot = self._snapshot.get() + for skill in plugin_skills: + if skill.name in seen_names: continue skills.append( { - "name": name, - "path": str(path), + "name": skill.name, + "path": str(skill.path), "source": "plugin", } ) - seen_names.add(name) + if snapshot is not None and skill.name not in disabled: + snapshot.documents[skill.name] = skill.content + snapshot.metadata[skill.name] = skill.metadata + seen_names.add(skill.name) if self.builtin_skills and self.builtin_skills.exists(): skills.extend( self._skill_entries_from_dir(self.builtin_skills, "builtin", skip_names=seen_names) ) - if self.disabled_skills: - disabled = set(self.disabled_skills) - for legacy, canonical in self._skill_aliases().items(): - if legacy in disabled or canonical in disabled: - disabled.update((legacy, canonical)) + if disabled: skills = [s for s in skills if s["name"] not in disabled] return skills @@ -161,6 +166,10 @@ class SkillsLoader: Returns: Skill content or None if not found. """ + with self.snapshot(): + return self._load_skill(name) + + def _load_skill(self, name: str) -> str | None: skills = self.list_skills(filter_unavailable=False) available = {skill["name"] for skill in skills} resolved = name if name in available else self._skill_aliases().get(name, name) diff --git a/tests/agent/test_agent_plugins.py b/tests/agent/test_agent_plugins.py index c8470b8c1..2d3fdaf16 100644 --- a/tests/agent/test_agent_plugins.py +++ b/tests/agent/test_agent_plugins.py @@ -2,10 +2,12 @@ import json import os import shutil from pathlib import Path +from threading import Event, Thread import pytest from nanobot.agent import plugins as agent_plugins +from nanobot.agent.loop import AgentLoop from nanobot.agent.plugins import ( AGENT_PLUGIN_MCP_SCHEMA, AGENT_PLUGIN_SCHEMA, @@ -18,12 +20,15 @@ from nanobot.agent.plugins import ( from nanobot.agent.skills import SkillsLoader from nanobot.agent.tools.context import ToolContext from nanobot.agent.tools.filesystem import ReadFileTool, WriteFileTool +from nanobot.bus.queue import MessageBus from nanobot.config.schema import ToolsConfig +from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse from nanobot.security.workspace_access import ( bind_workspace_scope, reset_workspace_scope, validate_workspace_scope_payload, ) +from nanobot.session.manager import SessionManager @pytest.fixture(autouse=True) @@ -62,12 +67,14 @@ def _loaded_skills(workspace: Path) -> list[str]: def test_plugin_skill_lifecycle_and_precedence(tmp_path: Path) -> None: plugin = _plugin(tmp_path) - _skill( + plugin_skill = _skill( plugin / "skills", "shared", "name: shared\ndescription: Plugin version.\nalways: true", "Plugin body.", - ) + ) / "SKILL.md" + plugin_content = plugin_skill.read_text(encoding="utf-8") + plugin_skill.write_bytes(plugin_content.replace("\n", "\r\n").encode("utf-8")) _skill(tmp_path / "builtin", "shared", body="Built-in body.") workspace_skill = _skill( tmp_path / "skills", "shared", "name: shared\ndescription: Workspace version." @@ -83,17 +90,135 @@ def test_plugin_skill_lifecycle_and_precedence(tmp_path: Path) -> None: assert [entry["source"] for entry in loader.list_skills()] == ["plugin"] assert loader.get_explicitly_invoked_skills("Use $shared") == ["shared"] assert loader.get_always_skills() == ["shared"] - assert "Plugin body" in (loader.load_skill("shared") or "") + assert loader.load_skill("shared") == plugin_content summary = loader.build_skills_summary() assert "### Agent Plugin skills (`plugins`)" in summary assert "`demo/skills/shared/SKILL.md`" in summary assert str(tmp_path.resolve()) not in summary + disabled_loader = SkillsLoader( + tmp_path, builtin_skills_dir=tmp_path / "builtin", disabled_skills={"shared"}, + ) + with disabled_loader.snapshot(): + assert disabled_loader.list_skills() == [] + assert disabled_loader.load_skill("shared") is None + assert disabled_loader.get_skill_metadata("shared") is None + set_agent_plugin_enabled(tmp_path, "demo", False) assert [entry["source"] for entry in loader.list_skills()] == ["builtin"] assert "Built-in body" in (loader.load_skill("shared") or "") +@pytest.mark.asyncio +@pytest.mark.parametrize("boundary", ["after-verification", "during-verification"]) +async def test_prompt_snapshot_uses_approved_plugin_bytes_after_replacement( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, boundary: str, +) -> None: + monkeypatch.setattr("nanobot.config.home._home_path", tmp_path / "instance") + monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config" / "config.json") + + class CaptureProvider(LLMProvider): + def __init__(self): + super().__init__(provider_name="test") + self.generation = GenerationSettings(max_tokens=1024) + self.prompts: list[str] = [] + + def get_default_model(self): + return "test" + + async def chat(self, messages, tools=None, **kwargs): + self.prompts.append(messages[0]["content"]) + return LLMResponse(content="done") + + workspace = tmp_path / "workspace" + (workspace / "skills").mkdir(parents=True) + builtin = tmp_path / "builtin" + builtin.mkdir() + plugin = _plugin(workspace) + skill_dir = _skill( + plugin / "skills", "trusted-skill", + "name: trusted-skill\ndescription: Approved plugin.\nalways: true", + "ORIGINAL_APPROVED_INSTRUCTIONS", + ) + document = skill_dir / "SKILL.md" + original = document.read_text(encoding="utf-8") + replacement = original.replace("ORIGINAL_APPROVED_INSTRUCTIONS", "REPLACEMENT_INSTRUCTIONS") + set_agent_plugin_enabled(workspace, "demo", True) + provider = CaptureProvider() + sessions = SessionManager(workspace, sessions_root=tmp_path / "sessions") + loop = AgentLoop( + bus=MessageBus(), provider=provider, workspace=workspace, session_manager=sessions, + model="test", context_window_tokens=64000, max_iterations=1, + ) + loop.context.skills = SkillsLoader(workspace, builtin_skills_dir=builtin) + reached = Event() + replaced = Event() + errors: list[Exception] = [] + writer: Thread | None = None + + def pause_for_replacement(): + reached.set() + assert replaced.wait(timeout=10), "package editor did not finish" + + def replace_package(): + try: + assert reached.wait(timeout=10), "prompt did not reach the replacement boundary" + document.write_text(replacement, encoding="utf-8") + except Exception as exc: + errors.append(exc) + finally: + replaced.set() + + try: + await loop.process_direct("Explain this project", session_key="cli:approved") + assert "ORIGINAL_APPROVED_INSTRUCTIONS" in provider.prompts[-1] + original_iterdir = Path.iterdir + original_read_bytes = Path.read_bytes + + def iterdir(path): + if path == workspace / "skills" and not reached.is_set(): + pause_for_replacement() + return original_iterdir(path) + + def read_bytes(path): + content = original_read_bytes(path) + if path == document and not reached.is_set(): + pause_for_replacement() + return content + + # Both boundaries retain the approved bytes: after discovery returns, + # and while the fingerprint scan still holds bytes read before an edit. + with monkeypatch.context() as race: + if boundary == "after-verification": + race.setattr(Path, "iterdir", iterdir) + else: + race.setattr(Path, "read_bytes", read_bytes) + writer = Thread(target=replace_package) + writer.start() + await loop.process_direct("Explain this project", session_key="cli:replacement-race") + writer.join(timeout=10) + assert not writer.is_alive() and not errors + assert reached.is_set() + assert "ORIGINAL_APPROVED_INSTRUCTIONS" in provider.prompts[-1] + assert "REPLACEMENT_INSTRUCTIONS" not in provider.prompts[-1] + + await loop.process_direct("Explain this project", session_key="cli:unapproved") + assert discover_agent_plugins(workspace)[0].enabled is False + assert "ORIGINAL_APPROVED_INSTRUCTIONS" not in provider.prompts[-1] + assert "REPLACEMENT_INSTRUCTIONS" not in provider.prompts[-1] + + set_agent_plugin_enabled(workspace, "demo", True) + await loop.process_direct("Explain this project", session_key="cli:reenabled") + assert discover_agent_plugins(workspace)[0].enabled is True + assert "REPLACEMENT_INSTRUCTIONS" in provider.prompts[-1] + finally: + reached.set() + replaced.set() + if writer is not None: + writer.join(timeout=10) + await loop.subagents.close() + + def test_plugin_skills_are_direct_valid_and_contained(tmp_path: Path) -> None: plugin = _plugin(tmp_path) skills = plugin / "skills" @@ -230,10 +355,12 @@ async def test_restricted_project_can_read_only_enabled_plugin_skill( activation_checks = 0 activation_marker = agent_plugins._activation_marker - def count_activation_checks(plugin: agent_plugins.AgentPlugin) -> str | None: + def count_activation_checks( + plugin: agent_plugins.AgentPlugin, *, documents: dict[Path, bytes | None] | None = None, + ) -> str | None: nonlocal activation_checks activation_checks += 1 - return activation_marker(plugin) + return activation_marker(plugin, documents=documents) monkeypatch.setattr(agent_plugins, "_activation_marker", count_activation_checks) scope = validate_workspace_scope_payload(