Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

39.6 KB
Raw Blame
"""Turn-language detection and resolution (de / en / es / pt).

Live forensic 2026-06-10 23:12 (data/jarvis_desktop.log): ``[stt].language``
pins Groq Whisper to German, and Whisper echoes the pin back in its response —
so every transcript was tagged ``language=german``, including pure-English
speech (``text="What's weather like tomorrow?" language=German``). Every
consumer trusting that tag (TTS voice pin, ack-brain language, spoken fallback
phrases) then spoke German to an English speaker.

This module is the single source of truth for the language of a turn:

* :func:`detect_text_language` — cheap token-overlap heuristic over the
  transcribed text. Returns a code only when the text is clearly one language;
  ``"unknown"`` otherwise (single proper nouns, "ok", ...). Tokens shared by
  two of the supported languages ("in", "an", "es", "was", "me", "no", "a",
  "que", "para", "um", "das") are deliberately excluded from all sets — the
  historical "'in' counts as EN" trap. Spanish and Portuguese share most
  accented vowels, so only their distinctive characters (``ñ ¿ ¡`` versus
  ``ã õ ç â ê ô à``) are strong script signals.
* :func:`normalize_language_tag` — maps the two tag shapes seen live (Whisper
  language NAMES like ``"german"`` from the cloud API, ISO codes like ``"de"``
  from local faster-whisper, BCP-47 like ``"de-DE"``) to plain codes, so
  downstream maps such as ``{"de": "de-DE"}.get(lang)`` stop silently missing.
* :func:`resolve_turn_language` — text wins when decisive, the STT tag breaks
  ties, an explicit default comes last.

Pure regex / set lookups — no LLM, no IO. Safe on the voice critical path
(AP-9 / AP-11).
"""

from __future__ import annotations

import re
import unicodedata
from collections.abc import Iterable, Mapping
from contextvars import ContextVar
from dataclasses import dataclass
from typing import Literal

from dodaios.i18n.locales import DEFAULT_LOCALE, LANGUAGE_NAMES, SUPPORTED_LOCALES

__all__ = [
    "DEFAULT_LOCALE",
    "TURN_LANGUAGE",
    "conversation_language_from_history",
    "detect_conversation_language",
    "normalize_any_language_tag",
    "resolve_conversation_language",
    "OutputLanguageValidation",
    "detect_language_request",
    "detect_text_language",
    "is_substantive_turn",
    "normalize_language_tag",
    "resolve_output_language",
    "resolve_transcript_language",
    "resolve_turn_language",
    "validate_output_language",
]

# ``DEFAULT_LOCALE`` (imported above, re-exported) is the fallback language of
# every system phrase: a turn whose language cannot be detected, or is one
# without translated phrases, AND no ``brain.reply_language`` pin. ONE shared
# constant so every output layer agrees instead of each hardcoding its own (the
# historical "pipeline defaults en, action phrases default de" split).

#: The person's language for the brain turn running in this context (any code,
#: or "unknown"), resolved once at the top of ``BrainManager.generate()`` and
#: scoped to that call. Concurrent turns (a chat and a voice call) each read
#: their own; a system phrase deep in a turn reads it instead of re-deriving
#: the language from text that may be an internal English prompt. ``None``
#: outside a turn, ``""`` inside one before the language is known.
TURN_LANGUAGE: ContextVar[str | None] = ContextVar("jarvis.turn_language", default=None)

#: The codes an explicit ``brain.reply_language`` pin may carry when that pin
#: also selects translated system phrases (``"auto"`` is deliberately absent —
#: it means "no pin, mirror the input"). French is a speech pin without a
#: catalog; it lives on the brain's reply-language set, not here.
_REPLY_PINS: frozenset[str] = frozenset(SUPPORTED_LOCALES)

#: A turn with at most this many word tokens is a "thin" turn — a one- or
#: two-word interjection ("Now", "Stop now", "jetzt", a lone loanword). A thin
#: turn must NOT redefine an established conversation's language; it is spoken in
#: the conversation language instead. Explicit corrections are substantive even
#: when short. Natural-flow forensic 2026-06-18: a single English "Now" in
#: a German voice chat flipped the whole turn to English.
_THIN_TURN_MAX_TOKENS = 2

#: Evidence a thin turn needs to switch into a language without translated
#: phrases: its own script (10), or a letter of it (3) plus one of its words.
_THIN_TURN_SWITCH_EVIDENCE = 4

_TOKEN_RE = re.compile(r"\b[\w']+\b", re.UNICODE)

# Match complete language instructions, never a language name embedded in a
# translation, quotation, negation, or task. The vocabulary is speech input.
_LANGUAGE_REQUEST_RE = re.compile(
    r"(?:jarvis[\s,]+)?"
    r"(?:(?:please|bitte|por favor)[\s,]+)?"  # i18n-allow
    r"(?:(?:always|from now on|immer|ab jetzt|siempre|a partir de ahora|sempre"  # i18n-allow
    r"|a partir de agora)\s+)?"  # i18n-allow
    r"(?:(?:can|could|would) you\s+|(?:kannst|könntest) du\s+|puedes\s+"  # i18n-allow
    r"|(?:podes|consegues|pode|podia|podias)\s+)?"  # i18n-allow
    r"(?:(?:please|bitte|por favor)\s+)?"  # i18n-allow
    r"(?:(?:speak|reply|respond|answer|write|continue|switch)(?:\s+to me)?\s+"
    r"|(?:sprich|spreche|antworte|antworten|schreib|schreibe|rede|wechsel|wechsle)\s+"  # i18n-allow
    r"|(?:sollst|du sollst)\s+"  # i18n-allow
    r"|(?:habla|háblame|responde|contesta|escribe|cambia)\s+"
    r"|(?:fala|fale|falar|responde|responda|responder|escreve|escreva|escrever"  # i18n-allow
    r"|muda|mude|passa|continua)(?:-me)?(?:\s+comigo)?\s+)?"  # i18n-allow
    r"(?:(?:please|bitte|por favor)\s+)?"  # i18n-allow
    r"(?:(?:always|from now on|immer|ab jetzt|siempre|a partir de ahora|sempre"  # i18n-allow
    r"|a partir de agora)\s+)?"  # i18n-allow
    r"(?:(?:in|auf|en|to|zu|a|em|para)\s+)?"  # i18n-allow
    r"(?P<language>deutsch|german|alemán|aleman|english|englisch|inglés|ingles"  # i18n-allow
    r"|español|espanol|spanish|spanisch"  # i18n-allow
    r"|português|portugues|portugués|portuguese|portugiesisch"  # i18n-allow
    r"|alemão|alemao|inglês|espanhol"  # i18n-allow
    r"|turkish|türkisch|türkçe|turkce|french|französisch|italian|italienisch"  # i18n-allow
    r"|dutch|niederländisch|polish|polnisch|russian|russisch|greek|griechisch"  # i18n-allow
    r"|arabic|arabisch|japanese|japanisch|korean|koreanisch|chinese|chinesisch)"  # i18n-allow
    r"(?:\s+(?:antworten|sprechen|konuş|konus|cevap ver))?"  # i18n-allow
    r"(?:[\s,]+(?:please|bitte|por favor|now|jetzt|ahora|agora))?"  # i18n-allow
    r"[\s.!?]*",
    re.IGNORECASE,
)
_REQUEST_LANGUAGE_CODES = {
    "deutsch": "de", "german": "de", "alemán": "de", "aleman": "de",  # i18n-allow
    "english": "en", "englisch": "en", "inglés": "en", "ingles": "en",  # i18n-allow
    "español": "es", "espanol": "es", "spanish": "es", "spanisch": "es",  # i18n-allow
    "português": "pt", "portugues": "pt", "portugués": "pt",  # i18n-allow
    "portuguese": "pt", "portugiesisch": "pt",  # i18n-allow
    "alemão": "de", "alemao": "de", "inglês": "en", "espanhol": "es",  # i18n-allow
    # Languages without translated system phrases: the model still answers in them.
    "turkish": "tr", "türkisch": "tr", "türkçe": "tr", "turkce": "tr",  # i18n-allow
    "french": "fr", "französisch": "fr", "italian": "it", "italienisch": "it",  # i18n-allow
    "dutch": "nl", "niederländisch": "nl", "polish": "pl", "polnisch": "pl",  # i18n-allow
    "russian": "ru", "russisch": "ru", "greek": "el", "griechisch": "el",  # i18n-allow
    "arabic": "ar", "arabisch": "ar", "japanese": "ja", "japanisch": "ja",  # i18n-allow
    "korean": "ko", "koreanisch": "ko", "chinese": "zh", "chinesisch": "zh",  # i18n-allow
}

# Output validation deliberately ignores code and links. They frequently carry
# English keywords or non-Latin identifiers regardless of the language of the
# surrounding answer, so treating them as prose would create false positives.
_CODE_FENCE_RE = re.compile(r"```.*?```", re.DOTALL)
_INLINE_CODE_RE = re.compile(r"`[^`\r\n]*`")
_URL_RE = re.compile(r"\b(?:https?://|www\.)\S+", re.IGNORECASE)

# Han text has a unique script signal. A ratio is still required so a German,
# English, or Spanish sentence containing a Chinese name remains valid.
_HAN_RE = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]")
_LATIN_LETTER_RE = re.compile(r"[A-Za-z\u00c0-\u024f]")
_MIN_GROSS_HAN_CHARS = 10

# Vietnamese uses Latin script, so script alone is insufficient. The validator
# combines its characteristic letters/tones with a vocabulary signal and only
# returns a verdict when both make a gross mismatch unambiguous.
_VI_DISTINCTIVE_CHAR_RE = re.compile(
    r"[\u0103\u00e2\u0111\u00ea\u00f4\u01a1\u01b0"
    r"\u1ea3\u1ea1\u1eb1\u1eaf\u1eb3\u1eb5\u1eb7"
    r"\u1ea7\u1ea5\u1ea9\u1eab\u1ead\u1ebb\u1ebd\u1eb9"
    r"\u1ec1\u1ebf\u1ec3\u1ec5\u1ec7\u1ec9\u1ecb"
    r"\u1ecf\u1ecd\u1ed3\u1ed1\u1ed5\u1ed7\u1ed9"
    r"\u1edd\u1edb\u1edf\u1ee1\u1ee3\u1ee7\u1ee5"
    r"\u1eeb\u1ee9\u1eed\u1eef\u1ef1\u1ef3\u1ef7\u1ef9\u1ef5]",
    re.IGNORECASE,
)
_VI_TOKENS: frozenset[str] = frozenset(
    """
    bạn bằng các chào chúng có của đã được giúp hãy không là một này người
    những sẽ thể tiếng tôi việt với
    """.split()
)

OutputLanguageStatus = Literal["match", "mismatch", "indeterminate"]


@dataclass(frozen=True, slots=True)
class OutputLanguageValidation:
    """Deterministic verdict for text checked against a resolved turn language.

    ``indeterminate`` is intentionally fail-open: short replies, code, names,
    numbers, and ambiguous prose do not provide enough evidence to suppress
    user-facing output. Only ``mismatch`` is safe to block before text/audio
    release.
    """

    status: OutputLanguageStatus
    resolved_language: str
    detected_language: str

    @property
    def should_block(self) -> bool:
        """Whether the caller should suppress this output and retry/fallback."""
        return self.status == "mismatch"


# Strong script signals: German-specific letters, Spanish ñ and inverted
# punctuation, and Portuguese nasal vowels, cedilla and circumflexes. The acute
# vowels á/í/ó/ú are written in BOTH Spanish and Portuguese, so they only add a
# weak point to each of the two (the pan-European acute-e counts for nothing).
_DE_SCRIPT_RE = re.compile(r"[äöüÄÖÜß]")  # i18n-allow: German-script regex
_ES_SCRIPT_RE = re.compile(r"[ñÑ¿¡]")
_PT_SCRIPT_RE = re.compile(r"[ãõçâêôàÃÕÇÂÊÔÀ]")
_IBERIAN_ACUTE_RE = re.compile(r"[áíóúÁÍÓÚ]")

# Function-word sets, kept mutually disjoint. Words common to more than one of
# the supported languages are excluded on purpose (see module docstring).
_DE_TOKENS: frozenset[str] = frozenset({
    "der", "die", "das", "den", "dem", "des", "ein", "eine", "einen", "einem",  # i18n-allow
    "und", "oder", "aber", "nicht", "ist", "sind", "bin", "bist", "wird",  # i18n-allow
    "ich", "du", "wir", "ihr", "mir", "mich", "dir", "dich", "uns", "euch",  # i18n-allow
    "bitte", "danke", "wie", "wo", "wann", "warum", "wieso", "welche",  # i18n-allow
    "kann", "kannst", "koennen", "können", "soll", "sollst", "muss", "musst",  # i18n-allow
    "mach", "mache", "machst", "macht", "oeffne", "öffne", "zeig", "zeige",  # i18n-allow
    "lies", "sag", "schreib", "heute", "morgen", "jetzt", "gleich", "schon",  # i18n-allow
    "noch", "auch", "doch", "mal", "sehr", "gut", "ja", "nein", "kein",  # i18n-allow
    "keine", "mein", "meine", "dein", "deine", "fuer", "für", "mit", "von",  # i18n-allow
    "auf", "aus", "bei", "nach", "ueber", "über", "wetter", "geht", "gibt",  # i18n-allow
})
_EN_TOKENS: frozenset[str] = frozenset({
    "the", "and", "you", "your", "that", "this", "these", "those", "with",
    "for", "what", "what's", "whats", "how", "when", "where", "why", "who",
    "which", "can", "can't", "could", "couldn't", "would", "should", "will",
    "won't", "please", "tell", "give", "show", "open", "read", "write",
    "is", "isn't", "are", "aren't", "do", "does", "did", "don't", "doesn't",
    "it", "it's", "its", "like", "today", "tomorrow", "tonight", "now",
    "yes", "thanks", "thank", "hello", "of", "to", "from", "my", "mine",
    "our", "have", "has", "had", "want", "need", "get", "got", "going",
    "be", "been", "i'm", "i", "we", "they", "he", "she", "weather",
    "yesterday",
})
# Spanish words also common in Portuguese ("que", "como", "por", "favor",
# "para", "está", "estás", "abre", "clima") are excluded.
_ES_TOKENS: frozenset[str] = frozenset({
    "el", "la", "los", "las", "un", "una", "unos", "unas", "qué",
    "cómo", "cuándo", "cuando", "dónde", "donde", "quién", "quien",
    "hace", "hacer", "hoy", "mañana", "ahora", "estoy", "tiempo", "gracias",
    "hola", "sí", "puedes", "puedo", "puede", "quiero", "necesito", "dime",
    "dame", "muestra", "lee", "escribe", "y", "pero", "con", "del", "al",
    "muy", "bien", "hay", "yo", "tú", "lo", "eso", "esto", "también",
    "entonces", "tengo",
})
# Portuguese words also common in Spanish, German or English ("que", "para",
# "está", "da", "dos", "das", "um", "as", "do", "o", "e", "na", "tu", "porque",
# "com" — a ".com" domain) are excluded.
_PT_TOKENS: frozenset[str] = frozenset({
    "não", "nao", "você", "voce", "obrigado", "obrigada", "também", "tambem",
    "então", "entao", "isso", "isto", "muito", "muita", "uma", "os", "ao",
    "à", "pelo", "pela", "num", "numa", "eu", "ele", "ela", "nós", "sim",
    "olá", "ola", "bom", "boa", "fazer", "faz", "ficheiro", "ecrã", "agora",
    "quando", "mais", "já", "só", "é", "estou", "tenho", "tens", "podes",
    "pode", "consegues", "queres", "quero", "vou", "vai", "hoje", "amanhã",
    "onde", "meu", "minha", "teu", "tua", "sua", "em", "tempo", "ainda",
    "depois", "tudo", "coisa", "diz", "dizer", "mostra", "escreve", "lê",
    "são", "foi", "bem", "neste", "nesta", "nesse", "nessa",
})

_SETS: tuple[tuple[str, frozenset[str]], ...] = (
    ("de", _DE_TOKENS),
    ("en", _EN_TOKENS),
    ("es", _ES_TOKENS),
    ("pt", _PT_TOKENS),
)

# Whisper cloud APIs return language NAMES; local faster-whisper returns ISO
# codes; some TTS configs use BCP-47 ("pt-PT", "pt-BR"). All collapse to
# de/en/es/pt here.
_TAG_TO_CODE: dict[str, str] = {
    "de": "de", "deu": "de", "ger": "de", "german": "de", "deutsch": "de",
    "en": "en", "eng": "en", "english": "en", "englisch": "en",
    "es": "es", "spa": "es", "spanish": "es", "spanisch": "es",
    "espanol": "es", "español": "es", "castellano": "es",
    "pt": "pt", "por": "pt", "portuguese": "pt", "português": "pt",  # i18n-allow
    "portugues": "pt", "portugués": "pt", "portugiesisch": "pt",  # i18n-allow
}


def normalize_language_tag(tag: object) -> str:
    """Collapse an STT/TTS tag to ``de``/``en``/``es``/``pt``/``unknown``."""
    if not tag:
        return "unknown"
    head = str(tag).strip().lower().replace("_", "-").split("-", 1)[0]
    return _TAG_TO_CODE.get(head, "unknown")


# --- Languages without translated system phrases --------------------------
#
# The four supported languages are not the only ones people speak. Without a
# way to say "this is something else", Turkish scored as German on umlauts, as
# Portuguese on the cedilla and as Spanish on "al"/"el", so the conversation language
# jumped between them and the model was told to answer in each in turn
# (forensic 2026-10-19). These signals only have to recognise that a text is
# in another language; they never decide between the four.

# Whisper reports language NAMES; local STT reports ISO codes.
_OTHER_TAG_TO_CODE: dict[str, str] = {
    **{code: code for code in LANGUAGE_NAMES if code not in _REPLY_PINS},
    **{
        name.lower(): code
        for code, name in LANGUAGE_NAMES.items()
        if code not in _REPLY_PINS
    },
    "tur": "tr", "fra": "fr", "fre": "fr", "ita": "it", "nld": "nl", "dut": "nl",
    "pol": "pl", "ces": "cs", "cze": "cs", "ron": "ro", "rum": "ro", "hun": "hu",
    "rus": "ru", "ukr": "uk", "ell": "el", "gre": "el", "ara": "ar", "fas": "fa",
    "per": "fa", "heb": "he", "hin": "hi", "tha": "th", "jpn": "ja", "kor": "ko",
    "zho": "zh", "chi": "zh", "vie": "vi", "mandarin": "zh", "cantonese": "zh",
    "farsi": "fa",
}

# Non-Latin scripts: the script itself names the language.
_SCRIPT_LANGUAGES: tuple[tuple[str, re.Pattern[str]], ...] = (
    ("ja", re.compile(r"[\u3040-\u30ff]")),  # kana (checked before Han)
    ("ko", re.compile(r"[\uac00-\ud7af\u1100-\u11ff]")),  # Hangul
    ("zh", _HAN_RE),
    ("uk", re.compile(r"[\u0456\u0457\u0454\u0491\u0406\u0407\u0404\u0490]")),
    ("ru", re.compile(r"[\u0400-\u04ff]")),  # Cyrillic
    ("el", re.compile(r"[\u0370-\u03ff]")),  # Greek
    ("fa", re.compile(r"[\u067e\u0686\u0698\u06af\u06cc]")),  # Persian letters
    ("ar", re.compile(r"[\u0600-\u06ff]")),  # Arabic script
    ("he", re.compile(r"[\u0590-\u05ff]")),  # Hebrew
    ("hi", re.compile(r"[\u0900-\u097f]")),  # Devanagari
    ("th", re.compile(r"[\u0e00-\u0e7f]")),  # Thai
)
_ANY_LETTER_RE = re.compile(r"[^\W\d_]", re.UNICODE)

# The wider script a marker-letter language is written in: Ukrainian letters
# inside a mostly Cyrillic text, Persian letters inside a mostly Arabic one.
_SCRIPT_MARKERS: dict[str, re.Pattern[str]] = {
    "uk": re.compile(r"[\u0400-\u04ff]"),
    "fa": re.compile(r"[\u0600-\u06ff]"),
}

# Latin-script letters no supported language writes.
_OTHER_LATIN_CHARS: dict[str, re.Pattern[str]] = {
    "tr": re.compile(r"[\u0131\u0130\u011f\u011e\u015f\u015e]"),  # ı İ ğ Ğ ş Ş
    "pl": re.compile(
        r"[\u0142\u0141\u0105\u0104\u0119\u0118\u015b\u015a\u017a\u0179"
        r"\u017c\u017b\u0144\u0143\u0107\u0106]"
    ),  # ł ą ę ś ź ż ń ć
    "cs": re.compile(r"[\u0159\u0158\u011b\u011a\u016f\u016e]"),  # ř ě ů
    "ro": re.compile(r"[\u0103\u0102\u0219\u0218\u021b\u021a]"),  # ă ș ț
    "hu": re.compile(r"[\u0151\u0150\u0171\u0170]"),  # ő ű
    "fr": re.compile(r"[\u0153\u0152]"),  # œ
}

# Function words of languages without translated phrases. Disjoint from the
# supported sets AND from words everyday German, English, Spanish or Portuguese
# use outside those sets ("nie", "sie", "le", "mi", "este", "van", "most", ...):
# a supported sentence must never read as another language. Guarded by
# tests/unit/brain/test_conversation_language_retention.py.
_SUPPORTED_COMMON_WORDS: frozenset[str] = frozenset(
    (
        "nie sie mit sei so man war am im um an in es da wo was wer hat hab habe le "  # i18n-allow
        "les me te se su sus mi mis tu tus al del ama sana hala sur tres uno una "  # i18n-allow
        "cosa mio mia tuo tua este esta eso nem ano nu eu ele ela posso mas ma van "  # i18n-allow
        "met op dank most mam bestand comment ne "  # i18n-allow
    ).split()
)


_OTHER_TOKENS: dict[str, frozenset[str]] = {
    code: frozenset(words.split()) - _SUPPORTED_COMMON_WORDS
    for code, words in {
        "tr": (
            "ve bir bu şu için icin ile mı mu mü misin mısın musun müsün miyim değil "  # i18n-allow
            "degil var yok sen biz siz onlar onu bunu şunu bana beni seni benim "  # i18n-allow
            "senin bizim çok cok daha gibi fakat nasıl nasil neden niye nerede şimdi "  # i18n-allow
            "simdi bugün bugun yarın yarin dün evet hayır hayir lütfen lutfen "  # i18n-allow
            "teşekkürler tesekkurler teşekkür sağol merhaba selam tamam iyi kadar "  # i18n-allow
            "sonra önce hiç hep şey sey yap yapar yapabilir yapıyorsun yapıyor olur "  # i18n-allow
            "oldu olarak hata dosya dosyayı aç kapat göster söyle yaz oku istiyorum "  # i18n-allow
            "lazım gerek çalışmıyor çalışıyor bitti mesaj neler nedir hangi niçin "  # i18n-allow
            "artık demek "  # i18n-allow
        ),
        "fr": (
            "est je vous nous pas une au aux avec pour dans ce cette qui quoi pourquoi "  # i18n-allow
            "bonjour merci oui très où c'est j'ai suis sont avez peux faire fais moi "  # i18n-allow
            "toi ça aujourd'hui demain fichier ouvre montre s'il plaît plait qu'est "  # i18n-allow
            "voudrais savoir marche "  # i18n-allow
        ),
        "it": (
            "che sono è questo questa quello perché perche grazie ciao buongiorno "  # i18n-allow
            "anche ancora molto fare puoi voglio della dello degli nel nella sul "  # i18n-allow
            "alla gli dove oggi domani adesso io ho hai abbiamo di stai "  # i18n-allow
        ),
        "nl": (
            "het een ik jij niet wat hoe waarom waar wanneer bedankt alsjeblieft "  # i18n-allow
            "alstublieft goed graag kun kunt kan mijn jouw zijn hebben heb deze dit "  # i18n-allow
            "dat voor naar nog ook maar vandaag zeg laat toon gaat "  # i18n-allow
        ),
        "pl": (
            "jest się jak co czy dlaczego gdzie kiedy proszę prosze dziękuję "  # i18n-allow
            "dziekuje dzień dzien dobry tak masz jestem ty mój moj moja może moze "  # i18n-allow
            "teraz dzisiaj jutro plik otwórz pokaż że ze "  # i18n-allow
        ),
        "cs": (
            "není neni jsem jsi proč proc kde kdy děkuji dekuji prosím prosim dobrý "  # i18n-allow
            "dobry "  # i18n-allow
        ),
        "ro": (
            "și sunt mulțumesc multumesc bună pentru cu acum astăzi astazi mâine "  # i18n-allow
            "maine vă rog "  # i18n-allow
        ),
        "hu": (
            "igen köszönöm koszonom és hogy nincs kérem kerem szia holnap egy az ez "  # i18n-allow
            "miért miert hol mikor "  # i18n-allow
        ),
    }.items()
}


def normalize_any_language_tag(tag: object) -> str:
    """Like :func:`normalize_language_tag`, but also places languages without
    translated phrases (``"turkish"`` -> ``"tr"``); ``"unknown"`` otherwise."""
    code = normalize_language_tag(tag)
    if code != "unknown" or not tag:
        return code
    text = str(tag).strip().lower().replace("_", "-")
    return _OTHER_TAG_TO_CODE.get(text) or _OTHER_TAG_TO_CODE.get(
        text.split("-", 1)[0], "unknown"
    )


def _detect_script_language(text: str) -> str:
    """A non-Latin script that makes up most of the letters, else ``""``."""
    letters = len(_ANY_LETTER_RE.findall(text))
    if not letters:
        return ""
    for code, pattern in _SCRIPT_LANGUAGES:
        found = len(pattern.findall(text))
        if code == "ja" and found:
            # Kana only appear in Japanese; Han may make up most of it.
            if found + len(_HAN_RE.findall(text)) >= max(2, letters / 2):
                return code
            continue
        if found >= 2 and found >= letters / 2:
            return code
        if code in _SCRIPT_MARKERS and found:
            if len(_SCRIPT_MARKERS[code].findall(text)) >= max(2, letters / 2):
                return code
    return ""


def _other_language_scores(text: str, tokens: set[str]) -> dict[str, int]:
    scores = {code: len(tokens & vocabulary) for code, vocabulary in _OTHER_TOKENS.items()}
    for code, pattern in _OTHER_LATIN_CHARS.items():
        if pattern.search(text):
            scores[code] = scores.get(code, 0) + 3
    return scores


def _detect_other_language(text: str) -> tuple[str, int]:
    """``(code, evidence)`` when *text* is in a language without translated
    phrases, else ``("", 0)``.

    It must beat every supported language on the same text, so a German
    sentence that mentions "Łukasz" or "Istanbul" stays German.
    """
    script = _detect_script_language(text)
    if script:
        return script, 10
    words = [tok.lower() for tok in _TOKEN_RE.findall(text)]
    if _detect_gross_vietnamese_output(text, words):
        return "vi", 10
    tokens = set(words)
    other = _other_language_scores(text, tokens)
    best_code, best = max(other.items(), key=lambda kv: kv[1])
    if best < 2 or sum(1 for value in other.values() if value == best) > 1:
        return "", 0
    supported = {code: len(tokens & vocab) for code, vocab in _SETS}
    _add_script_scores(text, supported)
    supported_best = max(supported.values())
    if best <= supported_best:
        return "", 0
    if supported_best and not tokens & _OTHER_TOKENS.get(best_code, frozenset()):
        # Only a letter, inside a sentence with supported words: a name
        # ("Ruf bitte Łukasz an"), not a language.
        return "", 0
    return best_code, best


def detect_conversation_language(text: str) -> str:
    """The language *text* is written in, supported or not, else ``unknown``.

    ``de``/``en``/``es``/``pt`` as :func:`detect_text_language` finds them;
    any other recognised language by its code (``tr``, ``fr``, ``ru``, ...).
    This answers "which language should the model reply in". Which language
    a system phrase uses is a separate step (:func:`dodaios.i18n.phrase_locale`).
    """
    t = (text or "").strip()
    if not t:
        return "unknown"
    other, _evidence = _detect_other_language(t)
    if other:
        return other
    return _detect_supported_language(t)


def detect_text_language(text: str) -> str:
    """Classify *text* as ``de``/``en``/``es``/``pt`` — or ``unknown`` when unclear.

    A language must score strictly higher than every other to win; ties and
    zero-overlap text (proper nouns, "ok") return ``"unknown"`` so the caller
    can fall back to the STT tag. Text in another recognisable language
    (Turkish, French, Russian, ...) is ``"unknown"`` too: it is NOT the
    supported language whose letters it happens to share.
    """
    t = (text or "").strip()
    if not t:
        return "unknown"
    if _detect_other_language(t)[0]:
        return "unknown"
    return _detect_supported_language(t)


def _detect_supported_language(t: str) -> str:
    tokens = {tok.lower() for tok in _TOKEN_RE.findall(t)}
    scores = {code: len(tokens & vocab) for code, vocab in _SETS}
    _add_script_scores(t, scores)
    best_code, best = max(scores.items(), key=lambda kv: kv[1])
    if best == 0 or sum(1 for s in scores.values() if s == best) > 1:
        return "unknown"
    return best_code


def _add_script_scores(text: str, scores: dict[str, int]) -> None:
    """Add the character-level hints shared by input and output detection."""
    if _DE_SCRIPT_RE.search(text):
        scores["de"] += 2
    if _ES_SCRIPT_RE.search(text):
        scores["es"] += 2
    if _PT_SCRIPT_RE.search(text):
        scores["pt"] += 2
    if _IBERIAN_ACUTE_RE.search(text):
        scores["es"] += 1
        scores["pt"] += 1


def _prose_for_output_validation(text: str) -> str:
    """Remove content whose syntax is not evidence of the reply language."""
    prose = unicodedata.normalize("NFC", text or "")
    prose = _CODE_FENCE_RE.sub(" ", prose)
    prose = _INLINE_CODE_RE.sub(" ", prose)
    return _URL_RE.sub(" ", prose).strip()


def _detect_gross_han_output(text: str) -> bool:
    han_count = len(_HAN_RE.findall(text))
    # A short Han span is commonly a person, organization, or product name,
    # including a compact label value. It is not enough evidence to suppress
    # an otherwise correctly resolved answer.
    if han_count < _MIN_GROSS_HAN_CHARS:
        return False
    latin_count = len(_LATIN_LETTER_RE.findall(text))
    script_ratio = han_count / max(1, han_count + latin_count)
    return script_ratio >= 0.55


def _detect_gross_vietnamese_output(text: str, tokens: list[str]) -> bool:
    if len(tokens) < 5:
        return False
    characteristic_chars = len(_VI_DISTINCTIVE_CHAR_RE.findall(text))
    distinct_vocabulary_hits = len(set(tokens) & _VI_TOKENS)
    return characteristic_chars >= 2 and distinct_vocabulary_hits >= 2


def _detect_strong_supported_output(text: str, tokens: list[str]) -> str:
    """Return de/en/es/pt only when multiple independent prose signals agree."""
    if len(tokens) < 4:
        return "unknown"
    scores = {
        code: sum(token in vocabulary for token in tokens)
        for code, vocabulary in _SETS
    }
    _add_script_scores(text, scores)
    ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)
    (best_code, best_score), (_, second_score) = ranked[:2]
    if best_score < 3 or best_score == second_score:
        return "unknown"
    return best_code


def validate_output_language(
    text: str,
    *,
    resolved_language: object,
) -> OutputLanguageValidation:
    """Validate reply *text* against a resolved ``de``/``en``/``es``/``pt``.

    The target MUST come from :func:`resolve_output_language`; this function
    never derives or changes the turn language. It only detects high-confidence
    output corruption before text or audio is released. Detection is regex/set
    based, has no IO or model call, and treats uncertain content as
    ``indeterminate`` (non-blocking).
    """
    target = normalize_language_tag(resolved_language)
    if target not in _REPLY_PINS:
        return OutputLanguageValidation("indeterminate", target, "unknown")

    prose = _prose_for_output_validation(text)
    if not prose:
        return OutputLanguageValidation("indeterminate", target, "unknown")

    if _detect_gross_han_output(prose):
        detected = "zh"
    else:
        tokens = [token.lower() for token in _TOKEN_RE.findall(prose)]
        if _detect_gross_vietnamese_output(prose, tokens):
            detected = "vi"
        else:
            detected = _detect_strong_supported_output(prose, tokens)

    if detected == "unknown":
        status: OutputLanguageStatus = "indeterminate"
    elif detected == target:
        status = "match"
    else:
        status = "mismatch"
    return OutputLanguageValidation(status, target, detected)


def resolve_turn_language(
    stt_language: object, text: str, *, default: str = "en"
) -> str:
    """Resolve the language of a turn: text first, STT tag second, default last.

    The transcribed text is the most reliable signal — the STT tag merely
    echoes a configured pin when ``[stt].language`` is set (the 2026-06-10
    live bug). Only ambiguous text defers to the tag.
    """
    detected = detect_text_language(text)
    if detected != "unknown":
        return detected
    code = normalize_language_tag(stt_language)
    if code != "unknown":
        return code
    return default


def resolve_transcript_language(reported: object, text: str) -> str:
    """Which language a TRANSCRIPT may be run through text rules as.

    Sibling of :func:`resolve_turn_language`, and deliberately stricter: that
    one answers "which language do we SPEAK back", where a wrong guess sounds
    odd; this one answers "whose word list may DELETE tokens from what the user
    said", where a wrong guess removes content and reports success. Returns a
    code (``de`` / ``en`` / ``es`` / ``pt``) or ``"unknown"`` — and ``"unknown"`` means
    *run no language's rules*, never *pick a default*.

    Precedence, and the order is the whole point:

    1. **A tag we cannot place stays unplaced.** ``detect_text_language`` only
       knows four languages, so letting it overrule a "French" or "ja" tag
       would relabel that utterance as whichever of the four it scored highest
       on and then run THAT language's word lists over it. ``unknown`` is the
       honest answer for ~95 of the 100 recognition languages STT supports.
    2. **Otherwise the TEXT outranks a tag that contradicts it.** The cloud
       Whisper APIs report a language on every request and report it
       confidently when it is wrong — the live history has German utterances
       tagged "English", and ``[stt].language`` pins make the provider echo the
       pin back for speech in any language at all (forensic 2026-06-10). A
       filler list applied on that word deletes function words from a sentence
       it has no business touching: German "um" is the English hesitation
       sound, so the transcript came back grammatically broken while the
       cleanup reported a clean success (2026-07-30)::

           "Kümmere dich um das Update" -> "Kümmere dich das Update"  # i18n-allow
    3. **Ambiguous text defers to the tag.** Text too short or too neutral to
       place ("ok", a bare proper noun) leaves the provider's reading standing.

    Pure set lookups, no IO — safe on the voice critical path.
    """
    lowered = str(reported or "").strip().lower()
    tag_code = normalize_language_tag(lowered)
    if not (text or "").strip():
        return tag_code
    if _detect_other_language(text)[0]:
        # Another language: no supported word list may touch it, whatever a
        # pinned STT tag echoes.
        return "unknown"
    detected = detect_text_language(text)
    if detected != "unknown" and (
        # Nothing to contradict: no tag at all, or one that says "I could not
        # tell".
        lowered in ("", "auto", "unknown", "und")
        # A tag we CAN place, which the text disagrees with.
        or (tag_code != "unknown" and tag_code != detected)
    ):
        return detected
    return tag_code


def is_substantive_turn(text: str) -> bool:
    """True if *text* is substantial or explicitly requests a reply language.

    A one- or two-word interjection ("Now", "Stop now", "jetzt", a lone
    loanword) is NOT substantive — it inherits the running conversation language
    rather than switching it. Used by the conversation-stickiness logic so a
    stray English word never flips an established German chat. A short explicit
    language correction provides intent without needing a longer utterance.
    """
    return (
        bool(detect_language_request(text))
        or len(_TOKEN_RE.findall(text or "")) > _THIN_TURN_MAX_TOKENS
    )


def detect_language_request(text: str) -> str:
    """Return the requested reply language of a complete instruction, else "".

    Full matching deliberately excludes quoted/reported speech, translation
    content, and negative commands. A bare language name alone is ambiguous;
    it needs a command, preposition, or politeness marker to establish intent.
    """
    value = unicodedata.normalize("NFC", text or "").strip()
    match = _LANGUAGE_REQUEST_RE.fullmatch(value)
    if match is None or len(_TOKEN_RE.findall(value)) < 2:
        return ""
    return _REQUEST_LANGUAGE_CODES[match.group("language").lower()]


def _has_language_switch_evidence(text: str, detected: str) -> bool:
    """Require independent vocabulary evidence before replacing sticky state.

    A lone accented name, repeated loanword, or provider language tag is too
    weak to redefine a conversation. Existing text detection still handles a
    first turn, for which there is no established language to protect. A
    language without translated phrases carries its own evidence: the
    detector only names it on several matching words or its own script.
    """
    if detected not in SUPPORTED_LOCALES:
        return detected != "unknown" and _detect_other_language(text or "")[0] == detected
    tokens = {token.lower() for token in _TOKEN_RE.findall(text or "")}
    scores = {code: len(tokens & vocabulary) for code, vocabulary in _SETS}
    score = scores.get(detected, 0)
    runner_up = max(value for code, value in scores.items() if code != detected)
    return score >= 2 and score - runner_up >= 2


def _known_language(code: object) -> str:
    value = str(code or "").strip().lower()
    return value if value in LANGUAGE_NAMES else ""


def resolve_conversation_language(
    reply_language: object,
    stt_language: object,
    text: str,
    *,
    conversation_language: object = "",
) -> str:
    """The language the person is speaking in this turn: any code, or ``unknown``.

    This is what the MODEL is told to answer in, so it is not limited to the
    languages with translated system phrases: a Turkish conversation stays
    Turkish. :func:`resolve_output_language` narrows it to a phrase language.

    Precedence, highest first:

    1. an explicit ``brain.reply_language`` pin (``de``/``en``/``es``/``pt``) — the
       user-selected language wins over everything, including what STT heard;
    2. else an explicit language instruction, even a two-word correction;
    3. else, in auto mode, conversation stickiness: a "thin" turn (a one- or
       two-word interjection like "Now"/"Stop"/"jetzt", or a lone loanword) is
       in ``conversation_language`` — it must NOT flip an established
       conversation. A switch needs independent text evidence; STT tags alone
       cannot replace an established language;
    4. else the detected language of the turn (text first, the STT tag breaks
       ties), an ambiguous substantive turn inheriting ``conversation_language``;
    5. else ``"unknown"``.
    """
    pin = str(reply_language or "").strip().lower()
    if pin in _REPLY_PINS:
        return pin
    requested = detect_language_request(text)
    if requested:
        return requested
    conv = _known_language(conversation_language)
    detected = detect_conversation_language(text)
    if conv and len(_TOKEN_RE.findall(text or "")) <= _THIN_TURN_MAX_TOKENS:
        # A short turn only switches on unmistakable evidence: its own script,
        # or a letter AND a word of a language without translated phrases
        # ("Dosyayı aç"). "Now" or "ok" never does.
        other, evidence = _detect_other_language(text or "")
        if other and other != conv and evidence >= _THIN_TURN_SWITCH_EVIDENCE:
            return other
        return conv
    if conv:
        if detected == conv or not _has_language_switch_evidence(text, detected):
            return conv
        return detected
    if detected != "unknown":
        return detected
    return normalize_any_language_tag(stt_language)


def resolve_output_language(
    reply_language: object,
    stt_language: object,
    text: str,
    *,
    default: str = DEFAULT_LOCALE,
    conversation_language: object = "",
) -> str:
    """The SINGLE authoritative output language for one turn (de/en/es/pt).

    Every spoken or written layer — the deep-brain reply, the ack-brain
    preamble, spawn announcements, every canned status / error / clarify /
    timeout / provider-down phrase, the deterministic Computer-Use readbacks,
    and the TTS voice pin — must resolve language through THIS function so no
    layer can diverge from another (2026-06-18 forensic).

    It is :func:`resolve_conversation_language` narrowed to the languages
    with translated phrases: a supported language is itself; a language
    without translations (Turkish, French, ...) is ``DEFAULT_LOCALE``
    (English) — never the supported language it happens to resemble
    (forensic 2026-10-19); an undetectable turn is ``default``.

    ``reply_language`` is tolerant: case/whitespace-insensitive, and any value
    that is not a pin (``"auto"``, ``""``, ``None``, a typo) means "no pin —
    mirror the input". ``conversation_language`` is the language of the
    conversation so far (any code); pass ``""`` when none is established yet.
    """
    language = resolve_conversation_language(
        reply_language,
        stt_language,
        text,
        conversation_language=conversation_language,
    )
    if language in _REPLY_PINS:
        return language
    if language == "unknown":
        return default
    return DEFAULT_LOCALE


def conversation_language_from_history(
    messages: Iterable[object], *, reply_language: object = None
) -> str:
    """The conversation language a stored history establishes, else ``""``.

    Replays the person's own messages through the same stickiness rules as a
    live turn, so a chat restored after a crash or restart picks up the
    language it was in instead of starting from nothing. Accepts brain
    messages (``.role``/``.content``) or plain ``{"role", "content"}`` dicts;
    only ``user`` text counts.
    """
    language = ""
    for message in messages:
        if isinstance(message, Mapping):
            role, content = message.get("role"), message.get("content")
        else:
            role, content = getattr(message, "role", None), getattr(message, "content", None)
        if role != "user" or not isinstance(content, str) or not content.strip():
            continue
        resolved = resolve_conversation_language(
            reply_language, None, content, conversation_language=language
        )
        if resolved != "unknown":
            language = resolved
    return language