perf(agent): reuse skill discovery within each prompt

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-15 01:47:06 +08:00
1 parent 1a77d8fc66
commit 3a28b9e6ce
3 files changed
+215 -42

No files matched your search

+33 -31
View File
@@ -115,16 +115,17 @@ class ContextBuilder:
if memory and not self._is_template_content(memory, "memory/MEMORY.md"): if memory and not self._is_template_content(memory, "memory/MEMORY.md"):
parts.append(f"# Memory\n\n## Long-term Memory\n{memory}") parts.append(f"# Memory\n\n## Long-term Memory\n{memory}")
active_skills = self.skills.get_always_skills() with self.skills.snapshot():
if active_skills: active_skills = self.skills.get_always_skills()
active_content = self.skills.load_skills_for_context(active_skills) if active_skills:
if active_content: active_content = self.skills.load_skills_for_context(active_skills)
parts.append(f"# Active Skills\n\n{active_content}") if active_content:
parts.append(f"# Active Skills\n\n{active_content}")
skills_summary = self.skills.build_skills_summary( skills_summary = self.skills.build_skills_summary(
exclude=set(active_skills), exclude=set(active_skills),
workspace=root, workspace=root,
) )
if skills_summary: if skills_summary:
parts.append(render_template("agent/skills_section.md", skills_summary=skills_summary)) parts.append(render_template("agent/skills_section.md", skills_summary=skills_summary))
@@ -269,29 +270,30 @@ class ContextBuilder:
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
"""Build a model transcript while preserving the fresh-turn boundary.""" """Build a model transcript while preserving the fresh-turn boundary."""
root = workspace or self.workspace root = workspace or self.workspace
messages: list[dict[str, Any]] = [ with self.skills.snapshot():
{ messages: list[dict[str, Any]] = [
"role": "system", {
"content": self.build_system_prompt( "role": "system",
channel=channel, "content": self.build_system_prompt(
session_summary=transcript.session_summary, channel=channel,
workspace=root, session_summary=transcript.session_summary,
include_memory=include_memory, workspace=root,
), include_memory=include_memory,
}, ),
*transcript.history, },
] *transcript.history,
if transcript.current_message is None: ]
return messages if transcript.current_message is None:
return messages
current = self.build_current_message( current = self.build_current_message(
transcript.current_message, transcript.current_message,
media=list(transcript.media) if transcript.media else None, media=list(transcript.media) if transcript.media else None,
current_role=transcript.current_role, current_role=transcript.current_role,
runtime_context_blocks=transcript.runtime_context_blocks, runtime_context_blocks=transcript.runtime_context_blocks,
) )
messages.append(current) messages.append(current)
return messages return messages
def build_current_message( def build_current_message(
self, self,
+93 -11
View File
@@ -4,6 +4,10 @@ import json
import os import os
import re import re
import shutil import shutil
from collections.abc import Generator
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass, field
from pathlib import Path from pathlib import Path
from typing import Any, cast from typing import Any, cast
@@ -24,6 +28,15 @@ from nanobot.runtime_context import RuntimeContextBlock
_SKILL_REFERENCE = re.compile(r"(?<![\w$])\$([A-Za-z0-9_-]+)") _SKILL_REFERENCE = re.compile(r"(?<![\w$])\$([A-Za-z0-9_-]+)")
@dataclass
class _SkillSnapshot:
entries: list[dict[str, str]] | None = None
aliases: dict[str, str] | None = None
documents: dict[str, str] = field(default_factory=dict)
metadata: dict[str, dict[str, object] | None] = field(default_factory=dict)
binaries: dict[str, bool] = field(default_factory=dict)
class SkillsLoader: class SkillsLoader:
""" """
Loader for agent skills. Loader for agent skills.
@@ -37,15 +50,34 @@ class SkillsLoader:
self.workspace_skills = workspace / "skills" self.workspace_skills = workspace / "skills"
self.builtin_skills = builtin_skills_dir or BUILTIN_SKILLS_DIR self.builtin_skills = builtin_skills_dir or BUILTIN_SKILLS_DIR
self.disabled_skills = disabled_skills or set() self.disabled_skills = disabled_skills or set()
self._snapshot: ContextVar[_SkillSnapshot | None] = ContextVar("skill_snapshot", default=None)
@contextmanager
def snapshot(self) -> Generator[None, None, None]:
"""Reuse discovery, documents, metadata, and CLI checks until this scope exits."""
if self._snapshot.get() is not None:
yield
return
token = self._snapshot.set(_SkillSnapshot())
try:
yield
finally:
self._snapshot.reset(token)
def _skill_aliases(self) -> dict[str, str]: def _skill_aliases(self) -> dict[str, str]:
"""Return compatibility aliases owned by installed CLI Apps.""" """Return compatibility aliases owned by installed CLI Apps."""
from nanobot.apps.cli import CliAppManager from nanobot.apps.cli import CliAppManager
snapshot = self._snapshot.get()
if snapshot is not None and snapshot.aliases is not None:
return snapshot.aliases
try: try:
return CliAppManager(workspace=self.workspace).installed_skill_aliases() aliases = CliAppManager(workspace=self.workspace).installed_skill_aliases()
except OSError: except OSError:
return {} aliases = {}
if snapshot is not None:
snapshot.aliases = aliases
return aliases
def _skill_entries_from_dir(self, base: Path, source: str, *, skip_names: set[str] | None = None) -> list[dict[str, str]]: def _skill_entries_from_dir(self, base: Path, source: str, *, skip_names: set[str] | None = None) -> list[dict[str, str]]:
if not base.exists(): if not base.exists():
@@ -73,6 +105,22 @@ class SkillsLoader:
Returns: Returns:
List of skill info dicts with 'name', 'path', 'source'. List of skill info dicts with 'name', 'path', 'source'.
""" """
with self.snapshot():
return self._list_skills(filter_unavailable)
def _list_skills(self, filter_unavailable: bool) -> list[dict[str, str]]:
snapshot = self._snapshot.get()
if snapshot is not None and snapshot.entries is not None:
skills = snapshot.entries
else:
skills = self._discover_skills()
if snapshot is not None:
snapshot.entries = skills
if filter_unavailable:
return [skill for skill in skills if self._check_requirements(self._get_skill_meta(skill["name"]))]
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_skills
plugin_skills = enabled_agent_plugin_skills(self.workspace) plugin_skills = enabled_agent_plugin_skills(self.workspace)
@@ -101,8 +149,6 @@ class SkillsLoader:
disabled.update((legacy, canonical)) disabled.update((legacy, canonical))
skills = [s for s in skills if s["name"] not in disabled] skills = [s for s in skills if s["name"] not in disabled]
if filter_unavailable:
return [skill for skill in skills if self._check_requirements(self._get_skill_meta(skill["name"]))]
return skills return skills
def load_skill(self, name: str) -> str | None: def load_skill(self, name: str) -> str | None:
@@ -119,7 +165,15 @@ class SkillsLoader:
available = {skill["name"] for skill in skills} available = {skill["name"] for skill in skills}
resolved = name if name in available else self._skill_aliases().get(name, name) resolved = name if name in available else self._skill_aliases().get(name, name)
entry = next((skill for skill in skills if skill["name"] == resolved), None) entry = next((skill for skill in skills if skill["name"] == resolved), None)
return Path(entry["path"]).read_text(encoding="utf-8") if entry else None if entry is None:
return None
snapshot = self._snapshot.get()
if snapshot is not None and resolved in snapshot.documents:
return snapshot.documents[resolved]
content = Path(entry["path"]).read_text(encoding="utf-8")
if snapshot is not None:
snapshot.documents[resolved] = content
return content
def load_skills_for_context(self, skill_names: list[str]) -> str: def load_skills_for_context(self, skill_names: list[str]) -> str:
""" """
@@ -140,7 +194,8 @@ class SkillsLoader:
def get_explicitly_invoked_skills(self, text: str) -> list[str]: def get_explicitly_invoked_skills(self, text: str) -> list[str]:
"""Resolve ``$skill-name`` references to enabled, available skills.""" """Resolve ``$skill-name`` references to enabled, available skills."""
if not text: references = list(_SKILL_REFERENCE.finditer(text))
if not references:
return [] return []
available = { available = {
entry["name"] entry["name"]
@@ -148,7 +203,7 @@ class SkillsLoader:
} }
aliases = self._skill_aliases() aliases = self._skill_aliases()
invoked: list[str] = [] invoked: list[str] = []
for match in _SKILL_REFERENCE.finditer(text): for match in references:
requested = match.group(1) requested = match.group(1)
name = requested if requested in available else aliases.get(requested, requested) name = requested if requested in available else aliases.get(requested, requested)
if name in available and name not in invoked: if name in available and name not in invoked:
@@ -160,6 +215,10 @@ class SkillsLoader:
text: str, text: str,
) -> RuntimeContextBlock | None: ) -> RuntimeContextBlock | None:
"""Load non-always skills explicitly invoked by the current message.""" """Load non-always skills explicitly invoked by the current message."""
with self.snapshot():
return self._build_explicit_skill_runtime_context(text)
def _build_explicit_skill_runtime_context(self, text: str) -> RuntimeContextBlock | None:
skill_names = self.get_explicitly_invoked_skills(text) skill_names = self.get_explicitly_invoked_skills(text)
if not skill_names: if not skill_names:
return None return None
@@ -196,6 +255,10 @@ class SkillsLoader:
Returns: Returns:
Markdown-formatted skills summary. Markdown-formatted skills summary.
""" """
with self.snapshot():
return self._build_skills_summary(exclude, workspace=workspace)
def _build_skills_summary(self, exclude: set[str] | None, *, workspace: Path | None) -> str:
all_skills = self.list_skills(filter_unavailable=False) all_skills = self.list_skills(filter_unavailable=False)
if not all_skills: if not all_skills:
return "" return ""
@@ -256,7 +319,7 @@ class SkillsLoader:
"""Get a description of missing requirements.""" """Get a description of missing requirements."""
required_bins, required_env_vars = self._requirement_lists(skill_meta) required_bins, required_env_vars = self._requirement_lists(skill_meta)
return ", ".join( return ", ".join(
[f"CLI: {command_name}" for command_name in required_bins if not shutil.which(command_name)] [f"CLI: {command_name}" for command_name in required_bins if not self._binary_available(command_name)]
+ [f"ENV: {env_name}" for env_name in required_env_vars if not os.environ.get(env_name)] + [f"ENV: {env_name}" for env_name in required_env_vars if not os.environ.get(env_name)]
) )
@@ -272,7 +335,7 @@ class SkillsLoader:
return { return {
"bins": bins, "bins": bins,
"env": env, "env": env,
"missing_bins": [value for value in bins if not shutil.which(value)], "missing_bins": [value for value in bins if not self._binary_available(value)],
"missing_env": [value for value in env if not os.environ.get(value)], "missing_env": [value for value in env if not os.environ.get(value)],
} }
@@ -316,10 +379,19 @@ class SkillsLoader:
def _check_requirements(self, skill_meta: dict[str, Any]) -> bool: def _check_requirements(self, skill_meta: dict[str, Any]) -> bool:
"""Check if skill requirements are met (bins, env vars).""" """Check if skill requirements are met (bins, env vars)."""
required_bins, required_env_vars = self._requirement_lists(skill_meta) required_bins, required_env_vars = self._requirement_lists(skill_meta)
return all(shutil.which(cmd) for cmd in required_bins) and all( return all(self._binary_available(cmd) for cmd in required_bins) and all(
os.environ.get(var) for var in required_env_vars os.environ.get(var) for var in required_env_vars
) )
def _binary_available(self, command: str) -> bool:
snapshot = self._snapshot.get()
if snapshot is not None and command in snapshot.binaries:
return snapshot.binaries[command]
available = shutil.which(command) is not None
if snapshot is not None:
snapshot.binaries[command] = available
return available
def _get_skill_meta(self, name: str) -> dict[str, Any]: def _get_skill_meta(self, name: str) -> dict[str, Any]:
"""Get nanobot metadata for a skill (cached in frontmatter).""" """Get nanobot metadata for a skill (cached in frontmatter)."""
raw_meta = self.get_skill_metadata(name) or {} raw_meta = self.get_skill_metadata(name) or {}
@@ -327,6 +399,10 @@ class SkillsLoader:
def get_always_skills(self) -> list[str]: def get_always_skills(self) -> list[str]:
"""Get skills marked as always=true that meet requirements.""" """Get skills marked as always=true that meet requirements."""
with self.snapshot():
return self._get_always_skills()
def _get_always_skills(self) -> list[str]:
return [ return [
entry["name"] entry["name"]
for entry in self.list_skills(filter_unavailable=True) for entry in self.list_skills(filter_unavailable=True)
@@ -347,4 +423,10 @@ class SkillsLoader:
Returns: Returns:
Metadata dict or None. Metadata dict or None.
""" """
return parse_skill_metadata(self.load_skill(name) or "") snapshot = self._snapshot.get()
if snapshot is not None and name in snapshot.metadata:
return snapshot.metadata[name]
metadata = parse_skill_metadata(self.load_skill(name) or "")
if snapshot is not None:
snapshot.metadata[name] = metadata
return metadata
+89
View File
@@ -7,6 +7,8 @@ from pathlib import Path
import pytest import pytest
from nanobot.agent import skills as agent_skills
from nanobot.agent.context import ContextBuilder
from nanobot.agent.skills import SkillsLoader from nanobot.agent.skills import SkillsLoader
from nanobot.agent.tools.filesystem import ListDirTool, WriteFileTool from nanobot.agent.tools.filesystem import ListDirTool, WriteFileTool
from nanobot.agent.tools.search import GrepTool from nanobot.agent.tools.search import GrepTool
@@ -465,6 +467,93 @@ def test_multiple_explicit_skills_share_one_ordered_runtime_context(tmp_path: Pa
assert "### Skill: always" not in context.content assert "### Skill: always" not in context.content
def test_plain_message_skips_explicit_skill_discovery(tmp_path: Path, monkeypatch) -> None:
loader = SkillsLoader(tmp_path)
def unexpected_discovery():
pytest.fail("ordinary chat must not scan skills for explicit references")
monkeypatch.setattr(loader, "_discover_skills", unexpected_discovery)
assert loader.build_explicit_skill_runtime_context("Explain this project") is None
@pytest.mark.parametrize("explicit", [False, True])
def test_prompt_reads_skills_once_and_refreshes_on_next_build(
tmp_path: Path, monkeypatch, explicit: bool,
) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir()
builtin = tmp_path / "builtin"
builtin.mkdir()
skills = workspace / "skills"
alpha = _write_skill(skills, "alpha", metadata_json={"always": True}, body="First instructions")
beta = _write_skill(skills, "beta", metadata_json={"requires": {"bins": ["prompt-test-cli"]}})
builder = ContextBuilder(workspace)
builder.skills = SkillsLoader(workspace, builtin_skills_dir=builtin)
documents = {alpha, beta}
reads: list[Path] = []
parses: list[str] = []
original_read = Path.read_text
original_parse = agent_skills.parse_skill_metadata
original_discover = builder.skills._discover_skills
discoveries = 0
command_available = False
checks: list[str] = []
def discover():
nonlocal discoveries
discoveries += 1
return original_discover()
def read(path, *args, **kwargs):
if path in documents:
reads.append(path)
return original_read(path, *args, **kwargs)
def parse(content):
parses.append(content)
return original_parse(content)
def which(command):
checks.append(command)
return "installed-command" if command_available else None
def build_prompt():
if explicit:
messages = builder.build_messages(history=[], current_message="Use $alpha and $beta")
return "\n".join(message["content"] for message in messages)
return builder.build_system_prompt()
monkeypatch.setattr(builder.skills, "_discover_skills", discover)
monkeypatch.setattr(Path, "read_text", read)
monkeypatch.setattr(agent_skills, "parse_skill_metadata", parse)
monkeypatch.setattr("nanobot.agent.skills.shutil.which", which)
first = build_prompt()
assert "First instructions" in first
assert "unavailable: CLI: prompt-test-cli" in first
assert discoveries == 1
assert all(reads.count(path) == 1 for path in documents)
assert len(parses) == len(documents)
assert checks == ["prompt-test-cli"]
alpha.write_text(original_read(alpha).replace("First instructions", "Updated instructions"), encoding="utf-8")
beta.write_text(original_read(beta).replace("---\n", "---\ndescription: Updated description\n", 1), encoding="utf-8")
command_available = True
documents.add(_write_skill(skills, "gamma", body="New skill"))
reads.clear()
parses.clear()
checks.clear()
second = build_prompt()
assert "Updated instructions" in second and "First instructions" not in second
assert "Updated description" in second
assert "unavailable: CLI: prompt-test-cli" not in second
assert "**gamma**" in second
assert discoveries == 2
assert all(reads.count(path) == 1 for path in documents)
assert len(parses) == len(documents)
assert checks == ["prompt-test-cli"]
# -- multiline description tests (YAML folded > and literal |) ----------------- # -- multiline description tests (YAML folded > and literal |) -----------------