kuri-skill-gate/__init__.py

206 lines
6.9 KiB
Python

"""Block gated tools until their required safety skill has been read."""
from __future__ import annotations
import json
import os
import re
import threading
import time
from collections.abc import Callable
from typing import Any
# ── Tool → required safety skill mapping ────────────────────────────
_TOOL_SKILL_MAP: dict[str, str] = {
"patch": "patch-tool-safety",
"delegate_task": "delegate-task-best-practices",
}
# Keys are regex patterns matched against independent command tokens.
# Do not strip quotes: shell subcommands such as `sh -c 'gh pr view'` execute
# the quoted content and must remain gated.
_COMMAND_PATTERN_GATES: dict[str, str] = {
r"(?<![^\s;|&()<>\"'])gh(?![^\s;|&()<>\"'])": "gh-cli",
}
_PLUGIN_DIR = os.path.realpath(os.path.dirname(os.path.abspath(__file__)))
_SESSION_TTL_SECONDS = 24 * 60 * 60
_MAX_TRACKED_SESSIONS = 1024
class _SessionSkillState:
"""Loaded skills and last activity for one session."""
def __init__(self, skills: set[str], last_seen: float) -> None:
self.skills = skills
self.last_seen = last_seen
_loaded_skills: dict[str, _SessionSkillState] = {}
_lock = threading.Lock()
def _all_gated_skills() -> set[str]:
"""Return the union of all skill names required by this plugin."""
return set(_TOOL_SKILL_MAP.values()) | set(_COMMAND_PATTERN_GATES.values())
def _block_msg(tool_name: str, skill: str) -> str:
return json.dumps(
{
"error": "blocked by kuri-skill-gate",
"message": (
f"使用 {tool_name} 前請先以 skill_view(name='{skill}') 讀取 {skill}。"
"完成閱讀後再執行。可確認操作方式與限制。"
),
},
ensure_ascii=False,
)
def _block_cmd_msg(pattern: str, skill: str) -> str:
return json.dumps(
{
"error": "blocked by kuri-skill-gate",
"message": (
f"此 terminal 指令包含需要先閱讀的操作「{pattern}」。"
f"請先以 skill_view(name='{skill}') 讀取 {skill}。再執行指令。"
),
},
ensure_ascii=False,
)
def _prune_loaded_skills(now: float) -> None:
"""Remove expired state and evict least-recent sessions over the cap.
The caller must hold ``_lock``.
"""
expiry = now - _SESSION_TTL_SECONDS
expired = [sid for sid, state in _loaded_skills.items() if state.last_seen < expiry]
for session_id in expired:
del _loaded_skills[session_id]
overflow = len(_loaded_skills) - _MAX_TRACKED_SESSIONS
if overflow > 0:
oldest = sorted(_loaded_skills, key=lambda sid: _loaded_skills[sid].last_seen)
for session_id in oldest[:overflow]:
del _loaded_skills[session_id]
def _has_loaded_skill(session_id: str, skill: str) -> bool:
now = time.monotonic()
with _lock:
_prune_loaded_skills(now)
state = _loaded_skills.get(session_id)
if state is None:
return False
state.last_seen = now
return skill in state.skills
def _is_successful_skill_view_result(result: Any) -> bool:
"""Return whether the native skill_view result explicitly reports success."""
if isinstance(result, str):
try:
result = json.loads(result)
except json.JSONDecodeError:
return False
return isinstance(result, dict) and result.get("success") is True
def _record_successful_skill_read(session_id: str, args: dict[str, Any], result: Any) -> None:
"""Track only successful main SKILL.md reads for skills this plugin gates."""
name = args.get("name")
if (
not isinstance(name, str)
or name not in _all_gated_skills()
or args.get("file_path") is not None
or not _is_successful_skill_view_result(result)
):
return
now = time.monotonic()
with _lock:
_prune_loaded_skills(now)
state = _loaded_skills.get(session_id)
if state is None:
state = _SessionSkillState(skills=set(), last_seen=now)
_loaded_skills[session_id] = state
state.skills.add(name)
state.last_seen = now
_prune_loaded_skills(now)
def _resolve_tool_requirement(tool_name: str, args: dict[str, Any]) -> str | None:
"""Return the skill required for a non-terminal tool invocation."""
if tool_name == "skill_manage" and args.get("action") == "patch":
return "patch-tool-safety"
return _TOOL_SKILL_MAP.get(tool_name)
def _resolve_terminal_requirement(args: dict[str, Any]) -> tuple[str, str] | None:
"""Return the matched terminal pattern and required skill, if any."""
command = args.get("command")
if not isinstance(command, str):
return None
for pattern, skill in _COMMAND_PATTERN_GATES.items():
if re.search(pattern, command, re.IGNORECASE):
return pattern, skill
return None
def _is_existing_self_target(args: dict[str, Any]) -> bool:
"""Allow only existing targets resolved inside this plugin's real directory."""
target = args.get("path")
if not isinstance(target, str) or not target:
return False
candidate = os.path.abspath(target)
if not os.path.isfile(candidate):
return False
resolved_target = os.path.realpath(candidate)
try:
return os.path.commonpath((_PLUGIN_DIR, resolved_target)) == _PLUGIN_DIR
except ValueError:
return False
def _call_next(next_call: Callable[[dict[str, Any]], Any] | None, args: dict[str, Any]) -> Any:
return next_call(args) if next_call is not None else None
def register(ctx: Any) -> None:
"""Register the tool-execution middleware."""
ctx.register_middleware("tool_execution", _on_tool_execution)
def _on_tool_execution(**kwargs: Any) -> Any:
tool_name = kwargs.get("tool_name", "")
raw_args = kwargs.get("args", {})
args = raw_args if isinstance(raw_args, dict) else {}
raw_session_id = kwargs.get("session_id", "")
session_id = raw_session_id if isinstance(raw_session_id, str) else ""
next_call = kwargs.get("next_call")
if tool_name == "skill_view":
result = _call_next(next_call, args)
_record_successful_skill_read(session_id, args, result)
return result
if tool_name == "patch" and _is_existing_self_target(args):
return _call_next(next_call, args)
required_skill = _resolve_tool_requirement(tool_name, args)
if required_skill is not None and not _has_loaded_skill(session_id, required_skill):
return _block_msg(tool_name, required_skill)
if tool_name == "terminal":
terminal_requirement = _resolve_terminal_requirement(args)
if terminal_requirement is not None:
pattern, terminal_skill = terminal_requirement
if not _has_loaded_skill(session_id, terminal_skill):
return _block_cmd_msg(pattern, terminal_skill)
return _call_next(next_call, args)