# Source SHA-256: 6c6ffe1a1598097cc0167f506794cddaaa11f0792179f6361a70af383572a182
# Templ Agent API 1 client. Compare this file's SHA-256 with agents.python.sha256 in /api/status on the app you downloaded it from.
"""Templ Agent API client for Python: API major version 1, up to 1.1.

Standard library only (Python 3.10 or newer). One file you download from
<app origin>/templ_agent.py and check against agents.python.sha256 in
<app origin>/api/status.

The client signs in an AI agent's own wallet and answers the workspace's
support requests through the Agent API. It never holds a key: you pass a
signer callable that signs one sign-in message and returns the signature.
The client checks every line of the sign-in message before it asks the
signer, so the signer only ever sees Templ's own sign-in text.

EVM wallets sign in with Sign In With Ethereum: the signer takes the
message text and returns an EIP-191 personal_sign signature as hex. Solana
wallets sign in with Sign In With Solana: the signer takes the message bytes
and returns the 64-byte Ed25519 signature.

What the client never does:

- It never signs or sends a transaction, and chat text can't make it.
- It never asks for or returns a key or a recovery phrase.
- It never follows a redirect, so the session cookie goes to Templ only.
- It logs nothing. repr() shows the workspace and the wallet only.

A wallet an app reports for a member stays unproven. `workflow()` returns it
as `access.claimedWallet`; only `wallet` is a wallet the member proved.

Errors raise TemplError with the HTTP status (0 for a network failure) and
the service's reason code. Branch on both, and treat an unknown reason like
an unknown error. Reasons an agent meets: stale (409, read again),
handed-off (409, a person owns the request), ai-drafts-only and ai-off
(409, a person limited the AI on this request), person-only (403),
secret-refused and secret-request-refused (422, nothing was stored; hand
the request to a person), reply-held (422, the workspace holds AI replies
whose figures fail the citation check; TemplError.held names the draft),
support-reply-allowance and support-coverage-ended (403, stop answering
new people).

One request runs at a time. From asyncio, call a method with
`await asyncio.to_thread(agent.reply, ...)`.
"""

from __future__ import annotations

import base64
import http.client
import json
import re
import secrets
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any, Callable, Iterator, Optional

API_MAJOR = 1
API_VERSIONS = ("1.0", "1.1")
SIGN_IN_STATEMENT = "Sign in to your Templ chat."

# The service's handoff reasons (SUPPORT_HANDOFF_REASONS in the TypeScript
# package). A test compares the two lists.
HANDOFF_REASONS = (
    "quote",
    "privacy",
    "account",
    "billing",
    "legal",
    "safety",
    "transaction",
    "bug",
    "person",
    "unsure",
    "other",
    "strategy",
    "access",
    "recovery",
    "decision",
    "internal",
)
TIME_SPENT = ("under-5", "5-15", "15-30", "30-60", "over-60")
CONVERSATION_FILTERS = (
    "open",
    "resolved",
    "all",
    "unassigned",
    "mine",
    "waiting",
    "needs-person",
    "needs-reply",
    "needs-you",
    "ai-handling",
    "waiting-on-member",
)
# Why an agent declines a team's Ask AI question.
AI_DECLINES = ("handoff", "unsure", "no-access", "unavailable", "refused", "other")
FOLLOW_UP_VIEWS = ("open", "overdue", "mine", "group")

Signer = Callable[[Any], Any]
Transport = Callable[
    [str, str, dict, Optional[bytes], float],
    "tuple[int, dict[str, list[str]], bytes]",
]

_SESSION_COOKIE = "__Host-templ_session"
_NONCE_COOKIE = "__Host-templ_nonce"
_SESSION_SECONDS = 30 * 24 * 60 * 60
_BODY_BYTES = 1_048_576
_ERROR_BYTES = 4_096
_REASON = re.compile(r"^[a-z0-9-]{1,40}$")
_UUID = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
_UUID_V7 = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$")
_EVM_ADDRESS = re.compile(r"^0x[0-9a-fA-F]{40}$")
_BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
_THREAD = re.compile(r"^tc-[0-9a-f]{32}$")
_MESSAGE_ID = re.compile(r"^[1-9][0-9]{0,14}$")
_EVENT_ID = re.compile(r"^[1-9][0-9]{0,18}$")
_CURSOR = re.compile(r"^[A-Za-z0-9_-]{1,120}$")
_PAGE_CURSOR = re.compile(r"^[A-Za-z0-9_.:-]{1,200}$")
_NONCE = re.compile(r"^[a-zA-Z0-9]{8,128}$")
_TIME = r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z"
_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
_FOLLOW_UP_ID = re.compile(r"^[1-9][0-9]{0,7}-[1-9][0-9]?$")
_CHECK_ID = re.compile(r"^dx-[0-9a-f]{16}$")
_SIWE = re.compile(
    r"https://(?P<domain>[^\s/]+) wants you to sign in with your Ethereum account:\n"
    r"(?P<address>0x[0-9a-fA-F]{40})\n\n"
    r"(?P<statement>[^\n]*)\n\n"
    r"URI: (?P<uri>[^\n]+)\n"
    r"Version: 1\n"
    r"Chain ID: (?P<chain>[1-9][0-9]{0,15})\n"
    r"Nonce: (?P<nonce>[^\n]+)\n"
    rf"Issued At: (?P<issued>{_TIME})\n"
    rf"Expiration Time: (?P<expires>{_TIME})"
)
_SIWS = re.compile(
    r"(?P<domain>[^\s/]+) wants you to sign in with your Solana account:\n"
    r"(?P<address>[1-9A-HJ-NP-Za-km-z]{32,44})\n\n"
    r"(?P<statement>[^\n]*)\n\n"
    r"URI: (?P<uri>[^\n]+)\n"
    r"Version: 1\n"
    r"Chain ID: mainnet\n"
    r"Nonce: (?P<nonce>[^\n]+)\n"
    rf"Issued At: (?P<issued>{_TIME})\n"
    rf"Expiration Time: (?P<expires>{_TIME})"
)


class TemplError(Exception):
    """A refused or failed request.

    status: the HTTP status, or 0 for a network failure or timeout.
    reason: the service's reason code, or None.
    retry_after: seconds to wait before retrying (429 and some 503), or None.
    held: on 422 reply-held, {"draft", "case", "problems"}; otherwise None.
    """

    def __init__(
        self,
        status: int,
        reason: Optional[str] = None,
        retry_after: Optional[int] = None,
        held: Optional[dict] = None,
        message: Optional[str] = None,
    ) -> None:
        self.status = status
        self.reason = reason
        self.retry_after = retry_after
        self.held = held
        super().__init__(message or _error_text(status, retry_after))


def _error_text(status: int, retry_after: Optional[int]) -> str:
    if status == 0:
        return "Templ could not be reached."
    if status == 401:
        return "Sign in to Templ first."
    if status == 429:
        return (
            "Templ asked this client to slow down."
            if retry_after is None
            else f"Templ asked this client to wait {retry_after} seconds."
        )
    if status >= 500:
        return f"Templ is unavailable right now ({status})."
    return f"Templ answered with status {status}."


@dataclass(frozen=True)
class Latest:
    """The message a reply answers, as you read it: its id and revision."""

    id: str
    revision: int


def new_message_id(now_ms: Optional[int] = None) -> str:
    """A UUIDv7 client id: the time in its first 48 bits, then random bits."""
    now = int(time.time() * 1000) if now_ms is None else now_ms
    if not isinstance(now, int) or now < 0 or now > 0xFFFFFFFFFFFF:
        raise ValueError("Invalid message time.")
    raw = bytearray(secrets.token_bytes(16))
    raw[0:6] = now.to_bytes(6, "big")
    raw[6] = (raw[6] & 0x0F) | 0x70
    raw[8] = (raw[8] & 0x3F) | 0x80
    text = raw.hex()
    return f"{text[0:8]}-{text[8:12]}-{text[12:16]}-{text[16:20]}-{text[20:32]}"


def base58_decode(value: str) -> bytes:
    """Decodes base58 text (the Bitcoin alphabet Solana uses)."""
    number = 0
    for char in value:
        index = _BASE58.find(char)
        if index < 0:
            raise ValueError("Invalid base58.")
        number = number * 58 + index
    body = number.to_bytes((number.bit_length() + 7) // 8, "big") if number else b""
    zeros = len(value) - len(value.lstrip("1"))
    return b"\x00" * zeros + body


def is_solana_address(value: Any) -> bool:
    if not isinstance(value, str) or not 32 <= len(value) <= 44:
        return False
    try:
        return len(base58_decode(value)) == 32
    except ValueError:
        return False


def _origin(value: Any, name: str) -> str:
    if not isinstance(value, str):
        raise ValueError(f"{name} must be an https origin.")
    parsed = urllib.parse.urlsplit(value)
    if (
        parsed.scheme != "https"
        or not parsed.hostname
        or parsed.username is not None
        or parsed.password is not None
        or parsed.path not in ("",)
        or parsed.query
        or parsed.fragment
        or value != f"https://{parsed.netloc}"
        or parsed.netloc != parsed.netloc.lower()
    ):
        raise ValueError(f"{name} must be an https origin with no path.")
    return value


def _millis(stamp: str) -> int:
    parsed = datetime.fromisoformat(stamp.replace("Z", "+00:00"))
    return int(parsed.astimezone(timezone.utc).timestamp() * 1000)


def _text(value: Any, name: str = "text", limit: int = 4_000) -> str:
    text = value.strip() if isinstance(value, str) else ""
    if not text or len(text.encode("utf-8")) > limit or _CONTROL.search(text):
        raise ValueError(
            f"Use 1 to {limit:,} UTF-8 bytes of {name} without control characters."
        )
    return text


def _client_id(value: Any) -> str:
    text = value.lower() if isinstance(value, str) else ""
    if not _UUID_V7.match(text):
        raise ValueError("Use a UUIDv7 client id (new_message_id()).")
    return text


def _thread(value: Any) -> str:
    if not isinstance(value, str) or not _THREAD.match(value):
        raise ValueError("Invalid conversation id.")
    return value


def _message_id(value: Any) -> str:
    if not isinstance(value, str) or not _MESSAGE_ID.match(value):
        raise ValueError("Invalid message id.")
    return value


def _latest(value: Any) -> dict:
    if not isinstance(value, Latest) or not isinstance(value.revision, int) or value.revision < 1:
        raise ValueError("Use if_latest with a Latest(id, revision) you read.")
    return {"id": _message_id(value.id), "revision": value.revision}


def _positive(value: Any, name: str, most: int) -> int:
    if not isinstance(value, int) or isinstance(value, bool) or not 1 <= value <= most:
        raise ValueError(f"Use a {name} from 1 to {most:,}.")
    return value


def _page_cursor(value: Any) -> str:
    if not isinstance(value, str) or not _PAGE_CURSOR.match(value):
        raise ValueError("Invalid page cursor.")
    return value


def _json_object(value: Any, name: str) -> dict:
    if not isinstance(value, dict):
        raise ValueError(f"Send {name} as a dict.")
    try:
        text = json.dumps(value, ensure_ascii=False, allow_nan=False)
    except (TypeError, ValueError) as error:
        raise ValueError(f"Send {name} as JSON values.") from error
    if len(text.encode("utf-8")) > 64_000:
        raise ValueError(f"{name} is too large.")
    return json.loads(text)


def _held(reason: Optional[str], body: Any) -> Optional[dict]:
    if reason != "reply-held" or not isinstance(body, dict):
        return None
    held = body.get("held")
    if not isinstance(held, dict):
        return None
    draft, case, problems = held.get("draft"), held.get("case"), held.get("problems")
    if (
        not isinstance(draft, str)
        or not _UUID_V7.match(draft)
        or not isinstance(case, int)
        or isinstance(case, bool)
        or case < 1
        or not isinstance(problems, list)
        or len(problems) > 100
        or not all(isinstance(item, dict) and item.get("kind") in CITATION_PROBLEM_KINDS for item in problems)
    ):
        return None
    return {"draft": draft, "case": case, "problems": problems}


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):  # noqa: D401
        return None


def _urllib_transport(
    method: str, url: str, headers: dict, body: Optional[bytes], timeout: float
) -> "tuple[int, dict[str, list[str]], bytes]":
    opener = urllib.request.build_opener(_NoRedirect())
    request = urllib.request.Request(url, data=body, headers=headers, method=method)
    try:
        response = opener.open(request, timeout=timeout)
    except urllib.error.HTTPError as error:
        response = error
    except (urllib.error.URLError, OSError, http.client.HTTPException) as error:
        raise TemplError(0) from error
    status = response.status if hasattr(response, "status") else response.code
    collected: dict[str, list[str]] = {}
    for name, value in response.headers.items():
        collected.setdefault(name.lower(), []).append(value)
    try:
        # Read one byte past the limit so an oversized body is caught.
        data = response.read(_BODY_BYTES + 1)
    except (OSError, http.client.HTTPException) as error:
        raise TemplError(0) from error
    finally:
        response.close()
    return status, collected, data


class TemplAgent:
    """One agent wallet in one workspace. Keep one instance per wallet."""

    def __init__(
        self,
        *,
        address: str,
        sign: Signer,
        room: str,
        app_origin: str,
        api_origin: str,
        sign_in_chain_id: Optional[int] = None,
        network: str = "evm",
        timeout: float = 20.0,
        transport: Optional[Transport] = None,
        clock: Callable[[], float] = time.time,
    ) -> None:
        if network not in ("evm", "solana"):
            raise ValueError('Choose network="evm" or network="solana".')
        if network == "evm":
            if not isinstance(address, str) or not _EVM_ADDRESS.match(address):
                raise ValueError("Use the agent's 0x wallet address.")
            if (
                not isinstance(sign_in_chain_id, int)
                or isinstance(sign_in_chain_id, bool)
                or sign_in_chain_id < 1
            ):
                raise ValueError(
                    "Use agents.api.signInChainId from /api/status as sign_in_chain_id."
                )
        elif not is_solana_address(address):
            raise ValueError("Use the agent's Solana wallet address.")
        if not isinstance(room, str) or not _UUID.match(room):
            raise ValueError("Use the workspace UUID as room.")
        if not callable(sign):
            raise ValueError("Pass a signer callable as sign.")
        if not isinstance(timeout, (int, float)) or not 1 <= timeout <= 60:
            raise ValueError("Use a timeout of 1 to 60 seconds.")
        self._network = network
        self._address = address.lower() if network == "evm" else address
        self._sign = sign
        self._room = room
        self._app = _origin(app_origin, "app_origin")
        self._api = _origin(api_origin, "api_origin")
        self._chain = sign_in_chain_id
        self._timeout = float(timeout)
        self._transport = transport or _urllib_transport
        self._clock = clock
        self._cookies: dict[str, tuple[str, float]] = {}
        self._session: Optional[dict] = None
        self._lock = threading.RLock()

    def __repr__(self) -> str:
        return f"TemplAgent(room={self._room!r}, address={self._address!r})"

    # ------------------------------------------------------------------
    # Transport

    def _now(self) -> float:
        return self._clock()

    def _cookie_header(self) -> str:
        now = self._now()
        for name in [name for name, (_, expires) in self._cookies.items() if expires <= now]:
            del self._cookies[name]
        return "; ".join(f"{name}={value}" for name, (value, _) in self._cookies.items())

    def _receive_cookies(self, headers: dict) -> None:
        now = self._now()
        for line in headers.get("set-cookie", []):
            # A comma inside Expires is not followed by a name=value pair.
            for part in re.split(r",(?=\s*[^\s;,=]+\s*=)", line):
                pair, *attributes = part.split(";")
                if "=" not in pair:
                    continue
                name, value = (item.strip() for item in pair.split("=", 1))
                if name not in (_SESSION_COOKIE, _NONCE_COOKIE):
                    continue
                attrs: dict[str, str] = {}
                for attribute in attributes:
                    key, _, attr_value = attribute.partition("=")
                    attrs[key.strip().lower()] = attr_value.strip()
                if (
                    "domain" in attrs
                    or attrs.get("path") != "/"
                    or "secure" not in attrs
                    or "httponly" not in attrs
                ):
                    continue
                expires = now + _SESSION_SECONDS
                if "max-age" in attrs:
                    if not re.fullmatch(r"-?\d+", attrs["max-age"]):
                        continue
                    expires = now + min(int(attrs["max-age"]), _SESSION_SECONDS)
                elif "expires" in attrs:
                    try:
                        stamp = datetime.strptime(attrs["expires"], "%a, %d %b %Y %H:%M:%S GMT")
                    except ValueError:
                        continue
                    expires = min(
                        stamp.replace(tzinfo=timezone.utc).timestamp(),
                        now + _SESSION_SECONDS,
                    )
                if expires <= now:
                    self._cookies.pop(name, None)
                    continue
                if re.fullmatch(r"[0-9a-f]{64}", value):
                    self._cookies[name] = (value, expires)

    def _call(
        self,
        method: str,
        path: str,
        body: Optional[dict] = None,
        *,
        origin: Optional[str] = None,
        max_bytes: int = _BODY_BYTES,
    ) -> Any:
        url = f"{origin or self._api}{path}"
        headers = {"Origin": self._app, "Accept": "application/json"}
        cookie = self._cookie_header() if origin is None else ""
        if cookie:
            headers["Cookie"] = cookie
        data = None
        if body is not None:
            headers["Content-Type"] = "application/json"
            data = json.dumps(body, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
        try:
            status, response_headers, raw = self._transport(
                method, url, headers, data, self._timeout
            )
        except TemplError:
            raise
        except Exception as error:  # the transport's own failure
            raise TemplError(0) from error
        response_headers = {key.lower(): value for key, value in response_headers.items()}
        # Never carry a session or a sign-in challenge to a redirect target.
        if 300 <= status < 400:
            raise TemplError(status)
        if origin is None:
            self._receive_cookies(response_headers)
        if not 200 <= status < 300:
            if status == 401 and origin is None:
                self._session = None
                self._cookies.pop(_SESSION_COOKIE, None)
            retry = (response_headers.get("retry-after") or [None])[0]
            retry_after = min(int(retry), 3600) if retry and retry.isdigit() else None
            reason = None
            held = None
            if len(raw) <= _ERROR_BYTES:
                try:
                    parsed = json.loads(raw.decode("utf-8", errors="strict"))
                except (UnicodeDecodeError, ValueError):
                    parsed = None
                code = parsed.get("reason") if isinstance(parsed, dict) else None
                reason = code if isinstance(code, str) and _REASON.match(code) else None
                held = _held(reason, parsed) if status == 422 else None
            raise TemplError(status, reason, retry_after, held)
        if status == 204:
            return None
        if len(raw) > max_bytes:
            raise TemplError(502, message="Templ sent a response that was too large.")
        try:
            return json.loads(raw.decode("utf-8", errors="strict"))
        except (UnicodeDecodeError, ValueError) as error:
            raise TemplError(502, message="Templ sent a response that was not JSON.") from error

    def _room_path(self, suffix: str) -> str:
        return f"/rooms/{self._room}{suffix}"

    def _authorized(self) -> str:
        session = self._session
        if (
            session is None
            or session["expiresAt"] <= self._now() * 1000
            or _SESSION_COOKIE not in self._cookies
            or self._cookies[_SESSION_COOKIE][1] <= self._now()
        ):
            self._session = None
            raise TemplError(401)
        return session["principalId"]

    def _get(self, suffix: str, query: Optional[dict] = None, **options: Any) -> Any:
        with self._lock:
            self._authorized()
            search = f"?{urllib.parse.urlencode(query)}" if query else ""
            return self._call("GET", self._room_path(suffix) + search, **options)

    def _post(self, suffix: str, body: dict) -> Any:
        with self._lock:
            payload = dict(body)
            payload["expectedPrincipalId"] = self._authorized()
            return self._call("POST", self._room_path(suffix), payload)

    @staticmethod
    def _shape(value: Any, check: Callable[[Any], bool]) -> Any:
        if not isinstance(value, dict) or not check(value):
            raise TemplError(502, message="Templ sent a response in an unexpected shape.")
        return value

    # ------------------------------------------------------------------
    # Sign-in

    def _check_session(self, value: Any) -> dict:
        def invalid() -> dict:
            self._cookies.clear()
            self._session = None
            raise TemplError(401, message="The wallet session could not be verified.")

        now_ms = self._now() * 1000
        if not isinstance(value, dict):
            return invalid()
        principal = value.get("principalId")
        principals = value.get("servicePrincipals")
        expires = value.get("expiresAt")
        wallet_ok = (
            value.get("authMethod") == "wallet"
            and isinstance(value.get("address"), str)
            and value["address"].lower() == self._address
            if self._network == "evm"
            else value.get("authMethod") == "solana"
            and value.get("solanaAddress") == self._address
        )
        if (
            not wallet_ok
            or not isinstance(principal, str)
            or not principal
            or (principals is not None and (not isinstance(principals, list) or principal not in principals))
            or not isinstance(expires, (int, float))
            or isinstance(expires, bool)
            or expires <= now_ms
            or expires > now_ms + (_SESSION_SECONDS + 60) * 1000
            or _SESSION_COOKIE not in self._cookies
        ):
            return invalid()
        self._session = {"principalId": principal, "expiresAt": expires, "session": value}
        return value

    def _read_session(self) -> Optional[dict]:
        try:
            value = self._call("GET", "/auth/session")
        except TemplError as error:
            if error.status == 401:
                return None
            raise
        return self._check_session(value)

    def session(self) -> Optional[dict]:
        """The current session, or None when signed out."""
        with self._lock:
            return self._read_session()

    def _check_times(self, match: "re.Match[str]", challenge_expires: Any) -> None:
        now_ms = int(self._now() * 1000)
        issued = _millis(match["issued"])
        expires = _millis(match["expires"])
        if (
            issued > now_ms + 60_000
            or issued < now_ms - 5 * 60_000
            or expires <= now_ms
            or expires > now_ms + 6 * 60_000
            or not isinstance(challenge_expires, int)
            or isinstance(challenge_expires, bool)
            or expires != challenge_expires
        ):
            raise TemplError(0, message="The sign-in request could not be verified.")

    def check_sign_in_message(self, message: Any, expires_at: Any, nonce_cookie: Optional[str]) -> None:
        """Raises unless `message` is exactly Templ's sign-in text for this
        wallet, app and network, with a fresh window that ends at
        `expires_at` (ms) and the nonce of the nonce cookie."""
        refused = TemplError(0, message="The sign-in request could not be verified.")
        if not isinstance(message, str) or len(message) > 4_096:
            raise refused
        host = urllib.parse.urlsplit(self._app).netloc
        if self._network == "evm":
            match = _SIWE.fullmatch(message)
            if (
                not match
                or match["address"].lower() != self._address
                or int(match["chain"]) != self._chain
            ):
                raise refused
        else:
            match = _SIWS.fullmatch(message)
            if not match or match["address"] != self._address:
                raise refused
        if (
            match["domain"] != host
            or match["uri"] != self._app
            or match["statement"] != SIGN_IN_STATEMENT
            or not _NONCE.match(match["nonce"])
            or nonce_cookie != match["nonce"]
        ):
            raise refused
        self._check_times(match, expires_at)

    def sign_in(self) -> dict:
        """Signs in, reusing a live session. Checks the sign-in text before
        the signer sees it and the session the service returns."""
        with self._lock:
            existing = self._read_session()
            if existing is not None:
                return existing
            if self._network == "evm":
                challenge = self._call(
                    "POST", "/auth/nonce", {"address": self._address, "chainId": self._chain}
                )
            else:
                challenge = self._call("POST", "/auth/solana/nonce", {"address": self._address})
            if not isinstance(challenge, dict):
                raise TemplError(502, message="Templ sent an invalid sign-in challenge.")
            message = challenge.get("message")
            nonce = self._cookies.get(_NONCE_COOKIE, (None, 0))[0]
            self.check_sign_in_message(message, challenge.get("expiresAt"), nonce)
            if self._network == "evm":
                signature = self._sign(message)
                if not isinstance(signature, str) or not re.fullmatch(r"(0x)?[0-9a-fA-F]{130}", signature):
                    raise ValueError("The signer must return a 65-byte hex signature.")
                verified = self._call(
                    "POST",
                    "/auth/verify",
                    {"message": message, "signature": "0x" + signature.removeprefix("0x").lower()},
                )
            else:
                signature = self._sign(message.encode("utf-8"))
                if not isinstance(signature, (bytes, bytearray)) or len(signature) != 64:
                    raise ValueError("The signer must return the 64-byte Ed25519 signature.")
                verified = self._call(
                    "POST",
                    "/auth/solana/verify",
                    {"message": message, "signature": base64.b64encode(bytes(signature)).decode("ascii")},
                )
            return self._check_session(verified)

    def sign_out(self) -> None:
        """Ends the session everywhere. The cookie stops working."""
        with self._lock:
            try:
                self._call("POST", "/auth/logout", {})
            finally:
                self._cookies.clear()
                self._session = None

    # ------------------------------------------------------------------
    # Status

    def status(self) -> dict:
        """<app>/api/status. Raises TemplError(0, "api-version") unless the
        service publishes Agent API major version 1."""
        with self._lock:
            value = self._call("GET", "/api/status", origin=self._app)
        api = ((value or {}).get("agents") or {}).get("api") if isinstance(value, dict) else None
        version = api.get("version") if isinstance(api, dict) else None
        if not isinstance(version, str) or version.split(".")[0] != str(API_MAJOR):
            raise TemplError(0, "api-version", message="Templ doesn't publish Agent API 1 here.")
        self._api_version = version
        return value

    def _needs(self, version: str) -> None:
        live = getattr(self, "_api_version", None)
        if live is not None and API_VERSIONS.index(live) < API_VERSIONS.index(version):
            raise TemplError(0, "api-version", message=f"This needs Agent API {version}.")

    # ------------------------------------------------------------------
    # Agent API 1.0

    def bots(self) -> list:
        """The workspace's registered bots. Check that the agent is listed."""
        return self._shape(self._get("/bots"), lambda body: isinstance(body.get("bots"), list))["bots"]

    def conversation_status(self) -> dict:
        return self._shape(
            self._get("/conversations/status"),
            lambda body: isinstance(body.get("available"), bool) and isinstance(body.get("team"), bool),
        )

    def conversations(self, filter: str = "needs-reply", cursor: Optional[str] = None) -> dict:
        """One page of the queue. needs-reply lists the oldest wait first."""
        if filter not in CONVERSATION_FILTERS:
            raise ValueError(f"Filter by one of: {', '.join(CONVERSATION_FILTERS)}.")
        query = {"filter": filter}
        if cursor is not None:
            if not isinstance(cursor, str) or not _CURSOR.match(cursor):
                raise ValueError("Invalid conversation cursor.")
            query["cursor"] = cursor
        return self._shape(
            self._get("/conversations", query),
            lambda body: isinstance(body.get("conversations"), list)
            and (body.get("nextCursor") is None or isinstance(body.get("nextCursor"), str)),
        )

    def iter_conversations(self, filter: str = "needs-reply") -> Iterator[dict]:
        """Every row of the queue, page by page. Raises on a repeated page."""
        seen: set[str] = set()
        cursor = None
        while True:
            page = self.conversations(filter, cursor)
            yield from page["conversations"]
            cursor = page.get("nextCursor")
            if not cursor:
                return
            if cursor in seen:
                raise TemplError(502, message="The queue repeated a page.")
            seen.add(cursor)

    def conversation(self, tc: str) -> dict:
        body = self._shape(
            self._get(f"/conversations/{_thread(tc)}"),
            lambda value: isinstance(value.get("conversation"), dict),
        )
        return body["conversation"]

    def messages(self, tc: str, before: Optional[str] = None, limit: int = 50) -> dict:
        query: dict = {"limit": str(_positive(limit, "limit", 50))}
        if before is not None:
            query["before"] = _message_id(before)
        return self._shape(
            self._get(f"/conversations/{_thread(tc)}/messages", query),
            lambda body: isinstance(body.get("messages"), list) and isinstance(body.get("conversation"), dict),
        )

    def workflow(self, tc: str) -> dict:
        """The request's details: context (network, transactions), the
        proven `wallet`, `access.claimedWallet` (unproven), notes and
        activity. A member gets a safe subset."""
        body = self._shape(
            self._get(f"/conversations/{_thread(tc)}/workflow"),
            lambda value: isinstance(value.get("workflow"), dict),
        )
        return body["workflow"]

    def reply(
        self,
        tc: str,
        text: str,
        *,
        client_id: Optional[str] = None,
        if_latest: Optional[Latest] = None,
        reply_to: Optional[str] = None,
        provenance: Optional[dict] = None,
    ) -> dict:
        """Posts a reply. With if_latest the service refuses it (409 stale)
        when the member wrote or edited since. `provenance` (API 1.1) tells
        the team why the agent wrote it; figures cite evidence rows with
        [ev:n] markers, which the service removes before storing."""
        body: dict = {"text": _text(text), "clientId": _client_id(client_id or new_message_id())}
        if if_latest is not None:
            body["ifLatest"] = _latest(if_latest)
        if reply_to is not None:
            body["replyTo"] = _message_id(reply_to)
        if provenance is not None:
            self._needs("1.1")
            body["provenance"] = _json_object(provenance, "provenance")
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/messages", body),
            lambda value: isinstance(value.get("message"), dict),
        )

    def note(self, tc: str, text: str, *, client_id: str, mentions: Optional[list] = None) -> dict:
        """An internal note the member never sees. A retry with the same
        client_id returns the first note."""
        body: dict = {"action": "note", "text": _text(text), "clientId": _client_id(client_id)}
        if mentions is not None:
            if not isinstance(mentions, list) or len(mentions) > 10:
                raise ValueError("Mention up to 10 staff accounts.")
            body["mentions"] = list(dict.fromkeys(mentions))
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/workflow", body),
            lambda value: isinstance(value.get("workflow"), dict),
        )["workflow"]

    def hand_off(self, tc: str, reason: str, *, if_latest: Optional[Latest] = None) -> dict:
        """Asks a person to answer. Until one does, the service refuses this
        agent's replies with 409 handed-off."""
        if reason not in HANDOFF_REASONS:
            raise ValueError(f"Choose a handoff reason: {', '.join(HANDOFF_REASONS)}.")
        body: dict = {"action": "handoff", "reason": reason}
        if if_latest is not None:
            body["ifLatest"] = _latest(if_latest)
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/workflow", body),
            lambda value: isinstance(value.get("workflow"), dict),
        )["workflow"]

    def typing(self, tc: str) -> None:
        """Shows the member that the agent is writing, for about 12 seconds."""
        result = self._post(f"/conversations/{_thread(tc)}/typing", {})
        if result is not None:
            raise TemplError(502, message="Templ sent a response in an unexpected shape.")

    def resolve(self, tc: str, resolved: bool = True, *, time_spent: Optional[str] = None) -> dict:
        if not isinstance(resolved, bool):
            raise ValueError("Resolve takes True or False.")
        body: dict = {"resolved": resolved}
        if time_spent is not None:
            if not resolved or time_spent not in TIME_SPENT:
                raise ValueError(f"Record time spent only when resolving, as {', '.join(TIME_SPENT)}.")
            body["timeSpent"] = time_spent
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/resolve", body),
            lambda value: isinstance(value.get("conversation"), dict),
        )["conversation"]

    def events(self, after: Optional[str] = None, limit: int = 100) -> dict:
        query: dict = {"limit": str(_positive(limit, "limit", 200))}
        if after is not None:
            if not isinstance(after, str) or not _EVENT_ID.match(after):
                raise ValueError("Invalid event cursor.")
            query["after"] = after
        return self._shape(self._get("/events", query), lambda body: isinstance(body.get("events"), list))

    def pulse(self) -> dict:
        """The team's live queue as counts and times, with no thread or person."""
        return self._shape(
            self._get("/conversations/pulse"),
            lambda body: body.get("schemaVersion") in (1, 2)
            and all(isinstance(body.get(key), int) for key in ("needsReply", "needsYou", "aiHandling")),
        )

    @staticmethod
    def latest(page: dict) -> Optional[Latest]:
        """The id and revision of the newest message in a messages() page."""
        messages = page.get("messages") if isinstance(page, dict) else None
        if not messages:
            return None
        newest = messages[-1]
        return Latest(id=newest["id"], revision=newest.get("revision") or 1)

    # ------------------------------------------------------------------
    # Agent API 1.1

    def cases(self, tc: str, before: Optional[int] = None) -> dict:
        """The thread's requests, newest first: times, counts and flags."""
        self._needs("1.1")
        query = {"before": str(_positive(before, "request number", 99_999_999))} if before is not None else None
        return self._shape(
            self._get(f"/conversations/{_thread(tc)}/cases", query),
            lambda body: isinstance(body.get("cases"), list),
        )

    def case(self, tc: str, seq: int) -> dict:
        """One request with its frame, evidence rows, drafts and Ask AI
        questions."""
        self._needs("1.1")
        return self._shape(
            self._get(
                f"/conversations/{_thread(tc)}/cases",
                {"seq": str(_positive(seq, "request number", 99_999_999))},
            ),
            lambda body: isinstance(body.get("case"), dict) and isinstance(body.get("evidence"), list),
        )

    def set_case_frame(
        self,
        tc: str,
        seq: int,
        *,
        set: Optional[dict] = None,
        clear: Optional[list] = None,
        if_revision: Optional[int] = None,
    ) -> dict:
        """Sets or clears frame fields: product, network, metric, window,
        reported, question (text). With if_revision the service refuses a
        frame someone changed since you read it (409 frame-stale)."""
        self._needs("1.1")
        body: dict = {"action": "frame", "case": _positive(seq, "request number", 99_999_999)}
        if set is not None:
            body["set"] = _json_object(set, "the frame fields")
        if clear is not None:
            if not isinstance(clear, list):
                raise ValueError("Clear a list of frame fields.")
            body["clear"] = list(clear)
        if if_revision is not None:
            if not isinstance(if_revision, int) or if_revision < 0:
                raise ValueError("Use if_revision from the frame you read.")
            body["ifRevision"] = if_revision
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/workflow", body),
            lambda value: isinstance(value.get("frame"), dict),
        )["frame"]

    def add_evidence(self, tc: str, seq: int, *, rows: list, client_id: str) -> list:
        """Adds 1 to 10 evidence rows, each with where its value came from.
        A retry with the same client_id and rows returns the first rows."""
        self._needs("1.1")
        if not isinstance(rows, list) or not 1 <= len(rows) <= 10:
            raise ValueError("Send 1 to 10 evidence rows.")
        body = {
            "action": "evidence",
            "case": _positive(seq, "request number", 99_999_999),
            "rows": [_json_object(row, "an evidence row") for row in rows],
            "clientId": _client_id(client_id),
        }
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/workflow", body),
            lambda value: isinstance(value.get("evidence"), list),
        )["evidence"]

    def withdraw_evidence(self, tc: str, seq: int, n: int) -> dict:
        """Withdraws one of the agent's own evidence rows. It stays listed."""
        self._needs("1.1")
        body = {
            "action": "withdraw-evidence",
            "case": _positive(seq, "request number", 99_999_999),
            "n": _positive(n, "evidence row number", 9_999),
        }
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/workflow", body),
            lambda value: isinstance(value.get("evidence"), dict),
        )["evidence"]

    def draft_requests(self, after: Optional[str] = None, limit: int = 50) -> dict:
        """The team's pending Ask AI questions, oldest first. Read the
        question with case()."""
        self._needs("1.1")
        query: dict = {"limit": str(_positive(limit, "limit", 50))}
        if after is not None:
            query["after"] = _page_cursor(after)
        return self._shape(
            self._get("/conversations/draft-requests", query),
            lambda body: isinstance(body.get("requests"), list),
        )

    def add_draft(
        self,
        tc: str,
        text: str,
        *,
        client_id: str,
        request: Optional[str] = None,
        for_message: Optional[Latest] = None,
        provenance: Optional[dict] = None,
    ) -> Optional[dict]:
        """A draft for the team, never sent to the member: the answer to
        one Ask AI question (request) or a suggestion for the member message
        you read (for_message). One suggestion per member message (409
        draft-exists)."""
        self._needs("1.1")
        if (request is None) == (for_message is None):
            raise ValueError("Draft for one Ask AI request or one member message.")
        body: dict = {"action": "draft", "text": _text(text), "clientId": _client_id(client_id)}
        if request is not None:
            body["request"] = _client_id(request)
        if for_message is not None:
            body["forMessage"] = _latest(for_message)
        if provenance is not None:
            body["provenance"] = _json_object(provenance, "provenance")
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/workflow", body),
            lambda value: "draft" in value,
        )["draft"]

    def decline_draft_request(self, tc: str, request: str, reason: str) -> dict:
        """Declines an Ask AI question with one of AI_DECLINES."""
        self._needs("1.1")
        if reason not in AI_DECLINES:
            raise ValueError(f"Decline with one of: {', '.join(AI_DECLINES)}.")
        body = {"action": "draft-decline", "request": _client_id(request), "reason": reason}
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/workflow", body),
            lambda value: isinstance(value.get("request"), dict),
        )["request"]

    def follow_ups(self, tc: str, case: Optional[int] = None) -> dict:
        """The request's follow-ups and which requests wait on the team."""
        self._needs("1.1")
        query = {"case": str(_positive(case, "request number", 99_999_999))} if case is not None else None
        return self._shape(
            self._get(f"/conversations/{_thread(tc)}/follow-ups", query),
            lambda body: isinstance(body.get("followUps"), list),
        )

    def add_follow_up(self, tc: str, *, client_id: str, type: str, title: str, **fields: Any) -> dict:
        """Adds a follow-up to the latest request. The agent's follow-up stays
        team-only, with no owner or date, until a person takes it."""
        self._needs("1.1")
        body = _json_object({**fields, "type": type, "title": _text(title, "title", 480)}, "the follow-up")
        body["clientId"] = _client_id(client_id)
        return self._shape(
            self._post(f"/conversations/{_thread(tc)}/follow-ups", body),
            lambda value: isinstance(value.get("followUps"), list),
        )

    def diagnoses(self, tc: str, check: Optional[str] = None) -> dict:
        """The thread's transaction checks, newest first, as the agent reads
        them: what happened, findings, a draft for the member and `claims`,
        the values a reply may restate. Never the team's next steps."""
        self._needs("1.1")
        query = None
        if check is not None:
            if not isinstance(check, str) or not _CHECK_ID.match(check):
                raise ValueError("Use a check id from the check list.")
            query = {"id": check}
        return self._shape(
            self._get(f"/conversations/{_thread(tc)}/diagnosis", query),
            lambda body: isinstance(body.get("diagnoses"), list) or isinstance(body.get("diagnosis"), dict),
        )


# ----------------------------------------------------------------------
# Citations: the same check the service runs on an AI agent's reply. The
# answers match packages/chat/test-vectors/citations.json.

CITATION_PROBLEM_KINDS = (
    "uncited-figure",
    "unknown-evidence",
    "withdrawn-evidence",
    "superseded-evidence",
    "unlabeled-mix",
    "unlabeled-comparison",
    "too-many-citations",
    "no-case",
    "evidence-unreadable",
    "unknown-diagnosis",
    "diagnosis-figure-not-in-check",
)
_MARKER = re.compile(
    r"[ \t]?\[(?:ev:(\d{1,4}(?:,\d{1,4}){0,7})|dx:(dx-[0-9a-f]{16}(?:,dx-[0-9a-f]{16}){0,7}))\]",
    re.ASCII,
)
_MASKS = (
    re.compile(r"https?://[^\s<>()\[\]]+", re.ASCII),
    re.compile(r"0x[0-9a-fA-F]+", re.ASCII),
    re.compile(r"(?:…|\.\.\.)[0-9a-fA-F]{2,}\b", re.ASCII),
    re.compile(r"eip155:\d+", re.ASCII),
    re.compile(r"[1-9A-HJ-NP-Za-km-z]{26,}", re.ASCII),
    re.compile(r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?Z?)?", re.ASCII),
    re.compile(r"\b\d{1,2}:\d{2}(?::\d{2})?\b", re.ASCII),
    re.compile(r"\b(?:ERC|EIP|BIP|CAIP|SLIP)-?\d+\b", re.ASCII | re.IGNORECASE),
    re.compile(r"\bv?\d+(?:\.\d+){2,}\b", re.ASCII),
    re.compile(r"^[ \t]*\d{1,2}[.)](?=\s)", re.ASCII | re.MULTILINE),
    re.compile(
        r"(?<![\d.,$€£])(?:19|20)\d{2}(?![\d.,%])(?!\s?(?:bps\b|[kKmMbB]\b|[a-z]{0,3}[A-Z]))",
        re.ASCII,
    ),
)
_CANDIDATE = re.compile(
    r"(?<![A-Za-z0-9_.])(?:[$€£]\s?)?\d(?:[\d,]*\d)?(?:\.\d+)?(?:\s?(?:%|bps\b|[kKmMbB](?![A-Za-z])|x(?![A-Za-z])))?",
    re.ASCII,
)
_TICKER = re.compile(r"^\s?[a-z]{0,3}[A-Z][A-Za-z0-9]{1,11}\b", re.ASCII)
_AMOUNT = re.compile(r"([$€£])?\s?(-?\d(?:[\d,]*\d)?(?:\.(\d+))?)\s?(%|bps|[kKmMbB](?![A-Za-z]))?", re.ASCII)
_SENTENCE_BREAK = re.compile(r"(?<=[.!?])\s+|\n+")
_MAX_MARKERS = 40


def strip_citation_markers(text: str) -> "tuple[str, list[dict]]":
    """The reply without well-formed markers, and where each marker was."""
    markers: list[dict] = []
    out = ""
    last = 0
    for match in _MARKER.finditer(text):
        start = match.start()
        lead = "" if match.group(0).startswith("[") else match.group(0)[0]
        lead_at_line_start = lead != "" and (start == 0 or text[start - 1] == "\n")
        out += text[last:start] + (lead if lead_at_line_start else "")
        if match.group(1) is not None:
            markers.append({"at": len(out), "ids": [int(item) for item in match.group(1).split(",")]})
        else:
            markers.append({"at": len(out), "ids": [], "dx": list(dict.fromkeys(match.group(2).split(",")))})
        last = match.end()
    return out + text[last:], markers


def _mask(text: str) -> str:
    for pattern in _MASKS:
        text = pattern.sub(lambda found: " " * len(found.group(0)), text)
    return text


def find_figures(text: str) -> list:
    """The figures a text states, in order: amounts, percentages, prices,
    anything with a decimal point or four or more digits."""
    masked = _mask(text)
    figures = []
    for match in _CANDIDATE.finditer(masked):
        found = match.group(0)
        end = match.end()
        digits = re.sub(r"[^\d]", "", found)
        integer = re.sub(r"^[$€£]\s?", "", found).split(".")[0]
        if (
            re.match(r"^[$€£]", found)
            or re.search(r"(%|bps|[kKmMbB]|x)$", found)
            or "." in found
            or "," in found
            or len(integer.replace(",", "")) >= 4
            or len(digits) >= 4
            or _TICKER.match(masked[end:])
        ):
            figures.append({"start": match.start(), "end": end, "text": found})
    return figures


def _sentences(text: str) -> list:
    out = []
    start = 0
    for match in _SENTENCE_BREAK.finditer(text):
        out.append({"start": start, "end": match.start(), "text": text[start : match.start()]})
        start = match.end()
    out.append({"start": start, "end": len(text), "text": text[start:]})
    return out


def _sentence_at(items: list, at: int) -> int:
    for index in range(len(items) - 1, -1, -1):
        if at >= items[index]["start"]:
            if not items[index]["text"].strip() and index > 0:
                return index - 1
            return index
    return 0


def _label(tag: dict) -> str:
    return tag.get("label") if tag.get("label") is not None else tag["key"]


def _names(sentence: str, tag: dict) -> bool:
    text = _label(tag)
    return len(text) >= 2 and text.lower() in sentence.lower()


def _parse_amount(text: str) -> Optional[dict]:
    match = _AMOUNT.search(text)
    if not match:
        return None
    try:
        value = float(match.group(2).replace(",", ""))
    except ValueError:
        return None
    suffix = (match.group(4) or "").lower()
    if match.group(1):
        unit = "currency"
    elif suffix == "%":
        unit = "percent"
    elif suffix == "bps":
        unit = "bps"
    elif suffix in ("k", "m", "b"):
        unit = suffix
    else:
        unit = "plain"
    return {"value": value, "unit": unit, "step": 10 ** -len(match.group(3) or "")}


def _mismatch(figure: str, row: dict) -> bool:
    value = row["value"]
    said = _parse_amount(figure)
    stored = _parse_amount(
        f"{value['number']}{'%' if value.get('unit') == '%' else ''}"
        if value.get("number") is not None
        else value["text"]
    )
    if not said or not stored or said["unit"] != stored["unit"]:
        return False
    return abs(said["value"] - stored["value"]) > said["step"] / 2 + 1e-12


_SCALE = {"k": 1e3, "m": 1e6, "b": 1e9}


def _stated_by(figure: str, numbers: list) -> bool:
    said = _parse_amount(figure)
    if not said:
        return False
    scale = _SCALE.get(said["unit"], 1)
    value = said["value"] * scale
    tolerance = said["step"] * scale / 2 + 1e-9
    for number in numbers:
        if not re.match(r"^\d", number):
            continue
        try:
            stored = float(number.replace(",", ""))
        except ValueError:
            continue
        if abs(stored - value) <= tolerance:
            return True
    return False


def check_citations(text: str, rows: Optional[list], diagnoses: Optional[list] = None) -> dict:
    """Checks a reply against the evidence rows of the request it answers,
    as the service does before it sends an AI agent's reply. `rows` None
    means the reply answers no request. `diagnoses` lists the checks a
    [dx:...] marker may name, as {"id", "numbers"}. Returns ok, text (the
    reply without markers), citations, figures, problems and advice."""
    body, markers = strip_citation_markers(text)
    items = _sentences(body)
    figures = find_figures(body)
    problems: list = []
    advice: list = []
    ev_markers = [marker for marker in markers if "dx" not in marker]
    citations = [
        {"sentence": _sentence_at(items, marker["at"]) + 1, "evidence": list(dict.fromkeys(marker["ids"]))}
        for marker in ev_markers
    ]
    dx_markers = [marker for marker in markers if "dx" in marker]
    diagnosis_citations = [
        {"sentence": _sentence_at(items, marker["at"]) + 1, "diagnoses": marker["dx"]} for marker in dx_markers
    ]
    extra = {"diagnosisCitations": diagnosis_citations} if diagnosis_citations else {}
    if not markers and not figures:
        return {"ok": True, "text": body, "citations": citations, **extra, "figures": 0, "problems": [], "advice": []}
    if len(markers) > _MAX_MARKERS:
        problems.append({"kind": "too-many-citations"})
    if rows is None and (ev_markers or not dx_markers):
        problems.append({"kind": "no-case"})
    known = {item["id"]: item for item in (diagnoses or [])}
    seen_dx: set = set()
    for marker in dx_markers:
        for ident in marker["dx"]:
            if ident in seen_dx:
                continue
            seen_dx.add(ident)
            if ident not in known:
                problems.append({"kind": "unknown-diagnosis", "diagnosis": ident})
    by_n = {row["n"]: row for row in (rows or [])}
    seen: set = set()
    for citation in citations:
        for n in citation["evidence"]:
            if n in seen:
                continue
            seen.add(n)
            if rows is None:
                continue
            row = by_n.get(n)
            if row is None:
                problems.append({"kind": "unknown-evidence", "evidence": n})
            elif row["withdrawn"]:
                problems.append({"kind": "withdrawn-evidence", "evidence": n})
            elif row.get("supersededBy") is not None:
                problems.append({"kind": "superseded-evidence", "evidence": n, "by": row["supersededBy"]})
    placed = [{**marker, "sentence": _sentence_at(items, marker["at"])} for marker in markers]
    for index, figure in enumerate(figures):
        sentence = _sentence_at(items, figure["start"])
        following = figures[index + 1] if index + 1 < len(figures) else None
        marker = next(
            (
                entry
                for entry in placed
                if entry["at"] >= figure["end"]
                and entry["sentence"] == sentence
                and not (
                    following
                    and following["start"] < entry["at"]
                    and _sentence_at(items, following["start"]) == sentence
                )
            ),
            None,
        )
        if marker is None:
            problems.append({"kind": "uncited-figure", "figure": figure["text"], "sentence": sentence + 1})
            continue
        if "dx" in marker:
            cited = [known[ident] for ident in marker["dx"] if ident in known]
            if cited and not any(_stated_by(figure["text"], item["numbers"]) for item in cited):
                problems.append(
                    {
                        "kind": "diagnosis-figure-not-in-check",
                        "figure": figure["text"],
                        "sentence": sentence + 1,
                        "diagnoses": [item["id"] for item in cited],
                    }
                )
            continue
        for n in dict.fromkeys(marker["ids"]):
            row = by_n.get(n)
            if row is not None and not row["withdrawn"] and _mismatch(figure["text"], row):
                advice.append(
                    {"kind": "value-mismatch", "figure": figure["text"], "evidence": n, "value": row["value"]["text"]}
                )

    def cited_rows(sentence: int) -> list:
        ids = dict.fromkeys(n for marker in placed if marker["sentence"] == sentence for n in marker["ids"])
        return sorted((by_n[n] for n in ids if n in by_n), key=lambda row: row["n"])

    mixed: set = set()
    for index, sentence in enumerate(items):
        here = cited_rows(index)
        if len(here) < 2:
            continue
        for dimension in ("product", "metric", "window"):
            if len({row[dimension]["key"] for row in here}) < 2:
                continue
            if all(_names(sentence["text"], row[dimension]) for row in here):
                continue
            mixed.add((index, dimension))
            problems.append(
                {
                    "kind": "unlabeled-mix",
                    "sentence": index + 1,
                    "dimension": dimension,
                    "evidence": [row["n"] for row in here],
                }
            )
    every = sorted(
        (by_n[n] for n in dict.fromkeys(n for marker in placed for n in marker["ids"]) if n in by_n),
        key=lambda row: row["n"],
    )
    reported: set = set()
    for i in range(len(every)):
        for j in range(i + 1, len(every)):
            a, b = every[i], every[j]
            if a["metric"]["key"] != b["metric"]["key"]:
                continue
            if a["window"]["key"] != b["window"]["key"]:
                dimension = "window"
            elif a["product"]["key"] != b["product"]["key"]:
                dimension = "product"
            else:
                continue
            unlabeled = False
            for index, sentence in enumerate(items):
                if (index, dimension) in mixed:
                    continue
                here = cited_rows(index)
                if any(
                    any(entry["n"] == row["n"] for entry in here) and not _names(sentence["text"], row[dimension])
                    for row in (a, b)
                ):
                    unlabeled = True
                    break
            key = (dimension, a["n"], b["n"])
            if unlabeled and key not in reported:
                reported.add(key)
                problems.append({"kind": "unlabeled-comparison", "dimension": dimension, "evidence": [a["n"], b["n"]]})
    return {
        "ok": not problems,
        "text": body,
        "citations": citations,
        **extra,
        "figures": len(figures),
        "problems": problems,
        "advice": advice,
    }
