OUTPUT #1041 | 4883 karakter | 135 satır

========== YENİ KOMUT | 23.09.2026 13:06:58 ==========

"""Hermes Jev plugin: lets TypeSafe Jev take the cheap decisions off the agent's plate.

Uses only public plugin seams, so it survives `hermes update`:

* ``pre_llm_call``       once per fresh user turn: remembers the turn, and (if on) suggests a skill
* ``llm_request``        middleware: swaps the model for that turn, within the connected provider
* ``transform_llm_output`` optionally shows the one-line routing notice
* tools + ``/jev``        memory filter, compaction selection, action chooser, status and switches

Everything fails open. If Jev is slow, down, unsure, or the turn looks private,
Hermes behaves exactly as it did before this plugin existed.
"""
from __future__ import annotations

import json
import os
import threading
import time
from pathlib import Path
from typing import Any, Dict, List, Optional

from .jevkit import catalog, choose, compact, keystore, ladder, rerank, route, search, skillpick, supervise, turn

_LOCK = threading.Lock()
_TURNS: Dict[str, Dict[str, Any]] = {}      # session_id -> the current turn's text and decision
_MAX_SESSIONS = 256
_CTX: Any = None


# ── settings ─────────────────────────────────────────────────────────────────

def _home() -> Path:
    return Path(os.environ.get("HERMES_HOME") or Path.home() / ".hermes")


def _root() -> Path:
    home = _home()
    return home.parent.parent if home.parent.name == "profiles" else home


def _state_path(shared: bool = False) -> Path:
    return (_root() if shared else _home()) / "jev" / "state.json"


def _read(path: Path) -> Dict[str, Any]:
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
        return data if isinstance(data, dict) else {}
    except (OSError, json.JSONDecodeError):
        return {}


def _state() -> Dict[str, Any]:
    """The shared file is the default for every profile; a profile's own switches override it."""
    return {**_read(_state_path(shared=True)), **_read(_state_path())}


def _setting(name: str, default: str) -> str:
    """A `/jev` switch wins, then plugin settings in config.yaml, then the default."""
    value = _state().get(name)
    if value is None and _CTX is not None:
        try:
            value = _CTX.get_config(name, None)
        except Exception:  # noqa: BLE001
            value = None
    return str(value if value is not None else default).lower()


def _profile() -> str:
    home = _home()
    return home.name if home.parent.name == "profiles" else "default"


def _log(entry: Dict[str, Any]) -> None:
    """Decisions only. Never prompt text, never model output."""
    try:
        path = _home() / "logs" / "jev-decisions.jsonl"
        path.parent.mkdir(parents=True, exist_ok=True)
        entry = {"ts": round(time.time(), 3), "profile": _profile(), **entry}
        fd = os.open(str(path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
        with os.fdopen(fd, "a", encoding="utf-8") as handle:
            handle.write(json.dumps(entry, separators=(",", ":")) + "\n")
    except OSError:
        pass


def _hermes_config() -> Dict[str, Any]:
    """This profile's config.yaml as Hermes parsed it. Empty outside Hermes or when it cannot be read."""
    try:
        from hermes_cli.config import load_config_readonly  # type: ignore

        config = load_config_readonly()
        return config if isinstance(config, dict) else {}
    except Exception:  # noqa: BLE001
        return {}


def _default_model() -> Optional[str]:
    try:
        model = _hermes_config().get("model") or {}
        return model.get("default") if isinstance(model, dict) else str(model)
    except Exception:  # noqa: BLE001
        return None


def _disabled_skills() -> Any:
    try:
        from agent.skill_utils import get_disabled_skill_names  # type: ignore

        return set(get_disabled_skill_names())
    except Exception:  # noqa: BLE001
        return set()


def _hermes_skill_roots() -> List[Path]:
    """Hermes's own answer for the session in flight, or [] when it cannot be asked.

    The plugin used to derive the roots from ``HERMES_HOME`` alone. Under a named profile
    that home can still be the default one, so Jev ranked the DEFAULT profile's catalog and
    suggested skills the running profile cannot open at all (three of them in two sessions:
    ``skill_view`` answered "not found" every time). Hermes already knows the answer per
    session, profile and ``skills.external_dirs`` included, so ask it instead of guessing.
    """
    try:
        from agent.skill_utils import get_all_skills_dirs  # type: ignore

        return [Path(root) for root in get_all_skills_dirs()]
    except Exception:  # noqa: BLE001
        return []

root@213-238-170-219:/home/hermes#