"""canary_middleware.py: the CanaryVaults client for an agent, in one file.

This file is the whole client: nothing else from CanaryVaults needs to be
installed. It needs Python 3.10 or newer and one package:

    pip install httpx

Put it beside your agent's code and import from it:

    import os
    from canary_middleware import Agent, Shield

    agent = Agent(os.environ["CANARY_API_KEY"], "billing-agent")
    beats = agent.start_heartbeat(interval=60)      # a daemon thread
    agent.log_action("export_invoices", "success")  # one sealed CanaryAudit record
    beats.stop()                                    # the last beat says "stopping"

    shield = Shield(os.environ["CANARY_API_KEY"])
    verdict = shield.inspect(user_message)
    if verdict.blocked:
        reply = verdict.safe_message                # a placeholder, never the attack

The key comes from Settings > API keys. Agent needs the canaryagent:write and
canaryaudit:write scopes and Shield needs canaryshield:write; * covers both.
Both learn the account id from the key. What each call returns, and when it
raises, is written at the top of the Shield and Agent sections below.

The four functions earlier versions of this file had are still here, at the
end, so an agent that already calls them keeps working. They read these from
the environment:

    CANARY_API_KEY=cv_...
    CANARY_AGENT_ID=billing-agent      # how this agent is named in the console

Optional: CANARY_USER_ID (learned from the key when unset) and CANARY_API_URL
(https://api.canaryvaults.com unless you run your own backend).

Nothing in them raises for a CanaryVaults problem, and nothing is reported as
done when it was not: every return value says whether the call really ran.

    before_action(user_message)
        -> {"blocked", "inspected", "reason", "detail", "message", ...verdict}
        inspected=True   CanaryShield scored the message; "blocked" is a verdict.
        inspected=False  nothing looked at it. "blocked" is False because nothing
                         looked, not because it was found clean. "reason" says why:
                         not_configured, plan_limit, auth, rejected, server_error,
                         rate_limited, timeout, connection_error, redirect, bad_response.
        "message" is the text to carry forward: the sanitized message on a pass,
        a placeholder on a block, your original when nothing looked. It is never
        the attack.

    after_action(agent_id, action_type, trigger, detail, outcome)
    heartbeat(agent_id, status="running", actions_last_60s=None, memory_tokens=None)
        -> {"recorded", "reason", "detail", ...}
        Telemetry. recorded=False means the row never landed. A heartbeat
        carries only the numbers you pass; nothing is measured for you.

    start_heartbeat(agent_id, interval_seconds=60)
        -> a handle with .stop(), or None when nothing is configured.
        Heartbeats on a daemon thread. Call .stop() when the agent shuts down:
        the last heartbeat then says "stopping" and the silence alert that
        would follow a crash is not sent for a stop.

An empty agent_id falls back to CANARY_AGENT_ID. Heartbeats go to
https://api.canaryvaults.com/canaryagent/heartbeat, action records to
/canaryaudit/log and inspections to /canaryshield/inspect, with the key in
the X-API-Key header and never anywhere else.

Version 0.2.0, generated from packages/sdk-python by
scripts/build-single-file-client.py. Do not edit this file by hand: change
the package and run the script again.
"""

from __future__ import annotations

import atexit
import json
import logging
import os
import threading
import time
from dataclasses import asdict, dataclass, field
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from typing import Any, Callable, Mapping, Optional

import httpx

__all__ = [
    "__version__",
    "DEFAULT_BASE_URL",
    "RetryConfig",
    "Shield",
    "Verdict",
    "Agent",
    "AuditResult",
    "HeartbeatHandle",
    "HeartbeatResult",
    "SkillVerdict",
    "CanaryVaultsError",
    "APIError",
    "AuthError",
    "PlanLimitReached",
    "ValidationError",
    "RateLimitError",
    "ServerError",
    "NetworkError",
    "RequestTimeout",
    "RedirectRefused",
    "ShieldUnavailable",
    "before_action",
    "after_action",
    "heartbeat",
    "start_heartbeat",
]


# ===========================================================================
# _retry.py
# ===========================================================================

#: Status codes retried by default (plus 429, which is handled separately).
DEFAULT_RETRY_STATUSES: frozenset[int] = frozenset({500, 502, 503, 504})


@dataclass(frozen=True)
class RetryConfig:
    """Configuration for the retry loop.

    ``max_retries`` is the number of retries *after* the initial attempt,
    so ``max_retries=3`` means up to four requests in total.
    """

    max_retries: int = 3
    backoff_factor: float = 0.5
    max_backoff: float = 30.0
    retry_statuses: frozenset[int] = field(default_factory=lambda: DEFAULT_RETRY_STATUSES)
    retry_on_rate_limit: bool = True


def compute_backoff(config: RetryConfig, attempt: int) -> float:
    """Exponential backoff for the given zero-based attempt number."""
    delay = config.backoff_factor * (2.0**attempt)
    return min(delay, config.max_backoff)


def parse_retry_after(value: str | None) -> float | None:
    """Parse a ``Retry-After`` header (delta-seconds or HTTP-date)."""
    if not value:
        return None
    text = value.strip()
    if not text:
        return None
    try:
        seconds = float(text)
    except ValueError:
        try:
            when = parsedate_to_datetime(text)
        except (TypeError, ValueError):
            return None
        if when is None:
            return None
        if when.tzinfo is None:
            when = when.replace(tzinfo=timezone.utc)
        seconds = (when - datetime.now(timezone.utc)).total_seconds()
    return max(0.0, seconds)


def should_retry_status(config: RetryConfig, status_code: int) -> bool:
    """Whether a response status is retryable under this policy."""
    if status_code == 429:
        return config.retry_on_rate_limit
    if status_code in config.retry_statuses:
        return True
    return 500 <= status_code <= 599


# ===========================================================================
# _version.py
# ===========================================================================
#
# Package version (single source of truth for the User-Agent header).

__version__ = "0.2.0"

USER_AGENT = f"canaryvaults-python/{__version__}"


# ===========================================================================
# client.py, DEFAULT_BASE_URL only: the rest of it is not in this file
# ===========================================================================

DEFAULT_BASE_URL = "https://api.canaryvaults.com"


# ===========================================================================
# exceptions.py
# ===========================================================================
#
# Typed exceptions raised by the CanaryVaults SDK.
#
# Mapping from HTTP status codes:
#
# * 401 / 403       -> :class:`AuthError`
# * 402             -> :class:`PlanLimitReached` (carries the plan, the metric and the limit)
# * 400 / 404 / 422 -> :class:`ValidationError`
# * 429             -> :class:`RateLimitError` (carries ``retry_after``)
# * 5xx             -> :class:`ServerError`
# * transport-level -> :class:`NetworkError` (:class:`RequestTimeout` when the deadline passed)
# * a 3xx answer    -> :class:`RedirectRefused` (the product clients never follow one)
# * anything else   -> :class:`APIError`
#
# :class:`ShieldUnavailable` is raised by :class:`Shield` when
# no verdict could be had and the caller did not choose fail-open.

class CanaryVaultsError(Exception):
    """Base class for every error raised by this SDK."""

    def __init__(self, message: str) -> None:
        super().__init__(message)
        self.message = message


class APIError(CanaryVaultsError):
    """An HTTP error response returned by the CanaryVaults API."""

    def __init__(
        self,
        message: str,
        *,
        status_code: int,
        body: Any = None,
        errors: list[dict[str, Any]] | None = None,
    ) -> None:
        super().__init__(message)
        self.status_code = status_code
        self.body = body
        #: Field-level errors from 422 responses ({"detail": ..., "errors": [...]}).
        self.errors = errors or []

    def __str__(self) -> str:  # pragma: no cover - cosmetic
        return f"[HTTP {self.status_code}] {self.message}"


class AuthError(APIError):
    """Authentication or authorization failed (HTTP 401 / 403)."""


class ValidationError(APIError):
    """The request was rejected as invalid (HTTP 400 / 404 / 422)."""


class RateLimitError(APIError):
    """Rate limit exceeded (HTTP 429)."""

    def __init__(
        self,
        message: str,
        *,
        status_code: int = 429,
        body: Any = None,
        errors: list[dict[str, Any]] | None = None,
        retry_after: float | None = None,
    ) -> None:
        super().__init__(message, status_code=status_code, body=body, errors=errors)
        #: Seconds the server asked us to wait (parsed from ``Retry-After``).
        self.retry_after = retry_after


class ServerError(APIError):
    """The API returned a 5xx response after exhausting retries."""


class PlanLimitReached(APIError):
    """The plan's allowance for this call is used up (HTTP 402).

    The API answers a 402 with a ``detail`` object rather than a string. Its
    fields are carried here so a caller can say which metric ran out and when
    it resets, instead of parsing the message. ``message`` is the plan's own
    sentence, which is what the API put in ``detail.message``.
    """

    def __init__(
        self,
        message: str,
        *,
        status_code: int = 402,
        body: Any = None,
        errors: list[dict[str, Any]] | None = None,
    ) -> None:
        super().__init__(message, status_code=status_code, body=body, errors=errors)
        detail = body.get("detail") if isinstance(body, dict) else None
        detail = detail if isinstance(detail, dict) else {}
        self.metric = _as_text(detail.get("metric"))
        self.plan = _as_text(detail.get("plan"))
        self.plan_display_name = _as_text(detail.get("plan_display_name"))
        self.limit = _as_int(detail.get("limit"))
        self.used = _as_int(detail.get("used"))
        self.resets_at = _as_text(detail.get("resets_at")) or None
        self.upgrade_url = _as_text(detail.get("upgrade_url")) or None


class NetworkError(CanaryVaultsError):
    """A transport-level failure (DNS, connection, timeout, ...)."""

    def __init__(self, message: str, *, cause: BaseException | None = None) -> None:
        super().__init__(message)
        self.cause = cause


class RequestTimeout(NetworkError):
    """The call did not complete within the client's timeout.

    A subclass of :class:`NetworkError`, so an ``except NetworkError`` still
    catches it. It exists because the product clients report a timeout under
    its own name: a service that answers slowly and one that cannot be reached
    are different problems to an operator reading the log.
    """

    def __init__(self, message: str, *, timeout: float, cause: BaseException | None = None) -> None:
        super().__init__(message, cause=cause)
        self.timeout = timeout


class RedirectRefused(CanaryVaultsError):
    """The API answered with a redirect, which the product clients refuse to follow.

    The API key travels in a custom header, and every HTTP client tested
    (requests, httpx, Node fetch) keeps custom headers across a cross-host
    redirect even though it drops ``Authorization``. Following one would hand
    the key to whatever host the ``Location`` line names, so the client stops
    here and says so.
    """

    def __init__(self, message: str, *, status_code: int, location: str) -> None:
        super().__init__(message)
        self.status_code = status_code
        self.location = location


class ShieldUnavailable(CanaryVaultsError):
    """CanaryShield gave no verdict and the caller did not choose fail-open.

    Raised for a 5xx, a 429, a timeout, a connection failure, a refused
    redirect or a 2xx whose body is not a verdict. ``reason`` is the short
    code the fail-open verdict would have carried in ``Verdict.reason``.
    """

    def __init__(self, message: str, *, reason: str, cause: BaseException | None = None) -> None:
        super().__init__(message)
        self.reason = reason
        self.cause = cause


def _as_text(value: Any) -> str:
    if value is None:
        return ""
    return str(value).strip()


def _as_int(value: Any) -> int | None:
    try:
        return int(value)
    except (TypeError, ValueError):
        return None


def _extract_detail(body: Any, fallback: str) -> tuple[str, list[dict[str, Any]]]:
    if isinstance(body, dict):
        detail = body.get("detail") or body.get("error") or body.get("message")
        raw_errors = body.get("errors")
        errors = raw_errors if isinstance(raw_errors, list) else []
        if isinstance(detail, str) and detail.strip():
            return detail, errors
        if isinstance(detail, dict):
            # A plan-limit 402 and a burst 429 put an object in ``detail``
            # whose ``message`` is the sentence meant for a person.
            nested = detail.get("message") or detail.get("error")
            if isinstance(nested, str) and nested.strip():
                return nested, errors
        return fallback, errors
    return fallback, []


def error_for_status(
    status_code: int,
    body: Any = None,
    *,
    retry_after: float | None = None,
) -> APIError:
    """Build the appropriate :class:`APIError` subclass for an HTTP status."""
    message, errors = _extract_detail(body, f"HTTP {status_code} error")
    if status_code in (401, 403):
        return AuthError(message, status_code=status_code, body=body, errors=errors)
    if status_code == 402:
        return PlanLimitReached(message, status_code=status_code, body=body, errors=errors)
    if status_code == 429:
        return RateLimitError(
            message,
            status_code=status_code,
            body=body,
            errors=errors,
            retry_after=retry_after,
        )
    if status_code in (400, 404, 422):
        return ValidationError(message, status_code=status_code, body=body, errors=errors)
    if status_code >= 500:
        return ServerError(message, status_code=status_code, body=body, errors=errors)
    return APIError(message, status_code=status_code, body=body, errors=errors)


# ===========================================================================
# _http.py
# ===========================================================================
#
# The one HTTP layer under the product clients (``Shield`` and ``Agent``).
#
# It is deliberately small, because these clients run inside a customer's
# agent loop and the rules are stricter there:
#
# * every call has a deadline (10 seconds by default), and there is no way to
#   switch it off: a CanaryVaults problem must never stall the agent;
# * the API key goes in ``X-API-Key`` and only ever to the configured host.
#   Redirects are not followed, because HTTP clients keep custom headers across
#   a cross-host redirect, and a request that would leave the host is refused
#   before it is sent;
# * the only thing retried is a failure to connect. A request that reached the
#   server is never sent twice: an inspection spends quota and an audit record
#   is a row, so a retry on a 5xx or a timeout could charge or write twice.
#   A 4xx is never retried either;
# * the deadline is the call's, not each attempt's. A retry is sent with what
#   is left of it, and a retry that could not start in time is not made, so a
#   slow name lookup on each attempt cannot stretch a call past its timeout.

#: Seconds a product call may take before it is given up on.
DEFAULT_PRODUCT_TIMEOUT = 10.0

_warned: set[str] = set()
_warned_lock = threading.Lock()


def warn_once(logger: Any, key: str, message: str, *args: Any) -> None:
    """Log ``message`` at WARNING the first time ``key`` is seen in this process, then at DEBUG.

    Telemetry that cannot land (a used-up plan, a host that is down) would
    otherwise write the same warning on every heartbeat for as long as the
    condition lasts, and a log that repeats itself every minute gets muted.
    One warning per reason says what is wrong; the rest is there at DEBUG for
    anyone looking closely.
    """
    with _warned_lock:
        first = key not in _warned
        _warned.add(key)
    (logger.warning if first else logger.debug)(message, *args)


def _reset_warned() -> None:
    """For tests: forget which warnings have been given."""
    with _warned_lock:
        _warned.clear()

# Two more attempts after a refused connection, a quarter and a half second
# apart: enough to ride out a connection reset, short enough that a host that
# is down costs the agent well under a second on top of the connect timeout.
_DEFAULT_RETRY = RetryConfig(max_retries=2, backoff_factor=0.25)

# The least an attempt is given, so a deadline already spent by the clock's
# own rounding still makes one real request rather than a zero timeout.
_MIN_ATTEMPT_SECONDS = 0.001

_LOCAL_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})


def json_object(response: httpx.Response) -> dict[str, Any] | None:
    """The response body when it parses as a JSON object, otherwise ``None``."""
    try:
        parsed = response.json()
    except Exception:
        return None
    return parsed if isinstance(parsed, dict) else None


class ProductHttp:
    """Sends the product clients' requests. Not part of the public API."""

    def __init__(
        self,
        *,
        api_key: str,
        base_url: str = DEFAULT_BASE_URL,
        timeout: float = DEFAULT_PRODUCT_TIMEOUT,
        retry: RetryConfig | None = None,
        transport: httpx.BaseTransport | None = None,
    ) -> None:
        key = api_key.strip() if isinstance(api_key, str) else ""
        if not key:
            raise ValueError("api_key is required: make one at https://www.canaryvaults.com/settings#api-keys")
        # None would tell httpx to wait forever, and a zero or negative value
        # is a mistake: both are refused rather than silently repaired.
        if not isinstance(timeout, (int, float)) or isinstance(timeout, bool) or not timeout > 0:
            raise ValueError("timeout must be a positive number of seconds")

        cleaned = base_url.strip().rstrip("/") if isinstance(base_url, str) else ""
        try:
            parsed = httpx.URL(cleaned) if cleaned else None
        except Exception:
            parsed = None
        if parsed is None or not parsed.host or parsed.scheme not in ("https", "http"):
            raise ValueError("base_url must be an http(s) URL naming a host")
        if parsed.scheme == "http" and parsed.host not in _LOCAL_HOSTS:
            # The key is a bearer secret in a header; plain http is for a
            # development backend on this machine only.
            raise ValueError("base_url must use https (plain http is allowed for localhost only)")

        self.api_key = key
        self.base_url = cleaned
        self.timeout = float(timeout)
        self.retry = retry or _DEFAULT_RETRY
        self._origin = (parsed.scheme, parsed.host.lower(), parsed.port)
        self._http = httpx.Client(
            base_url=self.base_url,
            timeout=httpx.Timeout(self.timeout),
            transport=transport,
            headers={"User-Agent": USER_AGENT, "Accept": "application/json", "X-API-Key": key},
            # Pinned, not inherited from httpx's default: see the module docstring.
            follow_redirects=False,
        )
        self._user_id: str | None = None
        self._user_id_lock = threading.Lock()

    # -- lifecycle ----------------------------------------------------------

    def close(self) -> None:
        self._http.close()

    @property
    def host(self) -> str:
        return self._origin[1]

    # -- requests -----------------------------------------------------------

    def request(self, method: str, path: str, *, json: Any = None) -> httpx.Response:
        """Send one request and return the response, whatever its status.

        Raises :class:`NetworkError` (or :class:`RequestTimeout`) when no
        response was had, and :class:`RedirectRefused` for a 3xx. Status codes
        of 400 and above are returned, not raised: each client maps them to
        its own contract.
        """
        url = self._http.build_request(method, path).url
        if (url.scheme, (url.host or "").lower(), url.port) != self._origin:
            # Only the configured host ever sees the key. The paths are the
            # clients' own, so this can only trip on a programming error, and
            # it trips before anything is sent.
            raise CanaryVaultsError(
                f"Refusing to send the API key to {url.host}: this client talks to {self.host} only."
            )

        # One deadline for the whole call: each attempt gets what is left of it.
        deadline = time.monotonic() + self.timeout
        attempt = 0
        while True:
            remaining = max(deadline - time.monotonic(), _MIN_ATTEMPT_SECONDS)
            try:
                # Built afresh for each attempt so no body stream is reused.
                response = self._http.send(self._http.build_request(method, path, json=json, timeout=remaining))
            except httpx.ConnectError as exc:
                pause = compute_backoff(self.retry, attempt)
                if attempt >= self.retry.max_retries or time.monotonic() + pause >= deadline:
                    raise NetworkError(f"Could not connect to {self.host}: {exc}", cause=exc) from exc
                time.sleep(pause)
                attempt += 1
                continue
            except httpx.TimeoutException as exc:
                raise RequestTimeout(
                    f"{method} {path} on {self.host} did not finish within {self.timeout:g}s",
                    timeout=self.timeout,
                    cause=exc,
                ) from exc
            except httpx.HTTPError as exc:
                raise NetworkError(f"{method} {path} on {self.host} failed: {exc}", cause=exc) from exc

            if 300 <= response.status_code < 400:
                location = response.headers.get("location", "")
                raise RedirectRefused(
                    f"{self.host} answered {method} {path} with a redirect to {location or 'an unnamed location'}; "
                    "the API key is not sent anywhere else.",
                    status_code=response.status_code,
                    location=location,
                )
            return response

    def whoami(self) -> str:
        """The account the API key belongs to, asked once and then remembered.

        ``GET /api/auth/whoami`` answers ``{"userId": ...}`` for a key the
        middleware has checked. Every product route takes that id in its body
        or path, so a client that was not told it learns it here. Errors are
        the usual typed ones: :class:`AuthError` for a key the API refuses,
        :class:`ServerError` or :class:`NetworkError` when it could not be
        asked.
        """
        with self._user_id_lock:
            if self._user_id:
                return self._user_id
            response = self.request("GET", "/api/auth/whoami")
            if response.status_code >= 400:
                raise error_for_status(response.status_code, json_object(response) or response.text)
            body = json_object(response) or {}
            user_id = str(body.get("userId") or "").strip()
            if not user_id:
                raise ServerError(
                    "whoami answered without a userId", status_code=response.status_code, body=body
                )
            self._user_id = user_id
            return user_id


# ===========================================================================
# shield.py
# ===========================================================================
#
# CanaryShield from your own code: score a message before your agent acts on it.
#
# Quick start::
#
#     from canary_middleware import Shield
#
#     shield = Shield(api_key="cv_...")
#     verdict = shield.inspect(user_message)
#     if verdict.blocked:
#         return verdict.safe_message      # a placeholder, never the attack
#     messages.append({"role": "user", "content": verdict.safe_message})
#
# ``inspect`` calls ``POST /canaryshield/inspect`` with the key in
# ``X-API-Key``. The account id the route needs is learned from the key
# (``GET /api/auth/whoami``) the first time, or given as ``user_id``.
#
# What a verdict can be, and what the caller has to decide:
#
# * ``blocked`` is CanaryShield's verdict. ``safe_message`` is the text to carry
#   forward: on a pass it is the message as the server handed it back (layer 3
#   may have excised a span; for clean text it is the original), and on a block
#   it is a short placeholder naming the attack class. It is never the attack.
# * ``inspected`` says whether a verdict was had at all. It is ``False`` only
#   when the service could not answer (a 5xx, a 429, a timeout, a connection
#   failure, a refused redirect, a body that is not a verdict) and the client
#   was built with ``fail_open=True``. Then ``blocked`` is ``False`` because
#   nothing looked, not because the message was found clean, ``reason`` says
#   what happened and ``safe_message`` is the original. With the default
#   ``fail_open=False`` those cases raise :class:`ShieldUnavailable` instead.
# * A used-up plan allowance raises :class:`PlanLimitReached` whichever way
#   the client was built: it is a billing fact, not an outage, and it carries
#   the plan's own message. A refused key raises :class:`AuthError` and a
#   request the API will not take raises :class:`ValidationError`; those mean
#   the call is wrong, so fail-open does not cover them.

logger = logging.getLogger("canaryvaults")

#: What ``safe_message`` holds on a block. Plainly not user text, and it
#: carries nothing of the message, so forwarding it by mistake forwards nothing.
BLOCKED_PLACEHOLDER = "[CanaryShield blocked this message: {attack_type}, confidence {confidence}%]"

#: The API refuses a longer history with a 422 rather than trimming it.
MAX_HISTORY_TURNS = 20

#: The reasons ``Verdict.reason`` and ``ShieldUnavailable.reason`` can carry.
REASON_SERVER_ERROR = "server_error"
REASON_RATE_LIMITED = "rate_limited"
REASON_TIMEOUT = "timeout"
REASON_CONNECTION = "connection_error"
REASON_REDIRECT = "redirect"
REASON_BAD_RESPONSE = "bad_response"


@dataclass(frozen=True)
class Verdict:
    """What CanaryShield said about one message. See the module docstring."""

    blocked: bool
    attack_type: str | None
    confidence: int
    explanation: str
    safe_message: str
    inspected: bool
    #: Which layer decided: ``"rules"`` or ``"semantic"``. ``None`` when not inspected.
    decided_by: str | None = None
    #: Why there was no inspection (``""`` when there was one).
    reason: str = ""


def _clamp_confidence(value: Any) -> int:
    try:
        parsed = int(value)
    except (TypeError, ValueError):
        return 0
    return max(0, min(100, parsed))


def _text(value: Any) -> str:
    return value.strip() if isinstance(value, str) else ""


def _require_message(message: Any) -> str:
    if not isinstance(message, str) or not message.strip():
        raise ValueError("message must be a non-empty string")
    return message


def _normalize_history(history: Any) -> list[str] | None:
    if history is None:
        return None
    if not isinstance(history, (list, tuple)):
        raise ValueError("history must be a list of earlier user turns, oldest first")
    if any(not isinstance(turn, str) for turn in history):
        raise ValueError("history must hold strings only")
    turns = [turn for turn in history if _text(turn)]
    if len(turns) > MAX_HISTORY_TURNS:
        raise ValueError(
            f"history holds {len(turns)} turns; the API takes at most {MAX_HISTORY_TURNS}, "
            "so send the most recent ones"
        )
    return turns or None


class Shield:
    """Client for ``POST /canaryshield/inspect`` and the OpenAI-compatible proxy.

    Args:
        api_key: a CanaryVaults API key with the ``canaryshield:write`` scope
            (or ``*``), from Settings > API keys.
        user_id: the account's id. Optional: learned from the key on the first
            call when not given.
        base_url: the API origin. The key is sent to this host and no other.
        timeout: seconds each call may take, 10 by default. Required to be
            positive: there is no "wait forever".
        fail_open: what to do when no verdict can be had. ``False`` (the
            default) raises :class:`ShieldUnavailable`; ``True`` returns a
            verdict with ``inspected=False`` that passes the original message
            through and says why.
    """

    def __init__(
        self,
        api_key: str,
        *,
        user_id: str | None = None,
        base_url: str = DEFAULT_BASE_URL,
        timeout: float = DEFAULT_PRODUCT_TIMEOUT,
        fail_open: bool = False,
        retry: RetryConfig | None = None,
        transport: httpx.BaseTransport | None = None,
    ) -> None:
        self._http = ProductHttp(
            api_key=api_key, base_url=base_url, timeout=timeout, retry=retry, transport=transport
        )
        self._user_id = _text(user_id) or None
        self.fail_open = bool(fail_open)
        self.timeout = self._http.timeout
        self.base_url = self._http.base_url

    # -- lifecycle ----------------------------------------------------------

    def close(self) -> None:
        self._http.close()

    def __enter__(self) -> "Shield":
        return self

    def __exit__(self, *exc_info: object) -> None:
        self.close()

    # -- identity -----------------------------------------------------------

    def user_id(self) -> str:
        """The account id the inspect route is asked for, from the key if need be."""
        if self._user_id is None:
            self._user_id = self._http.whoami()
        return self._user_id

    # -- the proxy ----------------------------------------------------------

    def proxy_base_url(self, mode: str = "enforce") -> str:
        """The OpenAI-compatible base URL, for an OpenAI SDK client.

        Point the SDK at it and keep your provider key where it was; add the
        CanaryVaults key as a default header::

            from openai import OpenAI

            client = OpenAI(
                api_key="sk-...",                       # your provider key, forwarded unchanged
                base_url=shield.proxy_base_url(),       # or proxy_base_url("flag") to observe only
                default_headers=shield.proxy_headers(),  # X-API-Key: your CanaryVaults key
            )

        The proxy serves ``POST /chat/completions`` and nothing else, inspects
        the user turns of each request before anything is sent, and relays a
        ``stream=True`` completion as the provider produces it. A block is an
        OpenAI-shaped 400 with ``error.code == "canaryshield_blocked"``. Mode
        ``"flag"`` records and alerts on a detection but forwards the request
        anyway, reporting the verdict in ``x-canaryshield-*`` response headers.
        """
        if mode == "enforce":
            return f"{self.base_url}/canaryshield/v1"
        if mode == "flag":
            return f"{self.base_url}/canaryshield/v1/flag"
        raise ValueError('mode must be "enforce" or "flag"')

    def proxy_headers(self) -> dict[str, str]:
        """The header that identifies you to the proxy: ``X-API-Key``."""
        return {"X-API-Key": self._http.api_key}

    # -- inspect ------------------------------------------------------------

    def inspect(
        self,
        message: str,
        *,
        history: list[str] | None = None,
        system_prompt: str | None = None,
    ) -> Verdict:
        """Score one message. See the module docstring for what comes back.

        ``history`` is up to 20 earlier user turns, oldest first, so an attack
        staged across turns is judged against the conversation.
        ``system_prompt`` lets the analyzer score an override attempt against
        the instructions it is trying to override.
        """
        text = _require_message(message)
        turns = _normalize_history(history)
        prompt = _text(system_prompt) or None

        try:
            body: dict[str, Any] = {"user_id": self.user_id(), "user_message": text}
            if prompt:
                body["system_prompt"] = prompt
            if turns:
                body["history"] = turns
            response = self._http.request("POST", "/canaryshield/inspect", json=body)
        except RequestTimeout as exc:
            return self._unavailable(text, REASON_TIMEOUT, str(exc), exc)
        except NetworkError as exc:
            return self._unavailable(text, REASON_CONNECTION, str(exc), exc)
        except RedirectRefused as exc:
            return self._unavailable(text, REASON_REDIRECT, str(exc), exc)
        except ServerError as exc:
            # whoami failed on the server's side: no verdict was had.
            return self._unavailable(text, REASON_SERVER_ERROR, str(exc), exc)
        except RateLimitError as exc:
            # whoami has its own per-address limit; a fleet starting at once can meet it.
            return self._unavailable(text, REASON_RATE_LIMITED, exc.message, exc)

        status = response.status_code
        parsed = json_object(response)
        if status == 429:
            error = error_for_status(status, parsed or response.text)
            return self._unavailable(text, REASON_RATE_LIMITED, error.message, error)
        if status >= 500:
            error = error_for_status(status, parsed or response.text)
            return self._unavailable(text, REASON_SERVER_ERROR, error.message, error)
        if status >= 400:
            # 402 (PlanLimitReached), 401/403 (AuthError), 400/404/422
            # (ValidationError): the call is wrong or the plan is used up.
            raise error_for_status(status, parsed or response.text)
        if parsed is None or "blocked" not in parsed:
            return self._unavailable(
                text,
                REASON_BAD_RESPONSE,
                f"CanaryShield answered HTTP {status} with a body that is not a verdict.",
                None,
            )

        blocked = bool(parsed.get("blocked"))
        attack_type = _text(parsed.get("attack_type")) or None
        confidence = _clamp_confidence(parsed.get("confidence"))
        explanation = _text(parsed.get("explanation"))
        decided_by = _text(parsed.get("decided_by")) or None
        if blocked:
            safe_message = BLOCKED_PLACEHOLDER.format(
                attack_type=attack_type or "UNKNOWN", confidence=confidence
            )
        else:
            sanitized = parsed.get("sanitized_message")
            safe_message = sanitized if isinstance(sanitized, str) and sanitized.strip() else text
        return Verdict(
            blocked=blocked,
            attack_type=attack_type,
            confidence=confidence,
            explanation=explanation,
            safe_message=safe_message,
            inspected=True,
            decided_by=decided_by,
        )

    def _unavailable(
        self, text: str, reason: str, detail: str, cause: BaseException | None
    ) -> Verdict:
        if not self.fail_open:
            raise ShieldUnavailable(
                f"CanaryShield gave no verdict ({reason}): {detail}", reason=reason, cause=cause
            ) from cause
        # Once per reason at WARNING, then DEBUG: an outage would otherwise
        # write this for every message the agent handles. The verdict itself
        # says inspected=False on every one of them.
        warn_once(
            logger,
            f"shield.uninspected.{reason}",
            "CanaryShield gave no verdict (%s); messages pass through uninspected until it answers again: %s",
            reason,
            detail,
        )
        return Verdict(
            blocked=False,
            attack_type=None,
            confidence=0,
            explanation=detail,
            safe_message=text,
            inspected=False,
            decided_by=None,
            reason=reason,
        )


# ===========================================================================
# agent.py
# ===========================================================================
#
# CanaryAgent from your own code: heartbeats, action records and skill scans.
#
# Quick start::
#
#     from canary_middleware import Agent
#
#     agent = Agent(api_key="cv_...", agent_id="billing-agent")
#     beats = agent.start_heartbeat(interval=60)     # a daemon thread; the console lists the agent on the first beat
#     ...
#     agent.log_action("export_invoices", "success", detail="batch 2026-08 to the archive")
#     ...
#     beats.stop()                                   # a last heartbeat says the agent is stopping on purpose
#
# Three kinds of call, with three different contracts:
#
# * **Telemetry** (``heartbeat``, ``log_action``) never raises for anything the
#   service answers or fails to answer. Each returns a result whose ``recorded``
#   says whether the row landed and whose ``reason`` says why not: a used-up
#   plan (402), a refused key, a 5xx, a timeout, a host that cannot be reached.
#   Losing telemetry is survivable; a security add-on that crashes the agent it
#   watches is not. The first failure of each kind is logged at WARNING through
#   ``logging.getLogger("canaryvaults")`` and the rest at DEBUG.
# * **A verdict** (``scan_skill``) raises the typed errors, because a scan that
#   did not run must never look like a pass: :class:`PlanLimitReached` on a
#   402, :class:`AuthError`, :class:`ValidationError`, :class:`RateLimitError`,
#   :class:`ServerError`, :class:`NetworkError`.
# * **Wrong arguments** raise :class:`ValueError` from every call: those are
#   bugs in the caller, and hiding them helps nobody.
#
# The account id every route needs is learned from the key (``GET
# /api/auth/whoami``) the first time it is needed, or given as ``user_id``.
# Nothing is ever measured on the caller's behalf: a heartbeat carries
# ``actions_last_60s`` and ``memory_tokens`` only when the caller passes them.

logger = logging.getLogger("canaryvaults")

#: The ``status`` a stopping agent's last heartbeat carries. The silence
#: monitor does not alert on an agent whose last heartbeat said this.
STOPPING_STATUS = "stopping"

#: When no trigger is given for an action, the record says so rather than
#: carrying a made-up one.
NO_TRIGGER = "not recorded"

_MAX_ACTIONS_LAST_60S = 1_000_000
_MAX_MEMORY_TOKENS = 10_000_000


@dataclass(frozen=True)
class HeartbeatResult:
    """Whether a heartbeat landed. ``reason`` and ``detail`` say why not."""

    recorded: bool
    reason: str = ""
    detail: str = ""
    heartbeat_id: str = ""
    pinged_at: str = ""
    status: str = ""


@dataclass(frozen=True)
class AuditResult:
    """Whether an action record was written to CanaryAudit."""

    recorded: bool
    reason: str = ""
    detail: str = ""
    log_id: str = ""
    content_hash: str = ""
    sealed: bool = False
    anchored: bool = False


@dataclass(frozen=True)
class SkillVerdict:
    """What the skill scan found. ``blocked`` is the verdict to branch on."""

    blocked: bool
    safe: bool
    risk_level: str
    issues: tuple[str, ...]
    recommendation: str
    skill_scan_id: str = ""
    scanned_at: str = ""


def _text(value: Any) -> str:
    return value.strip() if isinstance(value, str) else ""


def _require_text(value: Any, name: str) -> str:
    if not isinstance(value, str) or not value.strip():
        raise ValueError(f"{name} must be a non-empty string")
    return value.strip()


def _optional_count(value: Any, name: str, ceiling: int) -> int | None:
    """A measurement the caller took, or ``None`` for one they did not."""
    if value is None:
        return None
    if isinstance(value, bool) or not isinstance(value, int):
        raise ValueError(f"{name} must be an int the caller measured, or None")
    if value < 0 or value > ceiling:
        raise ValueError(f"{name} must be between 0 and {ceiling}")
    return value


def _failure(exc: BaseException) -> tuple[str, str]:
    """The ``(reason, detail)`` a telemetry result carries for an error."""
    if isinstance(exc, PlanLimitReached):
        return "plan_limit", exc.message
    if isinstance(exc, AuthError):
        return "auth", exc.message
    if isinstance(exc, RateLimitError):
        return "rate_limited", exc.message
    if isinstance(exc, ServerError):
        return "server_error", exc.message
    if isinstance(exc, APIError):
        return "rejected", exc.message
    if isinstance(exc, RequestTimeout):
        return "timeout", str(exc)
    if isinstance(exc, NetworkError):
        return "connection_error", str(exc)
    if isinstance(exc, RedirectRefused):
        return "redirect", str(exc)
    return "error", str(exc)


class Agent:
    """Client for the CanaryAgent and CanaryAudit routes an agent calls.

    Args:
        api_key: a CanaryVaults API key with the ``canaryagent:write`` and
            ``canaryaudit:write`` scopes (or ``*``), from Settings > API keys.
        agent_id: how this agent is named in the console, up to 255 characters.
        user_id: the account's id. Optional: learned from the key when not given.
        base_url: the API origin. The key is sent to this host and no other.
        timeout: seconds each call may take, 10 by default. Must be positive.
    """

    def __init__(
        self,
        api_key: str,
        agent_id: str,
        *,
        user_id: str | None = None,
        base_url: str = DEFAULT_BASE_URL,
        timeout: float = DEFAULT_PRODUCT_TIMEOUT,
        retry: RetryConfig | None = None,
        transport: httpx.BaseTransport | None = None,
    ) -> None:
        self.agent_id = _require_text(agent_id, "agent_id")
        if len(self.agent_id) > 255:
            raise ValueError("agent_id must be at most 255 characters")
        self._http = ProductHttp(
            api_key=api_key, base_url=base_url, timeout=timeout, retry=retry, transport=transport
        )
        self._user_id = _text(user_id) or None
        self.timeout = self._http.timeout
        self.base_url = self._http.base_url

    # -- lifecycle ----------------------------------------------------------

    def close(self) -> None:
        self._http.close()

    def __enter__(self) -> "Agent":
        return self

    def __exit__(self, *exc_info: object) -> None:
        self.close()

    # -- identity -----------------------------------------------------------

    def user_id(self) -> str:
        """The account id the routes are asked for, from the key if need be."""
        if self._user_id is None:
            self._user_id = self._http.whoami()
        return self._user_id

    # -- heartbeats ---------------------------------------------------------

    def heartbeat(
        self,
        *,
        status: str = "running",
        actions_last_60s: int | None = None,
        memory_tokens: int | None = None,
    ) -> HeartbeatResult:
        """Say the agent is alive. Never raises for a service problem.

        ``actions_last_60s`` and ``memory_tokens`` are sent only when given:
        the client measures nothing, so a number that was not passed is not
        in the request, and the console shows nothing for it rather than a
        zero that looks like a reading.
        """
        status_text = _require_text(status, "status")
        if len(status_text) > 80:
            raise ValueError("status must be at most 80 characters")
        actions = _optional_count(actions_last_60s, "actions_last_60s", _MAX_ACTIONS_LAST_60S)
        memory = _optional_count(memory_tokens, "memory_tokens", _MAX_MEMORY_TOKENS)

        try:
            body: dict[str, Any] = {
                "user_id": self.user_id(),
                "agent_id": self.agent_id,
                "status": status_text,
            }
            if actions is not None:
                body["actions_last_60s"] = actions
            if memory is not None:
                body["memory_tokens"] = memory
            response = self._http.request("POST", "/canaryagent/heartbeat", json=body)
            parsed = json_object(response)
            if response.status_code >= 400:
                raise error_for_status(response.status_code, parsed or response.text)
        except CanaryVaultsError as exc:
            reason, detail = _failure(exc)
            warn_once(logger, f"heartbeat.{reason}", "CanaryAgent heartbeat not recorded (%s): %s", reason, detail)
            return HeartbeatResult(recorded=False, reason=reason, detail=detail, status=status_text)

        parsed = parsed or {}
        return HeartbeatResult(
            recorded=True,
            heartbeat_id=_text(parsed.get("heartbeat_id")),
            pinged_at=_text(parsed.get("pinged_at")),
            status=status_text,
        )

    def start_heartbeat(
        self,
        interval: float = 60.0,
        *,
        metrics: Callable[[], Mapping[str, int | None]] | None = None,
    ) -> "HeartbeatHandle":
        """Send a heartbeat now and then every ``interval`` seconds, on a daemon thread.

        The console counts an agent as online while a heartbeat has arrived
        in the last two minutes and alerts after five quiet minutes, so keep
        the interval well under 120 seconds. ``metrics``, if given, is called
        before each beat and may return ``actions_last_60s`` and
        ``memory_tokens`` the caller measured; a key it leaves out is not
        sent. Nothing the thread does can raise into the caller: a failing
        ``metrics`` or a failed beat is logged and the loop goes on.

        Call ``stop()`` on the handle when the agent shuts down. It ends the
        loop and sends one last heartbeat with ``status: "stopping"``, which
        tells the silence monitor the quiet that follows is deliberate.
        Without it, the monitor alerts five minutes after the last beat, as
        it should for a crash. The handle is also registered with ``atexit``,
        so an interpreter that exits normally sends the stopping beat even if
        ``stop()`` was never called; a process that is killed does not.
        """
        if isinstance(interval, bool) or not isinstance(interval, (int, float)) or not interval > 0:
            raise ValueError("interval must be a positive number of seconds")
        if metrics is not None and not callable(metrics):
            raise ValueError("metrics must be a callable returning a mapping, or None")
        return HeartbeatHandle(self, float(interval), metrics)

    # -- actions ------------------------------------------------------------

    def log_action(
        self,
        action: str,
        outcome: str,
        *,
        trigger: str = "",
        detail: str = "",
        metadata: Mapping[str, Any] | None = None,
    ) -> AuditResult:
        """Seal one action into CanaryAudit. Never raises for a service problem.

        ``action`` is the record's ``action_type`` and ``outcome`` what came
        of it. ``trigger`` is what set the action off and ``detail`` what was
        done; when ``detail`` is left out the action's name stands in for it,
        and when ``trigger`` is left out the record says "not recorded".
        A used-up plan (402) comes back as ``recorded=False`` with reason
        ``"plan_limit"``, warned about once and never raised.
        """
        action_type = _require_text(action, "action")
        outcome_text = _require_text(outcome, "outcome")
        trigger_text = _text(trigger) or NO_TRIGGER
        detail_text = _text(detail) or action_type
        if metadata is not None and not isinstance(metadata, Mapping):
            raise ValueError("metadata must be a mapping, or None")
        if metadata:
            try:
                json.dumps(dict(metadata))
            except (TypeError, ValueError) as exc:
                # A caller's bug, found before the request rather than as an
                # encoding error from inside the HTTP client.
                raise ValueError(f"metadata must be JSON-serializable: {exc}") from None

        try:
            body: dict[str, Any] = {
                "user_id": self.user_id(),
                "agent_id": self.agent_id,
                "action_type": action_type,
                "input_trigger": trigger_text,
                "action_detail": detail_text,
                "outcome": outcome_text,
            }
            if metadata:
                body["metadata"] = dict(metadata)
            response = self._http.request("POST", "/canaryaudit/log", json=body)
            parsed = json_object(response)
            if response.status_code >= 400:
                raise error_for_status(response.status_code, parsed or response.text)
        except CanaryVaultsError as exc:
            reason, detail_message = _failure(exc)
            warn_once(
                logger, f"log_action.{reason}", "CanaryAudit record not written (%s): %s", reason, detail_message
            )
            return AuditResult(recorded=False, reason=reason, detail=detail_message)

        parsed = parsed or {}
        return AuditResult(
            recorded=True,
            log_id=_text(parsed.get("log_id")),
            content_hash=_text(parsed.get("content_hash")),
            sealed=bool(parsed.get("sealed")),
            anchored=bool(parsed.get("anchored")),
        )

    # -- skill scans --------------------------------------------------------

    def scan_skill(self, name: str, code: str) -> SkillVerdict:
        """Scan a skill's source before the agent loads it. Raises on any failure.

        A scan spends plan quota, so a used-up allowance raises
        :class:`PlanLimitReached`; a scan engine outage raises
        :class:`ServerError` (503) and the quota is not spent.
        """
        skill_name = _require_text(name, "name")
        skill_code = code if isinstance(code, str) and code.strip() else ""
        if not skill_code:
            raise ValueError("code must be a non-empty string")
        body = {"user_id": self.user_id(), "skill_name": skill_name, "skill_code": skill_code}
        response = self._http.request("POST", "/canaryagent/skill-scan", json=body)
        parsed = json_object(response)
        if response.status_code >= 400:
            raise error_for_status(response.status_code, parsed or response.text)
        if parsed is None or "risk_level" not in parsed:
            raise ServerError(
                "the skill scan answered with a body that is not a verdict",
                status_code=response.status_code,
                body=parsed if parsed is not None else response.text,
            )
        raw_issues = parsed.get("issues")
        issues = tuple(_text(issue) for issue in raw_issues if _text(issue)) if isinstance(raw_issues, list) else ()
        return SkillVerdict(
            blocked=bool(parsed.get("blocked")),
            safe=bool(parsed.get("safe")),
            risk_level=_text(parsed.get("risk_level")).upper() or "UNKNOWN",
            issues=issues,
            recommendation=_text(parsed.get("recommendation")),
            skill_scan_id=_text(parsed.get("skill_scan_id")),
            scanned_at=_text(parsed.get("scanned_at")),
        )


class HeartbeatHandle:
    """The running heartbeat loop. ``stop()`` ends it; see ``Agent.start_heartbeat``."""

    def __init__(
        self,
        agent: Agent,
        interval: float,
        metrics: Callable[[], Mapping[str, int | None]] | None,
    ) -> None:
        self._agent = agent
        self.interval = interval
        self._metrics = metrics
        self._stop_event = threading.Event()
        self._stop_lock = threading.Lock()
        self._stopped = False
        self.last_result: HeartbeatResult | None = None
        self._thread = threading.Thread(target=self._run, name="canaryvaults-heartbeat", daemon=True)
        atexit.register(self.stop)
        self._thread.start()

    @property
    def running(self) -> bool:
        return self._thread.is_alive() and not self._stopped

    def _run(self) -> None:
        while not self._stop_event.is_set():
            self._beat()
            self._stop_event.wait(self.interval)

    def _measure(self) -> tuple[int | None, int | None]:
        """What the caller's gauge says, or nothing when it fails.

        A broken gauge must cost the numbers, never the heartbeat: a loop
        that stopped beating because a reading threw would have the monitor
        call a live agent silent.
        """
        if self._metrics is None:
            return None, None
        try:
            measured = self._metrics()
            if not isinstance(measured, Mapping):
                raise ValueError("metrics must return a mapping")
            return (
                _optional_count(measured.get("actions_last_60s"), "actions_last_60s", _MAX_ACTIONS_LAST_60S),
                _optional_count(measured.get("memory_tokens"), "memory_tokens", _MAX_MEMORY_TOKENS),
            )
        except Exception as exc:
            warn_once(
                logger,
                f"heartbeat.metrics.{type(exc).__name__}",
                "CanaryAgent heartbeat metrics failed (%s: %s); beating without them",
                type(exc).__name__,
                exc,
            )
            return None, None

    def _beat(self) -> None:
        # Nothing here may reach the caller's threads: a heartbeat is
        # telemetry, and the agent must keep running whatever happens to it.
        try:
            actions, memory = self._measure()
            self.last_result = self._agent.heartbeat(actions_last_60s=actions, memory_tokens=memory)
        except Exception as exc:
            self.last_result = HeartbeatResult(recorded=False, reason="error", detail=str(exc))
            warn_once(
                logger,
                f"heartbeat.loop.{type(exc).__name__}",
                "CanaryAgent heartbeat loop skipped a beat (%s: %s); the agent is unaffected",
                type(exc).__name__,
                exc,
            )

    def stop(self, timeout: float | None = None) -> HeartbeatResult | None:
        """End the loop and send a last heartbeat saying the agent is stopping.

        Waits for a beat in flight (at most ``timeout`` seconds, by default
        the client's timeout plus one), then sends ``status: "stopping"``
        from the calling thread. Never raises; returns that last beat's
        result, or ``None`` when the loop had already been stopped.
        """
        with self._stop_lock:
            if self._stopped:
                return None
            self._stopped = True
        self._stop_event.set()
        if threading.current_thread() is not self._thread:
            try:
                self._thread.join(timeout if timeout is not None else self._agent.timeout + 1.0)
            except Exception:
                # A thread that never started cannot be joined; there is
                # nothing to wait for either way.
                pass
        try:
            atexit.unregister(self.stop)
        except Exception:
            pass
        try:
            result = self._agent.heartbeat(status=STOPPING_STATUS)
        except Exception as exc:
            # heartbeat() does not raise for service problems; this catches
            # anything else, because stop() runs in shutdown paths.
            result = HeartbeatResult(recorded=False, reason="error", detail=str(exc), status=STOPPING_STATUS)
        self.last_result = result
        return result

    def __enter__(self) -> "HeartbeatHandle":
        return self

    def __exit__(self, *exc_info: object) -> None:
        self.stop()


# ===========================================================================
# The four functions earlier versions of this file had
# ===========================================================================
#
# The four functions earlier versions of canary_middleware.py had.
#
# They are kept so an agent that already calls them keeps working, and are
# written on the Agent and Shield clients above. What each one returns is at
# the top of this file.

DEFAULT_API_URL = DEFAULT_BASE_URL

_shield: Optional[Shield] = None
_agent: Optional[Agent] = None


def _setting(name: str, default: str = "") -> str:
    return os.getenv(name, default).strip()


def _not_configured(**result: Any) -> dict[str, Any]:
    detail = "Set CANARY_API_KEY, and CANARY_AGENT_ID for heartbeats and action records."
    return {**result, "reason": "not_configured", "detail": detail}


def _shield_client() -> Optional[Shield]:
    global _shield
    api_key = _setting("CANARY_API_KEY")
    if not api_key:
        return None
    if _shield is None:
        _shield = Shield(
            api_key,
            user_id=_setting("CANARY_USER_ID") or None,
            base_url=_setting("CANARY_API_URL", DEFAULT_API_URL),
            fail_open=True,
        )
    return _shield


def _agent_client(agent_id: str) -> Optional[Agent]:
    global _agent
    api_key = _setting("CANARY_API_KEY")
    name = (agent_id or "").strip() or _setting("CANARY_AGENT_ID")
    if not api_key or not name:
        return None
    if _agent is None or _agent.agent_id != name:
        _agent = Agent(
            api_key,
            name,
            user_id=_setting("CANARY_USER_ID") or None,
            base_url=_setting("CANARY_API_URL", DEFAULT_API_URL),
        )
    return _agent


def _failed(exc: Exception) -> tuple[str, str]:
    if isinstance(exc, PlanLimitReached):
        return "plan_limit", exc.message
    if isinstance(exc, AuthError):
        return "auth", exc.message
    return "rejected", str(exc)


def before_action(user_message: str) -> dict[str, Any]:
    """Have CanaryShield inspect user_message before your agent acts on it. Never raises."""
    uninspected = {"blocked": False, "inspected": False, "message": user_message}
    shield = _shield_client()
    if shield is None:
        return _not_configured(**uninspected)
    try:
        verdict = shield.inspect(user_message)
    except (CanaryVaultsError, ValueError) as exc:
        reason, detail = _failed(exc)
        return {**uninspected, "reason": reason, "detail": detail}
    fields = asdict(verdict)
    return {
        **fields,
        "message": verdict.safe_message,
        "detail": "" if verdict.inspected else verdict.explanation,
    }


def after_action(agent_id: str, action_type: str, trigger: str, detail: str, outcome: str) -> dict[str, Any]:
    """Seal one agent action into the CanaryAudit chain. Never raises."""
    agent = _agent_client(agent_id)
    if agent is None:
        return _not_configured(recorded=False)
    try:
        result = agent.log_action(action_type, outcome, trigger=trigger, detail=detail)
    except ValueError as exc:
        return {"recorded": False, "reason": "rejected", "detail": str(exc)}
    return asdict(result)


def heartbeat(
    agent_id: str,
    status: str = "running",
    actions_last_60s: Optional[int] = None,
    memory_tokens: Optional[int] = None,
) -> dict[str, Any]:
    """Report that this agent is alive. Never raises. Sends only the numbers you pass."""
    agent = _agent_client(agent_id)
    if agent is None:
        return _not_configured(recorded=False)
    try:
        result = agent.heartbeat(status=status, actions_last_60s=actions_last_60s, memory_tokens=memory_tokens)
    except ValueError as exc:
        return {"recorded": False, "reason": "rejected", "detail": str(exc)}
    return asdict(result)


def start_heartbeat(agent_id: str, interval_seconds: float = 60.0):
    """Heartbeat on a daemon thread until .stop() is called on the returned handle."""
    agent = _agent_client(agent_id)
    if agent is None:
        return None
    return agent.start_heartbeat(interval=interval_seconds)
