from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Dict, List, Optional from src.skills.registry import SkillDefinition, SkillRegistry from src.skills.models import SkillResult class SkillRuntime: """Request-scoped skill selection and bounded runtime switching.""" def __init__(self, registry: SkillRegistry, max_transitions: int = 8): self.registry = registry self.max_transitions = max_transitions self.active_skill: Optional[SkillDefinition] = None self.skill_trace: List[Dict[str, str]] = [] def select(self, skill_id: str, *, role: Optional[str] = None, intent: Optional[str] = None) -> SkillDefinition: definition = self.registry.resolve(skill_id) self._check_context(definition, role=role, intent=intent) self.active_skill = definition self.skill_trace.append({"event": "selected", "skill_id": definition.id, "version": definition.version}) return definition def switch(self, skill_id: str, *, role: Optional[str] = None, intent: Optional[str] = None) -> SkillDefinition: if len(self.skill_trace) >= self.max_transitions: raise RuntimeError("skill transition limit exceeded") previous = self.active_skill.id if self.active_skill else None definition = self.registry.resolve(skill_id) self._check_context(definition, role=role, intent=intent) self.active_skill = definition self.skill_trace.append({"event": "switched", "from": previous or "none", "skill_id": definition.id, "version": definition.version}) return definition def assert_tool_allowed(self, tool_name: str) -> None: if self.active_skill is None: raise RuntimeError("no active skill selected") if tool_name not in self.active_skill.allowed_tools: raise PermissionError(f"tool '{tool_name}' is not allowed for skill '{self.active_skill.id}'") def _check_context(self, definition: SkillDefinition, *, role: Optional[str], intent: Optional[str]) -> None: if role and definition.allowed_roles and role not in definition.allowed_roles: raise PermissionError(f"skill '{definition.id}' is not allowed for role '{role}'") if intent and definition.allowed_intents and intent not in definition.allowed_intents: raise PermissionError(f"skill '{definition.id}' is not allowed for intent '{intent}'")